Class: Morpheus::Cli::Instances

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

Instance Method Summary collapse

Methods included from ProvisioningHelper

#find_cloud_by_id, #find_cloud_by_name, #find_cloud_from_options, #find_group_by_id, #find_group_by_name, #find_group_from_options, #find_instance_type_by_code, #get_available_clouds, #get_available_groups, included, #instance_context_options, #prompt_network_interfaces, #prompt_new_instance, #prompt_resize_volumes, #prompt_volumes, #reject_networking_option_types, #reject_service_plan_option_types, #reject_volume_option_types

Methods included from CliCommand

#build_common_options, included

Constructor Details

#initialize ⇒ Instances

Returns a new instance of Instances.



13
14
15
16
# File 'lib/morpheus/cli/instances.rb', line 13

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

Instance Method Details

#add(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
162
163
164
165
166
# File 'lib/morpheus/cli/instances.rb', line 103

def add(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances add [type] [name]"
		opts.on( '-g', '--group GROUP', "Group Name" ) do |val|
			options[:group_name] = val
		end
		opts.on( '-G', '--group-id ID', "Group Id" ) do |val|
			options[:group_id] = val
		end
		opts.on( '-c', '--cloud CLOUD', "Cloud Name" ) do |val|
			options[:cloud_name] = val
		end
		# this conflicts with --nocolor option
		# opts.on( '-C', '--cloud CLOUD', "Cloud Id" ) do |val|
		# 	options[:cloud] = val
		# end
		opts.on( '-t', '--type CODE', "Instance Type" ) do |val|
			options[:instance_type_code] = val
		end
		build_common_options(opts, options, [:options, :json, :dry_run, :remote])
		
	end

	optparse.parse(args)
	connect(options)

	# support old format of `instance add TYPE NAME`
	if args[0] && args[0] !~ /\A\-/
		options[:instance_type_code] = args[0]
		if args[1] && args[1] !~ /\A\-/
			options[:instance_name] = args[1]
		end
	end
	
	# use active group by default
	if !options[:group_name] && !options[:group_id]
		options[:group_id] = @active_groups[@appliance_name.to_sym]
	end

	options[:name_required] = true
	
	begin

		payload = prompt_new_instance(options)

		if options[:dry_run]
			print_dry_run("POST #{@appliance_url}/api/instances", payload)
			return
		end
		json_response = @instances_interface.create(payload)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			instance_name = json_response["instance"]["name"]
			print_green_success "Provisioning instance #{instance_name}"
			list([])
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#apply_security_groups(args) ⇒ Object



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
# File 'lib/morpheus/cli/instances.rb', line 925

def apply_security_groups(args)
	options = {}
	clear_or_secgroups_specified = false
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances apply-security-groups [name] [options]"
		opts.on( '-c', '--clear', "Clear all security groups" ) do
			options[:securityGroupIds] = []
			clear_or_secgroups_specified = true
		end
		opts.on( '-S', '--secgroups SECGROUPS', "Apply the specified comma separated security group ids" ) do |secgroups|
			options[:securityGroupIds] = secgroups.split(",")
			clear_or_secgroups_specified = true
		end
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)

	if !clear_or_secgroups_specified 
		puts usage
		exit
	end

	begin
		instance = find_instance_by_name_or_id(args[0])
		@instances_interface.apply_security_groups(instance['id'], options)
		security_groups([args[0]])
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#backup(args) ⇒ Object



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

def backup(args) 
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances backup [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1 
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		json_response = @instances_interface.backup(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Backup initiated."
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#connect(opts) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/morpheus/cli/instances.rb', line 18

def connect(opts)
	if opts[:remote]
		@appliance_url = opts[:remote]
		@appliance_name = opts[:remote]
		@access_token = Morpheus::Cli::Credentials.new(@appliance_name,@appliance_url).request_credentials(opts)
	else
		@access_token = Morpheus::Cli::Credentials.new(@appliance_name,@appliance_url).request_credentials(opts)
	end
	@api_client = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url)		
	@instances_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instances
	@task_sets_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).task_sets
	@logs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).logs
	@tasks_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).tasks
	@instance_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instance_types
	@groups_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).groups
	@provision_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).provision_types
	@options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).options
	@active_groups = ::Morpheus::Cli::Groups.load_group_file
	if @access_token.empty?
		print_red_alert "Invalid Credentials. Unable to acquire access token. Please verify your credentials and try again."
		exit 1
	end
end

#delenv(args) ⇒ Object



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/morpheus/cli/instances.rb', line 448

def delenv(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances setenv INSTANCE NAME"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 2
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		@instances_interface.del_env(instance['id'], args[1])
		envs([args[0]])
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#details(args) ⇒ Object



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

def details(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances details [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		json_response = @instances_interface.get(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			return
		end
		instance = json_response['instance']
		stats = json_response['stats'] || {}
		# load_balancers = stats = json_response['loadBalancers'] || {}

		status_string = instance['status']
		if status_string == 'running'
			status_string = "#{green}#{status_string.upcase}#{cyan}"
		elsif status_string == 'stopped' or status_string == 'failed'
			status_string = "#{red}#{status_string.upcase}#{cyan}"
		elsif status_string == 'unknown'
			status_string = "#{white}#{status_string.upcase}#{cyan}"
		else
			status_string = "#{yellow}#{status_string.upcase}#{cyan}"
		end
		connection_string = ''
		if !instance['connectionInfo'].nil? && instance['connectionInfo'].empty? == false
			connection_string = "#{instance['connectionInfo'][0]['ip']}:#{instance['connectionInfo'][0]['port']}"
		end

		print "\n" ,cyan, bold, "Instance Details\n","==================", reset, "\n\n"
		print cyan
		puts "ID: #{instance['id']}"
		puts "Name: #{instance['name']}"
		puts "Description: #{instance['description']}"
		puts "Group: #{instance['group'] ? instance['group']['name'] : ''}"
		puts "Cloud: #{instance['cloud'] ? instance['cloud']['name'] : ''}"
		puts "Type: #{instance['instanceType']['name']}"
		puts "Environment: #{instance['instanceContext']}"
		puts "Nodes: #{instance['containers'] ? instance['containers'].count : 0}"
		puts "Connection: #{connection_string}"
		#puts "Account: #{instance['account'] ? instance['account']['name'] : ''}"
		puts "Status: #{status_string}"
		print cyan, "Memory: \t#{Filesize.from("#{stats['usedMemory']} B").pretty} / #{Filesize.from("#{stats['maxMemory']} B").pretty}\n"
		print cyan, "Storage: \t#{Filesize.from("#{stats['usedStorage']} B").pretty} / #{Filesize.from("#{stats['maxStorage']} B").pretty}\n\n",reset

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

#envs(args) ⇒ Object



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/instances.rb', line 385

def envs(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances envs [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		env_results = @instances_interface.get_envs(instance['id'])
		print "\n" ,cyan, bold, "#{instance['name']} (#{instance['instanceType']['name']})\n","==================", "\n\n", reset, cyan
		envs = env_results['envs'] || {}
		if env_results['readOnlyEnvs']
			envs += env_results['readOnlyEnvs'].map { |k,v| {:name => k, :value => k.downcase.include?("password") || v['masked'] ? "********" : v['value'], :export => true}}
		end
		tp envs, :name, :value, :export
		print "\n" ,cyan, bold, "Imported Envs\n","==================", "\n\n", reset, cyan
		 imported_envs = env_results['importedEnvs'].map { |k,v| {:name => k, :value => k.downcase.include?("password") || v['masked'] ? "********" : v['value']}}
		 tp imported_envs
		print reset, "\n"
		
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#firewall_disable(args) ⇒ Object



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
# File 'lib/morpheus/cli/instances.rb', line 842

def firewall_disable(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances firewall-disable [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		@instances_interface.firewall_disable(instance['id'])
		security_groups([args[0]])
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#firewall_enable(args) ⇒ Object



864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
# File 'lib/morpheus/cli/instances.rb', line 864

def firewall_enable(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances firewall-enable [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance_results = @instances_interface.get({name: args[0]})
		if instance_results['instances'].empty?
			puts "Instance not found by name #{args[0]}"
			return
		end
		@instances_interface.firewall_enable(instance_results['instances'][0]['id'])
		security_groups([args[0]])
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#handle(args) ⇒ Object



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/instances.rb', line 43

def handle(args) 
	usage = "Usage: morpheus instances [list,details,add,update,remove,stop,start,restart,backup,run-workflow,stop-service,start-service,restart-service,resize,upgrade,clone,envs,setenv,delenv] [name]"
	if args.empty?
		puts "\n#{usage}\n\n"
		return 
	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 'remove'
			remove(args[1..-1])
		when 'stop'
			stop(args[1..-1])
		when 'start'
			start(args[1..-1])
		when 'restart'
			restart(args[1..-1])
		when 'stop-service'
			stop_service(args[1..-1])
		when 'start-service'
			start_service(args[1..-1])
		when 'restart-service'
			restart_service(args[1..-1])
		when 'resize'
			resize(args[1..-1])
		when 'run-workflow'
			run_workflow(args[1..-1])
		when 'stats'
			stats(args[1..-1])
		when 'logs'
			logs(args[1..-1])
		when 'envs'
			envs(args[1..-1])
		when 'setenv'
			setenv(args[1..-1])	
		when 'delenv'
			delenv(args[1..-1])	
		when 'firewall-disable'
			firewall_disable(args[1..-1])	
		when 'firewall-enable'
			firewall_enable(args[1..-1])	
		when 'security-groups'	
			security_groups(args[1..-1])	
		when 'apply-security-groups'	
			apply_security_groups(args[1..-1])	
		when 'backup'
			backup(args[1..-1])	
		else
			puts "\n#{usage}\n\n"
			exit 127
	end
end

#list(args) ⇒ Object



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
779
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
# File 'lib/morpheus/cli/instances.rb', line 749

def list(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.on( '-g', '--group GROUP', "Group Name" ) do |val|
			options[:group_name] = val
		end
		build_common_options(opts, options, [:list, :json, :remote])
	end
	optparse.parse(args)
	connect(options)
	begin
		params = {}
		group = find_group_from_options(options)
		if group
			params['site'] = group['id']
		end
		[:phrase, :offset, :max, :sort, :direction].each do |k|
			params[k] = options[k] unless options[k].nil?
		end

		json_response = @instances_interface.get(params)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			instances = json_response['instances']

			print "\n" ,cyan, bold, "Morpheus Instances\n","==================", reset, "\n\n"
			if instances.empty?
				puts yellow,"No instances currently configured.",reset
			else
				print cyan
				instance_table = instances.collect do |instance|
					status_string = instance['status']
					if status_string == 'running'
						status_string = "#{green}#{status_string.upcase}#{cyan}"
					elsif status_string == 'stopped' or status_string == 'failed'
						status_string = "#{red}#{status_string.upcase}#{cyan}"
					elsif status_string == 'unknown'
						status_string = "#{white}#{status_string.upcase}#{cyan}"
					else
						status_string = "#{yellow}#{status_string.upcase}#{cyan}"
					end
					connection_string = ''
					if !instance['connectionInfo'].nil? && instance['connectionInfo'].empty? == false
						connection_string = "#{instance['connectionInfo'][0]['ip']}:#{instance['connectionInfo'][0]['port']}"
					end
					{id: instance['id'], name: instance['name'], connection: connection_string, environment: instance['instanceContext'], nodes: instance['containers'].count, status: status_string, type: instance['instanceType']['name'], group: !instance['group'].nil? ? instance['group']['name'] : nil, cloud: !instance['cloud'].nil? ? instance['cloud']['name'] : nil}
				end
				tp instance_table, :id, :name, :group, :cloud, :type, :environment, :nodes, :connection, :status
			end
			print reset,"\n\n"
		end
		
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#logs(args) ⇒ Object



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

def logs(args) 
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances logs [name]"
		opts.on( '-n', '--node NODE_ID', "Scope logs to specific Container or VM" ) do |node_id|
			options[:node_id] = node_id.to_i
		end
		build_common_options(opts, options, [:list, :json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		return
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		container_ids = instance['containers']
		if options[:node_id] && container_ids.include?(options[:node_id])
			container_ids = [options[:node_id]]
		end
		logs = @logs_interface.container_logs(container_ids, { max: options[:max] || 100, offset: options[:offset] || 0, query: options[:phrase]})
		if options[:json]
			puts logs
		else
			logs['data'].reverse.each do |log_entry|
				log_level = ''
				case log_entry['level']
					when 'INFO'
						log_level = "#{blue}#{bold}INFO#{reset}"
					when 'DEBUG'
						log_level = "#{white}#{bold}DEBUG#{reset}"
					when 'WARN'
						log_level = "#{yellow}#{bold}WARN#{reset}"
					when 'ERROR'
						log_level = "#{red}#{bold}ERROR#{reset}"
					when 'FATAL'
						log_level = "#{red}#{bold}FATAL#{reset}"
				end
				puts "[#{log_entry['ts']}] #{log_level} - #{log_entry['message']}"
			end
			print reset,"\n"
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#remove(args) ⇒ Object



809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'lib/morpheus/cli/instances.rb', line 809

def remove(args)
	options = {}
	query_params = {keepBackups: 'off', force: 'off'}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances remove [name] [-fB]"
		opts.on( '-f', '--force', "Force Remove" ) do
			query_params[:force] = 'on'
		end
		opts.on( '-B', '--keep-backups', "Preserve copy of backups" ) do
			query_params[:keepBackups] = 'on'
		end
		build_common_options(opts, options, [:auto_confirm, :json, :remote])

	end
	if args.count < 1
		puts "\n#{optparse}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the instance '#{instance['name']}'?", options)
			exit 1
		end
		@instances_interface.destroy(instance['id'],query_params)
		list([])
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#resize(args) ⇒ Object



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
717
718
719
# File 'lib/morpheus/cli/instances.rb', line 644

def resize(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances resize [name]"
		build_common_options(opts, options, [:options, :json, :dry_run, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])

		group_id = instance['group']['id']
		cloud_id = instance['cloud']['id']
		layout_id = instance['layout']['id']

		plan_id = instance['plan']['id']
		payload = {
			:instance => {:id => instance["id"]}
		}

		# avoid 500 error
		# payload[:servicePlanOptions] = {}

		puts "\nDue to limitations by most Guest Operating Systems, Disk sizes can only be expanded and not reduced.\nIf a smaller plan is selected, memory and CPU (if relevant) will be reduced but storage will not.\n\n"

		# prompt for service plan
		service_plans_json = @instances_interface.service_plans({zoneId: cloud_id, layoutId: layout_id})
		service_plans = service_plans_json["plans"]
		service_plans_dropdown = service_plans.collect {|sp| {'name' => sp["name"], 'value' => sp["id"]} } # already sorted
		service_plans_dropdown.each do |plan|
			if plan['value'] && plan['value'].to_i == plan_id.to_i
				plan['name'] = "#{plan['name']} (current)"
			end
		end
		plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'servicePlan', 'type' => 'select', 'fieldLabel' => 'Plan', 'selectOptions' => service_plans_dropdown, 'required' => true, 'description' => 'Choose the appropriately sized plan for this instance'}],options[:options])
		service_plan = service_plans.find {|sp| sp["id"] == plan_prompt['servicePlan'].to_i }
		new_plan_id = service_plan["id"]
		#payload[:servicePlan] = new_plan_id # ew, this api uses servicePlanId instead
		payload[:servicePlanId] = new_plan_id
		payload[:instance][:plan] = {id: service_plan["id"]}

		volumes_response = @instances_interface.volumes(instance['id'])
		current_volumes = volumes_response['volumes'].sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }

		# prompt for volumes
		volumes = prompt_resize_volumes(current_volumes, service_plan, options, @api_client, {})
		if !volumes.empty?
			payload[:volumes] = volumes
		end

		# only amazon supports this option
		# for now, always do this
		payload[:deleteOriginalVolumes] = true

		if options[:dry_run]
			print_dry_run("PUT #{@appliance_url}/api/instances/#{instance['id']}/resize", payload)
			return
		end
		json_response = @instances_interface.resize(instance['id'], payload)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			print_green_success "Resizing instance #{instance['name']}"
			list([])
		end
		
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#restart(args) ⇒ Object



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

def restart(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances restart [name]"
		build_common_options(opts, options, [:auto_confirm, :json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart this instance?", options)
			exit 1
		end
		json_response = @instances_interface.restart(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#restart_service(args) ⇒ Object



613
614
615
616
617
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
# File 'lib/morpheus/cli/instances.rb', line 613

def restart_service(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances restart-service [name]"
		build_common_options(opts, options, [:auto_confirm, :json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart this instance?", options)
			exit 1
		end
		json_response = @instances_interface.restart(instance['id'],false)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Restarting service on instance #{args[0]}"
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#run_workflow(args) ⇒ Object



963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
# File 'lib/morpheus/cli/instances.rb', line 963

def run_workflow(args)
	options = {}
	
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances run-workflow [INSTANCE] [name] [options]"
		build_common_options(opts, options, [:options, :json, :remote])
	end
	if args.count < 2
		puts "\n#{optparse}\n\n"
		exit 1
	end
	
	optparse.parse(args)
	connect(options)
	instance = find_instance_by_name_or_id(args[0])
	workflow = find_workflow_by_name(args[1])
	task_types = @tasks_interface.task_types()
	editable_options = []
	workflow['taskSetTasks'].sort{|a,b| a['taskOrder'] <=> b['taskOrder']}.each do |task_set_task|
		task_type_id = task_set_task['task']['taskType']['id']
		task_type = task_types['taskTypes'].find{ |current_task_type| current_task_type['id'] == task_type_id}
		task_opts = task_type['optionTypes'].select { |otype| otype['editable']}
		if !task_opts.nil? && !task_opts.empty?
			editable_options += task_opts.collect do |task_opt|
				new_task_opt = task_opt.clone
				new_task_opt['fieldContext'] = "#{task_set_task['id']}.#{new_task_opt['fieldContext']}"
			end
		end
	end
	params = options[:options] || {}

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

	workflow_payload = {taskSet: {"#{workflow['id']}" => params }}
	begin
		
		json_response = @instances_interface.workflow(instance['id'],workflow['id'], workflow_payload)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Running workflow..."
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#security_groups(args) ⇒ Object



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
916
917
918
919
920
921
922
923
# File 'lib/morpheus/cli/instances.rb', line 890

def security_groups(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances security-groups [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		instance_id = instance['id']
		json_response = @instances_interface.security_groups(instance_id)

		securityGroups = json_response['securityGroups']
		print "\n" ,cyan, bold, "Morpheus Security Groups for Instance:#{instance_id}\n","==================", reset, "\n\n"
		print cyan, "Firewall Enabled=#{json_response['firewallEnabled']}\n\n"
		if securityGroups.empty?
			puts yellow,"No security groups currently applied.",reset
		else
			securityGroups.each do |securityGroup|
				print cyan, "=  #{securityGroup['id']} (#{securityGroup['name']}) - (#{securityGroup['description']})\n"
			end
		end
		print reset,"\n\n"

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

#setenv(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
# File 'lib/morpheus/cli/instances.rb', line 417

def setenv(args)
	options = {}

	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances setenv INSTANCE NAME VALUE [-e]"
		opts.on( '-e', "Exportable" ) do |exportable|
			options[:export] = exportable
		end
		opts.on( '-M', "Masked" ) do |masked|
			options[:masked] = masked
		end
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 3
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		evar = {name: args[1], value: args[2], export: options[:export], masked: options[:masked]}
		params = {}
		@instances_interface.create_env(instance['id'], [evar])
		envs([args[0]])
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#start(args) ⇒ Object



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

def start(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances start [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		json_response = @instances_interface.start(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#start_service(args) ⇒ Object



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

def start_service(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances start-service [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		json_response = @instances_interface.start(instance['id'],false)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Starting service on #{args[0]}"
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#stats(args) ⇒ Object



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

def stats(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances stats [name]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		return
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		json_response = @instances_interface.get(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			return
		end
		instance = json_response['instance']
		stats = json_response['stats'] || {}
		if options[:json]
			print JSON.pretty_generate(stats)
			print "\n"
		else
			print "\n" ,cyan, bold, "#{instance['name']} (#{instance['instanceType']['name']})\n","==================", "\n\n", reset, cyan
			stats_map = {}
			stats_map[:memory] = "#{Filesize.from("#{stats['usedMemory']} B").pretty} / #{Filesize.from("#{stats['maxMemory']} B").pretty}"
			stats_map[:storage] = "#{Filesize.from("#{stats['usedStorage']} B").pretty} / #{Filesize.from("#{stats['maxStorage']} B").pretty}"
			stats_map[:cpu] = "#{stats['usedCpu'].to_f.round(2)}%"
			tp [stats_map], :memory,:storage,:cpu
			print reset, "\n"
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#stop(args) ⇒ Object



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

def stop(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances stop [name]"
		build_common_options(opts, options, [:auto_confirm, :json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop this instance?", options)
			exit 1
		end
		json_response = @instances_interface.stop(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#stop_service(args) ⇒ Object



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

def stop_service(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances stop-service [name]"
		build_common_options(opts, options, [:auto_confirm, :json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name_or_id(args[0])
		unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop this instance?", options)
			exit 1
		end
		json_response = @instances_interface.stop(instance['id'],false)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Stopping service on #{args[0]}"
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#update(args) ⇒ Object



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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/morpheus/cli/instances.rb', line 168

def update(args)
	usage = "Usage: morpheus instances update [name] [options]"
   options = {}
   optparse = OptionParser.new do|opts|
     opts.banner = usage
     build_common_options(opts, options, [:options, :json, :dry_run])
   end
   optparse.parse(args)
   if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
   connect(options)

   begin
 		
 		instance = find_instance_by_name_or_id(args[0])

		# group = find_group_from_options(options)

		payload = {
			'instance' => {id: instance["id"]}
		}

		update_instance_option_types = [
			{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Enter a name for this instance'},
			{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'required' => false},
			{'fieldName' => 'instanceContext', 'fieldLabel' => 'Environment', 'type' => 'select', 'required' => false, 'selectOptions' => instance_context_options()},
			{'fieldName' => 'tags', 'fieldLabel' => 'Tags', 'type' => 'text', 'required' => false}
		]

		params = options[:options] || {}

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

     instance_keys = ['name', 'description', 'instanceContext', 'tags']
     params = params.select {|k,v| instance_keys.include?(k) }
     params['tags'] = params['tags'].split(',').collect {|it| it.to_s.strip }.compact.uniq if params['tags']
     payload['instance'].merge!(params)
		
     json_response = @instances_interface.update(instance["id"], payload)

     if options[:dry_run]
     	print_dry_run("PUT #{@appliance_url}/api/instances", payload)
			return
		end

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

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