agent.rb 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. include WorkingHelpers
  14. include LiquidInterpolatable
  15. include HasGuid
  16. include LiquidDroppable
  17. markdown_class_attributes :description, :event_description
  18. 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
  19. 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]
  20. 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] })]
  21. attr_accessible :options, :memory, :name, :type, :schedule, :controller_ids, :control_target_ids, :disabled, :source_ids, :scenario_ids, :keep_events_for, :propagate_immediately
  22. json_serialize :options, :memory
  23. validates_presence_of :name, :user
  24. validates_inclusion_of :keep_events_for, :in => EVENT_RETENTION_SCHEDULES.map(&:last)
  25. validate :sources_are_owned
  26. validate :controllers_are_owned
  27. validate :control_targets_are_owned
  28. validate :scenarios_are_owned
  29. validate :validate_schedule
  30. validate :validate_options
  31. after_initialize :set_default_schedule
  32. before_validation :set_default_schedule
  33. before_validation :unschedule_if_cannot_schedule
  34. before_save :unschedule_if_cannot_schedule
  35. before_create :set_last_checked_event_id
  36. after_save :possibly_update_event_expirations
  37. belongs_to :user, :inverse_of => :agents
  38. belongs_to :service, :inverse_of => :agents
  39. has_many :events, -> { order("events.id desc") }, :dependent => :delete_all, :inverse_of => :agent
  40. has_one :most_recent_event, :inverse_of => :agent, :class_name => "Event", :order => "events.id desc"
  41. has_many :logs, -> { order("agent_logs.id desc") }, :dependent => :delete_all, :inverse_of => :agent, :class_name => "AgentLog"
  42. has_many :received_events, -> { order("events.id desc") }, :through => :sources, :class_name => "Event", :source => :events
  43. has_many :links_as_source, :dependent => :delete_all, :foreign_key => "source_id", :class_name => "Link", :inverse_of => :source
  44. has_many :links_as_receiver, :dependent => :delete_all, :foreign_key => "receiver_id", :class_name => "Link", :inverse_of => :receiver
  45. has_many :sources, :through => :links_as_receiver, :class_name => "Agent", :inverse_of => :receivers
  46. has_many :receivers, :through => :links_as_source, :class_name => "Agent", :inverse_of => :sources
  47. has_many :control_links_as_controller, dependent: :delete_all, foreign_key: 'controller_id', class_name: 'ControlLink', inverse_of: :controller
  48. has_many :control_links_as_control_target, dependent: :delete_all, foreign_key: 'control_target_id', class_name: 'ControlLink', inverse_of: :control_target
  49. has_many :controllers, through: :control_links_as_control_target, class_name: "Agent", inverse_of: :control_targets
  50. has_many :control_targets, through: :control_links_as_controller, class_name: "Agent", inverse_of: :controllers
  51. has_many :scenario_memberships, :dependent => :destroy, :inverse_of => :agent
  52. has_many :scenarios, :through => :scenario_memberships, :inverse_of => :agents
  53. scope :active, -> { where(disabled: false) }
  54. scope :of_type, lambda { |type|
  55. type = case type
  56. when Agent
  57. type.class.to_s
  58. else
  59. type.to_s
  60. end
  61. where(:type => type)
  62. }
  63. def short_type
  64. type.demodulize
  65. end
  66. def check
  67. # Implement me in your subclass of Agent.
  68. end
  69. def default_options
  70. # Implement me in your subclass of Agent.
  71. {}
  72. end
  73. def receive(events)
  74. # Implement me in your subclass of Agent.
  75. end
  76. def receive_web_request(params, method, format)
  77. # Implement me in your subclass of Agent.
  78. ["not implemented", 404]
  79. end
  80. # Implement me in your subclass to decide if your Agent is working.
  81. def working?
  82. raise "Implement me in your subclass"
  83. end
  84. def create_event(attrs)
  85. if can_create_events?
  86. events.create!({
  87. :user => user,
  88. :expires_at => new_event_expiration_date
  89. }.merge(attrs))
  90. else
  91. error "This Agent cannot create events!"
  92. end
  93. end
  94. def credential(name)
  95. @credential_cache ||= {}
  96. if @credential_cache.has_key?(name)
  97. @credential_cache[name]
  98. else
  99. @credential_cache[name] = user.user_credentials.where(:credential_name => name).first.try(:credential_value)
  100. end
  101. end
  102. def reload
  103. @credential_cache = {}
  104. super
  105. end
  106. def new_event_expiration_date
  107. keep_events_for > 0 ? keep_events_for.days.from_now : nil
  108. end
  109. def update_event_expirations!
  110. if keep_events_for == 0
  111. events.update_all :expires_at => nil
  112. else
  113. events.update_all "expires_at = " + rdbms_date_add("created_at", "DAY", keep_events_for.to_i)
  114. end
  115. end
  116. def trigger_web_request(params, method, format)
  117. if respond_to?(:receive_webhook)
  118. Rails.logger.warn "DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request."
  119. receive_webhook(params).tap do
  120. self.last_web_request_at = Time.now
  121. save!
  122. end
  123. else
  124. receive_web_request(params, method, format).tap do
  125. self.last_web_request_at = Time.now
  126. save!
  127. end
  128. end
  129. end
  130. def default_schedule
  131. self.class.default_schedule
  132. end
  133. def cannot_be_scheduled?
  134. self.class.cannot_be_scheduled?
  135. end
  136. def can_be_scheduled?
  137. !cannot_be_scheduled?
  138. end
  139. def cannot_receive_events?
  140. self.class.cannot_receive_events?
  141. end
  142. def can_receive_events?
  143. !cannot_receive_events?
  144. end
  145. def cannot_create_events?
  146. self.class.cannot_create_events?
  147. end
  148. def can_create_events?
  149. !cannot_create_events?
  150. end
  151. def can_control_other_agents?
  152. self.class.can_control_other_agents?
  153. end
  154. def log(message, options = {})
  155. puts "Agent##{id}: #{message}" unless Rails.env.test?
  156. AgentLog.log_for_agent(self, message, options)
  157. end
  158. def error(message, options = {})
  159. log(message, options.merge(:level => 4))
  160. end
  161. def delete_logs!
  162. logs.delete_all
  163. update_column :last_error_log_at, nil
  164. end
  165. # Callbacks
  166. def set_default_schedule
  167. self.schedule = default_schedule unless schedule.present? || cannot_be_scheduled?
  168. end
  169. def unschedule_if_cannot_schedule
  170. self.schedule = nil if cannot_be_scheduled?
  171. end
  172. def set_last_checked_event_id
  173. if newest_event_id = Event.order("id desc").limit(1).pluck(:id).first
  174. self.last_checked_event_id = newest_event_id
  175. end
  176. end
  177. def possibly_update_event_expirations
  178. update_event_expirations! if keep_events_for_changed?
  179. end
  180. #Validation Methods
  181. private
  182. def sources_are_owned
  183. errors.add(:sources, "must be owned by you") unless sources.all? {|s| s.user_id == user_id }
  184. end
  185. def controllers_are_owned
  186. errors.add(:controllers, "must be owned by you") unless controllers.all? {|s| s.user_id == user_id }
  187. end
  188. def control_targets_are_owned
  189. errors.add(:control_targets, "must be owned by you") unless control_targets.all? {|s| s.user_id == user_id }
  190. end
  191. def scenarios_are_owned
  192. errors.add(:scenarios, "must be owned by you") unless scenarios.all? {|s| s.user_id == user_id }
  193. end
  194. def validate_schedule
  195. unless cannot_be_scheduled?
  196. errors.add(:schedule, "is not a valid schedule") unless SCHEDULES.include?(schedule.to_s)
  197. end
  198. end
  199. def validate_options
  200. # Implement me in your subclass to test for valid options.
  201. end
  202. # Utility Methods
  203. def boolify(option_value)
  204. case option_value
  205. when true, 'true'
  206. true
  207. when false, 'false'
  208. false
  209. else
  210. nil
  211. end
  212. end
  213. # Class Methods
  214. class << self
  215. def build_clone(original)
  216. new(original.slice(:type, :options, :schedule, :controller_ids, :control_target_ids,
  217. :source_ids, :keep_events_for, :propagate_immediately)) { |clone|
  218. # Give it a unique name
  219. 2.upto(count) do |i|
  220. name = '%s (%d)' % [original.name, i]
  221. unless exists?(name: name)
  222. clone.name = name
  223. break
  224. end
  225. end
  226. }
  227. end
  228. def cannot_be_scheduled!
  229. @cannot_be_scheduled = true
  230. end
  231. def cannot_be_scheduled?
  232. !!@cannot_be_scheduled
  233. end
  234. def default_schedule(schedule = nil)
  235. @default_schedule = schedule unless schedule.nil?
  236. @default_schedule
  237. end
  238. def cannot_create_events!
  239. @cannot_create_events = true
  240. end
  241. def cannot_create_events?
  242. !!@cannot_create_events
  243. end
  244. def cannot_receive_events!
  245. @cannot_receive_events = true
  246. end
  247. def cannot_receive_events?
  248. !!@cannot_receive_events
  249. end
  250. def can_control_other_agents?
  251. include? AgentControllerConcern
  252. end
  253. # Find all Agents that have received Events since the last execution of this method. Update those Agents with
  254. # their new `last_checked_event_id` and queue each of the Agents to be called with #receive using `async_receive`.
  255. # This is called by bin/schedule.rb periodically.
  256. def receive!(options={})
  257. Agent.transaction do
  258. scope = Agent.
  259. select("agents.id AS receiver_agent_id, sources.id AS source_agent_id, events.id AS event_id").
  260. joins("JOIN links ON (links.receiver_id = agents.id)").
  261. joins("JOIN agents AS sources ON (links.source_id = sources.id)").
  262. joins("JOIN events ON (events.agent_id = sources.id AND events.id > links.event_id_at_creation)").
  263. where("NOT agents.disabled AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)")
  264. if options[:only_receivers].present?
  265. scope = scope.where("agents.id in (?)", options[:only_receivers])
  266. end
  267. sql = scope.to_sql()
  268. agents_to_events = {}
  269. Agent.connection.select_rows(sql).each do |receiver_agent_id, source_agent_id, event_id|
  270. agents_to_events[receiver_agent_id.to_i] ||= []
  271. agents_to_events[receiver_agent_id.to_i] << event_id
  272. end
  273. event_ids = agents_to_events.values.flatten.uniq.compact
  274. Agent.where(:id => agents_to_events.keys).each do |agent|
  275. agent.update_attribute :last_checked_event_id, event_ids.max
  276. Agent.async_receive(agent.id, agents_to_events[agent.id].uniq)
  277. end
  278. {
  279. :agent_count => agents_to_events.keys.length,
  280. :event_count => event_ids.length
  281. }
  282. end
  283. end
  284. # Given an Agent id and an array of Event ids, load the Agent, call #receive on it with the Event objects, and then
  285. # save it with an updated `last_receive_at` timestamp.
  286. #
  287. # This method is tagged with `handle_asynchronously` and will be delayed and run with delayed_job. It accepts Agent
  288. # and Event ids instead of a literal ActiveRecord models because it is preferable to serialize delayed_jobs with ids.
  289. def async_receive(agent_id, event_ids)
  290. agent = Agent.find(agent_id)
  291. begin
  292. return if agent.disabled?
  293. agent.receive(Event.where(:id => event_ids))
  294. agent.last_receive_at = Time.now
  295. agent.save!
  296. rescue => e
  297. agent.error "Exception during receive: #{e.message} -- #{e.backtrace}"
  298. raise
  299. end
  300. end
  301. handle_asynchronously :async_receive
  302. # Given a schedule name, run `check` via `bulk_check` on all Agents with that schedule.
  303. # This is called by bin/schedule.rb for each schedule in `SCHEDULES`.
  304. def run_schedule(schedule)
  305. return if schedule == 'never'
  306. types = where(:schedule => schedule).group(:type).pluck(:type)
  307. types.each do |type|
  308. type.constantize.bulk_check(schedule)
  309. end
  310. end
  311. # Schedule `async_check`s for every Agent on the given schedule. This is normally called by `run_schedule` once
  312. # per type of agent, so you can override this to define custom bulk check behavior for your custom Agent type.
  313. def bulk_check(schedule)
  314. raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent
  315. where("agents.schedule = ? and disabled = false", schedule).pluck("agents.id").each do |agent_id|
  316. async_check(agent_id)
  317. end
  318. end
  319. # Given an Agent id, load the Agent, call #check on it, and then save it with an updated `last_check_at` timestamp.
  320. #
  321. # This method is tagged with `handle_asynchronously` and will be delayed and run with delayed_job. It accepts an Agent
  322. # id instead of a literal Agent because it is preferable to serialize delayed_jobs with ids, instead of with the full
  323. # Agents.
  324. def async_check(agent_id)
  325. agent = Agent.find(agent_id)
  326. begin
  327. return if agent.disabled?
  328. agent.check
  329. agent.last_check_at = Time.now
  330. agent.save!
  331. rescue => e
  332. agent.error "Exception during check: #{e.message} -- #{e.backtrace}"
  333. raise
  334. end
  335. end
  336. handle_asynchronously :async_check
  337. end
  338. # Finally load all agent classes after necessary class methods are defined.
  339. load_types_in "Agents"
  340. end
  341. class AgentDrop
  342. def type
  343. @object.short_type
  344. end
  345. [
  346. :name,
  347. :type,
  348. :options,
  349. :memory,
  350. :sources,
  351. :receivers,
  352. :schedule,
  353. :controllers,
  354. :control_targets,
  355. :disabled,
  356. :keep_events_for,
  357. :propagate_immediately,
  358. ].each { |attr|
  359. define_method(attr) {
  360. @object.__send__(attr)
  361. } unless method_defined?(attr)
  362. }
  363. end