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, #handle_subcommand, included, #interactive?, #noninteractive, #print_usage, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Instance Method Details

#add(args) ⇒ Object



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

def add(args)
  image_type_name = 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
    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)
    params = Morpheus::Cli::OptionTypes.prompt(add_virtual_image_option_types(image_type), 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.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 !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 !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



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/virtual_images.rb', line 335

def add_file(args)
  image_type_name = nil
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [filepath]")
    build_common_options(opts, options, [: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)			
    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

  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



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

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)
    exit 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 "\n" ,cyan, bold, "Virtual Image Details\n","==================", reset, "\n\n"
      print cyan
      puts "ID: #{image['id']}"
      puts "Name: #{image['name']}"
      puts "Type: #{image_type_display}"
      #puts "Date Created: #{format_local_dt(image['dateCreated'])}"
      #puts "Last Updated: #{format_local_dt(image['lastUpdated'])}"
      if image_files
        puts "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
# 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']
      print "\n" ,cyan, bold, "Morpheus Virtual Images\n","=======================", reset, "\n\n"
      if images.empty?
        puts yellow,"No virtual images currently exist.",reset
      else
        print cyan
        image_table_data = 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
        tp image_table_data, :id, :name, :type, :storage, :size, :source
        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



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
441
442
443
444
445
446
447
448
449
# File 'lib/morpheus/cli/virtual_images.rb', line 416

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)
    exit 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



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

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)
    exit 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



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
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/morpheus/cli/virtual_images.rb', line 148

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)
    exit 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



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

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 "\n" ,cyan, bold, "Morpheus Virtual Image Types\n","============================", reset, "\n\n"
      if image_types.nil? || image_types.empty?
        puts yellow,"No image types currently exist on this appliance. This could be a seed issue.",reset
      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\n"
    end
              rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end