Class: Morpheus::Cli::Instances

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

Instance Method Summary collapse

Methods included from CliCommand

accountScopeOptions, genericOptions, included

Constructor Details

#initializeInstances

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



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
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
199
200
201
202
203
# File 'lib/morpheus/cli/instances.rb', line 98

def add(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances add TYPE NAME"
		opts.on( '-g', '--group GROUP', "Group" ) do |val|
			options[:group] = val
		end
		opts.on( '-c', '--cloud CLOUD', "Cloud" ) do |val|
			options[:cloud] = val
		end
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
		
	end

	if args.count < 2
		puts "\n#{optparse}\n\n"
		return
	end
	optparse.parse(args)
	connect(options)
	instance_name = args[1]
	instance_type_code = args[0]
	instance_type = find_instance_type_by_code(instance_type_code)
	if instance_type.nil?
		exit 1
	end
	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}"
		exit 1
	end

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

	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

	begin
		@instances_interface.create(payload)
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
	list([])
end

#apply_security_groups(args) ⇒ Object



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

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
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		@instances_interface.apply_security_groups(instance['id'], options)
		security_groups([args[0]])
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#backup(args) ⇒ Object



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# File 'lib/morpheus/cli/instances.rb', line 568

def backup(args) 
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances backup [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	end
	puts "\n#{optparse.banner}\n\n" and exit 1 if args.count < 1
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name(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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		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,bold, "\nInvalid Credentials. Unable to acquire access token. Please verify your credentials and try again.\n\n",reset
		exit 1
	end
end

#delenv(args) ⇒ Object



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/morpheus/cli/instances.rb', line 384

def delenv(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances setenv INSTANCE NAME"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		@instances_interface.del_env(instance['id'], args[1])
		envs([args[0]])
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#details(args) ⇒ Object



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 293

def details(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances details [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		return
	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
		instance = instance_results['instances'][0]
		instance_id = instance['id']
		stats = instance_results['stats'][instance_id.to_s]
		print "\n" ,cyan, bold, "#{instance['name']} (#{instance['instanceType']['name']})\n","==================", reset, "\n\n"
		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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

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

def envs(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances envs [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(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, :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}}
		 tp imported_envs
		print reset, "\n"
		
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#firewall_disable(args) ⇒ Object



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'lib/morpheus/cli/instances.rb', line 683

def firewall_disable(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances firewall-disable [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		@instances_interface.firewall_disable(instance['id'])
		security_groups([args[0]])
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#firewall_enable(args) ⇒ Object



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

def firewall_enable(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances firewall-enable [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		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
# File 'lib/morpheus/cli/instances.rb', line 43

def handle(args) 
	if args.empty?
		puts "\nUsage: morpheus instances [list,add,remove,stop,start,restart,backup,run-workflow,resize,upgrade,clone,envs,setenv,delenv,firewall_disable,firewall_enable,security_groups,apply_security_groups] [name]\n\n"
		return 
	end

	case args[0]
		when 'list'
			list(args[1..-1])
		when 'add'
			add(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 'run-workflow'
			run_workflow(args[1..-1])
		when 'stats'
			stats(args[1..-1])
		when 'logs'
			logs(args[1..-1])
		when 'details'
			details(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 "\nUsage: morpheus instances [list,add,remove,stop,start,restart,backup,run-workflow,stop-service,start-service,restart-service,resize,upgrade,clone,envs,setenv,delenv] [name]\n\n"
			exit 127
	end
end

#list(args) ⇒ Object



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

def list(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.on( '-g', '--group GROUP', "Group Name" ) do |group|
			options[:group] = group
		end
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	end
	optparse.parse(args)
	connect(options)
	begin
		params = {}
		if !options[:group].nil?
			group = find_group_by_name(options[:group])
			if !group.nil?
				params['site'] = group
			end
		end
		if !options[:max].nil?
			params['max'] = options[:max]
		end
		if !options[:offset].nil?
			params['offset'] = options[:offset]
		end
		if !options[:phrase].nil?
			params['phrase'] = options[:phrase]
		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']}
				end
				tp instance_table, :id, :name, :type, :environment, :nodes, :connection, :status
			end
			print reset,"\n\n"
		end
		
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#logs(args) ⇒ Object



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

def logs(args) 
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances logs [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
		opts.on( '-n', '--node NODE_ID', "Scope logs to specific Container or VM" ) do |node_id|
			options[:node_id] = node_id.to_i
		end
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		return
	end
	optparse.parse(args)
	connect(options)
	begin
		instance = find_instance_by_name(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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#remove(args) ⇒ Object



661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/morpheus/cli/instances.rb', line 661

def remove(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances remove [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		@instances_interface.destroy(instance['id'])
		list([])
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#restart(args) ⇒ Object



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

def restart(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances restart [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		json_response = @instances_interface.restart(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		end
		return
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#restart_service(args) ⇒ Object



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

def restart_service(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances restart-service [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#run_workflow(args) ⇒ Object



804
805
806
807
808
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# File 'lib/morpheus/cli/instances.rb', line 804

def run_workflow(args)
	options = {}
	
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances run-workflow [INSTANCE] [name] [options]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	end
	if args.count < 2
		puts "\n#{optparse}\n\n"
		exit 1
	end
	
	optparse.parse(args)
	connect(options)
	instance = find_instance_by_name(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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#security_groups(args) ⇒ Object



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
756
757
758
759
760
761
762
763
764
# File 'lib/morpheus/cli/instances.rb', line 731

def security_groups(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances security-groups [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#setenv(args) ⇒ Object



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

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
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		evar = {name: args[1], value: args[2], export: options[:export]}
		params = {}
		@instances_interface.create_env(instance['id'], [evar])
		envs([args[0]])
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#start(args) ⇒ Object



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

def start(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances start [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#start_service(args) ⇒ Object



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

def start_service(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances start-service [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#stats(args) ⇒ Object



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

def stats(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances stats [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		return
	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
		instance = instance_results['instances'][0]
		instance_id = instance['id']
		stats = instance_results['stats'][instance_id.to_s]
		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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#stop(args) ⇒ Object



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

def stop(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances stop [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		json_response = @instances_interface.stop(instance['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		end
		return
	rescue RestClient::Exception => e
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end

#stop_service(args) ⇒ Object



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

def stop_service(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus instances stop-service [name]"
		Morpheus::Cli::CliCommand.genericOptions(opts,options)
	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(args[0])
		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
		::Morpheus::Cli::ErrorHandler.new.print_rest_exception(e)
		exit 1
	end
end