agent_controller_concern.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. module AgentControllerConcern
  2. extend ActiveSupport::Concern
  3. included do
  4. validate :validate_control_action
  5. end
  6. def default_options
  7. {
  8. 'action' => 'run'
  9. }
  10. end
  11. def control_action
  12. interpolated['action']
  13. end
  14. def validate_control_action
  15. case options['action']
  16. when 'run'
  17. control_targets.each { |target|
  18. if target.cannot_be_scheduled?
  19. errors.add(:base, "#{target.name} cannot be scheduled")
  20. end
  21. }
  22. when 'configure'
  23. if !options['configure_options'].is_a?(Hash) || options['configure_options'].empty?
  24. errors.add(:base, "A non-empty hash must be specified in the 'configure_options' option when using the 'configure' action.")
  25. end
  26. when 'enable', 'disable'
  27. when nil
  28. errors.add(:base, "action must be specified")
  29. when /\{[%{]/
  30. # Liquid template
  31. else
  32. errors.add(:base, 'invalid action')
  33. end
  34. end
  35. def control!
  36. control_targets.each do |target|
  37. interpolate_with('target' => target) do
  38. begin
  39. case action = control_action
  40. when 'run'
  41. case
  42. when target.cannot_be_scheduled?
  43. error "'#{target.name}' cannot run without an incoming event"
  44. when target.disabled?
  45. log "Agent run ignored for disabled Agent '#{target.name}'"
  46. else
  47. Agent.async_check(target.id)
  48. log "Agent run queued for '#{target.name}'"
  49. end
  50. when 'enable'
  51. case
  52. when target.disabled?
  53. if boolify(interpolated['drop_pending_events'])
  54. target.drop_pending_events = true
  55. end
  56. target.update!(disabled: false)
  57. log "Agent '#{target.name}' is enabled"
  58. else
  59. log "Agent '#{target.name}' is already enabled"
  60. end
  61. when 'disable'
  62. case
  63. when target.disabled?
  64. log "Agent '#{target.name}' is alread disabled"
  65. else
  66. target.update!(disabled: true)
  67. log "Agent '#{target.name}' is disabled"
  68. end
  69. when 'configure'
  70. target.update! options: target.options.deep_merge(interpolated['configure_options'])
  71. log "Agent '#{target.name}' is configured with #{interpolated['configure_options'].inspect}"
  72. when ''
  73. log 'No action is performed.'
  74. else
  75. error "Unsupported action '#{action}' ignored for '#{target.name}'"
  76. end
  77. rescue => e
  78. error "Failed to #{action} '#{target.name}': #{e.message}"
  79. end
  80. end
  81. end
  82. end
  83. end