1
0

agent.rb 13 KB

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