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 = ENV['ONEVIEWSDK_URL']) ⇒ Object

Check, import, or list OneView certs


405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/oneview-sdk/cli.rb', line 405

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


344
345
346
347
348
349
350
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
# File 'lib/oneview-sdk/cli.rb', line 344

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


300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/oneview-sdk/cli.rb', line 300

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


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/oneview-sdk/cli.rb', line 321

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


142
143
144
145
146
147
148
# File 'lib/oneview-sdk/cli.rb', line 142

def list(type)
  resource_class = parse_type(type)
  client_setup
  data = []
  resource_class.get_all(@client).each { |r| data.push(r[:name]) }
  output data
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


231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/oneview-sdk/cli.rb', line 231

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

#search(type) ⇒ Object

Search for resource by key/value pair(s)


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/oneview-sdk/cli.rb', line 192

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 = []
    matches.each do |d|
      temp = {}
      options['attribute'].split(',').each do |attr|
        temp[attr] = d[attr]
      end
      data.push(d['name'] => temp)
    end
    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


161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/oneview-sdk/cli.rb', line 161

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']
    new_data = {}
    options['attribute'].split(',').each do |attr|
      new_data[attr] = data[attr]
    end
    data = new_data
  end
  output data
end

#to_file(type, name) ⇒ Object

Save resource details to file


391
392
393
394
395
396
397
398
399
400
401
# File 'lib/oneview-sdk/cli.rb', line 391

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


273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/oneview-sdk/cli.rb', line 273

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