summaryrefslogtreecommitdiff
path: root/lib/dslkeywords/agent.rb
blob: 3d6874c544667d788e9b0d293392115156787ca3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# frozen_string_literal: true

require_relative 'keyword'

module RCM
  # Stores a named shell command template for agent-backed file processing.
  class AgentDefinition < Keyword
    attr_reader :name

    class InvalidName < StandardError; end
    class InvalidRetrySetting < StandardError; end

    def self.id_for(name) = super(normalize_name(name))

    def self.normalize_name(name)
      normalized = name.to_s.strip.gsub(/\s+/, ' ')
      raise InvalidName, 'Agent name must not be empty' if normalized.empty?

      normalized
    end

    def initialize(name)
      @name = self.class.normalize_name(name)
      @retries = 2
      @retry_delay = 1.0
      @retry_backoff = 2.0
      super(@name)
    end

    def command(text = nil)
      return @command if text.nil?

      @command = text.to_s
    end

    def retries(value = nil)
      return @retries if value.nil?

      @retries = Integer(value)
      raise InvalidRetrySetting, 'Retry count must be non-negative' if @retries.negative?

      @retries
    rescue ArgumentError, TypeError
      raise InvalidRetrySetting, "Invalid retry count: #{value.inspect}"
    end

    def retry_delay(value = nil)
      return @retry_delay if value.nil?

      @retry_delay = Float(value)
      raise InvalidRetrySetting, 'Retry delay must be non-negative' if @retry_delay.negative?

      @retry_delay
    rescue ArgumentError, TypeError
      raise InvalidRetrySetting, "Invalid retry delay: #{value.inspect}"
    end

    def retry_backoff(value = nil)
      return @retry_backoff if value.nil?

      @retry_backoff = Float(value)
      raise InvalidRetrySetting, 'Retry backoff must be at least 1.0' if @retry_backoff < 1.0

      @retry_backoff
    rescue ArgumentError, TypeError
      raise InvalidRetrySetting, "Invalid retry backoff: #{value.inspect}"
    end
  end

  # Adds the `agent` definition keyword to the top-level DSL.
  class DSL
    def agent(name = nil, &block)
      return name if name.nil?
      return unless @conds_met

      definition = AgentDefinition.new(name)
      definition.dsl = self
      definition.command(definition.instance_eval(&block)) if block
      register(definition, schedule: false, duplicate_error: DuplicateDefinition)
    end
  end
end