agent.rb 10KB

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