Class: Morpheus::Cli::VirtualImages

Inherits:
Object
  • Object
show all
Includes:
CliCommand, ProvisioningHelper
Defined in:
lib/morpheus/cli/commands/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 ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_host_by_id, #find_host_by_name, #find_host_by_name_or_id, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_permissions_v2, #prompt_resize_volumes, #prompt_security_groups, #prompt_service_plan_options, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Instance Method Details

#_get(id, params, options) ⇒ Object



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

def _get(id, params, options)
    @virtual_images_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @virtual_images_interface.dry.get(id.to_i)
      return
    end
    json_response = @virtual_images_interface.get(id.to_i)
    image = json_response['virtualImage']
    image_config = image['config'] || {}
    image_volumes = image['volumes'] || []
    image_locations = image['locations'] || []
    image_files = json_response['cloudFiles'] || json_response['files']
    image_type = virtual_image_type_for_name_or_code(image['imageType'])
    image_type_display = image_type ? "#{image_type['name']}" : image['imageType']
    render_response(json_response, options, 'virtualImage') do
      get_available_virtual_image_types() # preload
      print_h1 "Virtual Image Details", [], options
      description_cols = {
        "ID" => 'id',
        "Name" => 'name',
        "Labels" => lambda {|it| format_list(it['labels']) },
        "Type" => lambda {|it| image_type_display },
        "Operating System" => lambda {|it| it['osType'] ? it['osType']['name'] : "" }, 
        "Storage" => lambda {|it| !image['storageProvider'].nil? ? image['storageProvider']['name'] : 'Default' }, 
        "Size" => lambda {|it| image['rawSize'].nil? ? 'Unknown' : "#{Filesize.from("#{image['rawSize']} B").pretty}" },
        "Azure Publisher" => lambda {|it| image_config['publisher'] },
        "Azure Offer" => lambda {|it| image_config['offer'] },
        "Azure Sku" => lambda {|it| image_config['sku'] },
        "Azure Version" => lambda {|it| image_config['version'] },
        "Source" => lambda {|it| format_virtual_image_source(it) }, 
        "Tags" => lambda {|it| it['tags'] ? it['tags'].collect {|m| "#{m['name']}: #{m['value']}" }.join(', ') : '' },
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
      }
      description_cols.delete("Tags") if image['tags'].nil? || image['tags'].empty?
      if image['imageType'] == "azure-reference" || image['imageType'] == "azure"
        description_cols.delete("Size")
        description_cols.delete("Storage")
        description_cols["Source"] = lambda {|it| "#{bold}#{cyan}AZURE#{reset}#{cyan}" }
      else
        description_cols.delete("Azure Publisher")
        description_cols.delete("Azure Sku")
        description_cols.delete("Azure Offer")
        description_cols.delete("Azure Version")
      end
      advanced_description_cols = {
        #"OS Type" => lambda {|it| it['osType'] ? it['osType']['name'] : "" }, # displayed above as Operating System
        "Min Memory" => lambda {|it| it['minRam'].to_i != 0 ? Filesize.from("#{it['minRam']} B").pretty : "" },
        "Min Disk" => lambda {|it| it['minDisk'].to_i != 0 ? Filesize.from("#{it['minDisk']} B").pretty : "" },
        "Cloud Init?" => lambda {|it| format_boolean it['osType'] },
        "Install Agent?" => lambda {|it| format_boolean it['osType'] },
        "SSH Username" => lambda {|it| it['sshUsername'] },
        "SSH Password" => lambda {|it| it['sshPassword'] },
        "User Data" => lambda {|it| it['userData'] },
        "Owner" => lambda {|it| it['tenant'].instance_of?(Hash) ? it['tenant']['name'] : it['ownerId'] },
        "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
        "Tenants" => lambda {|it| format_tenants(it['accounts']) },
        "Auto Join Domain?" => lambda {|it| format_boolean it['isAutoJoinDomain'] },
        "VirtIO Drivers Loaded?" => lambda {|it| format_boolean it['virtioSupported'] },
        "VM Tools Installed?" => lambda {|it| format_boolean it['vmToolsInstalled'] },
        "Force Guest Customization?" => lambda {|it| format_boolean it['isForceCustomization'] },
        "Trial Version" => lambda {|it| format_boolean it['trialVersion'] },
        "Sysprep Enabled?" => lambda {|it| format_boolean it['isSysprep'] },
      }
      if options[:details]
        description_cols.merge!(advanced_description_cols)
      end
      print_description_list(description_cols, image)

      if image_volumes && !image_volumes.empty?
        print_h2 "Volumes", options
        image_volume_rows = image_volumes.collect do |image_volume|
          {name: image_volume['name'], size: Filesize.from("#{image_volume['rawSize']} B").pretty}
        end
        print cyan
        print as_pretty_table(image_volume_rows, [:name, :size])
        print cyan
        # print "\n", reset
      end

      if image_files && !image_files.empty?
        print_h2 "Files (#{image_files.size})"
        # image_files.each {|image_file|
        #   pretty_filesize = Filesize.from("#{image_file['size']} B").pretty
        #   print cyan,"  =  #{image_file['name']} [#{pretty_filesize}]", "\n"
        # }
        # size property changed to GB to match volumes
        # contentLength is bytes
        image_file_rows = image_files.collect do |image_file|
          {filename: image_file['name'], size: Filesize.from("#{image_file['contentLength'] || image_file['size']} B").pretty}
        end
        print cyan
        print as_pretty_table(image_file_rows, [:filename, :size])
        # print reset,"\n"
      end
      
      if image_locations && !image_locations.empty?
        print_h2 "Locations", options
        print as_pretty_table(image_locations, virtual_image_location_list_column_definitions.upcase_keys!, options)
      end

      if options[:details] && image_config && !image_config.empty?
        print_h2 "Config", options
        print cyan
        print as_description_list(image_config, image_config.keys, options)
        # print "\n", reset
      end

      print reset,"\n"
    end
    return 0, nil
end

#add(args) ⇒ Object



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
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
477
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 417

def add(args)
  image_type_name = nil
  file_url = nil
  file_name = nil
  tenants_list = nil
  options = {}
  optparse = Morpheus::Cli::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( '--filename NAME', "Image File Name. Specify a name for the uploaded file." ) do |val|
      file_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
    opts.on( '-c', '--cloud CLOUD', "Cloud to scope image to, certain types require a cloud to be selected, eg. Azure Reference" ) do |val|
      # options[:cloud] = val
      options[:options]['cloud'] = val
    end
    opts.on( '--azure-offer OFFER', String, "Azure Reference offer value, only applies to Azure Reference" ) do |val|
      options[:options]['offer'] = val
    end
    opts.on( '--azure-sku SKU', String, "Azure SKU value, only applies to Azure Reference" ) do |val|
      options[:options]['sku'] = val
    end
    opts.on( '--azure-version VERSION', String, "Azure Version value, only applies to Azure Reference" ) do |val|
      options[:options]['version'] = val
    end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        tenants_list = []
      else
        tenants_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    opts.on('--tags LIST', String, "Metadata tags in the format 'name:value, name:value'") do |val|
      options[:tags] = val
    end
    # build_option_type_options(opts, options, add_virtual_image_option_types)
    # build_option_type_options(opts, options, add_virtual_image_advanced_option_types)
    build_standard_add_options(opts, options)

    opts.footer = "Create a virtual image."
  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

   payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({'virtualImage' => parse_passed_options(options)})
  else
    payload.deep_merge!({'virtualImage' => parse_passed_options(options)})
    virtual_image_payload = {}
    # v_prompt = Morpheus::Cli::OptionTypes.prompt(add_virtual_image_option_types, options[:options], @api_client, options[:params])
    if image_type_name
      image_type = virtual_image_type_for_name_or_code(image_type_name)
      # fix issue with api returning imageType vmware instead of vmdk
      if image_type.nil? && image_type_name == 'vmware'
        image_type = virtual_image_type_for_name_or_code('vmdk')
      elsif image_type.nil? && image_type_name == 'vmdk'
        image_type = virtual_image_type_for_name_or_code('vmware')
      end
      if image_type.nil?
        print_red_alert "Virtual Image Type not found by code '#{image_type_name}'"
        return 1
      end
      # 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

    # azure requires us to search the marketplace to select publisher, cloud, offerm sku
    if image_type['code'] == "azure-reference" || image_type['code'] == "azure"
      cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'fieldLabel' => 'Cloud', 'type' => 'select', 'optionSource' => 'clouds', 'required' => true, 'description' => 'Select Azure Cloud.', :fmt=>:natural}],options[:options],@api_client, {zoneTypeWhiteList: 'azure'})
      cloud_id = cloud_prompt['cloud'].to_i

      marketplace_config = prompt_azure_marketplace(cloud_id, options)
      virtual_image_payload['config'] ||= {}
      virtual_image_payload['config'].deep_merge!(marketplace_config)
    end

    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
    v_prompt = Morpheus::Cli::OptionTypes.prompt(my_option_types, options[:options], @api_client, options[:params])
    v_prompt.deep_compact!
    virtual_image_payload.deep_merge!(v_prompt)
    virtual_image_files = virtual_image_payload.delete('virtualImageFiles')
    upload_type = virtual_image_payload.delete('uploadType') # not used serverside
    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
    if tenants_list
      virtual_image_payload['accounts'] = tenants_list
    end
    # metadata tags
      if options[:tags]
        tags = (options[:tags])
        virtual_image_payload['tags'] = tags if tags
      else
        # tags = prompt_metadata(options)
        # virtual_image_payload['tags'] = tags of tags
      end
    # fix issue with api returning imageType vmware instead of vmdk
    if virtual_image_payload && virtual_image_payload['imageType'] == 'vmware'
      virtual_image_payload['imageType'] == 'vmdk'
    end
    # no need to make second request anymore, just include virtualImage.url
    if file_url
      virtual_image_payload['url'] = file_url
      file_url = nil
    end
    #payload = {'virtualImage' => virtual_image_payload}
    payload.deep_merge!({'virtualImage' => virtual_image_payload})
  end

  @virtual_images_interface.setopts(options)
  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, file_name)
    elsif virtual_image_files && !virtual_image_files.empty?
      virtual_image_files.each do |key, filepath|
        print_dry_run @virtual_images_interface.dry.upload(":id", "(Contents of file #{filepath})")
      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, file_name)
    # 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, filepath|
      unless options[:quiet]
        print cyan, "Uploading file (#{key}) #{filepath} ...", reset, "\n"
      end
      image_file = File.new(filepath, 'rb')
      upload_json_response = @virtual_images_interface.upload(virtual_image['id'], image_file, file_name)
      # if options[:json]
      #   print JSON.pretty_generate(upload_json_response)
      # end
    end
  else
    # puts cyan, "No files uploaded.", reset
  end

  render_response(json_response, options, 'virtualImage') do
    print_green_success "Added virtual image #{virtual_image['name']}"
    return _get(virtual_image["id"], {}, options)
  end
  return 0, nil
  
end

#add_file(args) ⇒ Object



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 618

def add_file(args)
  file_url = nil
  file_name = nil
  do_gzip = false
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [filepath]")
    opts.on('--filename FILENAME', String, "Filename for uploaded file. Derived from [filepath] by default." ) do |val|
      file_name = val
    end
    opts.on( '-U', '--url URL', "Image File URL. This can be used instead of [filepath]" ) do |val|
      file_url = val
    end
    opts.on( nil, '--gzip', "Compress uploaded file" ) do
      do_gzip = true
    end
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
    opts.footer = "Upload a virtual image file." + "\n" +
                  "[name] is required. This is the name or id of a virtual image." + "\n" +
                  "[filepath] or --url is required. This is location of the virtual image file."
  end
  optparse.parse!(args)
  image_name = args[0]
  filepath = nil
  if file_url
    if args.count < 1
      puts optparse
      exit 1
    end
  else
    if args.count < 2
      puts optparse
      exit 1
    end
    filepath = args[1]
  end

  connect(options)

  begin
    image = find_virtual_image_by_name_or_id(image_name)
    return 1 if image.nil?
    @virtual_images_interface.setopts(options)
    if file_url
      if options[:dry_run]
        print_dry_run @virtual_images_interface.dry.upload_by_url(image['id'], file_url, file_name)
        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, file_name)
      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(filepath, 'rb')
      if options[:dry_run]
        print_dry_run @virtual_images_interface.dry.upload(image['id'], image_file, file_name, do_gzip)
        return
      end
      unless options[:quiet]
        print cyan, "Uploading file #{filepath} ...", reset, "\n"
      end
      json_response = @virtual_images_interface.upload(image['id'], image_file, file_name, do_gzip)
      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



16
17
18
19
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 16

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @virtual_images_interface = @api_client.virtual_images
end

#get(args) ⇒ Object



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

def get(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image]")
    opts.on('-a', '--details', "Show more details." ) do
      options[:details] = true
    end
    opts.on('--tags LIST', String, "Metadata tags in the format 'name:value, name:value'") do |val|
      options[:tags] = val
    end
    build_standard_get_options(opts, options)
    opts.footer = <<-EOT
Get details about a virtual image.
[image] is required. This is the name or id of a virtual image.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  connect(options)
  id_list = parse_id_list(args)
  # lookup IDs if names are given
  id_list = id_list.collect do |id|
    if id.to_s =~ /\A\d{1,}\Z/
      id
    else
      image = find_virtual_image_by_name_or_id(id)
      if image
        image['id']
      else
        raise_command_error "virtual image not found for name '#{id}'"
      end
    end
  end
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, params, options)
  end
end

#get_location(args) ⇒ Object



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 822

def get_location(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image] [location]")
    build_standard_remove_options(opts, options)
    opts.footer = <<-EOT
Get details about a virtual image location.
[image] is required. This is the name or id of a virtual image.
[location] is required. This is the name or id of a virtual image location.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  image = find_virtual_image_by_name_or_id(args[0])
  return 1, "virtual image not found for '#{args[0]}'" if image.nil?
  location = find_virtual_image_location_by_name_or_id(image['id'], args[1])
  return 1, "location not found for '#{args[1]}'" if location.nil?
  params.merge!(parse_query_options(options))
  @virtual_images_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @virtual_images_interface.dry.get_location(image['id'], location['id'])
    return 0, nil
  end
  # json_response = @virtual_images_interface.get(image['id'], location['id'])
  json_response = {'location' => location} # skip redundant request
  render_response(json_response, options, 'location') do
    location = json_response['location']
    volumes = location['volumes'] || []
    print_h1 "Virtual Image Location Details", [], options
    print_description_list(virtual_image_location_column_definitions, location, options)
    if volumes && !volumes.empty?
      print_h2 "Volumes", options
      volume_rows = volumes.collect do |volume|
        {name: volume['name'], size: Filesize.from("#{volume['rawSize']} B").pretty}
      end
      print cyan
      print as_pretty_table(volume_rows, [:name, :size], options)
      print cyan
      # print "\n", reset
    end
    print reset,"\n"
  end
  return 0, nil
end

#handle(args) ⇒ Object



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

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



25
26
27
28
29
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
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
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 25

def list(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::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
     opts.on('--synced', "Synced Images" ) do
      options[:filterType] = 'Synced'
    end
    opts.on('-l', '--labels LABEL', String, "Filter by labels, can match any of the values") do |val|
      add_query_parameter(params, 'labels', parse_labels(val))
    end
    opts.on('--all-labels LABEL', String, "Filter by labels, must match all of the values") do |val|
      add_query_parameter(params, 'allLabels', parse_labels(val))
    end
    opts.on('--tags Name=Value',String, "Filter by tags (metadata name value pairs).") do |val|
      val.split(",").each do |value_pair|
        k,v = value_pair.strip.split("=")
        options[:tags] ||= {}
        options[:tags][k] ||= []
        options[:tags][k] << (v || '')
      end
    end
    opts.on('-a', '--details', "Show more details." ) do
      options[:details] = true
    end
    build_standard_list_options(opts, options)
    opts.footer = "List virtual images. Default list applies User filter"
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  if options[:imageType]
    params[:imageType] = options[:imageType]
  end
  if options[:filterType]
    params[:filterType] = options[:filterType]
  end
  if options[:tags]
    options[:tags].each do |k,v|
      params['tags.' + k] = v
    end
  end
  @virtual_images_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @virtual_images_interface.dry.list(params)
    return
  end
  json_response = @virtual_images_interface.list(params)
  images = json_response['virtualImages']
  render_response(json_response, options, 'virtualImages') do
    get_available_virtual_image_types() # preload
    title = "Morpheus Virtual Images"
    subtitles = parse_list_subtitles(options)
    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 cyan,"No virtual images found.",reset,"\n"
    else
      virtual_image_column_definitions = {
        "ID" => 'id',
        "Name" => 'name',
        "Labels" => lambda {|it| format_list(it['labels'], '', 3) rescue '' },
        "Type" => lambda {|it| 
          # yick, api should return the type with every virtualImage
          image_type = virtual_image_type_for_name_or_code(it['imageType'])
          image_type ? "#{image_type['name']}" : it['imageType']
        },
        "Operating System" => lambda {|it| it['osType'] ? it['osType']['name'] : "" }, 
        "Storage" => lambda {|it| !it['storageProvider'].nil? ? it['storageProvider']['name'] : 'Default' }, 
        "Size" => lambda {|it| it['rawSize'].nil? ? 'Unknown' : "#{Filesize.from("#{it['rawSize']} B").pretty}" },
        "Visibility" => lambda {|it| it['visibility'] },
        # "Tenant" => lambda {|it| it['account'].instance_of?(Hash) ? it['account']['name'] : it['ownerId'] },
        "Tenants" => lambda {|it| format_list(it['accounts'].collect {|a| a['name'] }, '', 3) rescue '' },
        "Source" => lambda {|it| format_virtual_image_source(it) }, 
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) },
        "Tags" => lambda {|it| it['tags'] ? it['tags'].collect {|m| "#{m['name']}: #{m['value']}" }.join(', ') : '' },
      }
      if json_response['multiTenant'] != true
        virtual_image_column_definitions.delete("Visibility")
        virtual_image_column_definitions.delete("Tenants")
      end
      if options[:details] != true
        virtual_image_column_definitions.delete("Tags")
        virtual_image_column_definitions.delete("Created")
        virtual_image_column_definitions.delete("Updated")
      end
      print as_pretty_table(images, virtual_image_column_definitions.upcase_keys!, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  if images.empty?
    return -1, "no virtual images found"
  else
    return 0, nil
  end
end

#list_locations(args) ⇒ Object



780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 780

def list_locations(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image]")
    build_standard_list_options(opts, options)
    opts.footer = <<-EOT
List virtual image locations for a specific virtual image.
[image] is required. This is the name or id of a virtual image.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  if args.count > 1
    options[:phrase] = args[1..-1].join(" ")
  end
  connect(options)
  image = find_virtual_image_by_name_or_id(args[0])
  return 1, "virtual image not found for '#{args[0]}'" if image.nil?
  params.merge!(parse_list_options(options))
  @virtual_images_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @virtual_images_interface.dry.list_locations(image['id'], params)
    return
  end
  json_response = @virtual_images_interface.list_locations(image['id'], params)
  records = json_response['locations']
  render_response(json_response, options, 'virtualImages') do
    title = "Virtual Image Locations"
    subtitles = parse_list_subtitles(options)
    print_h1 title, subtitles
    if records.empty?
      print cyan,"No virtual image locations found.",reset,"\n"
    else
      print as_pretty_table(records, virtual_image_location_list_column_definitions.upcase_keys!, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
end

#remove(args) ⇒ Object



737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 737

def remove(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image] [location]")
    opts.on('--remove-from-cloud [true|false]', String, "Remove from all clouds. Default is true.") do |val|
      options[:options]['removeFromCloud'] = ['','true','on'].include?(val.to_s)
    end
    build_standard_remove_options(opts, options)
    opts.footer = <<-EOT
Delete a virtual image.
[image] is required. This is the name or id of a virtual image.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  image = find_virtual_image_by_name_or_id(args[0])
  return 1, "virtual image not found for '#{args[0]}'" if image.nil?
  params.merge!(parse_query_options(options))
  # Delete prompt
  # [ X ] Remove from all clouds
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'removeFromCloud', 'fieldLabel' => 'Remove from all clouds', 'type' => 'checkbox', 'defaultValue' => true, 'required' => true, 'description' => "Remove from all clouds"}], options[:options], @api_client)
  remove_from_cloud = v_prompt['removeFromCloud'].to_s == 'true' || v_prompt['removeFromCloud'].to_s == 'on'
  params['removeFromCloud'] = remove_from_cloud
  
  # Delete confirmation
  unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the virtual image #{image['name']}?")
    return 9, "aborted"
  end
  
  @virtual_images_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @virtual_images_interface.dry.destroy(image['id'], params)
    return
  end
  json_response = @virtual_images_interface.destroy(image['id'], params)
  render_response(json_response, options) do
    print_green_success "Removed virtual image #{image['name']}"
  end
  return 0, nil
end

#remove_file(args) ⇒ Object



700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 700

def remove_file(args)
  options = {}
  optparse = Morpheus::Cli::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}?")
      return 9, "aborted"
    end
    @virtual_images_interface.setopts(options)
    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

#remove_location(args) ⇒ Object



869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 869

def remove_location(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image] [location]")
    opts.on('--remove-from-cloud [true|false]', String, "Remove from cloud. Default is true.") do |val|
      options[:options]['removeFromCloud'] = ['','true','on'].include?(val.to_s)
    end
    build_standard_remove_options(opts, options)
    opts.footer = <<-EOT
Delete a virtual image location.
[image] is required. This is the name or id of a virtual image.
[location] is required. This is the name or id of a virtual image location.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  image = find_virtual_image_by_name_or_id(args[0])
  return 1, "virtual image not found for '#{args[0]}'" if image.nil?
  location = find_virtual_image_location_by_name_or_id(image['id'], args[1])
  return 1, "location not found for '#{args[1]}'" if location.nil?

  params.merge!(parse_query_options(options))
  
  # Delete prompt
  # [ X ] Remove from cloud
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'removeFromCloud', 'fieldLabel' => 'Remove from cloud', 'type' => 'checkbox', 'defaultValue' => true, 'required' => true, 'description' => "Remove from cloud"}], options[:options], @api_client)
  remove_from_cloud = v_prompt['removeFromCloud'].to_s == 'true' || v_prompt['removeFromCloud'].to_s == 'on'
  params['removeFromCloud'] = remove_from_cloud
  
  # Delete confirmation
  unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the virtual image location #{location['id']}?")
    return 9, "aborted"
  end
  
  @virtual_images_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @virtual_images_interface.dry.destroy_location(image['id'], location['id'], params)
    return
  end
  json_response = @virtual_images_interface.destroy_location(image['id'], location['id'], params)
  render_response(json_response, options) do
    print_green_success "Removed virtual image location #{location['id']}"
  end
  return 0, nil
end

#update(args) ⇒ Object



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
370
371
372
373
374
375
376
377
378
# File 'lib/morpheus/cli/commands/virtual_images.rb', line 300

def update(args)
  image_name = args[0]
  options = {}
  tenants_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        tenants_list = []
      else
        tenants_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    opts.on('--tags LIST', String, "Tags in the format 'name:value, name:value'. This will add and remove tags.") do |val|
      options[:tags] = val
    end
    opts.on('--add-tags TAGS', String, "Add Tags in the format 'name:value, name:value'. This will only add/update tags.") do |val|
      options[:add_tags] = val
    end
    opts.on('--remove-tags TAGS', String, "Remove Tags in the format 'name, name:value'. This removes tags, the :value component is optional and must match if passed.") do |val|
      options[:remove_tags] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a virtual image." + "\n" +
                  "[name] is required. This is the name or id of a virtual image."
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)

  connect(options)
  
  virtual_image = find_virtual_image_by_name_or_id(image_name)
  return 1 if virtual_image.nil?

  passed_options = parse_passed_options(options)
  payload = nil
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({virtual_image_object_key => passed_options}) unless passed_options.empty?
  else
    virtual_image_payload = passed_options
    if tenants_list
      virtual_image_payload['accounts'] = tenants_list
    end
    # metadata tags
    if options[:tags]
      virtual_image_payload['tags'] = (options[:tags])
    else
      # tags = prompt_metadata(options)
      # payload[virtual_image_object_key]['tags'] = tags of tags
    end
    # metadata tags
    if options[:add_tags]
      virtual_image_payload['addTags'] = (options[:add_tags])
    end
    if options[:remove_tags]
      virtual_image_payload['removeTags'] = (options[:remove_tags])
    end
    if virtual_image_payload.empty?
      raise_command_error "Specify at least one option to update.\n#{optparse}"
    end
    payload = {'virtualImage' => virtual_image_payload}
  end
  @virtual_images_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @virtual_images_interface.dry.update(virtual_image['id'], payload)
    return
  end
  json_response = @virtual_images_interface.update(virtual_image['id'], payload)
  render_response(json_response, options, 'virtualImage') do
    print_green_success "Updated virtual image #{virtual_image['name']}"
    _get(virtual_image["id"], {}, options)
  end
  return 0, nil
  
end

#virtual_image_types(args) ⇒ Object



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

def virtual_image_types(args)
  options = {}
  optparse = Morpheus::Cli::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 = {}
    @virtual_images_interface.setopts(options)
    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 cyan,"No image types found.",reset,"\n"
      else
        rows = image_types.collect do |lb_type|
          {name: lb_type['name'], code: lb_type['code']}
        end
        puts as_pretty_table(rows, [:name, :code], options)
      end
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end