Class: Optica::Client::CLI

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

Overview

Command-line interface

Constant Summary collapse

TTY_TIMEOUT =

rate-limit when printing huge JSON to a tty

0.00001
USER_PATH =
Pathname.new('~/.optical').expand_path
CONFIG_PATH =
USER_PATH.join('config.yml')
CACHE_ROOT =
USER_PATH.join('cache').to_s
ERR_NOT_FOUND =
4
ERR_INVALID =
2
CACHE_MAX_AGE =

15 min

15 * 60

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCLI

Returns a new instance of CLI.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/optica/client/cli.rb', line 32

def initialize
  @config = ::Optica::Client::Config.from_file(CONFIG_PATH)
  @host = nil
  @fields = []
  @verbose = false
  @pretty = data_pipe.tty?
  @cache = ::FileCache.new(
    "requests",
    CACHE_ROOT,
    CACHE_MAX_AGE,
    1
  )
  @delete_cache = false
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



30
31
32
# File 'lib/optica/client/cli.rb', line 30

def cache
  @cache
end

#delete_cacheObject (readonly)

Returns the value of attribute delete_cache.



30
31
32
# File 'lib/optica/client/cli.rb', line 30

def delete_cache
  @delete_cache
end

#fieldsObject (readonly)

Returns the value of attribute fields.



30
31
32
# File 'lib/optica/client/cli.rb', line 30

def fields
  @fields
end

#verboseObject (readonly)

Returns the value of attribute verbose.



30
31
32
# File 'lib/optica/client/cli.rb', line 30

def verbose
  @verbose
end

Class Method Details

.run(argv) ⇒ Object



26
27
28
# File 'lib/optica/client/cli.rb', line 26

def self.run(argv)
  new.run(argv)
end

Instance Method Details

#data_pipeObject



296
297
298
# File 'lib/optica/client/cli.rb', line 296

def data_pipe
  $stdout
end

#fetch(req) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/optica/client/cli.rb', line 185

def fetch(req)
  log "URL:     #{req.root}"
  log "Filters: #{req.filters}"
  log "Fields:  #{req.select_all? ? '(all fields)' : req.fields.inspect}"
  log "GET      #{req.to_uri}"

  key = req.to_uri.to_s
  cache.get_or_set(key) do
    fetch_with_progress_bar(req.to_uri)
  end
end

#fetch_with_progress_bar(uri) ⇒ Object



224
225
226
227
228
229
230
231
# File 'lib/optica/client/cli.rb', line 224

def fetch_with_progress_bar(uri)
  ::Optica::Client.fetch_json(uri) do |_chunk, ratio|
    view = "Download #{progress_bar(ratio)}"

    ui_pipe.print "\r#{view}"
    ui_pipe.print "\n" if ratio == 1.0
  end
end

#hostObject



286
287
288
# File 'lib/optica/client/cli.rb', line 286

def host
  @host || @config.default_host
end

#log(msg) ⇒ Object



290
291
292
293
294
# File 'lib/optica/client/cli.rb', line 290

def log(msg)
  if verbose
    ui_pipe.puts(msg)
  end
end

#manage_cacheObject



214
215
216
217
218
219
220
221
222
# File 'lib/optica/client/cli.rb', line 214

def manage_cache
  # clean up expired stuff
  cache.purge

  if delete_cache
    log "deleting cache dir #{CACHE_ROOT}"
    FileUtils.rm_r(CACHE_ROOT)
  end
end

#option_parserOptionParser

Options for the CLI

Returns:

  • (OptionParser)


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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/optica/client/cli.rb', line 50

def option_parser
  @option_parser ||= OptionParser.new do |o|
    o.banner = "Usage: optical [options] [FIELD=FILTER] [FIELD2=FILTER2...]"

    o.separator ''
    o.separator <<-EOS
  Fetch host information from Optica, and cache it for 15 minutes.
  Output the fetched information as a JSON stream, suitable for processing with `jq`.

  FIELD: any optica field; see your optica host for availible fields
  FILTER: either a bare string, like "optica", or a regex string, like "/^(o|O)ptica?/"
    EOS

    o.separator ''
    o.separator 'Options:'

    o.on(
      '-s',
      '--select a,b,c',
      ::Array,
      'Retrieve the given fields, in addition to the defaults'
    ) do |fs|
      @fields.concat(fs)
    end

    o.on(
      '-a',
      '--all',
      'Retrieve all fields (default is just role,id,hostname)'
    ) do |all|
      @fields = nil if all
    end

    o.on(
      '-v',
      '--verbose',
      'Print debug information to STDERR'
    ) do |v|
      @verbose = v
    end

    o.on('-p', "--pretty[=#{data_pipe.tty?}]", "Pretty-print JSON (default true when STDOUT is a TTY)") do |p|
      @pretty = p
    end

    o.on(
      '-r',
      '--refresh',
      'Delete cache before performing request.'
    ) do |r|
      @delete_cache = r
    end

    o.on(
      '-h',
      '--host URI',
      "Optica host (default #{@config.default_host.inspect})"
    ) do |host|
      @host = host
    end

    o.on(
      '-H URI',
      '--set-default-host URI',
      'Set the default optica host'
    ) do |h|
      # TODO: move to #run
      @host = h
      @config.default_host = h
      @config.write!
      log "set default host to #{h}"
    end

    o.separator ''
    o.separator 'Examples:'
    o.separator <<-EOS
  Retrieve all nodes with a role starting with "example-":
    optical role=/^example-/

  Retrieve all the nodes registered to a test optica instance:
    optical -h https://optica-test.example.com

  Retrieve all data about my nodes:
    optical --all launched_by=`whoami`

  SSH into the first matched node:
    ssh $(optical role=example branch=jake-test | head -n 1 | jq -r .hostname)
    EOS
  end
end

#output(json) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/optica/client/cli.rb', line 197

def output(json)
  log "got #{json.size} entries"

  use_sleep = false
  if json.size >= 1000 && data_pipe.tty?
    log 'reducing output speed to allow Ctrl-C'
    use_sleep = true
  end

  json.each do |_ip, node|
    string = @pretty ? JSON.pretty_generate(node) : JSON.fast_generate(node)
    data_pipe.puts string
    # easier Ctrl-C in Tmux
    sleep TTY_TIMEOUT if use_sleep
  end
end

#parse_filter(string) ⇒ Hash<String, Any>

Parse a command-line argument into a single Optica filter.

Filter types:

  • exact string match: base case

    attribute=string
    
  • regex match: filter begins and ends with /

    attribute=/^[rR]egexp?/
    
  • array match: begins with [, ends with ]

    attribute=[one,two]
    

Parameters:

  • string (String)

Returns:

  • (Hash<String, Any>)

    a filter hash



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/optica/client/cli.rb', line 264

def parse_filter(string)
  unless string.include?('=')
    raise ArgumentError.new("Invalid filter: #{string.inspect}")
  end

  key, *values = string.split('=')
  value = values.join('=')

  # parse regex
  if value[0] == '/' && value[-1] == '/'
    return { key => /#{value[1...-1]}/ }
  end

  # parse array-like
  if value[0] == '[' && value[-1] == ']'
    return { key => value[1...-1].split(',') }
  end

  # just a string
  { key => value }
end

#progress_bar(ratio) ⇒ String

Returns a progress bar, as a string.

Looks kinda like this:

>>>>>

NN.NN%

Returns:

  • (String)


239
240
241
242
243
244
245
246
247
248
# File 'lib/optica/client/cli.rb', line 239

def progress_bar(ratio)
  width = 40
  chars = (width * ratio).to_i
  start = '['
  fin = ']'
  done = '>' * chars
  to_do = ' ' * (width - chars)
  percent = format(' %.2f%', ratio * 100)
  start + done + to_do + fin + percent
end

#run(argv) ⇒ Object

Run the CLI

Parameters:

  • argv (Array<String>)

    Command-line args



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/optica/client/cli.rb', line 144

def run(argv)
  args = option_parser.parse(argv)

  begin
    filters = args.map { |arg| parse_filter(arg) }.reduce({}, :merge)
  rescue ArgumentError => err
    ui_pipe.puts err.message
    ui_pipe.puts ''
    ui_pipe.puts option_parser
    return ERR_INVALID
  end

  if host.nil?
    ui_pipe.puts 'No host given.'
    ui_pipe.puts 'Set the default with -H, or for the invocation with -h.'
    ui_pipe.puts ''
    ui_pipe.puts option_parser
    return ERR_INVALID
  end

  manage_cache

  req = ::Optica::Client::Request.new(host).where(filters)
  if fields
    req.select(*fields)
  else
    req.select_all
  end

  json = fetch(req)
  output(json['nodes'])

  if json['nodes'].any?
    # happy!
    return 0
  else
    # none found
    return ERR_NOT_FOUND
  end
end

#ui_pipeObject



300
301
302
# File 'lib/optica/client/cli.rb', line 300

def ui_pipe
  $stderr
end