Class: Morpheus::Cli::ContainersCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProvisioningHelper

#api_client, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #get_available_clouds, #get_available_groups, included, #instance_context_options, #instance_types_interface, #instances_interface, #options_interface, #prompt_evars, #prompt_instance_load_balancer, #prompt_metadata, #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, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Instance Method Details

#_eject(container_id, options) ⇒ Object



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/morpheus/cli/containers_command.rb', line 332

def _eject(container_id, options)
  container = find_container_by_id(container_id) # could skip this since only id is supported
  return 1 if container.nil?
  if options[:dry_run]
    print_dry_run @containers_interface.dry.eject(container['id'])
    return 0
  end
  json_response = @containers_interface.eject(container['id'])
  # just assume json_response["success"] == true,  it always is with 200 OK
  if options[:json]
    puts as_json(json_response, options)
  elsif !options[:quiet]
    print green, "Ejecting container #{container['id']}", reset, "\n"
  end
  return 0
end

#_get(arg, options) ⇒ Object



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

def _get(arg, options)
  begin
    if options[:dry_run]
      print_dry_run @containers_interface.dry.get(arg.to_i)
      return
    end
    #container = find_container_by_id(arg)
    #return 1 if container.nil?
    json_response = @containers_interface.get(arg.to_i)
    if options[:json]
      puts as_json(json_response, options, "container")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "container")
      return 0
    end

    if options[:csv]
      puts records_as_csv([json_response['container']], options)
      return 0
    end
    container = json_response['container']
    # stats = json_response['stats'] || {}
    stats = container['stats'] || {}
    
    # load_balancers = stats = json_response['loadBalancers'] || {}

    # todo: show as 'VM' instead of 'Container' maybe..err
    # may need to fetch instance by id too..
    # ${[null,'docker'].contains(instance?.layout?.provisionType?.code) ? 'CONTAINERS' : 'VMs'}

    print_h1 "Container Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      #"Name" => 'name',
      "Name" => lambda {|it| it['server'] ? it['server']['name'] : '(no server)' }, # there is a server.displayName too?
      "Type" => lambda {|it| it['containerType'] ? it['containerType']['name'] : '' },
      "Plan" => lambda {|it| it['plan'] ? it['plan']['name'] : '' },
      "Instance" => lambda {|it| it['instance'] ? it['instance']['name'] : '' },
      "Cloud" => lambda {|it| it['cloud'] ? it['cloud']['name'] : '' },
      "Location" => lambda {|it| format_container_connection_string(it) },
      # "Description" => 'description',
      # "Group" => lambda {|it| it['group'] ? it['group']['name'] : '' },
      # "Cloud" => lambda {|it| it['cloud'] ? it['cloud']['name'] : '' },
      # "Type" => lambda {|it| it['instanceType']['name'] },
      # "Plan" => lambda {|it| it['plan'] ? it['plan']['name'] : '' },
      # "Environment" => 'instanceContext',
      # "Nodes" => lambda {|it| it['containers'] ? it['containers'].count : 0 },
      # "Connection" => lambda {|it| format_container_connection_string(it) },
      #"Account" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
      "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) },
      "Status" => lambda {|it| format_container_status(it) }
    }
    print_description_list(description_cols, container)

    if (stats)
      print_h2 "Container Usage"
      print_stats_usage(stats)
    end

    if options[:include_available_actions]
      if (container["availableActions"])
        print_h2 "Available Actions"
        print as_pretty_table(container["availableActions"], [:id, :name])
        print reset, "\n"
      else
        print "#{yellow}No available actions#{reset}\n\n"
      end
    end

    print reset, "\n"

    # refresh until a status is reached
    if options[:refresh_until_status]
      if options[:refresh_interval].nil? || options[:refresh_interval].to_f < 0
        options[:refresh_interval] = 5
      end
      while container['status'].to_s.downcase != options[:refresh_until_status].to_s.downcase
        print cyan
        print "Refreshing until status #{options[:refresh_until_status]} ..."
        sleep(options[:refresh_interval])
        _get(arg, options)
      end
    end

    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1 # , e
  end
end

#_restart(container_id, options) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/morpheus/cli/containers_command.rb', line 254

def _restart(container_id, options)
  container = find_container_by_id(container_id) # could skip this since only id is supported
  return 1 if container.nil?
  if options[:dry_run]
    print_dry_run @containers_interface.dry.restart(container['id'])
    return 0
  end
  json_response = @containers_interface.restart(container['id'])
  # just assume json_response["success"] == true,  it always is with 200 OK
  if options[:json]
    puts as_json(json_response, options)
  elsif !options[:quiet]
    print green, "Restarting container #{container['id']}", reset, "\n"
  end
  return 0
end

#_start(container_id, options) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/morpheus/cli/containers_command.rb', line 215

def _start(container_id, options)
  container = find_container_by_id(container_id) # could skip this since only id is supported
  return 1 if container.nil?
  if options[:dry_run]
    print_dry_run @containers_interface.dry.start(container['id'])
    return 0
  end
  json_response = @containers_interface.start(container['id'])
  # just assume json_response["success"] == true,  it always is with 200 OK
  if options[:json]
    puts as_json(json_response, options)
  elsif !options[:quiet]
    print green, "Starting container #{container['id']}", reset, "\n"
  end
  return 0
end

#_stop(container_id, options) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/morpheus/cli/containers_command.rb', line 176

def _stop(container_id, options)
  container = find_container_by_id(container_id) # could skip this since only id is supported
  return 1 if container.nil?
  if options[:dry_run]
    print_dry_run @containers_interface.dry.stop(container['id'])
    return 0
  end
  json_response = @containers_interface.stop(container['id'])
  # just assume json_response["success"] == true,  it always is with 200 OK
  if options[:json]
    puts as_json(json_response, options)
  elsif !options[:quiet]
    print green, "Stopping container #{container['id']}", reset, "\n"
  end
  return 0
end

#_suspend(container_id, options) ⇒ Object



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/morpheus/cli/containers_command.rb', line 293

def _suspend(container_id, options)
  container = find_container_by_id(container_id) # could skip this since only id is supported
  return 1 if container.nil?
  if options[:dry_run]
    print_dry_run @containers_interface.dry.suspend(container['id'])
    return 0
  end
  json_response = @containers_interface.suspend(container['id'])
  # just assume json_response["success"] == true,  it always is with 200 OK
  if options[:json]
    puts as_json(json_response, options)
  elsif !options[:quiet]
    print green, "Suspending container #{container['id']}", reset, "\n"
  end
  return 0
end

#action(args) ⇒ Object



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

def action(args)
  options = {}
  action_id = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id list] -a CODE")
    opts.on('-a', '--action CODE', "Container Action CODE to execute") do |val|
      action_id = val.to_s
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Execute an action for a container or containers"
  end
  optparse.parse!(args)
  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error "[id list] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  containers = []
  id_list.each do |container_id|
    container = find_container_by_id(container_id)
    if container.nil?
      # return 1
    else
      containers << container
    end
  end
  if containers.size != id_list.size
    #puts_error "containers not found"
    return 1
  end
  container_ids = containers.collect {|container| container["id"] }

  # figure out what action to run
  # assume that the action is available for all the containers..
  available_actions = containers.first['availableActions']
  if available_actions.empty?
    print_red_alert "Container #{container['id']} has no available actions"
    if container_ids.size > 1
      print_red_alert "The specified containers have no available actions in common"
    else
      print_red_alert "The specified container has no available actions"
    end
    return 1
  end
  container_action = nil
  if action_id.nil?
    available_actions_dropdown = available_actions.collect {|act| {'name' => act["name"], 'value' => act["code"]} } # already sorted
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'code', 'type' => 'select', 'fieldLabel' => 'Container Action', 'selectOptions' => available_actions_dropdown, 'required' => true, 'description' => 'Choose the container action to execute'}], options[:options])
    action_id = v_prompt['code']
    container_action = available_actions.find {|act| act['code'].to_s == action_id.to_s }
  else
    container_action = available_actions.find {|act| act['code'].to_s == action_id.to_s || act['name'].to_s.downcase == action_id.to_s.downcase }
    action_id = container_action["code"] if container_action
  end
  if !container_action
    # for testing bogus actions..
    # container_action = {"id" => action_id, "name" => "Unknown"}
    raise_command_error "Container Action '#{action_id}' not found."
  end

  action_display_name = "#{container_action['name']} [#{container_action['code']}]"
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to perform action #{action_display_name} on #{id_list.size == 1 ? 'container' : 'containers'} #{anded_list(id_list)}?", options)
    return 9, "aborted command"
  end

  # return run_command_for_each_arg(containers) do |arg|
  #   _action(arg, action_id, options)
  # end
  if options[:dry_run]
    print_dry_run @containers_interface.dry.action(container_ids, action_id)
    return 0
  end
  json_response = @containers_interface.action(container_ids, action_id)
  # just assume json_response["success"] == true,  it always is with 200 OK
  if options[:json]
    puts as_json(json_response, options)
  elsif !options[:quiet]
    # containers.each do |container|
    #   print green, "Action #{action_display_name} performed on container #{container['id']}", reset, "\n"
    # end
    print green, "Action #{action_display_name} performed on #{id_list.size == 1 ? 'container' : 'containers'} #{anded_list(id_list)}", reset, "\n"
  end
  return 0
end

#actions(args) ⇒ Object



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

def actions(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id list]")
    opts.footer = "This outputs the list of the actions available to specified container(s)."
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  id_list = parse_id_list(args)
  containers = []
  id_list.each do |container_id|
    container = find_container_by_id(container_id)
    if container.nil?
      # return 1
    else
      containers << container
    end
  end
  if containers.size != id_list.size
    #puts_error "containers not found"
    return 1
  end
  container_ids = containers.collect {|container| container["id"] }
  begin
    # container = find_container_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @containers_interface.dry.available_actions(container_ids)
      return 0
    end
    json_response = @containers_interface.available_actions(container_ids)
    if options[:json]
      puts as_json(json_response, options)
    else
      title = "Container Actions: #{anded_list(id_list)}"
      print_h1 title
      available_actions = json_response["actions"]
      if (available_actions && available_actions.size > 0)
        print as_pretty_table(available_actions, [:name, :code])
        print reset, "\n"
      else
        if container_ids.size > 1
          print "#{yellow}The specified containers have no available actions in common.#{reset}\n\n"
        else
          print "#{yellow}No available actions#{reset}\n\n"
        end
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



18
19
20
21
# File 'lib/morpheus/cli/containers_command.rb', line 18

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @containers_interface = @api_client.containers
end

#eject(args) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/morpheus/cli/containers_command.rb', line 310

def eject(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id list]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts_error "[id] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to eject #{id_list.size == 1 ? 'container' : 'containers'} #{anded_list(id_list)}?", options)
    return 9, "aborted command"
  end
  return run_command_for_each_arg(id_list) do |arg|
    _eject(arg, options)
  end
end

#get(args) ⇒ Object



27
28
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
# File 'lib/morpheus/cli/containers_command.rb', line 27

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( nil, '--actions', "Display Available Actions" ) do
      options[:include_available_actions] = true
    end
    opts.on('--refresh-until [status]', String, "Refresh until status is reached. Default status is running.") do |val|
      if val.to_s.empty?
        options[:refresh_until_status] = "running"
      else
        options[:refresh_until_status] = val.to_s.downcase
      end
    end
    opts.on('--refresh-interval seconds', String, "Refresh interval. Default is 5 seconds.") do |val|
      options[:refresh_interval] = val.to_f
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts_error "[id] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end

#handle(args) ⇒ Object



23
24
25
# File 'lib/morpheus/cli/containers_command.rb', line 23

def handle(args)
  handle_subcommand(args)
end

#restart(args) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/morpheus/cli/containers_command.rb', line 232

def restart(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id list]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts_error "[id] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart #{id_list.size == 1 ? 'container' : 'containers'} #{anded_list(id_list)}?", options)
    return 9, "aborted command"
  end
  return run_command_for_each_arg(id_list) do |arg|
    _restart(arg, options)
  end
end

#start(args) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/morpheus/cli/containers_command.rb', line 193

def start(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id list]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts_error "[id] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to start #{id_list.size == 1 ? 'container' : 'containers'} #{anded_list(id_list)}?", options)
    return 9, "aborted command"
  end
  return run_command_for_each_arg(id_list) do |arg|
    _start(arg, options)
  end
end

#stop(args) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/morpheus/cli/containers_command.rb', line 154

def stop(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id list]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts_error "[id] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop #{id_list.size == 1 ? 'container' : 'containers'} #{anded_list(id_list)}?", options)
    return 9, "aborted command"
  end
  return run_command_for_each_arg(id_list) do |arg|
    _stop(arg, options)
  end
end

#suspend(args) ⇒ Object



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/containers_command.rb', line 271

def suspend(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id list]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts_error "[id] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to suspend #{id_list.size == 1 ? 'container' : 'containers'} #{anded_list(id_list)}?", options)
    return 9, "aborted command"
  end
  return run_command_for_each_arg(id_list) do |arg|
    _suspend(arg, options)
  end
end