Class: Alerty::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/alerty/cli.rb

Instance Method Summary collapse

Instance Method Details

#parse_options(argv = ARGV) ⇒ Object



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
# File 'lib/alerty/cli.rb', line 7

def parse_options(argv = ARGV)
  op = OptionParser.new
  op.banner += ' -- command'

  (class<<self;self;end).module_eval do
    define_method(:usage) do |msg|
      puts op.to_s
      puts "error: #{msg}" if msg
      exit 1
    end
  end

  opts = {}
  op.on('-c', '--config CONFIG_FILE', "config file path (default: /etc/alerty/alerty.yml)") {|v|
    opts[:config_path] = v
  }
  op.on('--log LOG_FILE', "log file path (default: STDOUT)") {|v|
    opts[:log_path] = v
  }
  op.on('-l', '--log-level LOG_LEVEL', "log level (default: warn)") {|v|
    opts[:log_level] = v
  }
  op.on('--log-shift-age SHIFT_AGE', "Number of old log files to keep (default: 0 which means no log rotation)") {|v|
    opts[:log_shift_age] = Integer(v)
  }
  op.on('--log-shift-size SHIFT_SIZE', "Maximum logfile size in bytes (default: 1048576)") {|v|
    opts[:log_shift_age] = Integer(v)
  }
  op.on('-t', '--timeout SECONDS', "timeout the command (default: no timeout)") {|v|
    opts[:timeout] = v.to_f
  }
  op.on('--lock LOCK_FILE', "exclusive lock file to prevent running a command duplicatedly (default: no lock)") {|v|
    opts[:lock_path] = v
  }
  op.on('--retry-limit NUMBER', "number of retries (default: 0)") {|v|
    opts[:retry_limit] = v.to_i
  }
  op.on('--retry-wait SECONDS', "retry interval = retry wait +/- 12.5% randomness (default: 1.0)") {|v|
    opts[:retry_wait] = v.to_f
  }
  op.on('--dotenv', "Load environment variables from .env file with dotenv") {|v|
    opts[:dotenv] = true
  }
  op.on('-d', '--debug', "debug mode") {|v|
    opts[:debug] = true
  }
  op.on('-v', '--version', "print version") {|v|
    puts Alerty::VERSION
    exit 0
  }

  op.parse!(argv)
  opts[:command] = argv.join(' ') || ''

  opts
end

#runObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/alerty/cli.rb', line 64

def run
  begin
    opts = parse_options
  rescue OptionParser::InvalidOption => e
    usage e.message
  end
  
  Config.configure(opts)
  PluginFactory.plugins # load plugins in early stage

  if !opts[:command].empty?
    command = Command.new(command: opts[:command])
    record = command.run
    unless record[:exitstatus] == 0
      Alerty.send(record)
      exit record[:exitstatus]
    end
  else
    begin
      stdin = $stdin.read_nonblock(100 * 1024 * 1024)
      record = {hostname: Socket.gethostname, output: stdin}
      Alerty.send(record)
    rescue IO::EAGAINWaitReadable => e
      usage 'command argument or STDIN is required'
    end
  end
end