1
0

agent_controller_concern.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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'].nil? || options['configure_options'].keys.length == 0
  24. errors.add(:base, "The 'configure_options' options hash must be supplied 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 { |target|
  37. begin
  38. case control_action
  39. when 'run'
  40. case
  41. when target.cannot_be_scheduled?
  42. error "'#{target.name}' cannot run without an incoming event"
  43. when target.disabled?
  44. log "Agent run ignored for disabled Agent '#{target.name}'"
  45. else
  46. Agent.async_check(target.id)
  47. log "Agent run queued for '#{target.name}'"
  48. end
  49. when 'enable'
  50. case
  51. when target.disabled?
  52. target.update!(disabled: false)
  53. log "Agent '#{target.name}' is enabled"
  54. else
  55. log "Agent '#{target.name}' is already enabled"
  56. end
  57. when 'disable'
  58. case
  59. when target.disabled?
  60. log "Agent '#{target.name}' is alread disabled"
  61. else
  62. target.update!(disabled: true)
  63. log "Agent '#{target.name}' is disabled"
  64. end
  65. when 'configure'
  66. target.update!(options: target.options.merge(interpolated['configure_options']))
  67. log "Agent '#{target.name}' is configured with #{interpolated['configure_options'].inspect}"
  68. when ''
  69. # Do nothing
  70. else
  71. error "Unsupported action '#{control_action}' ignored for '#{target.name}'"
  72. end
  73. rescue => e
  74. error "Failed to #{control_action} '#{target.name}': #{e.message}"
  75. end
  76. }
  77. end
  78. end