agent.rb 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. require 'serialize_and_symbolize'
  2. require 'assignable_types'
  3. require 'markdown_class_attributes'
  4. require 'utils'
  5. class Agent < ActiveRecord::Base
  6. include SerializeAndSymbolize
  7. include AssignableTypes
  8. include MarkdownClassAttributes
  9. serialize_and_symbolize :options, :memory
  10. markdown_class_attributes :description, :event_description
  11. load_types_in "Agents"
  12. SCHEDULES = %w[every_2m every_5m every_10m every_30m every_1h every_2h every_5h every_12h every_1d every_2d every_7d
  13. midnight 1am 2am 3am 4am 5am 6am 7am 8am 9am 10am 11am noon 1pm 2pm 3pm 4pm 5pm 6pm 7pm 8pm 9pm 10pm 11pm]
  14. attr_accessible :options, :memory, :name, :type, :schedule, :source_ids
  15. validates_presence_of :name, :user
  16. validate :sources_are_owned
  17. validate :validate_schedule
  18. after_initialize :set_default_schedule
  19. before_validation :set_default_schedule
  20. before_validation :unschedule_if_cannot_schedule
  21. before_save :unschedule_if_cannot_schedule
  22. before_create :set_last_checked_event_id
  23. belongs_to :user, :inverse_of => :agents
  24. has_many :events, :dependent => :delete_all, :inverse_of => :agent, :order => "events.id desc"
  25. has_one :most_recent_event, :inverse_of => :agent, :class_name => "Event", :order => "events.id desc"
  26. has_many :logs, :dependent => :delete_all, :inverse_of => :agent, :class_name => "AgentLog", :order => "agent_logs.id desc"
  27. has_one :most_recent_log, :inverse_of => :agent, :class_name => "AgentLog", :order => "agent_logs.id desc"
  28. has_many :received_events, :through => :sources, :class_name => "Event", :source => :events, :order => "events.id desc"
  29. has_many :links_as_source, :dependent => :delete_all, :foreign_key => "source_id", :class_name => "Link", :inverse_of => :source
  30. has_many :links_as_receiver, :dependent => :delete_all, :foreign_key => "receiver_id", :class_name => "Link", :inverse_of => :receiver
  31. has_many :sources, :through => :links_as_receiver, :class_name => "Agent", :inverse_of => :receivers
  32. has_many :receivers, :through => :links_as_source, :class_name => "Agent", :inverse_of => :sources
  33. scope :of_type, lambda { |type|
  34. type = case type
  35. when String, Symbol, Class
  36. type.to_s
  37. when Agent
  38. type.class.to_s
  39. else
  40. type.to_s
  41. end
  42. where(:type => type)
  43. }
  44. def check
  45. # Implement me in your subclass of Agent.
  46. end
  47. def default_options
  48. # Implement me in your subclass of Agent.
  49. {}
  50. end
  51. def receive(events)
  52. # Implement me in your subclass of Agent.
  53. end
  54. def receive_webhook(params)
  55. # Implement me in your subclass of Agent.
  56. ["not implemented", 404]
  57. end
  58. # Implement me in your subclass to decide if your Agent is working.
  59. def working?
  60. raise "Implement me in your subclass"
  61. end
  62. def event_created_within(days)
  63. event = most_recent_event
  64. event && event.created_at > days.to_i.days.ago && event.payload.present? && event
  65. end
  66. def recent_error_logs?
  67. most_recent_log.try(:level) == 4
  68. end
  69. def sources_are_owned
  70. errors.add(:sources, "must be owned by you") unless sources.all? {|s| s.user == user }
  71. end
  72. def create_event(attrs)
  73. if can_create_events?
  74. events.create!({ :user => user }.merge(attrs))
  75. else
  76. error "This Agent cannot create events!"
  77. end
  78. end
  79. def validate_schedule
  80. unless cannot_be_scheduled?
  81. errors.add(:schedule, "is not a valid schedule") unless SCHEDULES.include?(schedule.to_s)
  82. end
  83. end
  84. def make_message(payload, message = options[:message])
  85. message.gsub(/<([^>]+)>/) { Utils.value_at(payload, $1) || "??" }
  86. end
  87. def trigger_webhook(params)
  88. receive_webhook(params).tap do
  89. self.last_webhook_at = Time.now
  90. save!
  91. end
  92. end
  93. def set_default_schedule
  94. self.schedule = default_schedule unless schedule.present? || cannot_be_scheduled?
  95. end
  96. def unschedule_if_cannot_schedule
  97. self.schedule = nil if cannot_be_scheduled?
  98. end
  99. def last_event_at
  100. @memoized_last_event_at ||= most_recent_event.try(:created_at)
  101. end
  102. def default_schedule
  103. self.class.default_schedule
  104. end
  105. def cannot_be_scheduled?
  106. self.class.cannot_be_scheduled?
  107. end
  108. def can_be_scheduled?
  109. !cannot_be_scheduled?
  110. end
  111. def cannot_receive_events?
  112. self.class.cannot_receive_events?
  113. end
  114. def can_receive_events?
  115. !cannot_receive_events?
  116. end
  117. def cannot_create_events?
  118. self.class.cannot_create_events?
  119. end
  120. def can_create_events?
  121. !cannot_create_events?
  122. end
  123. def set_last_checked_event_id
  124. if newest_event_id = Event.order("id desc").limit(1).pluck(:id).first
  125. self.last_checked_event_id = newest_event_id
  126. end
  127. end
  128. def log(message, options = {})
  129. AgentLog.log_for_agent(self, message, options)
  130. end
  131. def error(message, options = {})
  132. log(message, options.merge(:level => 4))
  133. end
  134. # Class Methods
  135. class << self
  136. def cannot_be_scheduled!
  137. @cannot_be_scheduled = true
  138. end
  139. def cannot_be_scheduled?
  140. !!@cannot_be_scheduled
  141. end
  142. def default_schedule(schedule = nil)
  143. @default_schedule = schedule unless schedule.nil?
  144. @default_schedule
  145. end
  146. def cannot_create_events!
  147. @cannot_create_events = true
  148. end
  149. def cannot_create_events?
  150. !!@cannot_create_events
  151. end
  152. def cannot_receive_events!
  153. @cannot_receive_events = true
  154. end
  155. def cannot_receive_events?
  156. !!@cannot_receive_events
  157. end
  158. def receive!
  159. sql = Agent.
  160. select("agents.id AS receiver_agent_id, sources.id AS source_agent_id, events.id AS event_id").
  161. joins("JOIN links ON (links.receiver_id = agents.id)").
  162. joins("JOIN agents AS sources ON (links.source_id = sources.id)").
  163. joins("JOIN events ON (events.agent_id = sources.id)").
  164. where("agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id").to_sql
  165. agents_to_events = {}
  166. Agent.connection.select_rows(sql).each do |receiver_agent_id, source_agent_id, event_id|
  167. agents_to_events[receiver_agent_id] ||= []
  168. agents_to_events[receiver_agent_id] << event_id
  169. end
  170. event_ids = agents_to_events.values.flatten.uniq.compact
  171. Agent.where(:id => agents_to_events.keys).each do |agent|
  172. agent.update_attribute :last_checked_event_id, event_ids.max
  173. Agent.async_receive(agent.id, agents_to_events[agent.id].uniq)
  174. end
  175. {
  176. :agent_count => agents_to_events.keys.length,
  177. :event_count => event_ids.length
  178. }
  179. end
  180. # Given an Agent id and an array of Event ids, load the Agent, call #receive on it with the Event objects, and then
  181. # save it with an updated _last_receive_at_ timestamp.
  182. #
  183. # This method is tagged with _handle_asynchronously_ and will be delayed and run with delayed_job. It accepts Agent
  184. # and Event ids instead of a literal ActiveRecord models because it is preferable to serialize delayed_jobs with ids.
  185. def async_receive(agent_id, event_ids)
  186. agent = Agent.find(agent_id)
  187. begin
  188. agent.receive(Event.where(:id => event_ids))
  189. agent.last_receive_at = Time.now
  190. agent.save!
  191. rescue => e
  192. agent.error "Exception during receive: #{e.message} -- #{e.backtrace}"
  193. raise
  194. end
  195. end
  196. handle_asynchronously :async_receive
  197. def run_schedule(schedule)
  198. types = where(:schedule => schedule).group(:type).pluck(:type)
  199. types.each do |type|
  200. type.constantize.bulk_check(schedule)
  201. end
  202. end
  203. # You can override this to define a custom bulk_check for your type of Agent.
  204. def bulk_check(schedule)
  205. raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent
  206. where(:schedule => schedule).pluck("agents.id").each do |agent_id|
  207. async_check(agent_id)
  208. end
  209. end
  210. # Given an Agent id, load the Agent, call #check on it, and then save it with an updated _last_check_at_ timestamp.
  211. #
  212. # This method is tagged with _handle_asynchronously_ and will be delayed and run with delayed_job. It accepts an Agent
  213. # id instead of a literal Agent because it is preferable to serialize delayed_jobs with ids.
  214. def async_check(agent_id)
  215. agent = Agent.find(agent_id)
  216. begin
  217. agent.check
  218. agent.last_check_at = Time.now
  219. agent.save!
  220. rescue => e
  221. agent.error "Exception during check: #{e.message} -- #{e.backtrace}"
  222. raise
  223. end
  224. end
  225. handle_asynchronously :async_check
  226. end
  227. end