Nessuna descrizione http://j1x-huginn.herokuapp.com

agent.rb 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. 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, :disabled, :source_ids, :keep_events_for, :propagate_immediately
  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 :validate_schedule
  25. validate :validate_options
  26. after_initialize :set_default_schedule
  27. before_validation :set_default_schedule
  28. before_validation :unschedule_if_cannot_schedule
  29. before_save :unschedule_if_cannot_schedule
  30. before_create :set_last_checked_event_id
  31. after_save :possibly_update_event_expirations
  32. belongs_to :user, :inverse_of => :agents
  33. has_many :events, -> { order("events.id desc") }, :dependent => :delete_all, :inverse_of => :agent
  34. has_one :most_recent_event, :inverse_of => :agent, :class_name => "Event", :order => "events.id desc"
  35. has_many :logs, -> { order("agent_logs.id desc") }, :dependent => :delete_all, :inverse_of => :agent, :class_name => "AgentLog"
  36. has_many :received_events, -> { order("events.id desc") }, :through => :sources, :class_name => "Event", :source => :events
  37. has_many :links_as_source, :dependent => :delete_all, :foreign_key => "source_id", :class_name => "Link", :inverse_of => :source
  38. has_many :links_as_receiver, :dependent => :delete_all, :foreign_key => "receiver_id", :class_name => "Link", :inverse_of => :receiver
  39. has_many :sources, :through => :links_as_receiver, :class_name => "Agent", :inverse_of => :receivers
  40. has_many :receivers, :through => :links_as_source, :class_name => "Agent", :inverse_of => :sources
  41. scope :of_type, lambda { |type|
  42. type = case type
  43. when String, Symbol, Class
  44. type.to_s
  45. when Agent
  46. type.class.to_s
  47. else
  48. type.to_s
  49. end
  50. where(:type => type)
  51. }
  52. def check
  53. # Implement me in your subclass of Agent.
  54. end
  55. def default_options
  56. # Implement me in your subclass of Agent.
  57. {}
  58. end
  59. def receive(events)
  60. # Implement me in your subclass of Agent.
  61. end
  62. def receive_web_request(params, method, format)
  63. # Implement me in your subclass of Agent.
  64. ["not implemented", 404]
  65. end
  66. # Implement me in your subclass to decide if your Agent is working.
  67. def working?
  68. raise "Implement me in your subclass"
  69. end
  70. def create_event(attrs)
  71. if can_create_events?
  72. events.create!({
  73. :user => user,
  74. :expires_at => new_event_expiration_date
  75. }.merge(attrs))
  76. else
  77. error "This Agent cannot create events!"
  78. end
  79. end
  80. def credential(name)
  81. @credential_cache ||= {}
  82. if @credential_cache.has_key?(name)
  83. @credential_cache[name]
  84. else
  85. @credential_cache[name] = user.user_credentials.where(:credential_name => name).first.try(:credential_value)
  86. end
  87. end
  88. def reload
  89. @credential_cache = {}
  90. super
  91. end
  92. def new_event_expiration_date
  93. keep_events_for > 0 ? keep_events_for.days.from_now : nil
  94. end
  95. def update_event_expirations!
  96. if keep_events_for == 0
  97. events.update_all :expires_at => nil
  98. else
  99. events.update_all "expires_at = " + rdbms_date_add("created_at", "DAY", keep_events_for.to_i)
  100. end
  101. end
  102. def make_message(payload, message = options[:message])
  103. message.gsub(/<([^>]+)>/) { Utils.value_at(payload, $1) || "??" }
  104. end
  105. def trigger_web_request(params, method, format)
  106. if respond_to?(:receive_webhook)
  107. Rails.logger.warn "DEPRECATED: The .receive_webhook method is deprecated, please switch your Agent to use .receive_web_request."
  108. receive_webhook(params).tap do
  109. self.last_web_request_at = Time.now
  110. save!
  111. end
  112. else
  113. receive_web_request(params, method, format).tap do
  114. self.last_web_request_at = Time.now
  115. save!
  116. end
  117. end
  118. end
  119. def default_schedule
  120. self.class.default_schedule
  121. end
  122. def cannot_be_scheduled?
  123. self.class.cannot_be_scheduled?
  124. end
  125. def can_be_scheduled?
  126. !cannot_be_scheduled?
  127. end
  128. def cannot_receive_events?
  129. self.class.cannot_receive_events?
  130. end
  131. def can_receive_events?
  132. !cannot_receive_events?
  133. end
  134. def cannot_create_events?
  135. self.class.cannot_create_events?
  136. end
  137. def can_create_events?
  138. !cannot_create_events?
  139. end
  140. def log(message, options = {})
  141. puts "Agent##{id}: #{message}" unless Rails.env.test?
  142. AgentLog.log_for_agent(self, message, options)
  143. end
  144. def error(message, options = {})
  145. log(message, options.merge(:level => 4))
  146. end
  147. def delete_logs!
  148. logs.delete_all
  149. update_column :last_error_log_at, nil
  150. end
  151. # Callbacks
  152. def set_default_schedule
  153. self.schedule = default_schedule unless schedule.present? || cannot_be_scheduled?
  154. end
  155. def unschedule_if_cannot_schedule
  156. self.schedule = nil if cannot_be_scheduled?
  157. end
  158. def set_last_checked_event_id
  159. if newest_event_id = Event.order("id desc").limit(1).pluck(:id).first
  160. self.last_checked_event_id = newest_event_id
  161. end
  162. end
  163. def possibly_update_event_expirations
  164. update_event_expirations! if keep_events_for_changed?
  165. end
  166. #Validation Methods
  167. private
  168. def sources_are_owned
  169. errors.add(:sources, "must be owned by you") unless sources.all? {|s| s.user == user }
  170. end
  171. def validate_schedule
  172. unless cannot_be_scheduled?
  173. errors.add(:schedule, "is not a valid schedule") unless SCHEDULES.include?(schedule.to_s)
  174. end
  175. end
  176. def validate_options
  177. # Implement me in your subclass to test for valid options.
  178. end
  179. # Class Methods
  180. class << self
  181. def build_clone(original)
  182. new(original.slice(:type, :options, :schedule, :source_ids, :keep_events_for, :propagate_immediately)) { |clone|
  183. # Give it a unique name
  184. 2.upto(count) do |i|
  185. name = '%s (%d)' % [original.name, i]
  186. unless exists?(name: name)
  187. clone.name = name
  188. break
  189. end
  190. end
  191. }
  192. end
  193. def cannot_be_scheduled!
  194. @cannot_be_scheduled = true
  195. end
  196. def cannot_be_scheduled?
  197. !!@cannot_be_scheduled
  198. end
  199. def default_schedule(schedule = nil)
  200. @default_schedule = schedule unless schedule.nil?
  201. @default_schedule
  202. end
  203. def cannot_create_events!
  204. @cannot_create_events = true
  205. end
  206. def cannot_create_events?
  207. !!@cannot_create_events
  208. end
  209. def cannot_receive_events!
  210. @cannot_receive_events = true
  211. end
  212. def cannot_receive_events?
  213. !!@cannot_receive_events
  214. end
  215. # Find all Agents that have received Events since the last execution of this method. Update those Agents with
  216. # their new `last_checked_event_id` and queue each of the Agents to be called with #receive using `async_receive`.
  217. # This is called by bin/schedule.rb periodically.
  218. def receive!(options={})
  219. Agent.transaction do
  220. scope = Agent.
  221. select("agents.id AS receiver_agent_id, sources.id AS source_agent_id, events.id AS event_id").
  222. joins("JOIN links ON (links.receiver_id = agents.id)").
  223. joins("JOIN agents AS sources ON (links.source_id = sources.id)").
  224. joins("JOIN events ON (events.agent_id = sources.id AND events.id > links.event_id_at_creation)").
  225. where("NOT agents.disabled AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)")
  226. if options[:only_receivers].present?
  227. scope = scope.where("agents.id in (?)", options[:only_receivers])
  228. end
  229. sql = scope.to_sql()
  230. agents_to_events = {}
  231. Agent.connection.select_rows(sql).each do |receiver_agent_id, source_agent_id, event_id|
  232. agents_to_events[receiver_agent_id.to_i] ||= []
  233. agents_to_events[receiver_agent_id.to_i] << event_id
  234. end
  235. event_ids = agents_to_events.values.flatten.uniq.compact
  236. Agent.where(:id => agents_to_events.keys).each do |agent|
  237. agent.update_attribute :last_checked_event_id, event_ids.max
  238. Agent.async_receive(agent.id, agents_to_events[agent.id].uniq)
  239. end
  240. {
  241. :agent_count => agents_to_events.keys.length,
  242. :event_count => event_ids.length
  243. }
  244. end
  245. end
  246. # Given an Agent id and an array of Event ids, load the Agent, call #receive on it with the Event objects, and then
  247. # save it with an updated `last_receive_at` timestamp.
  248. #
  249. # This method is tagged with `handle_asynchronously` and will be delayed and run with delayed_job. It accepts Agent
  250. # and Event ids instead of a literal ActiveRecord models because it is preferable to serialize delayed_jobs with ids.
  251. def async_receive(agent_id, event_ids)
  252. agent = Agent.find(agent_id)
  253. begin
  254. return if agent.disabled?
  255. agent.receive(Event.where(:id => event_ids))
  256. agent.last_receive_at = Time.now
  257. agent.save!
  258. rescue => e
  259. agent.error "Exception during receive: #{e.message} -- #{e.backtrace}"
  260. raise
  261. end
  262. end
  263. handle_asynchronously :async_receive
  264. # Given a schedule name, run `check` via `bulk_check` on all Agents with that schedule.
  265. # This is called by bin/schedule.rb for each schedule in `SCHEDULES`.
  266. def run_schedule(schedule)
  267. return if schedule == 'never'
  268. types = where(:schedule => schedule).group(:type).pluck(:type)
  269. types.each do |type|
  270. type.constantize.bulk_check(schedule)
  271. end
  272. end
  273. # Schedule `async_check`s for every Agent on the given schedule. This is normally called by `run_schedule` once
  274. # per type of agent, so you can override this to define custom bulk check behavior for your custom Agent type.
  275. def bulk_check(schedule)
  276. raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent
  277. where("agents.schedule = ? and disabled = false", schedule).pluck("agents.id").each do |agent_id|
  278. async_check(agent_id)
  279. end
  280. end
  281. # Given an Agent id, load the Agent, call #check on it, and then save it with an updated `last_check_at` timestamp.
  282. #
  283. # This method is tagged with `handle_asynchronously` and will be delayed and run with delayed_job. It accepts an Agent
  284. # id instead of a literal Agent because it is preferable to serialize delayed_jobs with ids, instead of with the full
  285. # Agents.
  286. def async_check(agent_id)
  287. agent = Agent.find(agent_id)
  288. begin
  289. return if agent.disabled?
  290. agent.check
  291. agent.last_check_at = Time.now
  292. agent.save!
  293. rescue => e
  294. agent.error "Exception during check: #{e.message} -- #{e.backtrace}"
  295. raise
  296. end
  297. end
  298. handle_asynchronously :async_check
  299. end
  300. end