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.



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

def initialize
  @config = ::Optica::Client::Config.from_file(CONFIG_PATH)
  @host = nil
  @fields = []
  @outs = []
  @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.



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

def cache
  @cache
end

#delete_cacheObject (readonly)

Returns the value of attribute delete_cache.



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

def delete_cache
  @delete_cache
end

#fieldsObject (readonly)

Returns the value of attribute fields.



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

def fields
  @fields
end

#verboseObject (readonly)

Returns the value of attribute verbose.



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

def verbose
  @verbose
end

Class Method Details

.run(argv) ⇒ Object



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

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

Instance Method Details

#data_pipeObject



317
318
319
# File 'lib/optica/client/cli.rb', line 317

def data_pipe
  $stdout
end

#fetch(req) ⇒ Object



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

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



245
246
247
248
249
250
251
252
# File 'lib/optica/client/cli.rb', line 245

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



307
308
309
# File 'lib/optica/client/cli.rb', line 307

def host
  @host || @config.default_host
end

#log(msg) ⇒ Object



311
312
313
314
315
# File 'lib/optica/client/cli.rb', line 311

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

#manage_cacheObject



235
236
237
238
239
240
241
242
243
# File 'lib/optica/client/cli.rb', line 235

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)


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
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/optica/client/cli.rb', line 52

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

    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(
      '-j',
      '--just a,b,c',
      ::Array,
      'Print just the given fields as tab-seperated strings, instead of outputting json. Implies selecting those fields.'
    ) do |outs|
      @outs.concat(outs)
      @fields.concat(outs)
    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 --just hostname role=example branch=jake-test | head -n 1)
    EOS
  end
end

#output(json) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/optica/client/cli.rb', line 214

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|
    if @outs.any?
      string = node.values_at(*@outs.uniq).join("\t")
    else
      string = @pretty ? JSON.pretty_generate(node) : JSON.fast_generate(node)
    end
    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



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/optica/client/cli.rb', line 285

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)


260
261
262
263
264
265
266
267
268
269
# File 'lib/optica/client/cli.rb', line 260

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



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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/optica/client/cli.rb', line 157

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

  if @outs.any? && @verbose
    ui_pipe.puts "Will print only: #{@outs}"
  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



321
322
323
# File 'lib/optica/client/cli.rb', line 321

def ui_pipe
  $stderr
end