Class: Morpheus::Cli::Instances

Inherits:
Object
  • Object
show all
Includes:
CliCommand, ProvisioningHelper
Defined in:
lib/morpheus/cli/instances.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_name, #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, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeInstances

Returns a new instance of Instances.



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

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

Instance Method Details

#_get(arg, options = {}) ⇒ Object



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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/morpheus/cli/instances.rb', line 575

def _get(arg, options={})
  begin
    if options[:dry_run]
      if arg.to_s =~ /\A\d{1,}\Z/
        print_dry_run @instances_interface.dry.get(arg.to_i)
      else
        print_dry_run @instances_interface.dry.get({name:arg})
      end
      return
    end
    instance = find_instance_by_name_or_id(arg)
    json_response = @instances_interface.get(instance['id'])
    if options[:json]
      if options[:include_fields]
        json_response = {"instance" => filter_data(json_response["instance"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    elsif options[:yaml]
      if options[:include_fields]
        json_response = {"instance" => filter_data(json_response["instance"], options[:include_fields]) }
      end
      puts as_yaml(json_response, options)
      return 0
    end

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

    # containers are fetched via separate api call
    containers = nil
    if options[:include_containers]
      containers = @instances_interface.containers(instance['id'])['containers']
    end

    # threshold is fetched via separate api call too
    instance_threshold = nil
    if options[:include_scaling]
      instance_threshold = @instances_interface.threshold(instance['id'])['instanceThreshold']
    end

    # loadBalancers is returned via show
    # parse the current api format of loadBalancers.first.lbs.first
    current_instance_lb = nil
    current_load_balancer_port = nil
    # if options[:include_lb]
    #   #load_balancers = @instances_interface.load_balancers(instance['id'])['loadBalancers']
    # end
    if json_response['loadBalancers'] && json_response['loadBalancers'][0] && json_response['loadBalancers'][0]['lbs'] && json_response['loadBalancers'][0]['lbs'][0]
      current_instance_lb = json_response['loadBalancers'][0]['lbs'][0]
      #current_load_balancer = current_instance_lb['loadBalancer']
      #current_load_balancer_port = current_instance_lb['port']
    end

    print_h1 "Instance Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "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_instance_connection_string(it) },
      #"Account" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Status" => lambda {|it| format_instance_status(it) }
    }
    print_description_list(description_cols, instance)

    if instance['statusMessage']
      print_h2 "Status Message"
      if instance['status'] == 'failed'
        print red, instance['statusMessage'], reset
      else
        print instance['statusMessage']
      end
      print "\n"
    end
    if instance['errorMessage']
      print_h2 "Error Message"
      print red, instance['errorMessage'], reset
      print "\n"
    end
    if stats
      print_h2 "Instance Usage"
      print_stats_usage(stats)
    end
    print reset, "\n"

    if options[:include_containers]
      print_h2 "Instance Containers"

      if containers.empty?
        print yellow,"No containers found for instance.",reset,"\n"
      else

        rows = containers.collect {|container| 
          stats = container['stats']
          cpu_usage_str = !stats ? "" : generate_usage_bar((stats['usedCpu'] || stats['cpuUsage']).to_f, 100, {max_bars: 10})
          memory_usage_str = !stats ? "" : generate_usage_bar(stats['usedMemory'], stats['maxMemory'], {max_bars: 10})
          storage_usage_str = !stats ? "" : generate_usage_bar(stats['usedStorage'], stats['maxStorage'], {max_bars: 10})
          row = {
            id: container['id'],
            status: format_container_status(container),
            name: container['server'] ? container['server']['name'] : '(no server)', # there is a server.displayName too?
            type: container['containerType'] ? container['containerType']['name'] : '',
            cloud: container['cloud'] ? container['cloud']['name'] : '',
            location: format_container_connection_string(container),
            cpu: cpu_usage_str + cyan,
            memory: memory_usage_str + cyan,
            storage: storage_usage_str + cyan
          }
          row
        }
        columns = [:id, :status, :name, :type, :cloud, :location]
        term_width = current_terminal_width()
        if term_width > 190
          columns += [:cpu, :memory, :storage]
        end
        # custom pretty table columns ...
        if options[:include_fields]
          columns = options[:include_fields]
        end
        print cyan
        print as_pretty_table(rows, columns, options)
        print reset
        #print_results_pagination({size: containers.size, total: containers.size}) # mock pagination
      end
      print reset,"\n"
    end

    # if options[:include_lb]
    if current_instance_lb
      print_h2 "Load Balancer"
      print cyan
      # this api response is going to change again.. port is no longer returned atm.
      description_cols = {
        "LB ID" => lambda {|it| it['loadBalancer']['id'] },
        "Name" => lambda {|it| it['loadBalancer']['name'] },
        "Type" => lambda {|it| it['loadBalancer']['type'] ? it['loadBalancer']['type']['name'] : '' },
        "Host Name" => lambda {|it| it['loadBalancer']['host'] }, # instance.hostName ?
        "Port" => lambda {|it| it['port'] ? it['port']['port'] : '' },
        "Protocol" => lambda {|it| it['port'] ? it['port']['proxyProtocol'] : '' },
        "SSL Enabled" => lambda {|it| it['port'] ? format_boolean(it['port']['sslEnabled']) : '' },
        "Cert" => lambda {|it| (it['port'] && it['port']['sslCert']) ? it['port']['sslCert']['name'] : '' }
      }
      print_description_list(description_cols, current_instance_lb)
      print "\n", reset
    end
    # end

    if options[:include_scaling]
      print_h2 "Instance Scaling"
      if instance_threshold.nil? || instance_threshold.empty?
        print yellow,"No scaling settings applied to this instance.",reset,"\n"
      else
        print cyan
        print_instance_threshold_description_list(instance_threshold)
        print reset,"\n"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#_list_containers(arg, options) ⇒ Object



769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
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
# File 'lib/morpheus/cli/instances.rb', line 769

def _list_containers(arg, options)
  begin
    instance = find_instance_by_name_or_id(arg)
    return 1 if instance.nil?
    if options[:dry_run]
      print_dry_run @instances_interface.dry.containers(instance['id'], params)
      return
    end
    json_response = @instances_interface.containers(instance['id'])
    if options[:json]
      if options[:include_fields]
        json_response = {"containers" => filter_data(json_response["containers"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    elsif options[:yaml]
      if options[:include_fields]
        json_response = {"containers" => filter_data(json_response["containers"], options[:include_fields]) }
      end
      puts as_yaml(json_response, options)
      return 0
    end

    if options[:csv]
      puts records_as_csv(json_response['containers'], options)
      return 0
    end
    

    containers = json_response['containers']

    title = "Instance Containers: #{instance['name']} (#{instance['instanceType']['name']})"
    print_h1 title
    if containers.empty?
      print yellow,"No containers found for instance.",reset,"\n"
    else

      rows = containers.collect {|container| 
        stats = container['stats']
        cpu_usage_str = !stats ? "" : generate_usage_bar((stats['usedCpu'] || stats['cpuUsage']).to_f, 100, {max_bars: 10})
        memory_usage_str = !stats ? "" : generate_usage_bar(stats['usedMemory'], stats['maxMemory'], {max_bars: 10})
        storage_usage_str = !stats ? "" : generate_usage_bar(stats['usedStorage'], stats['maxStorage'], {max_bars: 10})
        row = {
          id: container['id'],
          status: format_container_status(container),
          name: container['server'] ? container['server']['name'] : '(no server)', # there is a server.displayName too?
          type: container['containerType'] ? container['containerType']['name'] : '',
          cloud: container['cloud'] ? container['cloud']['name'] : '',
          location: format_container_connection_string(container),
          cpu: cpu_usage_str + cyan,
          memory: memory_usage_str + cyan,
          storage: storage_usage_str + cyan
        }
        row
      }
      columns = [:id, :status, :name, :type, :cloud, :location]
      term_width = current_terminal_width()
      if term_width > 190
        columns += [:cpu, :memory, :storage]
      end
      # custom pretty table columns ...
      if options[:include_fields]
        columns = options[:include_fields]
      end
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      print_results_pagination({size: containers.size, total: containers.size}) # mock pagination
    end
    print reset,"\n"

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

#_scaling(arg, options) ⇒ Object



1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
# File 'lib/morpheus/cli/instances.rb', line 1913

def _scaling(arg, options)
  instance = find_instance_by_name_or_id(arg)
  return 1 if instance.nil?
  if options[:dry_run]
    print_dry_run @instances_interface.dry.threshold(instance['id'], params)
    return 0
  end
  json_response = @instances_interface.threshold(instance['id'])
  if options[:include_fields]
    json_response = {"instanceThreshold" => filter_data(json_response["instanceThreshold"], options[:include_fields]) }
  end
  if options[:json]
    puts as_json(json_response, options)
    return 0
  elsif options[:yaml]
    puts as_yaml(json_response, options)
    return 0
  elsif options[:csv]
    puts records_as_csv([json_response['instanceThreshold']], options)
    return 0
  end

  instance_threshold = json_response['instanceThreshold']

  title = "Instance Scaling: [#{instance['id']}] #{instance['name']} (#{instance['instanceType']['name']})"
  print_h1 title
  if instance_threshold.empty?
    print yellow,"No scaling settings applied to this instance.",reset,"\n"
  else
    # print_h1 "Threshold Settings"
    print cyan
    print_instance_threshold_description_list(instance_threshold)
  end
  print reset, "\n"
  return 0

end

#_stats(arg, options) ⇒ Object



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

def _stats(arg, options)
  begin
    instance = find_instance_by_name_or_id(arg)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.get(instance['id'])
      return 0
    end
    json_response = @instances_interface.get(instance['id'])
    if options[:json]
      puts as_json(json_response, options)
      return 0
    elsif options[:yaml]
      if options[:include_fields]
        json_response = {"stats" => filter_data(json_response["stats"], options[:include_fields]) }
      end
      puts as_yaml(json_response, options)
      return 0
    end
    instance = json_response['instance']
    stats = json_response['stats'] || {}
    title = "Instance Stats: #{instance['name']} (#{instance['instanceType']['name']})"
    print_h1 title
    puts cyan + "Status: ".rjust(12) + format_instance_status(instance).to_s
    puts cyan + "Nodes: ".rjust(12) + (instance['containers'] ? instance['containers'].count : '').to_s
    # print "\n"
    #print_h2 "Instance Usage"
    print_stats_usage(stats)
    print reset, "\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#action(args) ⇒ Object



1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
# File 'lib/morpheus/cli/instances.rb', line 1381

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', "Instance 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 instance or instances"
  end
  optparse.parse!(args)
  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error "[id] argument is required"
    puts_error optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  instances = []
  id_list.each do |instance_id|
    instance = find_instance_by_name_or_id(instance_id)
    if instance.nil?
      # return 1
    else
      instances << instance
    end
  end
  if instances.size != id_list.size
    #puts_error "instances not found"
    return 1
  end
  instance_ids = instances.collect {|instance| instance["id"] }

  # figure out what action to run
  available_actions = @instances_interface.available_actions(instance_ids)["actions"]
  if available_actions.empty?
    if instance_ids.size > 1
      print_red_alert "The specified instances have no available actions in common."
    else
      print_red_alert "The specified instance has no available actions."
    end
    return 1
  end
  instance_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' => 'Instance Action', 'selectOptions' => available_actions_dropdown, 'required' => true, 'description' => 'Choose the instance action to execute'}], options[:options])
    action_id = v_prompt['code']
    instance_action = available_actions.find {|act| act['code'].to_s == action_id.to_s }
  else
    instance_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 = instance_action["code"] if instance_action
  end
  if !instance_action
    # for testing bogus actions..
    # instance_action = {"id" => action_id, "name" => "Unknown"}
    raise_command_error "Instance Action '#{action_id}' not found."
  end

  action_display_name = "#{instance_action['name']} [#{instance_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 ? 'instance' : 'instances'} #{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 @instances_interface.dry.action(instance_ids, action_id)
    return 0
  end
  json_response = @instances_interface.action(instance_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 ? 'instance' : 'instances'} #{anded_list(id_list)}", reset, "\n"
  end
  return 0
end

#actions(args) ⇒ Object



1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
# File 'lib/morpheus/cli/instances.rb', line 1325

def actions(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id or name list]")
    opts.footer = "This outputs the list of the actions available to specified instance(s)."
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} actions requires argument [id or name list]\n#{optparse}"
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  instances = []
  id_list.each do |instance_id|
    instance = find_instance_by_name_or_id(instance_id)
    if instance.nil?
      # return 1
    else
      instances << instance
    end
  end
  if instances.size != id_list.size
    #puts_error "instances not found"
    return 1
  end
  instance_ids = instances.collect {|instance| instance["id"] }
  begin
    # instance = find_instance_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @instances_interface.dry.available_actions(instance_ids)
      return 0
    end
    json_response = @instances_interface.available_actions(instance_ids)
    if options[:json]
      puts as_json(json_response, options)
    else
      title = "Instance 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
        print "#{yellow}No available actions#{reset}\n\n"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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
# File 'lib/morpheus/cli/instances.rb', line 183

def add(args)
  options = {}
  optparse = OptionParser.new do|opts|
    # opts.banner = subcommand_usage("[type] [name]")
    opts.banner = subcommand_usage("[name] -c CLOUD -t TYPE")
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    opts.on( '-t', '--type CODE', "Instance Type" ) do |val|
      options[:instance_type_code] = val
    end
    opts.on("--copies NUMBER", Integer, "Number of copies to provision") do |val|
      options[:copies] = val.to_i
    end
    opts.on("--layout-size NUMBER", Integer, "Apply a multiply factor of containers/vms within the instance") do |val|
      options[:layout_size] = val.to_i
    end
    opts.on("--workflow ID", String, "Automation: Workflow ID") do |val|
      options[:workflow_id] = val.to_i
    end
    # opts.on('-L', "--lb", "Enable Load Balancer") do
    #   options[:enable_load_balancer] = true
    # end
    opts.on("--shutdown-days NUMBER", Integer, "Automation: Shutdown Days") do |val|
      options[:expire_days] = val.to_i
    end
    opts.on("--expire-days NUMBER", Integer, "Automation: Expiration Days") do |val|
      options[:expire_days] = val.to_i
    end
    opts.on("--create-backup on|off", String, "Automation: Create Backups.  Default is off") do |val|
      options[:create_backup] = ['on','true','1'].include?(val.to_s.downcase) ? 'on' : 'off'
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
  end

  optparse.parse!(args)
  connect(options)

  if args.count > 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} add has just 1 (optional) argument: [name].  Got #{args.count} arguments: #{args.join(' ')}\n#{optparse}"
    return 1
  end
  if args[0]
    options[:instance_name] = args[0]
  end

  # use active group by default
  options[:group] ||= @active_group_id

  options[:name_required] = true
  begin
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # prompt for all the instance configuration options
      # this provisioning helper method handles all (most) of the parsing and prompting
      # and it relies on the method to exit non-zero on error, like a bad CLOUD or TYPE value
      payload = prompt_new_instance(options)
      # other stuff
      payload[:copies] = options[:copies] if options[:copies] && options[:copies] > 0
      payload[:layoutSize] = options[:layout_size] if options[:layout_size] && options[:layout_size] > 0 # aka Scale Factor
      payload[:createBackup] = options[:create_backup] ? 'on' : 'off' if options[:create_backup] == true
      payload['instance']['expireDays'] = options[:expire_days] if options[:expire_days]
      payload['instance']['shutdownDays'] = options[:shutdown_days] if options[:shutdown_days]
      if options[:workflow_id]
        payload['taskSetId'] = options[:workflow_id]
      end
      if options[:enable_load_balancer]
        lb_payload = prompt_instance_load_balancer(payload['instance'], nil, options)
        payload.deep_merge!(lb_payload)
      end
    end

    if options[:dry_run]
      print_dry_run @instances_interface.dry.create(payload)
      return 0
    end

    json_response = @instances_interface.create(payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      instance_id = json_response["instance"]["id"]
      instance_name = json_response["instance"]["name"]
      print_green_success "Provisioning instance [#{instance_id}] #{instance_name}"
      get([instance_id])
      #list([])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#apply_security_groups(args) ⇒ Object



1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
# File 'lib/morpheus/cli/instances.rb', line 1734

def apply_security_groups(args)
  options = {}
  security_group_ids = nil
  clear_or_secgroups_specified = false
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [-S] [-c]")
    opts.on( '-S', '--secgroups SECGROUPS', "Apply the specified comma separated security group ids" ) do |secgroups|
      security_group_ids = secgroups.split(",")
      clear_or_secgroups_specified = true
    end
    opts.on( '-c', '--clear', "Clear all security groups" ) do
      security_group_ids = []
      clear_or_secgroups_specified = true
    end
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  if !clear_or_secgroups_specified
    puts optparse
    exit
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    payload = {securityGroupIds: security_group_ids}
    if options[:dry_run]
      print_dry_run @instances_interface.dry.apply_security_groups(instance['id'], payload)
      return
    end
    json_response = @instances_interface.apply_security_groups(instance['id'], payload)
    if options[:json]
      print as_json(json_response, options), "\n"
      return
    end
    if !options[:quiet]
      security_groups([args[0]])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#backup(args) ⇒ Object



1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
# File 'lib/morpheus/cli/instances.rb', line 1543

def backup(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to backup the instance '#{instance['name']}'?", options)
      exit 1
    end
    if options[:dry_run]
      print_dry_run @instances_interface.dry.backup(instance['id'])
      return
    end
    json_response = @instances_interface.backup(instance['id'])
    if options[:json]
      puts as_json(json_response, options)
      return 0
    else
      puts "Backup initiated."
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#backups(args) ⇒ Object



846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
# File 'lib/morpheus/cli/instances.rb', line 846

def backups(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    params = {}
    if options[:dry_run]
      print_dry_run @instances_interface.dry.backups(instance['id'], params)
      return
    end
    json_response = @instances_interface.backups(instance['id'], params)
    if options[:json]
      puts as_json(json_response, options)
      return
    end
    backups = json_response['backups']

    print_h1 "Instance Backups: #{instance['name']} (#{instance['instanceType']['name']})"
    backup_rows = backups.collect {|r| 
      it = r['backup']
      {id: it['id'], name: it['name'], dateCreated: format_local_dt(it['dateCreated'])}
    }
    print cyan
    puts as_pretty_table backup_rows, [
      :id,
      :name,
      {:dateCreated => {:display_name => "Date Created"} }
    ]
    print reset, "\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#clone(args) ⇒ Object



890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
# File 'lib/morpheus/cli/instances.rb', line 890

def clone(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] -g GROUP")
    build_option_type_options(opts, options, clone_instance_option_types(false))
    opts.on( '-g', '--group GROUP', "Group Name or ID for the new instance" ) do |val|
      options[:group] = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  if !options[:group]
    print_red_alert "GROUP is required."
    puts optparse
    exit 1
  end
  connect(options)
  begin
    options[:options] ||= {}
    # use the -g GROUP or active group by default
    options[:options]['group'] ||= options[:group] # || @active_group_id # always choose a group for now?
    # support [new-name] 
    # if args[1]
    #   options[:options]['name'] = args[1]
    # end
    payload = {

    }
    params = Morpheus::Cli::OptionTypes.prompt(clone_instance_option_types, options[:options], @api_client, options[:params])
    group = find_group_by_name_or_id_for_provisioning(params.delete('group'))
    payload.merge!(params)
    payload['group'] = {id: group['id']}

    instance = find_instance_by_name_or_id(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to clone the instance '#{instance['name']}'?", options)
      exit 1
    end
    
    if options[:dry_run]
      print_dry_run @instances_interface.dry.clone(instance['id'], payload)
      return
    end
    json_response = @instances_interface.clone(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Cloning instance #{instance['name']} to '#{payload['name']}'"
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/morpheus/cli/instances.rb', line 23

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @instances_interface = @api_client.instances
  @task_sets_interface = @api_client.task_sets
  @logs_interface = @api_client.logs
  @tasks_interface = @api_client.tasks
  @instance_types_interface = @api_client.instance_types
  @clouds_interface = @api_client.clouds
  @servers_interface = @api_client.servers
  @provision_types_interface = @api_client.provision_types
  @options_interface = @api_client.options
  @active_group_id = Morpheus::Cli::Groups.active_group
end

#console(args) ⇒ Object



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

def console(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '-n', '--node NODE_ID', "Scope console to specific Container or VM" ) do |node_id|
      options[:node_id] = node_id.to_i
    end
    build_common_options(opts, options, [:remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)

  begin
    instance = find_instance_by_name_or_id(args[0])
    link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/terminal/#{instance['id']}"
    container_ids = instance['containers']
    if options[:node_id] && container_ids.include?(options[:node_id])
      link += "?containerId=#{options[:node_id]}"
    end

    if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
      system "start #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /darwin/
      system "open #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
      system "xdg-open #{link}"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#delenv(args) ⇒ Object



1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'lib/morpheus/cli/instances.rb', line 1031

def delenv(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] VAR")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @instances_interface.dry.del_env(instance['id'], args[1])
      return
    end
    json_response = @instances_interface.del_env(instance['id'], args[1])
    if options[:json]
      puts as_json(json_response, options)
      return
    end
    if !options[:quiet]
      envs([args[0]])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#eject(args) ⇒ Object



1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
# File 'lib/morpheus/cli/instances.rb', line 1195

def eject(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    # unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to eject this instance?", options)
    #   exit 1
    # end
    if options[:dry_run]
      print_dry_run @instances_interface.dry.eject(instance['id'])
      return
    end
    json_response = @instances_interface.eject(instance['id'])
    if options[:json]
      puts as_json(json_response, options)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#envs(args) ⇒ Object



950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
# File 'lib/morpheus/cli/instances.rb', line 950

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

#firewall_disable(args) ⇒ Object



1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
# File 'lib/morpheus/cli/instances.rb', line 1627

def firewall_disable(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @instances_interface.dry.firewall_disable(instance['id'])
      return
    end
    json_response = @instances_interface.firewall_disable(instance['id'])
    if options[:json]
      print as_json(json_response, options), "\n"
      return
    elsif !options[:quiet]
      security_groups([args[0]])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#firewall_enable(args) ⇒ Object



1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
# File 'lib/morpheus/cli/instances.rb', line 1658

def firewall_enable(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @instances_interface.dry.firewall_enable(instance['id'])
      return
    end
    json_response = @instances_interface.firewall_enable(instance['id'])
    if options[:json]
      print as_json(json_response, options), "\n"
      return
    elsif !options[:quiet]
      security_groups([args[0]])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( nil, '--containers', "Display Instance Containers" ) do
      options[:include_containers] = true
    end
    opts.on( nil, '--nodes', "Alias for --containers" ) do
      options[:include_containers] = true
    end
    opts.on( nil, '--vms', "Alias for --containers" ) do
      options[:include_containers] = true
    end
    opts.on( nil, '--scaling', "Display Instance Scaling Settings" ) do
      options[:include_scaling] = true
    end
    # opts.on( nil, '--threshold', "Alias for --scaling" ) do
    #   options[:include_scaling] = true
    # end
    opts.on( nil, '--lb', "Display Load Balancer Details" ) do
      options[:include_lb] = true
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 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



37
38
39
# File 'lib/morpheus/cli/instances.rb', line 37

def handle(args)
  handle_subcommand(args)
end

#import_snapshot(args) ⇒ Object



1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
# File 'lib/morpheus/cli/instances.rb', line 1837

def import_snapshot(args)
  options = {}
  storage_provider_id = nil
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    opts.on("--storage-provider ID", String, "Optional storage provider") do |val|
      storage_provider_id = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to import a snapshot of the instance '#{instance['name']}'?", options)
      exit 1
    end

    payload = {}

    # Prompt for Storage Provider, use default value.
    begin
      options[:options] ||= {}
      options[:options]['storageProviderId'] = storage_provider_id if storage_provider_id
      storage_provider_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'storageProviderId', 'type' => 'select', 'fieldLabel' => 'Storage Provider', 'optionSource' => 'storageProviders', 'required' => false, 'description' => 'Select Storage Provider.'}], options[:options], @api_client, {})
      if !storage_provider_prompt['storageProviderId'].empty?
        payload['storageProviderId'] = storage_provider_prompt['storageProviderId']
      end
    rescue RestClient::Exception => e
      puts "Failed to load storage providers"
      #print_rest_exception(e, options)
      exit 1
    end

    if options[:dry_run]
      print_dry_run @instances_interface.dry.import_snapshot(instance['id'], payload)
      return
    end
    json_response = @instances_interface.import_snapshot(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      puts "Snapshot import initiated."
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list(args) ⇒ Object



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
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
173
174
175
176
177
178
179
180
181
# File 'lib/morpheus/cli/instances.rb', line 41

def list(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    opts.on( '-H', '--host HOST', "Host Name or ID" ) do |val|
      options[:host] = val
    end
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    group = options[:group] ? find_group_by_name_or_id_for_provisioning(options[:group]) : nil
    if group
      params['siteId'] = group['id']
    end

    # argh, this doesn't work because group_id is required for options/clouds
    # cloud = options[:cloud] ? find_cloud_by_name_or_id_for_provisioning(group_id, options[:cloud]) : nil
    cloud = options[:cloud] ? find_zone_by_name_or_id(nil, options[:cloud]) : nil
    if cloud
      params['zoneId'] = cloud['id']
    end

    host = options[:host] ? find_host_by_name_or_id(options[:host]) : options[:host]
    if host
      params['serverId'] = host['id']
    end

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

    if options[:dry_run]
      print_dry_run @instances_interface.dry.list(params)
      return
    end
    json_response = @instances_interface.get(params)
    if options[:json]
      if options[:include_fields]
        json_response = {"instances" => filter_data(json_response["instances"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    elsif options[:yaml]
      if options[:include_fields]
        json_response = {"instances" => filter_data(json_response["instances"], options[:include_fields]) }
      end
      puts as_yaml(json_response, options)
      return 0
    elsif options[:csv]
      # merge stats to be nice here..
      if json_response['instances']
        all_stats = json_response['stats'] || {}
        json_response['instances'].each do |it|
          it['stats'] ||= all_stats[it['id'].to_s] || all_stats[it['id']]
        end
      end
      puts records_as_csv(json_response['instances'], options)
    else
      instances = json_response['instances']

      title = "Morpheus Instances"
      subtitles = []
      if group
        subtitles << "Group: #{group['name']}".strip
      end
      if cloud
        subtitles << "Cloud: #{cloud['name']}".strip
      end
      if host
        subtitles << "Host: #{host['name']}".strip
      end
      if params[:phrase]
        subtitles << "Search: #{params[:phrase]}".strip
      end
      print_h1 title, subtitles
      if instances.empty?
        print yellow,"No instances found.",reset,"\n"
      else
        # print_instances_table(instances)
        # server returns stats in a separate key stats => {"id" => {} }
        # the id is a string right now..for some reason..
        all_stats = json_response['stats'] || {} 
        instances.each do |it|
          if !it['stats']
            found_stats = all_stats[it['id'].to_s] || all_stats[it['id']]
            it['stats'] = found_stats # || {}
          end
        end

        rows = instances.collect {|instance| 
          stats = instance['stats']
          cpu_usage_str = !stats ? "" : generate_usage_bar((stats['usedCpu'] || stats['cpuUsage']).to_f, 100, {max_bars: 10})
          memory_usage_str = !stats ? "" : generate_usage_bar(stats['usedMemory'], stats['maxMemory'], {max_bars: 10})
          storage_usage_str = !stats ? "" : generate_usage_bar(stats['usedStorage'], stats['maxStorage'], {max_bars: 10})
          row = {
            id: instance['id'],
            name: instance['name'],
            connection: format_instance_connection_string(instance),
            environment: instance['instanceContext'],
            nodes: instance['containers'].count,
            status: format_instance_status(instance, cyan),
            type: instance['instanceType']['name'],
            group: !instance['group'].nil? ? instance['group']['name'] : nil,
            cloud: !instance['cloud'].nil? ? instance['cloud']['name'] : nil,
            version: instance['instanceVersion'] ? instance['instanceVersion'] : '',
            cpu: cpu_usage_str + cyan,
            memory: memory_usage_str + cyan,
            storage: storage_usage_str + cyan
          }
          row
        }
        columns = [:id, :name, :group, :cloud, :type, :version, :environment, :nodes, {:connection => {max_width: 30}}, :status]
        term_width = current_terminal_width()
        if term_width > 190
          columns += [:cpu, :memory, :storage]
        end
        # custom pretty table columns ...
        if options[:include_fields]
          columns = options[:include_fields]
        end
        print cyan
        print as_pretty_table(rows, columns, options)
        print reset
        print_results_pagination(json_response)
      end
      print reset,"\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_containers(args) ⇒ Object



751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
# File 'lib/morpheus/cli/instances.rb', line 751

def list_containers(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _list_containers(arg, options)
  end
end

#load_balancer_remove(args) ⇒ Object



2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
# File 'lib/morpheus/cli/instances.rb', line 2155

def load_balancer_remove(args)
  usage = "Usage: morpheus instances lb-remove [name] [options]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_option_type_options(opts, options, instance_scaling_option_types(nil))
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Remove a load balancer from an instance."
  end
  optparse.parse!(args)
  # if args.count < 1
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} lb-remove requires only one argument [id or name]\n#{optparse}"
    return 1
  end
  connect(options)

  begin

    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?

    # re-fetch via show() get loadBalancers
    json_response = @instances_interface.get(instance['id'])
    load_balancers = json_response['instance']['loadBalancers']

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the load balancer for instance '#{instance['name']}'?", options)
      return 9, "aborted command"
    end
    
    # no options here, just send DELETE request
    payload = {}

    if options[:dry_run]
      print_dry_run @instances_interface.dry.remove_load_balancer(instance['id'], payload)
      return
    end
    json_response = @instances_interface.remove_load_balancer(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Removed load balancer from instance #{instance['name']}"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#load_balancer_update(args) ⇒ Object



2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
# File 'lib/morpheus/cli/instances.rb', line 2072

def load_balancer_update(args)
  raise "Not Yet Implemented"
  usage = "Usage: morpheus instances lb-update [name] [options]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    #build_option_type_options(opts, options, instance_load_balancer_option_types(nil))
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
    opts.footer = "Assign a load balancer for an instance."
  end
  optparse.parse!(args)
  # if args.count < 1
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} lb-update requires only one argument [id or name]\n#{optparse}"
    return 1
  end
  connect(options)

  begin

    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
    # refetch to get loadBalancers from show()
    json_response = @instances_interface.get(instance['id'])

    current_instance_lb = nil
    # refetch to get current load balancer info from show()
    json_response = @instances_interface.get(instance['id'])
    #load_balancers = @instances_interface.threshold(instance['id'])['loadBalancers'] || {}
    if json_response['loadBalancers'] && json_response['loadBalancers'][0] && json_response['loadBalancers'][0]['lbs'] && json_response['loadBalancers'][0]['lbs'][0]
      current_instance_lb = json_response['loadBalancers'][0]['lbs'][0]
      #current_load_balancer = current_instance_lb['loadBalancer']
      #current_load_balancer_port = current_instance_lb['port']
    end

    #my_option_types = instance_load_balancer_option_types(instance)

    # todo...

    # Host Name
    # Load Balancer
    # Protocol
    # Port
    # SSL Cert
    # Scheme

    current_instance_lb = json_response['loadBalancers'][0]['lbs'][0]

    params = {}

    payload = {
      'instance' => {},
      'networkLoadBalancer' => {}
    }

    cur_host_name = instance['hostName']
    #host_name = params = Morpheus::Cli::OptionTypes.prompt([{'fieldName'=>'hostName', 'label'=>'Host Name', 'defaultValue'=>cur_host_name}], options[:options], @api_client, {})
    payload['instance']['hostName'] = instance['hostName']

    #payload['loadBalancerId'] = params['loadBalancerId']

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to update the load balancer for instance '#{instance['name']}'?", options)
      return 9, "aborted command"
    end
    
    if options[:dry_run]
      print_dry_run @instances_interface.dry.update_load_balancer(instance['id'], payload)
      return
    end
    json_response = @instances_interface.update_load_balancer(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Updated scaling settings for instance #{instance['name']}"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#logs(args) ⇒ Object



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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/morpheus/cli/instances.rb', line 467

def logs(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '-n', '--node NODE_ID', "Scope logs to specific Container or VM" ) do |node_id|
      options[:node_id] = node_id.to_i
    end
    build_common_options(opts, options, [:list, :json, :csv, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    container_ids = instance['containers']
    if options[:node_id] && container_ids.include?(options[:node_id])
      container_ids = [options[:node_id]]
    end
    params = {}
    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    if options[:dry_run]
      print_dry_run @logs_interface.dry.container_logs(container_ids, params)
      return
    end
    logs = @logs_interface.container_logs(container_ids, params)
    output = ""
    if options[:json]
      puts as_json(logs, options)
      return 0
    else
      title = "Instance Logs: #{instance['name']} (#{instance['instanceType'] ? instance['instanceType']['name'] : ''})"
      subtitles = []
      if params[:query]
        subtitles << "Search: #{params[:query]}".strip
      end
      # todo: startMs, endMs, sorts insteaad of sort..etc
      print_h1 title, subtitles
      if logs['data'].empty?
        puts "#{cyan}No logs found.#{reset}"
      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'].to_s.strip}"
        end
        print output, reset, "\n"
        return 0
      end
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
# File 'lib/morpheus/cli/instances.rb', line 1578

def remove(args)
  options = {}
  query_params = {keepBackups: 'off', force: 'off'}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [-fB]")
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'on'
    end
    opts.on( '-B', '--keep-backups', "Preserve copy of backups" ) do
      query_params[:keepBackups] = 'on'
    end
    opts.on('--remove-volumes [on|off]', ['on','off'], "Remove Volumes. Default is on. Applies to certain types only.") do |val|
      query_params[:removeVolumes] = val
    end
    opts.on('--releaseEIPs [on|off]', ['on','off'], "Release EIPs. Default is false. Applies to Amazon only.") do |val|
      query_params[:releaseEIPs] = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])

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

#resize(args) ⇒ Object



1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
# File 'lib/morpheus/cli/instances.rb', line 1467

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

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

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

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

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

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

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

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

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

    if options[:dry_run]
      print_dry_run @instances_interface.dry.resize(instance['id'], payload)
      return
    end
    json_response = @instances_interface.resize(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    else
      print_green_success "Resizing instance #{instance['name']}"
      #list([])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#restart(args) ⇒ Object



1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
# File 'lib/morpheus/cli/instances.rb', line 1129

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

#restart_service(args) ⇒ Object



1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
# File 'lib/morpheus/cli/instances.rb', line 1291

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

#run_workflow(args) ⇒ Object



1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
# File 'lib/morpheus/cli/instances.rb', line 1782

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

  if params.empty? && !editable_options.empty?
    puts optparse
    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
    if options[:dry_run]
      print_dry_run @instances_interface.dry.workflow(instance['id'],workflow['id'], workflow_payload)
      return
    end
    json_response = @instances_interface.workflow(instance['id'],workflow['id'], workflow_payload)
    if options[:json]
      print as_json(json_response, options), "\n"
      return
    else
      puts "Running workflow..."
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#scaling(args) ⇒ Object



1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
# File 'lib/morpheus/cli/instances.rb', line 1893

def scaling(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Show scaling threshold information for an instance."
  end
  optparse.parse!(args)
  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} scaling requires argument [id or name list]\n#{optparse}"
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _scaling(arg, options)
  end
end

#scaling_update(args) ⇒ Object



1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
# File 'lib/morpheus/cli/instances.rb', line 1951

def scaling_update(args)
  usage = "Usage: morpheus instances scaling-update [name] [options]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_option_type_options(opts, options, instance_scaling_option_types(nil))
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
    opts.footer = "Update scaling threshold information for an instance."
  end
  optparse.parse!(args)
  # if args.count < 1
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} scaling-update requires only one argument [id or name]\n#{optparse}"
    return 1
  end
  connect(options)

  begin

    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
    instance_threshold = @instances_interface.threshold(instance['id'])['instanceThreshold'] || {}
    my_option_types = instance_scaling_option_types(instance)

    # preserve current values by setting the prompt options defaultValue attribute
    # note: checkbox type converts true,false to 'on','off'
    my_option_types.each do |opt|
      field_key = opt['fieldName'] # .sub('instanceThreshold.', '')
      if instance_threshold[field_key] != nil
        opt['defaultValue'] = instance_threshold[field_key]
      end
    end
    
    # params = Morpheus::Cli::OptionTypes.prompt(my_option_types, options[:options], @api_client, {})

    # ok, gotta split these inputs into sections with conditional logic
    params = {}

    option_types_group = my_option_types.select {|opt| ['autoUp', 'autoDown'].include?(opt['fieldName']) }
    params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})

    option_types_group = my_option_types.select {|opt| ['zoneId'].include?(opt['fieldName']) }
    params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})
    if params['zoneId']
      if params['zoneId'] == '' || params['zoneId'] == 'null' || params['zoneId'].to_s == '0'
        params['zoneId'] = 0
      else
        params['zoneId'] = params['zoneId'].to_i
      end
    end

    option_types_group = my_option_types.select {|opt| ['minCount', 'maxCount'].include?(opt['fieldName']) }
    params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})

    option_types_group = my_option_types.select {|opt| ['memoryEnabled'].include?(opt['fieldName']) }
    params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})
    if params['memoryEnabled'] == 'on' || params['memoryEnabled'] == true
      option_types_group = my_option_types.select {|opt| ['minMemory', 'maxMemory'].include?(opt['fieldName']) }
      params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})
    else
      params['minMemory'] = nil
      params['maxMemory'] = nil
    end

    option_types_group = my_option_types.select {|opt| ['diskEnabled'].include?(opt['fieldName']) }
    params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})
    if params['diskEnabled'] == 'on' || params['diskEnabled'] == true
      option_types_group = my_option_types.select {|opt| ['minDisk', 'maxDisk'].include?(opt['fieldName']) }
      params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})
    else
      params['minDisk'] = nil
      params['maxDisk'] = nil
    end

    option_types_group = my_option_types.select {|opt| ['cpuEnabled'].include?(opt['fieldName']) }
    params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})
    if params['cpuEnabled'] == 'on' || params['cpuEnabled'] == true
      option_types_group = my_option_types.select {|opt| ['minCpu', 'maxCpu'].include?(opt['fieldName']) }
      params.merge! Morpheus::Cli::OptionTypes.prompt(option_types_group, options[:options], @api_client, {})
    else
      params['minCpu'] = nil
      params['maxCpu'] = nil
    end

    # argh, convert on/off to true/false
    # this needs a global solution...
    params.each do |k,v|
      if v == 'on' || v == 'true' || v == 'yes'
        params[k] = true
      elsif v == 'off' || v == 'false' || v == 'no'
        params[k] = false
      end
    end      

    payload = {
      'instanceThreshold' => {}
    }
    payload['instanceThreshold'].merge!(params)

    # unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to update the scaling settings for instance '#{instance['name']}'?", options)
    #   return 9, "aborted command"
    # end
    
    if options[:dry_run]
      print_dry_run @instances_interface.dry.update_threshold(instance['id'], payload)
      return
    end
    json_response = @instances_interface.update_threshold(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Updated scaling settings for instance #{instance['name']}"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#security_groups(args) ⇒ Object



1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
# File 'lib/morpheus/cli/instances.rb', line 1689

def security_groups(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @instances_interface.dry.security_groups(instance['id'])
      return
    end
    json_response = @instances_interface.security_groups(instance['id'])
    if options[:json]
      print as_json(json_response, options), "\n"
      return
    end
    securityGroups = json_response['securityGroups']
    print_h1 "Morpheus Security Groups for Instance: #{instance['name']}"
    print cyan
    print_description_list({"Firewall Enabled" => lambda {|it| format_boolean it['firewallEnabled'] } }, json_response)
    #print cyan, "Firewall Enabled=#{json_response['firewallEnabled']}\n\n"
    if securityGroups.empty?
      print yellow,"\n","No security groups currently applied.",reset,"\n"
    else
      print "\n"
      securityGroups.each do |securityGroup|
        print cyan, "=  #{securityGroup['id']} (#{securityGroup['name']}) - (#{securityGroup['description']})\n"
      end
      print "\n"
    end
    print reset, "\n"

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

#setenv(args) ⇒ Object



990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
# File 'lib/morpheus/cli/instances.rb', line 990

def setenv(args)
  options = {}

  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] VAR VALUE [-e]")
    opts.on( '-e', "Exportable" ) do |exportable|
      options[:export] = exportable
    end
    opts.on( '-M', "Masked" ) do |masked|
      options[:masked] = masked
    end
    build_common_options(opts, options, [:json, :dry_run, :remote, :quiet])
  end
  optparse.parse!(args)
  if args.count < 3
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    evar = {name: args[1], value: args[2], export: options[:export], masked: options[:masked]}
    payload = {envs: [evar]}
    if options[:dry_run]
      print_dry_run @instances_interface.dry.create_env(instance['id'], payload)
      return
    end
    json_response = @instances_interface.create_env(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
      return
    end
    if !options[:quiet]
      envs([args[0]])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#start(args) ⇒ Object



1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
# File 'lib/morpheus/cli/instances.rb', line 1097

def start(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @instances_interface.dry.start(instance['id'])
      return 0
    end
    json_response = @instances_interface.start(instance['id'])
    if options[:json]
      puts as_json(json_response, options)
      return 0
    elsif !options[:quiet]
      print green, "Starting instance #{instance['name']}", reset, "\n"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#start_service(args) ⇒ Object



1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
# File 'lib/morpheus/cli/instances.rb', line 1261

def start_service(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:quiet, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @instances_interface.dry.start(instance['id'], false)
      return 0
    end
    json_response = @instances_interface.start(instance['id'],false)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print green, "Starting service on instance #{instance['name']}", reset, "\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#stats(args) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/morpheus/cli/instances.rb', line 377

def stats(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  ids = args
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _stats(arg, options)
  end
end

#status_check(args) ⇒ Object



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/morpheus/cli/instances.rb', line 344

def status_check(args)
  out = ""
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:quiet, :json, :remote]) # no :dry_run, just do it man
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  # todo: just return status or maybe check if instance['status'] == args[0]
  instance = find_instance_by_name_or_id(args[0])
  exit_code = 0
  if instance['status'].to_s.downcase != (args[1] || "running").to_s.downcase
    exit_code = 1
  end
  if options[:json]
    mock_json = {status: instance['status'], exit: exit_code}
    out << as_json(mock_json, options)
    out << "\n"
  elsif !options[:quiet]
    out << cyan
    out << "Status: #{format_instance_status(instance)}"
    out << reset
    out << "\n"
  end
  print out unless options[:quiet]
  exit exit_code #return exit_code
end

#stop(args) ⇒ Object



1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
# File 'lib/morpheus/cli/instances.rb', line 1063

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

#stop_service(args) ⇒ Object



1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# File 'lib/morpheus/cli/instances.rb', line 1227

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

#suspend(args) ⇒ Object



1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
# File 'lib/morpheus/cli/instances.rb', line 1163

def suspend(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to suspend this instance?", options)
      exit 1
    end
    if options[:dry_run]
      print_dry_run @instances_interface.dry.suspend(instance['id'])
      return
    end
    json_response = @instances_interface.suspend(instance['id'])
    if options[:json]
      puts as_json(json_response, options)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/morpheus/cli/instances.rb', line 283

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

  begin

    instance = find_instance_by_name_or_id(args[0])

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

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

    params = options[:options] || {}

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

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

    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Updated instance #{instance['name']}"
      #list([])
    end

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