Class: Morpheus::Cli::Hosts

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

Instance Method Summary collapse

Methods included from CliCommand

#build_common_options, included

Constructor Details

#initializeHosts

Returns a new instance of Hosts.



12
13
14
15
# File 'lib/morpheus/cli/hosts.rb', line 12

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

Instance Method Details

#add(args) ⇒ Object



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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/morpheus/cli/hosts.rb', line 158

def add(args)
	
	options = {zone: args[0], params:{}}
	name = args[1]

	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts add CLOUD NAME [options]"
		opts.on( '-t', '--type TYPE', "Server Type" ) do |server_type|
			options[:server_type] = server_type
		end
		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)

	params = {}
	
	zone=nil
	if !options[:zone].nil?
		zone = find_zone_by_name(nil, options[:zone])
		options[:params][:zoneId] = zone['id']
	end

	if zone.nil?
		print_red_alert "Either the cloud was not specified or was not found. Please make sure a cloud is specified at the beginning of the argument."
		exit 1
	else
		zone_type = cloud_type_for_id(zone['zoneTypeId'])
	end

	cloud_server_types = zone_type['serverTypes'].select{|b| b['creatable'] == true }
	if options[:server_type]
		server_type_code = options[:server_type]
	else
		server_type_options = cloud_server_types.collect {|it| {'name' => it['name'], 'value' => it['code']} }
		v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'type' => 'select', 'fieldLabel' => "Server Type", 'selectOptions' => server_type_options, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a server type.'}], options[:options])
   	server_type_code = v_prompt['type']
	end
	
   server_type = cloud_server_types.find {|it| it['code'] == server_type_code }

	if server_type.nil?
		print_red_alert "Server Type #{server_type_code} not found cloud #{zone['name']}"
		exit 1
	end

	params = Morpheus::Cli::OptionTypes.prompt(server_type['optionTypes'],options[:options],@api_client, options[:params])
	begin
		params['server'] = params['server'] || {}
		server_payload = {server: {name: name, zone: {id: zone['id']}, computeServerType: [id: server_type['id']]}.merge(params['server']), config: params['config'], network: params['network']}
		json_response = @servers_interface.create(server_payload)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			print_green_success "Provisioning Server..."
			list([])
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#connect(opts) ⇒ Object



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

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)
	@clouds_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).clouds
	@groups_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).groups
	@tasks_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).tasks
	@task_sets_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).task_sets
	@servers_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).servers
	@logs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).logs
	@cloud_types = @clouds_interface.cloud_types['zoneTypes']
	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

#handle(args) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/morpheus/cli/hosts.rb', line 39

def handle(args) 
	usage = "Usage: morpheus hosts [list,add,remove,logs,start,stop,run-workflow,make-managed,upgrade-agent,server-types] [name]"
	if args.empty?
		puts "\n#{usage}\n\n"
		exit 127
	end

	case args[0]
		when 'list'
			list(args[1..-1])
		when 'add'
			add(args[1..-1])
		when 'remove'
			remove(args[1..-1])
		when 'start'
			start(args[1..-1])
		when 'stop'
			start(args[1..-1])
		when 'run-workflow'
			run_workflow(args[1..-1])	
		when 'upgrade-agent'
			upgrade(args[1..-1])
		when 'logs'
			logs(args[1..-1])	
		when 'server-types'
			server_types(args[1..-1])
		else
			puts "\n#{usage}\n\n"
			exit 127 #Command now foud exit code
	end
end

#list(args) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/morpheus/cli/hosts.rb', line 298

def list(args)
	options = {}
	params = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts list"
		opts.on( '-g', '--group GROUP', "Group Name" ) do |group|
			options[:group] = group
		end
		
		build_common_options(opts, options, [:list, :json, :remote])
	end
	optparse.parse(args)
	connect(options)
	begin
		
		if !options[:group].nil?
			group = find_group_by_name(options[:group])
			if !group.nil?
				params['site'] = group['id']
			end
		end

		[:phrase, :offset, :max, :sort, :direction].each do |k|
			params[k] = options[k] unless options[k].nil?
		end

		json_response = @servers_interface.get(params)
		servers = json_response['servers']
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			print "\n" ,cyan, bold, "Morpheus Hosts\n","==================", reset, "\n\n"
			if servers.empty?
				puts yellow,"No hosts currently configured.",reset
			else
				

				server_table =servers.collect do |server|
					power_state = nil
					if server['powerState'] == 'on'
						power_state = "#{green}ON#{cyan}"
					elsif server['powerState'] == 'off'
						power_state = "#{red}OFF#{cyan}"
					else
						power_state = "#{white}#{server['powerState'].upcase}#{cyan}"
					end
					{id: server['id'], name: server['name'], platform: server['serverOs'] ? server['serverOs']['name'].upcase : 'N/A', type: server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged', status: server['status'], power: power_state}
					# print cyan, "= [#{server['id']}] #{server['name']} - #{server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged'} (#{server['status']}) Power: ", power_state, "\n"
				end
			end
			print cyan
			tp server_table, :id, :name, :type, :platform, :status, :power
			print reset,"\n\n"
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#logs(args) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/morpheus/cli/hosts.rb', line 71

def logs(args) 
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts logs [name]"
		build_common_options(opts, options, [:list, :json, :remote])
	end
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	optparse.parse(args)
	connect(options)
	begin
		host = find_host_by_name(args[0])
		logs = @logs_interface.server_logs([host['id']], { max: options[:max] || 100, offset: options[:offset] || 0, query: options[:phrase]})
		if options[:json]
			print JSON.pretty_generate(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



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/morpheus/cli/hosts.rb', line 227

def remove(args)
	options = {}
	query_params = {removeResources: 'on', force: 'off'}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts remove [name] [-c CLOUD] [-f] [-S]"
		opts.on( '-c', '--cloud CLOUD', "Cloud" ) do |cloud|
			options[:zone] = cloud
		end
		opts.on( '-f', '--force', "Force Remove" ) do
			query_params[:force] = 'on'
		end
		opts.on( '-S', '--skip-remove-infrastructure', "Skip removal of underlying cloud infrastructure" ) do
			query_params[:removeResources] = 'off'
		end
		
		build_common_options(opts, options, [:auto_confirm, :json, :remote])
	end
	optparse.parse(args)
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	connect(options)
	zone=nil
	if !options[:zone].nil?
		zone = find_zone_by_name(nil, options[:zone])
	end

	begin
		
		if zone 
			query_params[:zoneId] = zone['id']
		end
		server = nil
		server_results = @servers_interface.get({name: args[0]})
		if server_results['servers'].nil? || server_results['servers'].empty?
			server_results = @servers_interface.get(args[0].to_i)
			server = server_results['server']
		else
			if !server_results['servers'].empty? && server_results['servers'].count > 1
				puts "Multiple Servers exist with the same name. Try scoping by cloud or using id to confirm"
				exit 1
			end
			server = server_results['servers'][0] unless server_results['servers'].empty?
		end

		if server.nil?
			puts "Server not found by name #{args[0]}"
			exit 1
		else
			
		end
		
		unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove this server?", options)
			exit 1
		end

		json_response = @servers_interface.destroy(server['id'], query_params)
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			print_green_success "Removing Server..."
			list([])
		end
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#run_workflow(args) ⇒ Object



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

def run_workflow(args)
	options = {}
	
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts run-workflow [HOST] [name] [options]"
		build_common_options(opts, options, [:json, :remote])
	end
	if args.count < 2
		puts "\n#{optparse}\n\n"
		exit 1
	end
	
	optparse.parse(args)
	connect(options)
	host = find_host_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 = @servers_interface.workflow(host['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

#server_types(args) ⇒ Object



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

def server_types(args) 
	options = {zone: args[0]}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts server-types CLOUD"
		build_common_options(opts, options, [:json, :remote])
	end
	optparse.parse(args)
	if args.count < 1
		puts "\n#{optparse.banner}\n\n"
		exit 1
	end
	connect(options)
	params = {}
	
	zone=nil


	if !options[:zone].nil?
		zone = find_zone_by_name(nil, options[:zone])
	end

	if zone.nil?
		print_red_alert "Cloud not found"
		exit 1
	else
		zone_type = cloud_type_for_id(zone['zoneTypeId'])
	end
	cloud_server_types = zone_type['serverTypes'].select{|b| b['creatable'] == true}
	if options[:json]
		print JSON.pretty_generate(cloud_server_types)
		print "\n"
	else
		
		print "\n" ,cyan, bold, "Morpheus Server Types\n","==================", reset, "\n\n"
		if cloud_server_types.nil? || cloud_server_types.empty?
			puts yellow,"No server types found for the selected cloud.",reset
		else
			cloud_server_types.each do |server_type|
				print cyan, "=  #{server_type['code']} - #{server_type['name']}\n"
			end
		end
		print reset,"\n\n"
	end
end

#start(args) ⇒ Object



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

def start(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts 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
		host = find_host_by_name(args[0])
		json_response = @servers_interface.start(host['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Host #{host[name]} started."
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#stop(args) ⇒ Object



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/morpheus/cli/hosts.rb', line 388

def stop(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts stop [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
		host = find_host_by_name(args[0])
		json_response = @servers_interface.stop(host['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Host #{host[name]} stopped."
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end

#upgrade(args) ⇒ Object



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/morpheus/cli/hosts.rb', line 416

def upgrade(args)
	options = {}
	optparse = OptionParser.new do|opts|
		opts.banner = "Usage: morpheus hosts upgrade [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
		host = find_host_by_name(args[0])
		json_response = @servers_interface.upgrade(host['id'])
		if options[:json]
			print JSON.pretty_generate(json_response)
			print "\n"
		else
			puts "Host #{host[name]} upgrading..."
		end
		return
	rescue RestClient::Exception => e
		print_rest_exception(e, options)
		exit 1
	end
end