Class: Morpheus::Cli::VirtualImages

Inherits:
Object
  • Object
show all
Includes:
CliCommand
Defined in:
lib/morpheus/cli/virtual_images.rb

Overview

JD: I don't think a lot of this has ever worked, fix it up.

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Instance Method Details

#add(args) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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
# File 'lib/morpheus/cli/virtual_images.rb', line 254

def add(args)
  image_type_name = nil
  file_url = nil
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] -t TYPE")
    opts.on( '-t', '--type TYPE', "Virtual Image Type" ) do |val|
      image_type_name = val
    end
    opts.on( '-U', '--url URL', "Image File URL. This can be used instead of uploading local files." ) do |val|
      file_url = val
    end
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  # if args.count < 1
  # 	puts optparse
  # 	exit 1
  # end
  image_name = args[0]
  connect(options)

  # if image_type_name.nil?
  # 	puts "Virtual Image Type must be specified"
  # 	puts optparse
  # 	exit 1
  # end

  if image_name
    options[:options] ||= {}
    options[:options]['name'] ||= image_name
  end

  if image_type_name
    image_type = virtual_image_type_for_name_or_code(image_type_name)
    exit 1 if image_type.nil?
    # options[:options] ||= {}
    # options[:options]['imageType'] ||= image_type['code']
  else
    image_type_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'imageType', 'fieldLabel' => 'Image Type', 'type' => 'select', 'optionSource' => 'virtualImageTypes', 'required' => true, 'description' => 'Select Virtual Image Type.', 'displayOrder' => 2}],options[:options],@api_client,{})
    image_type = virtual_image_type_for_name_or_code(image_type_prompt['imageType'])
  end

  begin
    my_option_types = add_virtual_image_option_types(image_type, !file_url)
    # if options[:no_prompt]
    #   my_option_types.each do |it| 
    #     if it['fieldContext'] == 'virtualImageFiles'
    #       opt['required'] = false
    #     end
    #   end
    # end
    params = Morpheus::Cli::OptionTypes.prompt(my_option_types, options[:options], @api_client, options[:params])
    virtual_image_payload = {}.merge(params)
    virtual_image_files = virtual_image_payload.delete('virtualImageFiles')
    virtual_image_payload['imageType'] = image_type['code']
    storage_provider_id = virtual_image_payload.delete('storageProviderId')
    if !storage_provider_id.to_s.empty?
      virtual_image_payload['storageProvider'] = {id: storage_provider_id}
    end
    payload = {virtualImage: virtual_image_payload}

    if options[:dry_run]
      print_dry_run @virtual_images_interface.dry.create(payload)
      if file_url
        print_dry_run @virtual_images_interface.dry.upload_by_url(":id", file_url)
      elsif virtual_image_files && !virtual_image_files.empty?
        virtual_image_files.each do |key, filename|
          print_dry_run @virtual_images_interface.dry.upload(":id", "(Contents of file #{filename})")
        end
      end
      return
    end

    json_response = @virtual_images_interface.create(payload)
    virtual_image = json_response['virtualImage']

    if options[:json]
      print JSON.pretty_generate(json_response)
    elsif !options[:quiet]
      print "\n", cyan, "Virtual Image #{virtual_image['name']} created successfully", reset, "\n\n"
    end

    # now upload the file, do this in the background maybe?
    if file_url
      unless options[:quiet]
        print cyan, "Uploading file by url #{file_url} ...", reset, "\n"
      end
      upload_json_response = @virtual_images_interface.upload_by_url(virtual_image['id'], file_url)
      if options[:json]
        print JSON.pretty_generate(upload_json_response)
      end
    elsif virtual_image_files && !virtual_image_files.empty?
      virtual_image_files.each do |key, filename|
        unless options[:quiet]
          print cyan, "Uploading file (#{key}) #{filename} ...", reset, "\n"
        end
        image_file = File.new(filename, 'rb')
        upload_json_response = @virtual_images_interface.upload(virtual_image['id'], image_file)
        if options[:json]
          print JSON.pretty_generate(upload_json_response)
        end
      end
    else
      puts cyan, "No files uploaded.", reset
    end

    if !options[:json]
      get([virtual_image['id']])
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_file(args) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/morpheus/cli/virtual_images.rb', line 371

def add_file(args)
  image_type_name = nil
  file_url = nil
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [filepath]")
    opts.on( '-U', '--url URL', "Image File URL. This can be used instead of [filepath]" ) do |val|
      file_url = val
    end
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  image_name = args[0]
  filename = nil
  if file_url
    if args.count < 1
      puts optparse
      exit 1
    end
  else
    if args.count < 2
      puts optparse
      exit 1
    end
    filename = args[1]
  end

  connect(options)

  begin
    image = find_virtual_image_by_name_or_id(image_name)
    return 1 if image.nil?
    if file_url
      if options[:dry_run]
        print_dry_run @virtual_images_interface.dry.upload_by_url(image['id'], file_url)
        return
      end
      unless options[:quiet]
        print cyan, "Uploading file by url #{file_url} ...", reset, "\n"
      end
      json_response = @virtual_images_interface.upload_by_url(image['id'], file_url)
      if options[:json]
        print JSON.pretty_generate(json_response)
      elsif !options[:quiet]
        print "\n", cyan, "Virtual Image #{image['name']} successfully updated.", reset, "\n\n"
        get([image['id']])
      end
    else
      image_file = File.new(filename, 'rb')
      if options[:dry_run]
        print_dry_run @virtual_images_interface.dry.upload(image['id'], image_file)
        return
      end
      unless options[:quiet]
        print cyan, "Uploading file #{filename} ...", reset, "\n"
      end
      json_response = @virtual_images_interface.upload(image['id'], image_file)
      if options[:json]
        print JSON.pretty_generate(json_response)
      elsif !options[:quiet]
        print "\n", cyan, "Virtual Image #{image['name']} successfully updated.", reset, "\n\n"
        get([image['id']])
      end
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object

def initialize()

# @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance	

end



21
22
23
24
# File 'lib/morpheus/cli/virtual_images.rb', line 21

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @virtual_images_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).virtual_images
end

#get(args) ⇒ Object



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
153
154
155
156
157
158
159
160
161
# File 'lib/morpheus/cli/virtual_images.rb', line 103

def get(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  image_name = args[0]
  connect(options)
  begin
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @virtual_images_interface.dry.get(args[0].to_i)
      else
        print_dry_run @virtual_images_interface.dry.get({name:args[0]})
      end
      return
    end
    image = find_virtual_image_by_name_or_id(image_name)
    return 1 if image.nil?
    # refetch
    json_response = @virtual_images_interface.get(image['id'])
    image = json_response['virtualImage']
    image_files = json_response['cloudFiles'] || json_response['files']

    if options[:json]
      puts JSON.pretty_generate(json_response)
    else
      image_type = virtual_image_type_for_name_or_code(image['imageType'])
      image_type_display = image_type ? "#{image_type['name']}" : image['imageType']
      print_h1 "Virtual Image Details"
      print cyan
      description_cols = {
        "ID" => 'id',
        "Name" => 'name',
        "Type" => lambda {|it| image_type_display },
        # "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        # "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
      }
      print_description_list(description_cols, image)

      if image_files
        print_h2 "Files"
        image_files.each {|image_file|
          pretty_filesize = Filesize.from("#{image_file['size']} B").pretty
          print cyan,"  =  #{image_file['name']} [#{pretty_filesize}]", "\n"
        }
      end
      print reset,"\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#handle(args) ⇒ Object



26
27
28
# File 'lib/morpheus/cli/virtual_images.rb', line 26

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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

def list(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    opts.on( '-t', '--type IMAGE_TYPE', "Image Type" ) do |val|
      options[:imageType] = val.downcase
    end
    opts.on('--all', "All Images" ) do
      options[:filterType] = 'All'
    end
    opts.on('--user', "User Images" ) do
      options[:filterType] = 'User'
    end
    opts.on('--system', "System Images" ) do
      options[:filterType] = 'System'
    end
    build_common_options(opts, options, [:list, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end
    if options[:imageType]
      params[:imageType] = options[:imageType]
    end
    if options[:filterType]
      params[:filterType] = options[:filterType]
    end
    if options[:dry_run]
      print_dry_run @virtual_images_interface.dry.get(params)
      return
    end
    json_response = @virtual_images_interface.get(params)
    if options[:json]
      print JSON.pretty_generate(json_response)
    else
      images = json_response['virtualImages']
      title = "Morpheus Virtual Images"
      subtitles = []
      if options[:imageType]
        subtitles << "Image Type: #{options[:imageType]}".strip
      end
      if options[:filterType]
        subtitles << "Image Type: #{options[:filterType]}".strip
      end
      if params[:phrase]
        subtitles << "Search: #{params[:phrase]}".strip
      end
      print_h1 title, subtitles
      if images.empty?
        print yellow,"No virtual images found.",reset,"\n"
      else
        rows = images.collect do |image|
          image_type = virtual_image_type_for_name_or_code(image['imageType'])
          image_type_display = image_type ? "#{image_type['name']}" : image['imageType']
          {name: image['name'], id: image['id'], type: image_type_display, source: image['userUploaded'] ? "#{green}UPLOADED#{cyan}" : (image['systemImage'] ? 'SYSTEM' : "#{white}SYNCED#{cyan}"), storage: !image['storageProvider'].nil? ? image['storageProvider']['name'] : 'Default', size: image['rawSize'].nil? ? 'Unknown' : "#{Filesize.from("#{image['rawSize']} B").pretty}"}
        end
        columns = [:id, :name, :type, :storage, :size, :source]
        print cyan
        print as_pretty_table(rows, columns, options)
        print_results_pagination(json_response)
      end
      print reset,"\n"
    end
              rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/morpheus/cli/virtual_images.rb', line 478

def remove(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  image_name = args[0]
  connect(options)
  begin
    image = find_virtual_image_by_name_or_id(image_name)
    return 1 if image.nil?
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the virtual image #{image['name']}?")
      exit
    end
    if options[:dry_run]
      print_dry_run @virtual_images_interface.dry.destroy(image['id'])
      return
    end
    json_response = @virtual_images_interface.destroy(image['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
    else
      print "\n", cyan, "Virtual Image #{image['name']} removed", reset, "\n\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_file(args) ⇒ Object



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'lib/morpheus/cli/virtual_images.rb', line 442

def remove_file(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [filename]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    exit 1
  end
  image_name = args[0]
  filename = args[1]
  connect(options)
  begin
    image = find_virtual_image_by_name_or_id(image_name)
    return 1 if image.nil?
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the virtual image filename #{filename}?")
      exit
    end
    if options[:dry_run]
      print_dry_run @virtual_images_interface.dry.destroy_file(image['id'], filename)
      return
    end
    json_response = @virtual_images_interface.destroy_file(image['id'], filename)
    if options[:json]
      print JSON.pretty_generate(json_response)
    else
      print "\n", cyan, "Virtual Image #{image['name']} filename #{filename} removed", reset, "\n\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object

JD: I don't think this has ever worked



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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/morpheus/cli/virtual_images.rb', line 164

def update(args)
  image_name = args[0]
  options = {}
   = nil
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [options]")
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end

  connect(options)
      begin

    image = find_virtual_image_by_name_or_id(image_name)
    return 1 if image.nil?

    params = options[:options] || {}

    if params.empty?
      puts optparse
      option_lines = update_virtual_image_option_types().collect {|it| "\t-O #{it['fieldContext'] ? (it['fieldContext'] + '.') : ''}#{it['fieldName']}=\"value\"" }.join("\n")
      puts "\nAvailable Options:\n#{option_lines}\n\n"
      exit 1
    end

    image_payload = {id: image['id']}
    image_payload.merge(params)
    # JD: what can be updated?
    payload = {virtualImage: image_payload}
    if options[:dry_run]
      print_dry_run @virtual_images_interface.dry.update(image['id'], payload)
      return
    end
    response = @virtual_images_interface.update(image['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      if !response['success']
        exit 1
      end
    else
      print "\n", cyan, "Task #{response['task']['name']} updated", reset, "\n\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#virtual_image_types(args) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/morpheus/cli/virtual_images.rb', line 216

def virtual_image_types(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    if options[:dry_run]
      print_dry_run @virtual_images_interface.dry.virtual_image_types(params)
      return
    end
    json_response = @virtual_images_interface.virtual_image_types(params)
    if options[:json]
      print JSON.pretty_generate(json_response)
    else
      image_types = json_response['virtualImageTypes']
      print_h1 "Morpheus Virtual Image Types"
      if image_types.nil? || image_types.empty?
        print yellow,"No image types currently exist on this appliance. This could be a seed issue.",reset,"\n"
      else
        print cyan
        lb_table_data = image_types.collect do |lb_type|
          {name: lb_type['name'], code: lb_type['code']}
        end
        tp lb_table_data, :name, :code
      end

      print reset,"\n"
    end
              rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end