agent.rb 15KB

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