Class: Morpheus::Cli::AppTemplates

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

Instance Method Summary collapse

Methods included from CliCommand

#build_common_options, included

Constructor Details

#initializeAppTemplates

Returns a new instance of AppTemplates.



11
12
13
# File 'lib/morpheus/cli/app_templates.rb', line 11

def initialize() 
	@appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#add(args) ⇒ Object



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

def add(args)
	usage = "Usage: morpheus app-templates add"
   options = {}
   optparse = OptionParser.new do|opts|
     opts.banner = usage
     # opts.on( '-g', '--group GROUP', "Group Name" ) do |group|
     #   options[:options] ||= {}
     #   options[:options]['group'] = group
     # end
     build_common_options(opts, options, [:options, :json])
   end
   optparse.parse(args)
   connect(options)
   begin
 
     params = Morpheus::Cli::OptionTypes.prompt(add_app_template_option_types, options[:options], @api_client, options[:params])

     #puts "parsed params is : #{params.inspect}"
     app_template_keys = ['name']
     app_template_payload = params.select {|k,v| app_template_keys.include?(k) }
     
     group = nil
     if params['group'].to_s != ''
       group = find_group_by_name(params['group'])
       exit 1 if group.nil?
       #app_template_payload['siteId'] = {id: group['id']}
     end
     config = {
       nodes: []
     }
     request_payload = {appTemplate: app_template_payload}
     request_payload['siteId'] = group['id'] if group
     request_payload['config'] = config
     json_response = @app_templates_interface.create(request_payload)

     if options[:json]
       print JSON.pretty_generate(json_response)
       print "\n"
     else
       print_green_success "Added app template #{app_template_payload['name']}"
       details_options = [app_template_payload["name"]]
       details(details_options)
     end

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

#add_instance(args) ⇒ Object



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

def add_instance(args)
  usage = "Usage: morpheus app-templates add-instance [name] [tier] [instance-type]"
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = usage
    # opts.on( '-g', '--group GROUP', "Group" ) do |val|
    #   options[:group] = val
    # end
    # opts.on( '-c', '--cloud CLOUD', "Cloud" ) do |val|
    #   options[:cloud] = val
    # end
    build_common_options(opts, options, [:json])
  end
  optparse.parse(args)

  if args.count < 3
    puts "\n#{optparse}\n\n"
    exit 1
  end

  connect(options)

  name = args[0]
  tier_name = args[1]
  instance_type_code = args[2]

  app_template = find_app_template_by_name(name)
  exit 1 if app_template.nil?

  instance_type = find_instance_type_by_code(instance_type_code)
  if instance_type.nil?
    exit 1
  end

  groupId = app_template['config']['siteId']
  # groupId = nil
  # if !options[:group].nil?
  #   group = find_group_by_name(options[:group])
  #   if !group.nil?
  #     groupId = group
  #   end
  # else
  #   groupId = @active_groups[@appliance_name.to_sym]  
  # end

  if groupId.nil?
    #puts "Group not found or specified! \n #{optparse}"
    print_red_alert("Group not found or specified for this template!")
    puts "#{optparse}"
    exit 1
  end

  cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'optionSource' => 'clouds', 'required' => true, 'description' => 'Select Cloud.'}],options[:options],@api_client,{groupId: groupId})
  cloud = cloud_prompt['cloud']

  # if options[:cloud].nil?
  #   #puts "Cloud not specified! \n #{optparse}"
  #   print_red_alert("Cloud not specified!")
  #   puts "#{optparse}"
  #   exit 1
  # end
  # cloud = find_cloud_by_name(groupId,options[:cloud])
  # if cloud.nil?
  #   #puts "Cloud not found! \n #{optparse}"
  #   #print_red_alert("Cloud not found!")
  #   puts "#{optparse}"
  #   exit 1
  # end


  instance_option_types = [{'fieldName' => 'name', 'fieldLabel' => 'Instance Name', 'type' => 'text'}]
  instance_option_values = Morpheus::Cli::OptionTypes.prompt(instance_option_types, options[:options], @api_client, options[:params])
  instance_name = instance_option_values['name'] || ''

  # copied from instances command, this payload isn't used
  payload = {
    :servicePlan => nil,
    zoneId: cloud,
    :instance => {
      :name => instance_name,
      :site => {
        :id => groupId
      },
      :instanceType => {
        :code => instance_type_code
      }
    }
  }

  version_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'version', 'type' => 'select', 'fieldLabel' => 'Version', 'optionSource' => 'instanceVersions', 'required' => true, 'skipSingleOption' => true, 'description' => 'Select which version of the instance type to be provisioned.'}],options[:options],@api_client,{groupId: groupId, cloudId: cloud, instanceTypeId: instance_type['id']})
  layout_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'layout', 'type' => 'select', 'fieldLabel' => 'Layout', 'optionSource' => 'layoutsForCloud', 'required' => true, 'description' => 'Select which configuration of the instance type to be provisioned.'}],options[:options],@api_client,{groupId: groupId, cloudId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  layout_id = layout_prompt['layout']
  plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'servicePlan', 'type' => 'select', 'fieldLabel' => 'Plan', 'optionSource' => 'instanceServicePlans', 'required' => true, 'description' => 'Choose the appropriately sized plan for this instance'}],options[:options],@api_client,{groupId: groupId, zoneId: cloud, instanceTypeId: instance_type['id'], layoutId: layout_id, version: version_prompt['version']})
  payload[:servicePlan] = plan_prompt['servicePlan']

  layout = instance_type['instanceTypeLayouts'].find{ |lt| lt['id'].to_i == layout_id.to_i}
  instance_type['instanceTypeLayouts'].sort! { |x,y| y['sortOrder'] <=> x['sortOrder'] }
  
  payload[:instance][:layout] = {id: layout['id']}

  type_payload = {}
  if !layout['optionTypes'].nil? && !layout['optionTypes'].empty?
    type_payload = Morpheus::Cli::OptionTypes.prompt(layout['optionTypes'],options[:options],@api_client,{groupId: groupId, cloudId: cloud, zoneId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  elsif !instance_type['optionTypes'].nil? && !instance_type['optionTypes'].empty?
    type_payload = Morpheus::Cli::OptionTypes.prompt(instance_type['optionTypes'],options[:options],@api_client,{groupId: groupId, cloudId: cloud, zoneId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  end
  if !type_payload['config'].nil?
    payload.merge!(type_payload['config'])
  end

  provision_payload = {}
  if !layout['provisionType'].nil? && !layout['provisionType']['optionTypes'].nil? && !layout['provisionType']['optionTypes'].empty?
    puts "Checking for option Types"
    provision_payload = Morpheus::Cli::OptionTypes.prompt(layout['provisionType']['optionTypes'],options[:options],@api_client,{groupId: groupId, cloudId: cloud, zoneId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  end

  if !provision_payload.nil? && !provision_payload['config'].nil?
    payload.merge!(provision_payload['config'])
  end
  # if !provision_payload.nil? && !provision_payload['server'].nil?
  #   payload[:server] = provision_payload['server']
  # end


  config = app_template['config']['tierView']

  config['nodes'] ||= []

  tier = config['nodes'].find {|node| 
    node["data"] && node["data"]["type"] == "tier" && node["data"]["id"] == "newtier-#{tier_name}"
  }
  if !tier
    tier = {
      "classes"=>"tier newtier-#{tier_name}", 
      "data"=>{"id"=>"newtier-#{tier_name}", "name"=> tier_name, "type"=>"tier"}, 
      "grabbable"=>true, "group"=>"nodes","locked"=>false, 
      #"position"=>{"x"=>-2.5, "y"=>-45}, 
      "removed"=>false, "selectable"=>true, "selected"=>false
    }
    config['nodes'] << tier
  end
  
  instance_id = generate_id()

  instance_type_node = {
    "classes"=>"instance newinstance-#{instance_id} #{instance_type['code']}", 
    "data"=>{
      "controlName" => "instance.layout.id",
      "id"=>"newinstance-#{instance_id}", 
      "nodeId"=>["newinstance-#{instance_id}"], # not sure what this is for..
      "index"=>nil, 
      "instance.layout.id"=>layout_id.to_s,
      "instance.name"=>instance_name, 
      "instanceType"=>instance_type['code'], 
      "isPlaced"=>true, 
      "name"=> instance_name, 
      "parent"=>tier['data']['id'], 
      "type"=>"instance", 
      "typeName"=>instance_type['name'],
      "servicePlan"=>plan_prompt['servicePlan'].to_s,
      # "servicePlanOptions.maxCpu": "",
      # "servicePlanOptions.maxCpuId": nil,
      # "servicePlanOptions.maxMemory": "",
      # "servicePlanOptions.maxMemoryId": nil,
      
      # "volumes.datastoreId": nil,
      # "volumes.name": "root",
      # "volumes.rootVolume": "true",
      # "volumes.size": "5",
      # "volumes.sizeId": "5",
      # "volumes.storageType": nil,

      "version"=>version_prompt['version'],
      "siteId"=>groupId.to_s,
      "zoneId"=>cloud.to_s
    }, 
    "grabbable"=>true, "group"=>"nodes", "locked"=>false, 
    #"position"=>{"x"=>-79.83254449505226, "y"=>458.33806818181824}, 
    "removed"=>false, "selectable"=>true, "selected"=>false
  }

  if !type_payload['config'].nil?
    instance_type_node['data'].merge!(type_payload['config'])
  end

  if !provision_payload.nil? && !provision_payload['config'].nil?
    instance_type_node['data'].merge!(provision_payload['config'])
  end

  config['nodes'].push(instance_type_node)

  # re-index nodes for this tier
  tier_instances = config['nodes'].select {|node| node['data']['parent'] == tier['data']['id'] }
  tier_instances.each_with_index do |node, idx| 
    node['data']['index'] = idx
  end

  request_payload = {appTemplate: {} }
  request_payload['siteId'] = app_template['config']['siteId']
  # request_payload['config'] = config['tierView']
  request_payload['config'] = config

  begin
    json_response = @app_templates_interface.update(app_template['id'], request_payload)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Added instance type to app template #{app_template['name']}"
      details_options = [app_template['name']]
      details(details_options)
    end

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

#available_tiers(args) ⇒ Object



718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/morpheus/cli/app_templates.rb', line 718

def available_tiers(args)
  options = {}
  optparse = OptionParser.new do|opts|
    build_common_options(opts, options, [:json])
  end
  optparse.parse(args)
  connect(options)
  params = {}

  begin
    json_response = @app_templates_interface.list_tiers(params)
    tiers = json_response['tiers']
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print "\n" ,cyan, bold, "Tiers\n","==================", reset, "\n\n"
      if tiers.empty?
        puts yellow,"No tiers found.",reset
      else
        rows = tiers.collect do |tier|
          {
            id: tier['id'], 
            name: tier['name'], 
          }
        end
        print cyan
        tp rows, [:name]
        print reset
      end
      print reset,"\n\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
  
end

#available_types(args) ⇒ Object



757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# File 'lib/morpheus/cli/app_templates.rb', line 757

def available_types(args)
  options = {}
  optparse = OptionParser.new do|opts|
    build_common_options(opts, options, [:json])
  end
  optparse.parse(args)
  connect(options)
  params = {}

  begin
    json_response = @app_templates_interface.list_types(params)
    instance_types = json_response['types']
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print "\n" ,cyan, bold, "Instance Types\n","==================", reset, "\n\n"
      if instance_types.empty?
        puts yellow,"No instance types found.",reset
      else
        rows = instance_types.collect do |instance_type|
          {
            id: instance_type['id'], 
            code: instance_type['code'], 
            name: instance_type['name'], 
          }
        end
        print cyan
        tp rows, [:code, :name]
        print reset
      end
      print reset,"\n\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
  
end

#connect(opts) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/morpheus/cli/app_templates.rb', line 15

def connect(opts)
	@access_token = Morpheus::Cli::Credentials.new(@appliance_name,@appliance_url).request_credentials()
	if @access_token.empty?
		print_red_alert "Invalid Credentials. Unable to acquire access token. Please verify your credentials and try again."
		exit 1
	end
	@active_groups = ::Morpheus::Cli::Groups.load_group_file
	@api_client = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url)
	@app_templates_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).app_templates
   @groups_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).groups
   @instance_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instance_types
   @options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).options
end

#connect_tiers(args) ⇒ Object



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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/morpheus/cli/app_templates.rb', line 625

def connect_tiers(args)
  usage = "Usage: morpheus app-templates connect-tiers [name] [tier1] [tier2]"
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = usage
    build_common_options(opts, options, [:json])
  end
  optparse.parse(args)

  if args.count < 3
    puts "\n#{usage}\n\n"
    exit 1
  end
  name = args[0]
  tier1_name = args[1]
  tier2_name = args[2]

  connect(options)
  
  begin

    app_template = find_app_template_by_name(name)
    exit 1 if app_template.nil?

    config = app_template['config']['tierView']      

    config['nodes'] ||= []

    tier1 = config['nodes'].find {|node| 
      node["data"] && node["data"]["type"] == "tier" && node["data"]["id"] == "newtier-#{tier1_name}"
    }
    if tier1.nil?
      print_red_alert "Tier not found by name #{tier1_name}!"
      exit 1
    end

    tier2 = config['nodes'].find {|node| 
      node["data"] && node["data"]["type"] == "tier" && node["data"]["id"] == "newtier-#{tier2_name}"
    }
    if tier2.nil?
      print_red_alert "Tier not found by name #{tier2_name}!"
      exit 1
    end
    
    config['edges'] ||= []

    found_edge = config['edges'].find {|edge|
      (edge['data']['source'] == "newtier-#{tier1_name}" && edge['data']['target'] == "newtier-#{tier2_name}") &&
      (edge['data']['target'] == "newtier-#{tier2_name}" && edge['data']['source'] == "newtier-#{tier1_name}")
    }

    if found_edge
      puts yellow,"Tiers #{tier1_name} and #{tier2_name} are already connected.",reset
      exit
    end

    # not sure how this id is being generated in the ui exactly
    new_edge_index = (1..999).find {|i|
      !config['edges'].find {|edge| edge['data']['id'] == "ele#{i}" }
    }      
    new_edge = {
      "classes"=>"", 
      "data"=>{"id"=>"ele#{new_edge_index}", "source"=>tier1['data']['id'], "target"=>tier2['data']['id']}, 
      "grabbable"=>true, "group"=>"edges", "locked"=>false, 
      #"position"=>{}, 
      "removed"=>false, "selectable"=>true, "selected"=>false
    }

    config['edges'].push(new_edge)


    request_payload = {appTemplate: {} }
    request_payload['siteId'] = app_template['config']['siteId']
    # request_payload['config'] = config['tierView']
    request_payload['config'] = config
    json_response = @app_templates_interface.update(app_template['id'], request_payload)

    
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Connected tiers for app template #{app_template['name']}"
      details_options = [app_template['name']]
      details(details_options)
    end

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

#details(args) ⇒ Object



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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/morpheus/cli/app_templates.rb', line 96

def details(args)
	usage = "Usage: morpheus app-templates details [name]"
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = usage
     opts.on( '-c', '--config', "Display Config Data" ) do |val|
       options[:config] = true
     end
     build_common_options(opts, options, [:json])
	end
	optparse.parse(args)
   if args.count < 1
     puts "\n#{usage}\n\n"
     exit 1
   end
   name = args[0]
	connect(options)
	begin

		app_template = find_app_template_by_name(name)
		exit 1 if app_template.nil?

		json_response = @app_templates_interface.get(app_template['id'])
		app_template = json_response['appTemplate']

		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			print "\n" ,cyan, bold, "App Template Details\n","==================", reset, "\n\n"
			print cyan
			puts "ID: #{app_template['id']}"
			puts "Name: #{app_template['name']}"
			#puts "Category: #{app_template['category']}"
			puts "Account: #{app_template['account'] ? app_template['account']['name'] : ''}"
       instance_type_names = (app_template['instanceTypes'] || []).collect {|it| it['name'] }
       #puts "Instance Types: #{instance_type_names.join(', ')}"
       config = app_template['config']['tierView']
       tiers = config['nodes'].select {|node| node['data']['type'] == "tier" }
       if tiers.empty?
         puts yellow,"0 Tiers",reset
       else
         tiers.each do |tier|
           instances = config['nodes'].select {|node| node['data']['type'] == "instance" && node['data']['parent'] == tier['data']['id'] }.sort {|x,y| x['data']['index'].to_i <=> y['data']['index'].to_i }
           print "\n"
           print cyan, "=  #{tier['data']['name']}\n"
           instances.each do |instance|
             instance_id = instance['data']['id'].sub('newinstance-', '')
             print green, "     - #{instance['data']['typeName']} (#{instance_id})\n",reset
           end

         end
       end
       print cyan

       if options[:config]
         puts "\nConfig:"
         puts JSON.pretty_generate(config)
       end

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

#handle(args) ⇒ Object



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

def handle(args)
	usage = "Usage: morpheus app-templates [list,details,add,update,remove,add-instance,remove-instance,connect-tiers,available-tiers] [name]"
	if args.empty?
		puts "\n#{usage}\n\n"
		exit 1
	end

	case args[0]
		when 'list'
			list(args[1..-1])
		when 'details'
			details(args[1..-1])
		when 'add'
			add(args[1..-1])
		when 'update'
			update(args[1..-1])
     when 'add-instance'
       add_instance(args[1..-1])
     when 'remove-instance'
       remove_instance(args[1..-1])
     when 'connect-tiers'
       connect_tiers(args[1..-1])
		when 'remove'
			remove(args[1..-1])
     when 'available-tiers'
       available_tiers(args[1..-1])
     when 'available-types'
       available_types(args[1..-1])
		else
			puts "\n#{usage}\n\n"
			exit 127
	end
end

#list(args) ⇒ Object



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

def list(args)
	options = {}
	optparse = OptionParser.new do|opts|
		build_common_options(opts, options, [:list, :json])
	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

		json_response = @app_templates_interface.list(params)
		app_templates = json_response['appTemplates']
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			print "\n" ,cyan, bold, "Morpheus App Templates\n","==================", reset, "\n\n"
			if app_templates.empty?
				puts yellow,"No app templates found.",reset
			else
				print_app_templates_table(app_templates)
			end
			print reset,"\n\n"
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#remove(args) ⇒ Object



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

def remove(args)
  usage = "Usage: morpheus app-templates remove [name]"
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = usage
    build_common_options(opts, options, [:auto_confirm, :json])
  end
  optparse.parse(args)

  if args.count < 1
    puts "\n#{usage}\n\n"
    exit 1
  end
  name = args[0]

  connect(options)
  begin
    # allow finding by ID since name is not unique!
    app_template = ((name.to_s =~ /\A\d{1,}\Z/) ? find_app_template_by_id(name) : find_app_template_by_name(name) )
    exit 1 if app_template.nil?
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the app template #{app_template['name']}?")
      exit
    end
    json_response = @app_templates_interface.destroy(app_template['id'])
    
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "App Template #{app_template['name']} removed"
    end

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

#remove_instance(args) ⇒ Object



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
617
618
619
620
621
622
623
# File 'lib/morpheus/cli/app_templates.rb', line 542

def remove_instance(args)
  usage = "Usage: morpheus app-templates remove-instance [name] [instance-id]"
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = usage
    build_common_options(opts, options, [:auto_confirm, :json])
  end
  optparse.parse(args)

  if args.count < 2
    puts "\n#{usage}\n\n"
    exit 1
  end
  name = args[0]
  instance_id = args[1]

  connect(options)
  
  begin

    app_template = find_app_template_by_name(name)
    exit 1 if app_template.nil?

    config = app_template['config']['tierView']      

    config['nodes'] ||= []

    instance_node = config['nodes'].find { |node| 
      node["data"] && node["data"]["type"] == "instance" && node["data"]["id"] == "newinstance-#{instance_id}"
    }
    
    if instance_node.nil?
      print_red_alert "Instance not found by id #{instance_id}"
      exit 1
    end

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the app template #{instance_node['data']['typeName']} instance #{instance_id}?")
      exit
    end

    tier = config['nodes'].find {|node| 
      node["data"] && node["data"]["type"] == "tier" && node["data"]["id"] == instance_node['data']['parent']
    }

    if tier.nil?
      print_red_alert "Parent Tier not found for instance id #{instance_id}!"
      exit 1
    end

    # remove the one node
    config['nodes'] = config['nodes'].reject {|node|
      node["data"] && node["data"]["type"] == "instance" && node["data"]["id"] == "newinstance-#{instance_id}"
    }
    

    # re-index nodes for this tier
    tier_instances = config['nodes'].select {|node| node['data']['parent'] == tier['data']['id'] }
    tier_instances.each_with_index do |node, idx| 
      node['data']['index'] = idx
    end

    request_payload = {appTemplate: {} }
    request_payload['siteId'] = app_template['config']['siteId']
    # request_payload['config'] = config['tierView']
    request_payload['config'] = config
    json_response = @app_templates_interface.update(app_template['id'], request_payload)

    
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Added instance type to app template #{app_template['name']}"
      details_options = [app_template['name']]
      details(details_options)
    end

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

#update(args) ⇒ Object



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

def update(args)
	usage = "Usage: morpheus app-templates update [name] [options]"
   options = {}
   optparse = OptionParser.new do|opts|
     opts.banner = usage
     build_common_options(opts, options, [:options, :json])
   end
   optparse.parse(args)

   if args.count < 1
     puts "\n#{usage}\n\n"
     exit 1
   end
   name = args[0]

   connect(options)
   
   begin

     app_template = find_app_template_by_name(name)
     exit 1 if app_template.nil?

     #params = Morpheus::Cli::OptionTypes.prompt(update_app_template_option_types, options[:options], @api_client, options[:params])
     params = options[:options] || {}

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

     #puts "parsed params is : #{params.inspect}"
     app_template_keys = ['name']
     app_template_payload = params.select {|k,v| app_template_keys.include?(k) }
     
     group = nil
     if params['group'].to_s != ''
       group = find_group_by_name(params['group'])
       exit 1 if group.nil?
       #app_template_payload['siteId'] = {id: group['id']}
     end
     config = app_template['config'] # {}
     request_payload = {appTemplate: app_template_payload}
     if group
       request_payload['siteId'] = group['id']
     else
       request_payload['siteId'] = app_template['config']['siteId']
     end
     # request_payload['config'] = config['tierView']
     request_payload['config'] = config
     json_response = @app_templates_interface.update(app_template['id'], request_payload)

     
     if options[:json]
       print JSON.pretty_generate(json_response)
       print "\n"
     else
       print_green_success "Updated app template #{app_template_payload['name']}"
       details_options = [app_template_payload["name"] || app_template['name']]
       details(details_options)
     end

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