agent.rb 14KB

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