agent.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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/huginn/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 DryRunnable
  14. include SortableEvents
  15. markdown_class_attributes :description, :event_description
  16. load_types_in "Agents"
  17. SCHEDULES = %w[
  18. every_1m every_2m every_5m every_10m every_30m
  19. every_1h every_2h every_5h every_12h
  20. every_1d every_2d every_7d
  21. midnight 1am 2am 3am 4am 5am 6am 7am 8am 9am 10am 11am
  22. noon 1pm 2pm 3pm 4pm 5pm 6pm 7pm 8pm 9pm 10pm 11pm
  23. never
  24. ]
  25. EVENT_RETENTION_SCHEDULES = [
  26. ["Forever", 0], ['1 hour', 1.hour], ['6 hours', 6.hours], ["1 day", 1.day],
  27. *(
  28. [2, 3, 4, 5, 7, 14, 21, 30, 45, 90, 180, 365].map { |n|
  29. ["#{n} days", n.days]
  30. }
  31. )
  32. ]
  33. json_serialize :options, :memory
  34. validates_presence_of :name, :user
  35. validates_inclusion_of :keep_events_for, in: EVENT_RETENTION_SCHEDULES.map(&:last)
  36. validates :sources, owned_by: :user_id
  37. validates :receivers, owned_by: :user_id
  38. validates :controllers, owned_by: :user_id
  39. validates :control_targets, owned_by: :user_id
  40. validates :scenarios, owned_by: :user_id
  41. validate :validate_schedule
  42. validate :validate_options
  43. after_initialize :set_default_schedule
  44. before_validation :set_default_schedule
  45. before_validation :unschedule_if_cannot_schedule
  46. before_save :unschedule_if_cannot_schedule
  47. before_create :set_last_checked_event_id
  48. after_save :possibly_update_event_expirations
  49. belongs_to :user, inverse_of: :agents
  50. belongs_to :service, inverse_of: :agents, optional: true
  51. has_many :events, -> { order("events.id desc") }, dependent: :delete_all, inverse_of: :agent
  52. has_one :most_recent_event, -> { order("events.id desc") }, inverse_of: :agent, class_name: "Event"
  53. has_many :logs, -> { order("agent_logs.id desc") }, dependent: :delete_all, inverse_of: :agent, class_name: "AgentLog"
  54. has_many :links_as_source, dependent: :delete_all, foreign_key: "source_id", class_name: "Link",
  55. inverse_of: :source
  56. has_many :links_as_receiver, dependent: :delete_all, foreign_key: "receiver_id", class_name: "Link",
  57. inverse_of: :receiver
  58. has_many :sources, through: :links_as_receiver, class_name: "Agent", inverse_of: :receivers
  59. has_many :received_events, -> { order("events.id desc") }, through: :sources, class_name: "Event", source: :events
  60. has_many :receivers, through: :links_as_source, class_name: "Agent", inverse_of: :sources
  61. has_many :control_links_as_controller, dependent: :delete_all, foreign_key: 'controller_id',
  62. class_name: 'ControlLink', inverse_of: :controller
  63. has_many :control_links_as_control_target, dependent: :delete_all, foreign_key: 'control_target_id',
  64. class_name: 'ControlLink', inverse_of: :control_target
  65. has_many :controllers, through: :control_links_as_control_target, class_name: "Agent", inverse_of: :control_targets
  66. has_many :control_targets, through: :control_links_as_controller, class_name: "Agent", inverse_of: :controllers
  67. has_many :scenario_memberships, dependent: :destroy, inverse_of: :agent
  68. has_many :scenarios, through: :scenario_memberships, inverse_of: :agents
  69. scope :active, -> { where(disabled: false, deactivated: false) }
  70. scope :inactive, -> { where(disabled: true).or(where(deactivated: true)) }
  71. scope :of_type, ->(type) {
  72. case type
  73. when Agent
  74. where(type: type.class.to_s)
  75. else
  76. where(type: type.to_s)
  77. end
  78. }
  79. def short_type
  80. type.demodulize
  81. end
  82. def check
  83. # Implement me in your subclass of Agent.
  84. end
  85. def default_options
  86. # Implement me in your subclass of Agent.
  87. {}
  88. end
  89. def receive(events)
  90. # Implement me in your subclass of Agent.
  91. end
  92. def is_form_configurable?
  93. false
  94. end
  95. def receive_web_request(params, method, format)
  96. # Implement me in your subclass of Agent.
  97. ["not implemented", 404, "text/plain", {}] # last two elements in response array are optional
  98. end
  99. # alternate method signature for receive_web_request
  100. # def receive_web_request(request=ActionDispatch::Request.new( ... ))
  101. # end
  102. # Implement me in your subclass to decide if your Agent is working.
  103. def working?
  104. raise "Implement me in your subclass"
  105. end
  106. def build_event(event)
  107. event = events.build(event) if event.is_a?(Hash)
  108. event.agent = self
  109. event.user = user
  110. event.expires_at ||= new_event_expiration_date
  111. event
  112. end
  113. def create_event(event)
  114. if can_create_events?
  115. event = build_event(event)
  116. event.save!
  117. event
  118. else
  119. error "This Agent cannot create events!"
  120. end
  121. end
  122. def credential(name)
  123. @credential_cache ||= {}
  124. if @credential_cache.has_key?(name)
  125. @credential_cache[name]
  126. else
  127. @credential_cache[name] = user.user_credentials.where(credential_name: name).first.try(:credential_value)
  128. end
  129. end
  130. def reload
  131. @credential_cache = {}
  132. super
  133. end
  134. def new_event_expiration_date
  135. keep_events_for > 0 ? keep_events_for.seconds.from_now : nil
  136. end
  137. def update_event_expirations!
  138. if keep_events_for == 0
  139. events.update_all expires_at: nil
  140. else
  141. events.update_all "expires_at = " + rdbms_date_add("created_at", "SECOND", keep_events_for.to_i)
  142. end
  143. end
  144. def trigger_web_request(request)
  145. params = request.params.except(:action, :controller, :agent_id, :user_id, :format)
  146. if respond_to?(:receive_webhook)
  147. Rails.logger.warn "DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request."
  148. receive_webhook(params).tap do
  149. self.last_web_request_at = Time.now
  150. save!
  151. end
  152. else
  153. handled_request =
  154. if method(:receive_web_request).arity == 1
  155. receive_web_request(request)
  156. else
  157. receive_web_request(params, request.method_symbol.to_s, request.format.to_s)
  158. end
  159. handled_request.tap do
  160. self.last_web_request_at = Time.now
  161. save!
  162. end
  163. end
  164. end
  165. def unavailable?
  166. disabled? || dependencies_missing?
  167. end
  168. def dependencies_missing?
  169. self.class.dependencies_missing?
  170. end
  171. def default_schedule
  172. self.class.default_schedule
  173. end
  174. def cannot_be_scheduled?
  175. self.class.cannot_be_scheduled?
  176. end
  177. def can_be_scheduled?
  178. !cannot_be_scheduled?
  179. end
  180. def cannot_receive_events?
  181. self.class.cannot_receive_events?
  182. end
  183. def can_receive_events?
  184. !cannot_receive_events?
  185. end
  186. def cannot_create_events?
  187. self.class.cannot_create_events?
  188. end
  189. def can_create_events?
  190. !cannot_create_events?
  191. end
  192. def can_control_other_agents?
  193. self.class.can_control_other_agents?
  194. end
  195. def can_dry_run?
  196. self.class.can_dry_run?
  197. end
  198. def no_bulk_receive?
  199. self.class.no_bulk_receive?
  200. end
  201. def log(message, options = {})
  202. AgentLog.log_for_agent(self, message, options.merge(inbound_event: current_event))
  203. end
  204. def error(message, options = {})
  205. log(message, options.merge(level: 4))
  206. end
  207. def delete_logs!
  208. logs.delete_all
  209. update_column :last_error_log_at, nil
  210. end
  211. def drop_pending_events
  212. false
  213. end
  214. def drop_pending_events=(bool)
  215. set_last_checked_event_id if bool
  216. end
  217. # Callbacks
  218. def set_default_schedule
  219. self.schedule = default_schedule unless schedule.present? || cannot_be_scheduled?
  220. end
  221. def unschedule_if_cannot_schedule
  222. self.schedule = nil if cannot_be_scheduled?
  223. end
  224. def set_last_checked_event_id
  225. if can_receive_events? && newest_event_id = Event.maximum(:id)
  226. self.last_checked_event_id = newest_event_id
  227. end
  228. end
  229. def possibly_update_event_expirations
  230. update_event_expirations! if saved_change_to_keep_events_for?
  231. end
  232. # Validation Methods
  233. private
  234. attr_accessor :current_event
  235. def validate_schedule
  236. unless cannot_be_scheduled?
  237. errors.add(:schedule, "is not a valid schedule") unless SCHEDULES.include?(schedule.to_s)
  238. end
  239. end
  240. def validate_options
  241. # Implement me in your subclass to test for valid options.
  242. end
  243. # Utility Methods
  244. def boolify(option_value)
  245. case option_value
  246. when true, 'true'
  247. true
  248. when false, 'false'
  249. false
  250. else
  251. nil
  252. end
  253. end
  254. def is_positive_integer?(value)
  255. Integer(value) >= 0
  256. rescue StandardError
  257. false
  258. end
  259. # Class Methods
  260. class << self
  261. def build_clone(original)
  262. new(original.slice(
  263. :type, :options, :service_id, :schedule, :controller_ids, :control_target_ids,
  264. :source_ids, :receiver_ids, :keep_events_for, :propagate_immediately, :scenario_ids
  265. )) { |clone|
  266. # Give it a unique name
  267. 2.step do |i|
  268. name = '%s (%d)' % [original.name, i]
  269. unless exists?(name:)
  270. clone.name = name
  271. break
  272. end
  273. end
  274. }
  275. end
  276. def cannot_be_scheduled!
  277. @cannot_be_scheduled = true
  278. end
  279. def cannot_be_scheduled?
  280. !!@cannot_be_scheduled
  281. end
  282. def default_schedule(schedule = nil)
  283. @default_schedule = schedule unless schedule.nil?
  284. @default_schedule
  285. end
  286. def cannot_create_events!
  287. @cannot_create_events = true
  288. end
  289. def cannot_create_events?
  290. !!@cannot_create_events
  291. end
  292. def cannot_receive_events!
  293. @cannot_receive_events = true
  294. end
  295. def cannot_receive_events?
  296. !!@cannot_receive_events
  297. end
  298. def can_control_other_agents!
  299. @can_control_other_agents = true
  300. end
  301. def can_control_other_agents?
  302. !!@can_control_other_agents
  303. end
  304. def can_dry_run!
  305. @can_dry_run = true
  306. end
  307. def can_dry_run?
  308. !!@can_dry_run
  309. end
  310. def no_bulk_receive!
  311. @no_bulk_receive = true
  312. end
  313. def no_bulk_receive?
  314. !!@no_bulk_receive
  315. end
  316. def gem_dependency_check
  317. @gem_dependencies_checked = true
  318. @gem_dependencies_met = yield
  319. end
  320. def dependencies_missing?
  321. @gem_dependencies_checked && !@gem_dependencies_met
  322. end
  323. # Find all Agents that have received Events since the last execution of this method. Update those Agents with
  324. # their new `last_checked_event_id` and queue each of the Agents to be called with #receive using `async_receive`.
  325. # This is called by bin/schedule.rb periodically.
  326. def receive!(options = {})
  327. Agent.transaction do
  328. scope = Agent
  329. .select("agents.id AS receiver_agent_id, sources.type AS source_agent_type, agents.type AS receiver_agent_type, events.id AS event_id")
  330. .joins("JOIN links ON (links.receiver_id = agents.id)")
  331. .joins("JOIN agents AS sources ON (links.source_id = sources.id)")
  332. .joins("JOIN events ON (events.agent_id = sources.id AND events.id > links.event_id_at_creation)")
  333. .where("NOT agents.disabled AND NOT agents.deactivated AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)")
  334. if options[:only_receivers].present?
  335. scope = scope.where("agents.id in (?)", options[:only_receivers])
  336. end
  337. sql = scope.to_sql
  338. agents_to_events = {}
  339. Agent.connection.select_rows(sql).each do |receiver_agent_id, source_agent_type, receiver_agent_type, event_id|
  340. begin
  341. Object.const_get(source_agent_type)
  342. Object.const_get(receiver_agent_type)
  343. rescue NameError
  344. next
  345. end
  346. agents_to_events[receiver_agent_id.to_i] ||= []
  347. agents_to_events[receiver_agent_id.to_i] << event_id
  348. end
  349. Agent.where(id: agents_to_events.keys).each do |agent|
  350. event_ids = agents_to_events[agent.id].uniq
  351. agent.update_attribute :last_checked_event_id, event_ids.max
  352. if agent.no_bulk_receive?
  353. event_ids.each { |event_id| Agent.async_receive(agent.id, [event_id]) }
  354. else
  355. Agent.async_receive(agent.id, event_ids)
  356. end
  357. end
  358. {
  359. agent_count: agents_to_events.keys.length,
  360. event_count: agents_to_events.values.flatten.uniq.compact.length
  361. }
  362. end
  363. end
  364. # This method will enqueue an AgentReceiveJob job. It accepts Agent and Event ids instead of a literal ActiveRecord
  365. # models because it is preferable to serialize jobs with ids.
  366. def async_receive(agent_id, event_ids)
  367. AgentReceiveJob.perform_later(agent_id, event_ids)
  368. end
  369. # Given a schedule name, run `check` via `bulk_check` on all Agents with that schedule.
  370. # This is called by bin/schedule.rb for each schedule in `SCHEDULES`.
  371. def run_schedule(schedule)
  372. return if schedule == 'never'
  373. types = where(schedule:).group(:type).pluck(:type)
  374. types.each do |type|
  375. next unless valid_type?(type)
  376. type.constantize.bulk_check(schedule)
  377. end
  378. end
  379. # Schedule `async_check`s for every Agent on the given schedule. This is normally called by `run_schedule` once
  380. # per type of agent, so you can override this to define custom bulk check behavior for your custom Agent type.
  381. def bulk_check(schedule)
  382. raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent
  383. where("NOT disabled AND NOT deactivated AND schedule = ?", schedule).pluck("agents.id").each do |agent_id|
  384. async_check(agent_id)
  385. end
  386. end
  387. # This method will enqueue an AgentCheckJob job. It accepts an Agent id instead of a literal Agent because it is
  388. # preferable to serialize job with ids, instead of with the full Agents.
  389. def async_check(agent_id)
  390. AgentCheckJob.perform_later(agent_id)
  391. end
  392. end
  393. public def to_liquid
  394. Drop.new(self)
  395. end
  396. class Drop < LiquidDroppable::Drop
  397. def type
  398. @object.short_type
  399. end
  400. METHODS = %i[
  401. id
  402. name
  403. type
  404. options
  405. memory
  406. sources
  407. receivers
  408. schedule
  409. controllers
  410. control_targets
  411. disabled
  412. keep_events_for
  413. propagate_immediately
  414. ]
  415. METHODS.each { |attr|
  416. define_method(attr) {
  417. @object.__send__(attr)
  418. } unless method_defined?(attr)
  419. }
  420. def working
  421. @object.working?
  422. end
  423. def url
  424. Rails.application.routes.url_helpers.agent_url(
  425. @object,
  426. Rails.application.config.action_mailer.default_url_options
  427. )
  428. end
  429. end
  430. end