Class: Morpheus::Cli::ContainersCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, LogsHelper, 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 LogsHelper

#clusters_interface, #containers_interface, #format_log_level, #format_log_records, #format_log_table, included, #instances_interface, #logs_interface, #servers_interface

Methods included from ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_host_by_id, #find_host_by_name, #find_host_by_name_or_id, #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, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_resize_volumes, #prompt_security_groups, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Instance Method Details

#_eject(container_id, options) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/morpheus/cli/containers_command.rb', line 357

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?
  @containers_interface.setopts(options)
  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



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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/morpheus/cli/containers_command.rb', line 65

def _get(arg, options)
  begin
    @containers_interface.setopts(options)
    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'] : '' },
      # "Cost" => lambda {|it| it['hourlyCost'] ? format_money(it['hourlyCost'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
      # "Price" => lambda {|it| it['hourlyPrice'] ? format_money(it['hourlyPrice'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
      "Instance" => lambda {|it| it['instance'] ? it['instance']['name'] : '' },
      "Host" => lambda {|it| it['server'] ? it['server']['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"], [:name, :code])
        print reset, "\n"
      else
        print "#{yellow}No available actions#{reset}\n\n"
      end
    end

    if options[:include_costs]
      print_h2 "Container Cost"
      cost_columns = {
        "Cost" => lambda {|it| it['hourlyCost'] ? format_money(it['hourlyCost'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
        "Price" => lambda {|it| it['hourlyPrice'] ? format_money(it['hourlyPrice'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
      }
      print_description_list(cost_columns, container)
    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] = default_refresh_interval
      end
      statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
      if !statuses.include?(container['status'])
        print cyan
        print cyan, "Refreshing in #{options[:refresh_interval] > 1 ? options[:refresh_interval].to_i : options[:refresh_interval]} seconds"
        sleep_with_dots(options[:refresh_interval])
        print "\n"
        _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



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/morpheus/cli/containers_command.rb', line 277

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?
  @containers_interface.setopts(options)
  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



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

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?
  @containers_interface.setopts(options)
  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



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 197

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?
  @containers_interface.setopts(options)
  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



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/morpheus/cli/containers_command.rb', line 317

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?
  @containers_interface.setopts(options)
  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



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/morpheus/cli/containers_command.rb', line 435

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
  @containers_interface.setopts(options)
  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



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/morpheus/cli/containers_command.rb', line 375

def actions(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id list]")
    opts.footer = "List 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])
    @containers_interface.setopts(options)
    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



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

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @containers_interface = @api_client.containers
  @logs_interface = @api_client.logs
  @execution_request_interface = @api_client.execution_request
end

#eject(args) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/morpheus/cli/containers_command.rb', line 335

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

#execution_request(args) ⇒ Object



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

def execution_request(args)
  options = {}
  params = {}
  script_content = nil
  do_refresh = true
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id] [options]")
    opts.on('--script SCRIPT', "Script to be executed" ) do |val|
      script_content = val
    end
    opts.on('--file FILE', "File containing the script. This can be used instead of --script" ) do |filename|
      full_filename = File.expand_path(filename)
      if File.exists?(full_filename)
        script_content = File.read(full_filename)
      else
        print_red_alert "File not found: #{full_filename}"
        exit 1
      end
    end
    opts.on(nil, '--no-refresh', "Do not refresh until finished" ) do
      do_refresh = false
    end
    #build_option_type_options(opts, options, add_user_source_option_types())
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
    opts.footer = "Execute an arbitrary command or script on a container." + "\n" +
                  "[id] is required. This is the id a container." + "\n" +
                  "[script] is required. This is the script that is to be executed."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  
  
  begin
    container = find_container_by_id(args[0])
    return 1 if container.nil?
    params['containerId'] = container['id']
    # construct payload
    payload = {}
    if options[:payload]
      payload = options[:payload]
    else
      payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      # prompt for Script
      if script_content.nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'script', 'type' => 'code-editor', 'fieldLabel' => 'Script', 'required' => true, 'description' => 'The script content'}], options[:options])
        script_content = v_prompt['script']
      end
      payload['script'] = script_content
    end
    @execution_request_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execution_request_interface.dry.create(params, payload)
      return 0
    end
    # do it
    json_response = @execution_request_interface.create(params, payload)
    # print and return result
    if options[:quiet]
      return 0
    elsif options[:json]
      puts as_json(json_response, options)
      return 0
    end
    execution_request = json_response['executionRequest']
    print_green_success "Executing request #{execution_request['uniqueId']}"
    if do_refresh
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId'], "--refresh"]+ (options[:remote] ? ["-r",options[:remote]] : []))
    else
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId']]+ (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/morpheus/cli/containers_command.rb', line 31

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    opts.on( nil, '--actions', "Display Available Actions" ) do
      options[:include_available_actions] = true
    end
    opts.on( nil, '--costs', "Display Cost and Price" ) do
      options[:include_costs] = true
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until status is running,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_until_status] ||= "running,failed"
      if !val.to_s.empty?
        options[:refresh_interval] = val.to_f
      end
    end
    opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
      options[:refresh_until_status] = val.to_s.downcase
    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



27
28
29
# File 'lib/morpheus/cli/containers_command.rb', line 27

def handle(args)
  handle_subcommand(args)
end

#logs(args) ⇒ Object



524
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/morpheus/cli/containers_command.rb', line 524

def logs(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    opts.on('--start TIMESTAMP','--start TIMESTAMP', "Start timestamp. Default is 30 days ago.") do |val|
      options[:start] = parse_time(val) #.utc.iso8601
    end
    opts.on('--end TIMESTAMP','--end TIMESTAMP', "End timestamp. Default is now.") do |val|
      options[:end] = parse_time(val) #.utc.iso8601
    end
    opts.on('--level VALUE', String, "Log Level. DEBUG,INFO,WARN,ERROR") do |val|
      params['level'] = params['level'] ? [params['level'], val].flatten : [val]
    end
    opts.on('--table', '--table', "Format ouput as a table.") do
      options[:table] = true
    end
    opts.on('-a', '--all', "Display all details: entire message." ) do
      options[:details] = true
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List logs for a container.\n" +
                  "[id] is required. This is the id of a container."
  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)
  begin
    containers = id_list # heh
    params['level'] = params['level'].collect {|it| it.to_s.upcase }.join('|') if params['level'] # api works with INFO|WARN
    params.merge!(parse_list_options(options))
    params['query'] = params.delete('phrase') if params['phrase']
    params[:order] = params[:direction] unless params[:direction].nil? # old api version expects order instead of direction
    params['startMs'] = (options[:start].to_i * 1000) if options[:start]
    params['endMs'] = (options[:end].to_i * 1000) if options[:end]
    @logs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @logs_interface.dry.container_logs(containers, params)
      return
    end
    json_response = @logs_interface.container_logs(containers, params)
    render_result = json_response['logs'] ? render_with_format(json_response, options, 'logs') : render_with_format(json_response, options, 'data')
    return 0 if render_result

    logs = json_response
    title = "Container Logs: #{containers.join(', ')}"
    subtitles = parse_list_subtitles(options)
    if options[:start]
      subtitles << "Start: #{options[:start]}".strip
    end
    if options[:end]
      subtitles << "End: #{options[:end]}".strip
    end
    if params[:query]
      subtitles << "Search: #{params[:query]}".strip
    end
    if params['level']
      subtitles << "Level: #{params['level']}"
    end
    logs = json_response['data'] || json_response['logs']
    print_h1 title, subtitles, options
    if logs.empty?
      print "#{cyan}No logs found.#{reset}\n"
    else
      print format_log_records(logs, options)
      print_results_pagination({'meta'=>{'total'=>(json_response['total']['value'] rescue json_response['total']),'size'=>logs.size,'max'=>(json_response['max'] || options[:max]),'offset'=>(json_response['offset'] || options[:offset] || 0)}})
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#restart(args) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/morpheus/cli/containers_command.rb', line 255

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



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

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



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

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



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/morpheus/cli/containers_command.rb', line 295

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