agent_controller_concern.rb 2.6 KB

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