Няма описание http://j1x-huginn.herokuapp.com

scenario_import.rb 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. require 'ostruct'
  2. # This is a helper class for managing Scenario imports, used by the ScenarioImportsController. This class behaves much
  3. # like a normal ActiveRecord object, with validations and callbacks. However, it is never persisted to the database.
  4. class ScenarioImport
  5. include ActiveModel::Model
  6. include ActiveModel::Callbacks
  7. include ActiveModel::Validations::Callbacks
  8. DANGEROUS_AGENT_TYPES = %w[Agents::ShellCommandAgent]
  9. URL_REGEX = /\Ahttps?:\/\//i
  10. attr_accessor :file, :url, :data, :do_import, :merges
  11. attr_reader :user
  12. before_validation :parse_file
  13. before_validation :fetch_url
  14. validate :validate_presence_of_file_url_or_data
  15. validates_format_of :url, :with => URL_REGEX, :allow_nil => true, :allow_blank => true, :message => "appears to be invalid"
  16. validate :validate_data
  17. validate :generate_diff
  18. def step_one?
  19. data.blank?
  20. end
  21. def step_two?
  22. data.present?
  23. end
  24. def set_user(user)
  25. @user = user
  26. end
  27. def existing_scenario
  28. @existing_scenario ||= user.scenarios.find_by(:guid => parsed_data["guid"])
  29. end
  30. def dangerous?
  31. (parsed_data['agents'] || []).any? { |agent| DANGEROUS_AGENT_TYPES.include?(agent['type']) }
  32. end
  33. def parsed_data
  34. @parsed_data ||= (data && JSON.parse(data) rescue {}) || {}
  35. end
  36. def agent_diffs
  37. @agent_diffs || generate_diff
  38. end
  39. def should_import?
  40. do_import == "1"
  41. end
  42. def import(options = {})
  43. success = true
  44. guid = parsed_data['guid']
  45. description = parsed_data['description']
  46. name = parsed_data['name']
  47. links = parsed_data['links']
  48. source_url = parsed_data['source_url'].presence || nil
  49. @scenario = user.scenarios.where(:guid => guid).first_or_initialize
  50. @scenario.update_attributes!(:name => name, :description => description,
  51. :source_url => source_url, :public => false)
  52. unless options[:skip_agents]
  53. created_agents = agent_diffs.map do |agent_diff|
  54. agent = agent_diff.agent || Agent.build_for_type("Agents::" + agent_diff.type.incoming, user)
  55. agent.guid = agent_diff.guid.incoming
  56. agent.attributes = { :name => agent_diff.name.updated,
  57. :disabled => agent_diff.disabled.updated, # == "true"
  58. :options => agent_diff.options.updated,
  59. :scenario_ids => [@scenario.id] }
  60. agent.schedule = agent_diff.schedule.updated if agent_diff.schedule.present?
  61. agent.keep_events_for = agent_diff.keep_events_for.updated if agent_diff.keep_events_for.present?
  62. agent.propagate_immediately = agent_diff.propagate_immediately.updated if agent_diff.propagate_immediately.present? # == "true"
  63. agent.service_id = agent_diff.service_id.updated if agent_diff.service_id.present?
  64. unless agent.save
  65. success = false
  66. errors.add(:base, "Errors when saving '#{agent_diff.name.incoming}': #{agent.errors.full_messages.to_sentence}")
  67. end
  68. agent
  69. end
  70. if success
  71. links.each do |link|
  72. receiver = created_agents[link['receiver']]
  73. source = created_agents[link['source']]
  74. receiver.sources << source unless receiver.sources.include?(source)
  75. end
  76. end
  77. end
  78. success
  79. end
  80. def scenario
  81. @scenario || @existing_scenario
  82. end
  83. def will_request_local?(url_root)
  84. data.blank? && file.blank? && url.present? && url.starts_with?(url_root)
  85. end
  86. protected
  87. def parse_file
  88. if data.blank? && file.present?
  89. self.data = file.read
  90. end
  91. end
  92. def fetch_url
  93. if data.blank? && url.present? && url =~ URL_REGEX
  94. self.data = Faraday.get(url).body
  95. end
  96. end
  97. def validate_data
  98. if data.present?
  99. @parsed_data = JSON.parse(data) rescue {}
  100. if (%w[name guid agents] - @parsed_data.keys).length > 0
  101. errors.add(:base, "The provided data does not appear to be a valid Scenario.")
  102. self.data = nil
  103. end
  104. else
  105. @parsed_data = nil
  106. end
  107. end
  108. def validate_presence_of_file_url_or_data
  109. unless file.present? || url.present? || data.present?
  110. errors.add(:base, "Please provide either a Scenario JSON File or a Public Scenario URL.")
  111. end
  112. end
  113. def generate_diff
  114. @agent_diffs = (parsed_data['agents'] || []).map.with_index do |agent_data, index|
  115. # AgentDiff is defined at the end of this file.
  116. agent_diff = AgentDiff.new(agent_data)
  117. if existing_scenario
  118. # If this Agent exists already, update the AgentDiff with the local version's information.
  119. agent_diff.diff_with! existing_scenario.agents.find_by(:guid => agent_data['guid'])
  120. begin
  121. # Update the AgentDiff with any hand-merged changes coming from the UI. This only happens when this
  122. # Agent already exists locally and has conflicting changes.
  123. agent_diff.update_from! merges[index.to_s] if merges
  124. rescue JSON::ParserError
  125. errors.add(:base, "Your updated options for '#{agent_data['name']}' were unparsable.")
  126. end
  127. end
  128. if agent_diff.requires_service? && merges.present? && merges[index.to_s].present? && merges[index.to_s]['service_id'].present?
  129. agent_diff.service_id = AgentDiff::FieldDiff.new(merges[index.to_s]['service_id'].to_i)
  130. end
  131. agent_diff
  132. end
  133. end
  134. # AgentDiff is a helper object that encapsulates an incoming Agent. All fields will be returned as an array
  135. # of either one or two values. The first value is the incoming value, the second is the existing value, if
  136. # it differs from the incoming value.
  137. class AgentDiff < OpenStruct
  138. class FieldDiff
  139. attr_accessor :incoming, :current, :updated
  140. def initialize(incoming)
  141. @incoming = incoming
  142. @updated = incoming
  143. end
  144. def set_current(current)
  145. @current = current
  146. @requires_merge = (incoming != current)
  147. end
  148. def requires_merge?
  149. @requires_merge
  150. end
  151. end
  152. def initialize(agent_data)
  153. super()
  154. @requires_merge = false
  155. self.agent = nil
  156. store! agent_data
  157. end
  158. BASE_FIELDS = %w[name schedule keep_events_for propagate_immediately disabled guid]
  159. def agent_exists?
  160. !!agent
  161. end
  162. def requires_merge?
  163. @requires_merge
  164. end
  165. def requires_service?
  166. !!agent_instance.try(:oauthable?)
  167. end
  168. def store!(agent_data)
  169. self.type = FieldDiff.new(agent_data["type"].split("::").pop)
  170. self.options = FieldDiff.new(agent_data['options'] || {})
  171. BASE_FIELDS.each do |option|
  172. self[option] = FieldDiff.new(agent_data[option]) if agent_data.has_key?(option)
  173. end
  174. end
  175. def diff_with!(agent)
  176. return unless agent.present?
  177. self.agent = agent
  178. type.set_current(agent.short_type)
  179. options.set_current(agent.options || {})
  180. @requires_merge ||= type.requires_merge?
  181. @requires_merge ||= options.requires_merge?
  182. BASE_FIELDS.each do |field|
  183. next unless self[field].present?
  184. self[field].set_current(agent.send(field))
  185. @requires_merge ||= self[field].requires_merge?
  186. end
  187. end
  188. def update_from!(merges)
  189. each_field do |field, value, selection_options|
  190. value.updated = merges[field]
  191. end
  192. if options.requires_merge?
  193. options.updated = JSON.parse(merges['options'])
  194. end
  195. end
  196. def each_field
  197. boolean = [["True", "true"], ["False", "false"]]
  198. yield 'name', name if name.requires_merge?
  199. yield 'schedule', schedule, Agent::SCHEDULES.map {|s| [s.humanize.titleize, s] } if self['schedule'].present? && schedule.requires_merge?
  200. yield 'keep_events_for', keep_events_for, Agent::EVENT_RETENTION_SCHEDULES if self['keep_events_for'].present? && keep_events_for.requires_merge?
  201. yield 'propagate_immediately', propagate_immediately, boolean if self['propagate_immediately'].present? && propagate_immediately.requires_merge?
  202. yield 'disabled', disabled, boolean if disabled.requires_merge?
  203. end
  204. # Unfortunately Ruby 1.9's OpenStruct doesn't expose [] and []=.
  205. unless instance_methods.include?(:[]=)
  206. def [](key)
  207. self.send(sanitize key)
  208. end
  209. def []=(key, val)
  210. self.send("#{sanitize key}=", val)
  211. end
  212. def sanitize(key)
  213. key.gsub(/[^a-zA-Z0-9_-]/, '')
  214. end
  215. end
  216. def agent_instance
  217. "Agents::#{self.type.updated}".constantize.new
  218. end
  219. end
  220. end