Class: OneviewSDK::Cli

Inherits:
Thor
  • Object
show all
Defined in:
lib/oneview-sdk/cli.rb

Overview

command-line-interface for oneview-sdk When you install this gem, this cli should be available to you by running: ‘$ oneview-sdk-ruby`

Defined Under Namespace

Classes: Runner

Constant Summary collapse

SUPPORTED_VARIANTS =
OneviewSDK::API300::SUPPORTED_VARIANTS

Instance Method Summary collapse

Instance Method Details

#cert(type, url = ) ⇒ Object

Check, import, or list OneView certs



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/oneview-sdk/cli.rb', line 412

def cert(type, url = ENV['ONEVIEWSDK_URL'])
  case type.downcase
  when 'check'
    fail_nice 'Must specify a url' unless url
    puts "Checking certificate for '#{url}' ..."
    if OneviewSDK::SSLHelper.check_cert(url)
      puts 'Certificate is valid!'
    else
      fail_nice 'Certificate Validation Failed!'
    end
  when 'import'
    fail_nice 'Must specify a url' unless url
    puts "Importing certificate for '#{url}' into '#{OneviewSDK::SSLHelper::CERT_STORE}'..."
    OneviewSDK::SSLHelper.install_cert(url)
  when 'list'
    if File.file?(OneviewSDK::SSLHelper::CERT_STORE)
      puts File.read(OneviewSDK::SSLHelper::CERT_STORE)
    else
      puts 'No certs imported!'
    end
  else fail_nice "Invalid action '#{type}'. Valid actions are [check, import, list]"
  end
rescue StandardError => e
  fail_nice e.message
end

#consoleObject

Open a Ruby console with a connection to OneView



84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/oneview-sdk/cli.rb', line 84

def console
  client_setup({}, true, true)
  puts "Console Connected to #{@client.url}"
  puts "HINT: The @client object is available to you\n\n"
rescue
  puts "WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\n\n"
ensure
  require 'pry'
  Pry.config.prompt = proc { '> ' }
  Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable!
  Pry.plugins['byebug'] && Pry.plugins['byebug'].disable!
  Pry.start(OneviewSDK::Console.new(@client))
end

#create_from_file(file_path) ⇒ Object

Create/Update resource defined in file



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/oneview-sdk/cli.rb', line 351

def create_from_file(file_path)
  client_setup
  resource = OneviewSDK::Resource.from_file(@client, file_path)
  fail_nice 'Failed to determine resource type!' if resource.class == OneviewSDK::Resource
  existing_resource = resource.class.new(@client, resource.data)
  resource.data.delete('uri')
  if existing_resource.retrieve!
    if options['if_missing']
      puts "Skipped: #{resource.class.name.split('::').last} '#{resource[:name]}' already exists.\n#{existing_resource[:uri]}"
      return
    end
    if existing_resource.like?(resource.data)
      puts "Skipped: #{resource.class.name.split('::').last} '#{resource[:name]}' is up to date.\n#{existing_resource[:uri]}"
      return
    end
    begin
      existing_resource.update(resource.data)
      puts "Updated Successfully!\n#{existing_resource[:uri]}"
    rescue StandardError => e
      fail_nice "Failed to update #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}"
    end
  else
    begin
      resource.create
      puts "Created Successfully!\n#{resource[:uri]}"
    rescue StandardError => e
      fail_nice "Failed to create #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}"
    end
  end
rescue IncompleteResource => e
  fail_nice "Failed to create #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}"
rescue SystemCallError => e # File open errors
  fail_nice e
end

#delete(type, name) ⇒ Object

Delete resource by name



307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/oneview-sdk/cli.rb', line 307

def delete(type, name)
  resource_class = parse_type(type)
  client_setup
  matches = resource_class.find_by(@client, name: name)
  fail_nice('Not Found', 2) if matches.empty?
  resource = matches.first
  return unless options['force'] || agree("Delete '#{name}'? [Y/N] ")
  begin
    resource.delete
    puts 'Deleted Successfully!'
  rescue StandardError => e
    fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{name}': #{e}"
  end
end

#delete_from_file(file_path) ⇒ Object

Delete resource defined in file



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/oneview-sdk/cli.rb', line 328

def delete_from_file(file_path)
  client_setup
  resource = OneviewSDK::Resource.from_file(@client, file_path)
  fail_nice("#{resource.class.name.split('::').last} '#{resource[:name] || resource[:uri]}' Not Found", 2) unless resource.retrieve!
  return unless options['force'] || agree("Delete '#{resource[:name]}'? [Y/N] ")
  begin
    resource.delete
    puts 'Deleted Successfully!'
  rescue StandardError => e
    fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}"
  end
rescue IncompleteResource => e
  fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}"
rescue SystemCallError => e # File open errors
  fail_nice e
end

#envObject

Show environment variables for oneview-sdk-ruby



115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/oneview-sdk/cli.rb', line 115

def env
  data = {}
  OneviewSDK::ENV_VARS.each { |k| data[k] = ENV[k] }
  if @options['format'] == 'human'
    data.each do |key, value|
      value = "'#{value}'" if value && !%w[true false].include?(value)
      printf "%-#{data.keys.max_by(&:length).length}s = %s\n", key, value || 'nil'
    end
  else
    output(parse_hash(data, true))
  end
end

#list(type) ⇒ Object

List names of resources (and optionally, specific attributes)



148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/oneview-sdk/cli.rb', line 148

def list(type)
  resource_class = parse_type(type)
  client_setup
  all = resource_class.get_all(@client)
  if options['attribute']
    data = select_attributes_from_multiple(options['attribute'], all)
    output data, -2 # Shift left by 2 so things look right
  else # List names only by default
    names = []
    all.each { |r| names.push(r['name']) }
    output names
  end
end

#loginObject

Attempt authentication and return token



130
131
132
133
# File 'lib/oneview-sdk/cli.rb', line 130

def 
  client_setup
  puts "Login Successful! Token = #{@client.token}"
end

#rest(method, uri) ⇒ Object

Make REST call to the OneView API



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/oneview-sdk/cli.rb', line 238

def rest(method, uri)
  log_level = @options['log_level'] == :warn ? :error : @options['log_level'].to_sym # Default to :error
  client_setup('log_level' => log_level)
  uri_copy = uri.dup
  uri_copy.prepend('/') unless uri_copy.start_with?('/')
  if @options['data']
    begin
      data = { body: JSON.parse(@options['data']) }
    rescue JSON::ParserError => e
      fail_nice("Failed to parse data as JSON\n#{e.message}")
    end
  end
  data ||= {}
  response = @client.rest_api(method, uri_copy, data)
  if response.code.to_i.between?(200, 299)
    case @options['format']
    when 'yaml'
      puts JSON.parse(response.body).to_yaml
    when 'json'
      puts JSON.pretty_generate(JSON.parse(response.body))
    else # raw
      puts response.body
    end
  else
    body = JSON.pretty_generate(JSON.parse(response.body)) rescue response.body
    fail_nice("Request failed: #{response.inspect}\nHeaders: #{response.to_hash}\nBody: #{body}")
  end
rescue OneviewSDK::InvalidRequest => e
  fail_nice(e.message)
end

#scmbObject

Subscribe to the OneView SCMB



453
454
455
456
457
458
459
460
461
462
463
# File 'lib/oneview-sdk/cli.rb', line 453

def scmb
  client_setup
  connection = OneviewSDK::SCMB.new_connection(@client)
  q = OneviewSDK::SCMB.new_queue(connection, @options['route'])
  puts 'Subscribing to OneView messages. To exit, press Ctrl + c'
  q.subscribe(block: true) do |_delivery_info, _properties, payload|
    data = JSON.parse(payload) rescue payload
    puts "\n#{'=' * 50}\n\nReceived message with payload:"
    @options['format'] == 'raw' ? puts(payload) : output(data)
  end
end

#search(type) ⇒ Object

Search for resource by key/value pair(s)



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/oneview-sdk/cli.rb', line 206

def search(type)
  resource_class = parse_type(type)
  client_setup
  filter = parse_hash(options['filter'])
  matches = resource_class.find_by(@client, filter)
  if matches.empty? # Search with integers & booleans converted
    filter = parse_hash(options['filter'], true)
    matches = resource_class.find_by(@client, filter) unless filter == options['filter']
  end
  if options['attribute']
    data = select_attributes_from_multiple(options['attribute'], matches)
    output data, -2 # Shift left by 2 so things look right
  else # List names only by default
    names = []
    matches.each { |m| names.push(m['name']) }
    output names
  end
end

#show(type, name) ⇒ Object

Show resource details



176
177
178
179
180
181
182
183
184
185
186
# File 'lib/oneview-sdk/cli.rb', line 176

def show(type, name)
  resource_class = parse_type(type)
  client_setup
  matches = resource_class.find_by(@client, name: name)
  fail_nice 'Not Found' if matches.empty?
  data = matches.first.data
  if options['attribute']
    data = select_attributes(options['attribute'], data)
  end
  output data
end

#to_file(type, name) ⇒ Object

Save resource details to file



398
399
400
401
402
403
404
405
406
407
408
# File 'lib/oneview-sdk/cli.rb', line 398

def to_file(type, name)
  file = File.expand_path(options['path'])
  resource_class = parse_type(type)
  client_setup
  resource = resource_class.find_by(@client, name: name).first
  fail_nice "#{resource_class.name.split('::').last} '#{name}' not found" unless resource
  resource.to_file(file, options['format'])
  puts "Output to #{file}"
rescue SystemCallError => e
  fail_nice "Failed to create file! (You may need to create the necessary directories). Message: #{e}"
end

#update(type, name) ⇒ Object

Update resource by name



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/oneview-sdk/cli.rb', line 280

def update(type, name)
  resource_class = parse_type(type)
  client_setup
  fail_nice 'Must set the hash or json option' unless @options['hash'] || @options['json']
  fail_nice 'Must set the hash OR json option. Not both' if @options['hash'] && @options['json']
  begin
    data = @options['hash'] || JSON.parse(@options['json'])
  rescue JSON::ParserError => e
    fail_nice("Failed to parse json\n#{e.message}")
  end
  matches = resource_class.find_by(@client, name: name)
  fail_nice 'Not Found' if matches.empty?
  resource = matches.first
  begin
    resource.update(data)
    puts 'Updated Successfully!'
  rescue StandardError => e
    fail_nice "Failed to update #{resource.class.name.split('::').last} '#{name}': #{e}"
  end
end

#versionObject

Print gem and OneView appliance versions



100
101
102
103
104
105
106
# File 'lib/oneview-sdk/cli.rb', line 100

def version
  puts "Gem Version: #{OneviewSDK::VERSION}"
  client_setup({ 'log_level' => :error }, true)
  puts "OneView appliance API version at '#{@client.url}' = #{@client.max_api_version}"
rescue StandardError, SystemExit
  puts 'OneView appliance API version unknown'
end