agent_controller_concern.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. options['action'].presence || 'run'
  13. end
  14. def validate_control_action
  15. case control_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 'enable', 'disable'
  23. else
  24. errors.add(:base, 'invalid action')
  25. end
  26. end
  27. def control!
  28. control_targets.active.each { |target|
  29. begin
  30. case control_action
  31. when 'run'
  32. log "Agent run queued for '#{target.name}'"
  33. Agent.async_check(target.id)
  34. when 'enable'
  35. log "Enabling the Agent '#{target.name}'"
  36. target.update!(disable: false) if target.disabled?
  37. when 'disable'
  38. log "Disabling the Agent '#{target.name}'"
  39. target.update!(disable: true) unless target.disabled?
  40. end
  41. rescue => e
  42. error "Failed to #{control_action} '#{target.name}': #{e.message}"
  43. end
  44. }
  45. end
  46. end