Keine Beschreibung http://j1x-huginn.herokuapp.com

agent.rb 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. require 'json_serialized_field'
  2. require 'assignable_types'
  3. require 'markdown_class_attributes'
  4. require 'utils'
  5. # Agent is the core class in Huginn, representing a configurable, schedulable, reactive system with memory that can
  6. # be sub-classed for many different purposes. Agents can emit Events, as well as receive them and react in many different ways.
  7. # The basic Agent API is detailed on the Huginn wiki: https://github.com/cantino/huginn/wiki/Creating-a-new-agent
  8. class Agent < ActiveRecord::Base
  9. include AssignableTypes
  10. include MarkdownClassAttributes
  11. include JSONSerializedField
  12. include RDBMSFunctions
  13. markdown_class_attributes :description, :event_description
  14. load_types_in "Agents"
  15. SCHEDULES = %w[every_1m every_2m every_5m every_10m every_30m every_1h every_2h every_5h every_12h every_1d every_2d every_7d
  16. midnight 1am 2am 3am 4am 5am 6am 7am 8am 9am 10am 11am noon 1pm 2pm 3pm 4pm 5pm 6pm 7pm 8pm 9pm 10pm 11pm never]
  17. EVENT_RETENTION_SCHEDULES = [["Forever", 0], ["1 day", 1], *([2, 3, 4, 5, 7, 14, 21, 30, 45, 90, 180, 365].map {|n| ["#{n} days", n] })]
  18. attr_accessible :options, :memory, :name, :type, :schedule, :source_ids, :keep_events_for, :propagate_immediately
  19. json_serialize :options, :memory
  20. validates_presence_of :name, :user
  21. validates_inclusion_of :keep_events_for, :in => EVENT_RETENTION_SCHEDULES.map(&:last)
  22. validate :sources_are_owned
  23. validate :validate_schedule
  24. validate :validate_options
  25. after_initialize :set_default_schedule
  26. before_validation :set_default_schedule
  27. before_validation :unschedule_if_cannot_schedule
  28. before_save :unschedule_if_cannot_schedule
  29. before_create :set_last_checked_event_id
  30. after_save :possibly_update_event_expirations
  31. belongs_to :user, :inverse_of => :agents
  32. has_many :events, -> { order("events.id desc") }, :dependent => :delete_all, :inverse_of => :agent
  33. has_one :most_recent_event, :inverse_of => :agent, :class_name => "Event", :order => "events.id desc"
  34. has_many :logs, -> { order("agent_logs.id desc") }, :dependent => :delete_all, :inverse_of => :agent, :class_name => "AgentLog"
  35. has_many :received_events, -> { order("events.id desc") }, :through => :sources, :class_name => "Event", :source => :events
  36. has_many :links_as_source, :dependent => :delete_all, :foreign_key => "source_id", :class_name => "Link", :inverse_of => :source
  37. has_many :links_as_receiver, :dependent => :delete_all, :foreign_key => "receiver_id", :class_name => "Link", :inverse_of => :receiver
  38. has_many :sources, :through => :links_as_receiver, :class_name => "Agent", :inverse_of => :receivers
  39. has_many :receivers, :through => :links_as_source, :class_name => "Agent", :inverse_of => :sources
  40. scope :of_type, lambda { |type|
  41. type = case type
  42. when String, Symbol, Class
  43. type.to_s
  44. when Agent
  45. type.class.to_s
  46. else
  47. type.to_s
  48. end
  49. where(:type => type)
  50. }
  51. def check
  52. # Implement me in your subclass of Agent.
  53. end
  54. def default_options
  55. # Implement me in your subclass of Agent.
  56. {}
  57. end
  58. def receive(events)
  59. # Implement me in your subclass of Agent.
  60. end
  61. def receive_web_request(params, method, format)
  62. # Implement me in your subclass of Agent.
  63. ["not implemented", 404]
  64. end
  65. # Implement me in your subclass to decide if your Agent is working.
  66. def working?
  67. raise "Implement me in your subclass"
  68. end
  69. def event_created_within?(days)
  70. last_event_at && last_event_at > days.to_i.days.ago
  71. end
  72. def recent_error_logs?
  73. last_event_at && last_error_log_at && last_error_log_at > (last_event_at - 2.minutes)
  74. end
  75. def received_event_without_error?
  76. (last_receive_at.present? && last_error_log_at.blank?) || (last_receive_at.present? && last_error_log_at.present? && last_receive_at > last_error_log_at)
  77. end
  78. def create_event(attrs)
  79. if can_create_events?
  80. events.create!({
  81. :user => user,
  82. :expires_at => new_event_expiration_date
  83. }.merge(attrs))
  84. else
  85. error "This Agent cannot create events!"
  86. end
  87. end
  88. def credential(name)
  89. @credential_cache ||= {}
  90. if @credential_cache.has_key?(name)
  91. @credential_cache[name]
  92. else
  93. @credential_cache[name] = user.user_credentials.where(:credential_name => name).first.try(:credential_value)
  94. end
  95. end
  96. def reload
  97. @credential_cache = {}
  98. super
  99. end
  100. def new_event_expiration_date
  101. keep_events_for > 0 ? keep_events_for.days.from_now : nil
  102. end
  103. def update_event_expirations!
  104. if keep_events_for == 0
  105. events.update_all :expires_at => nil
  106. else
  107. events.update_all "expires_at = " + rdbms_date_add("created_at", "DAY", keep_events_for.to_i)
  108. end
  109. end
  110. def make_message(payload, message = options[:message])
  111. message.gsub(/<([^>]+)>/) { Utils.value_at(payload, $1) || "??" }
  112. end
  113. def trigger_web_request(params, method, format)
  114. if respond_to?(:receive_webhook)
  115. Rails.logger.warn "DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request."
  116. receive_webhook(params).tap do
  117. self.last_web_request_at = Time.now
  118. save!
  119. end
  120. else
  121. receive_web_request(params, method, format).tap do
  122. self.last_web_request_at = Time.now
  123. save!
  124. end
  125. end
  126. end
  127. def default_schedule
  128. self.class.default_schedule
  129. end
  130. def cannot_be_scheduled?
  131. self.class.cannot_be_scheduled?
  132. end
  133. def can_be_scheduled?
  134. !cannot_be_scheduled?
  135. end
  136. def cannot_receive_events?
  137. self.class.cannot_receive_events?
  138. end
  139. def can_receive_events?
  140. !cannot_receive_events?
  141. end
  142. def cannot_create_events?
  143. self.class.cannot_create_events?
  144. end
  145. def can_create_events?
  146. !cannot_create_events?
  147. end
  148. def log(message, options = {})
  149. puts "Agent##{id}: #{message}" unless Rails.env.test?
  150. AgentLog.log_for_agent(self, message, options)
  151. end
  152. def error(message, options = {})
  153. log(message, options.merge(:level => 4))
  154. end
  155. def delete_logs!
  156. logs.delete_all
  157. update_column :last_error_log_at, nil
  158. end
  159. # Callbacks
  160. def set_default_schedule
  161. self.schedule = default_schedule unless schedule.present? || cannot_be_scheduled?
  162. end
  163. def unschedule_if_cannot_schedule
  164. self.schedule = nil if cannot_be_scheduled?
  165. end
  166. def set_last_checked_event_id
  167. if newest_event_id = Event.order("id desc").limit(1).pluck(:id).first
  168. self.last_checked_event_id = newest_event_id
  169. end
  170. end
  171. def possibly_update_event_expirations
  172. update_event_expirations! if keep_events_for_changed?
  173. end
  174. #Validation Methods
  175. private
  176. def sources_are_owned
  177. errors.add(:sources, "must be owned by you") unless sources.all? {|s| s.user == user }
  178. end
  179. def validate_schedule
  180. unless cannot_be_scheduled?
  181. errors.add(:schedule, "is not a valid schedule") unless SCHEDULES.include?(schedule.to_s)
  182. end
  183. end
  184. def validate_options
  185. # Implement me in your subclass to test for valid options.
  186. end
  187. # Class Methods
  188. class << self
  189. def cannot_be_scheduled!
  190. @cannot_be_scheduled = true
  191. end
  192. def cannot_be_scheduled?
  193. !!@cannot_be_scheduled
  194. end
  195. def default_schedule(schedule = nil)
  196. @default_schedule = schedule unless schedule.nil?
  197. @default_schedule
  198. end
  199. def cannot_create_events!
  200. @cannot_create_events = true
  201. end
  202. def cannot_create_events?
  203. !!@cannot_create_events
  204. end
  205. def cannot_receive_events!
  206. @cannot_receive_events = true
  207. end
  208. def cannot_receive_events?
  209. !!@cannot_receive_events
  210. end
  211. # Find all Agents that have received Events since the last execution of this method. Update those Agents with
  212. # their new `last_checked_event_id` and queue each of the Agents to be called with #receive using `async_receive`.
  213. # This is called by bin/schedule.rb periodically.
  214. def receive!(options={})
  215. Agent.transaction do
  216. scope = Agent.
  217. select("agents.id AS receiver_agent_id, sources.id AS source_agent_id, events.id AS event_id").
  218. joins("JOIN links ON (links.receiver_id = agents.id)").
  219. joins("JOIN agents AS sources ON (links.source_id = sources.id)").
  220. joins("JOIN events ON (events.agent_id = sources.id AND events.id > links.event_id_at_creation)").
  221. where("agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id")
  222. if options[:only_receivers].present?
  223. scope = scope.where("agents.id in (?)", options[:only_receivers])
  224. end
  225. sql = scope.to_sql()
  226. agents_to_events = {}
  227. Agent.connection.select_rows(sql).each do |receiver_agent_id, source_agent_id, event_id|
  228. agents_to_events[receiver_agent_id.to_i] ||= []
  229. agents_to_events[receiver_agent_id.to_i] << event_id
  230. end
  231. event_ids = agents_to_events.values.flatten.uniq.compact
  232. Agent.where(:id => agents_to_events.keys).each do |agent|
  233. agent.update_attribute :last_checked_event_id, event_ids.max
  234. Agent.async_receive(agent.id, agents_to_events[agent.id].uniq)
  235. end
  236. {
  237. :agent_count => agents_to_events.keys.length,
  238. :event_count => event_ids.length
  239. }
  240. end
  241. end
  242. # Given an Agent id and an array of Event ids, load the Agent, call #receive on it with the Event objects, and then
  243. # save it with an updated `last_receive_at` timestamp.
  244. #
  245. # This method is tagged with `handle_asynchronously` and will be delayed and run with delayed_job. It accepts Agent
  246. # and Event ids instead of a literal ActiveRecord models because it is preferable to serialize delayed_jobs with ids.
  247. def async_receive(agent_id, event_ids)
  248. agent = Agent.find(agent_id)
  249. begin
  250. agent.receive(Event.where(:id => event_ids))
  251. agent.last_receive_at = Time.now
  252. agent.save!
  253. rescue => e
  254. agent.error "Exception during receive: #{e.message} -- #{e.backtrace}"
  255. raise
  256. end
  257. end
  258. handle_asynchronously :async_receive
  259. # Given a schedule name, run `check` via `bulk_check` on all Agents with that schedule.
  260. # This is called by bin/schedule.rb for each schedule in `SCHEDULES`.
  261. def run_schedule(schedule)
  262. return if schedule == 'never'
  263. types = where(:schedule => schedule).group(:type).pluck(:type)
  264. types.each do |type|
  265. type.constantize.bulk_check(schedule)
  266. end
  267. end
  268. # Schedule `async_check`s for every Agent on the given schedule. This is normally called by `run_schedule` once
  269. # per type of agent, so you can override this to define custom bulk check behavior for your custom Agent type.
  270. def bulk_check(schedule)
  271. raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent
  272. where(:schedule => schedule).pluck("agents.id").each do |agent_id|
  273. async_check(agent_id)
  274. end
  275. end
  276. # Given an Agent id, load the Agent, call #check on it, and then save it with an updated `last_check_at` timestamp.
  277. #
  278. # This method is tagged with `handle_asynchronously` and will be delayed and run with delayed_job. It accepts an Agent
  279. # id instead of a literal Agent because it is preferable to serialize delayed_jobs with ids, instead of with the full
  280. # Agents.
  281. def async_check(agent_id)
  282. agent = Agent.find(agent_id)
  283. begin
  284. agent.check
  285. agent.last_check_at = Time.now
  286. agent.save!
  287. rescue => e
  288. agent.error "Exception during check: #{e.message} -- #{e.backtrace}"
  289. raise
  290. end
  291. end
  292. handle_asynchronously :async_check
  293. end
  294. end