agent.rb 14 KB

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