Class: Morpheus::Cli::Instances

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProcessesHelper

#format_process_duration, #format_process_error, #format_process_output, #format_process_status, included

Methods included from ProvisioningHelper

#api_client, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #get_available_clouds, #get_available_groups, included, #instance_context_options, #instance_types_interface, #instances_interface, #options_interface, #prompt_evars, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_resize_volumes, #prompt_volumes, #reject_networking_option_types, #reject_service_plan_option_types, #reject_volume_option_types

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeInstances

Returns a new instance of Instances.



22
23
24
# File 'lib/morpheus/cli/instances.rb', line 22

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

Instance Method Details

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



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
845
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
889
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
948
949
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
# File 'lib/morpheus/cli/instances.rb', line 778

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]
      puts as_json(json_response, options, "instance")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "instance")
      return 0
    end

    if options[:csv]
      puts records_as_csv([json_response['instance']], options)
      return 0
    end
    instance = json_response['instance']
    stats = 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
    if instance["currentLoadBalancerInstances"]
      current_instance_lb = instance['currentLoadBalancerInstances'][0]
    end

    # support old format
    if !current_instance_lb && 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']
    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'] },
      "Layout" => lambda {|it| it['layout'] ? it['layout']['name'] : '' },
      "Version" => lambda {|it| it['instanceVersion'] },
      "Plan" => lambda {|it| it['plan'] ? it['plan']['name'] : '' },
      "Environment" => 'instanceContext',
      "Tags" => lambda {|it| it['tags'] ? it['tags'].join(',') : '' },
      "Metadata" => lambda {|it| it['metadata'] ? it['metadata'].collect {|m| "#{m['name']}: #{m['value']}" }.join(', ') : '' },
      "Power Schedule" => lambda {|it| (it['powerSchedule'] && it['powerSchedule']['type']) ? it['powerSchedule']['type']['name'] : '' },
      "Created By" => lambda {|it| it['createdBy'] ? (it['createdBy']['username'] || it['createdBy']['id']) : '' },
      "Date Created" => lambda {|it| format_local_dt(it['dateCreated']) },
      "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, "\n"
    end
    if !instance['notes'].to_s.empty?
      print_h2 "Instance Notes"
      print cyan, instance['notes'], reset, "\n"
    end
    if stats
      print_h2 "Instance Usage"
      print_stats_usage(stats)
    end
    print reset, "\n"

    # if options[:include_lb]
    if current_instance_lb
      print_h2 "Load Balancer"
      print cyan
      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['vipHostname'] || instance['hostName'] },
        "Port" => lambda {|it| it['vipPort'] },
        "Protocol" => lambda {|it| it['vipProtocol'] || 'tcp' },
        "SSL Enabled" => lambda {|it| format_boolean(it['sslEnabled']) },
        "SSL Cert" => lambda {|it| (it['sslCert']) ? it['sslCert']['name'] : '' },
        "In" => lambda {|it| instance['currentLoadBalancerContainersIn'] },
        "Out" => lambda {|it| instance['currentLoadBalancerContainersOutrelo'] }
      }
      print_description_list(description_cols, current_instance_lb)
      print "\n", reset
    end
    # end

    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_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

    # refresh until a status is reached
    if options[:refresh_until_status]
      if options[:refresh_interval].nil? || options[:refresh_interval].to_f < 0
        options[:refresh_interval] = 5
      end
      statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
      if !statuses.include?(instance['status'])
        print cyan
        print "Status is #{instance['status'] || 'unknown'}. Refreshing in #{options[:refresh_interval]} seconds"
        #sleep(options[:refresh_interval])
        sleep_with_dots(options[:refresh_interval])
        print "\n"
        _get(arg, options)
      end
    end

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

#_list_containers(arg, options) ⇒ Object



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

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]
      puts as_json(json_response, options, "containers")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "containers")
      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



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

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[:json]
    puts as_json(json_response, options, "instanceThreshold")
    return 0
  elsif options[:yaml]
    puts as_yaml(json_response, options, "instanceThreshold")
    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



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

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, "stats")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "stats")
      return 0
    end
    instance = json_response['instance']
    stats = 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



1623
1624
1625
1626
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
1657
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
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
# File 'lib/morpheus/cli/instances.rb', line 1623

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



1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
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
# File 'lib/morpheus/cli/instances.rb', line 1567

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



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
282
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
343
344
345
346
347
348
349
350
351
352
# File 'lib/morpheus/cli/instances.rb', line 211

def add(args)
  options = {}
  options[:create_user] = true
  optparse = Morpheus::Cli::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( '--name NAME', "Instance Name" ) do |val|
      options[:instance_name] = 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
    end
    # opts.on('-L', "--lb", "Enable Load Balancer") do
    #   options[:enable_load_balancer] = true
    # end
    opts.on("--create-user on|off", String, "User Config: Create Your User. Default is on") do |val|
      options[:create_user] = !['false','off','0'].include?(val.to_s)
    end
    opts.on("--user-group USERGROUP", String, "User Config: User Group") do |val|
      options[:user_group_id] = val
    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])
    opts.footer = "Create a new instance." + "\n" +
                  "[name] is required. This is the new instance name." + "\n" +
                  "The available options vary by --type."
  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]
      # support -O OPTION switch on top of --payload
      payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
    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)
      # clean payload of empty objects 
      # note: this is temporary and should be fixed upstream in OptionTypes.prompt()
      if payload['instance'].is_a?(Hash)
        payload['instance'].keys.each do |k|
          v = payload['instance'][k]
          payload['instance'].delete(k) if v.is_a?(Hash) && v.empty?
        end
      end
      if payload['config'].is_a?(Hash)
        payload['config'].keys.each do |k|
          v = payload['config'][k]
          payload['config'].delete(k) if v.is_a?(Hash) && v.empty?
        end
      end
    end

    if options[:instance_name]
      payload['instance'] ||= payload['instance']
      payload['instance']['name'] = options[:instance_name]
    end
    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.key?(:create_user)
      payload['config']['createUser'] = options[:create_user]
    end
    if options[:user_group_id]
      payload['instance']['userGroup'] = {'id' => options[:user_group_id] }
    end
    if options[:workflow_id]
      if options[:workflow_id].to_s =~ /\A\d{1,}\Z/
        payload['taskSetId'] = options[:workflow_id].to_i
      else
        payload['taskSetName'] = options[:workflow_id]
      end
    end
    if options[:enable_load_balancer]
      lb_payload = prompt_instance_load_balancer(payload['instance'], nil, options)
      payload.deep_merge!(lb_payload)
    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



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

def apply_security_groups(args)
  options = {}
  security_group_ids = nil
  clear_or_secgroups_specified = false
  optparse = Morpheus::Cli::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



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

def backup(args)
  options = {}
  optparse = Morpheus::Cli::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



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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
# File 'lib/morpheus/cli/instances.rb', line 1065

def backups(args)
  options = {}
  optparse = Morpheus::Cli::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



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
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
1162
1163
1164
1165
1166
# File 'lib/morpheus/cli/instances.rb', line 1109

def clone(args)
  options = {}
  optparse = Morpheus::Cli::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



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/morpheus/cli/instances.rb', line 26

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
  @execution_request_interface = @api_client.execution_request
end

#console(args) ⇒ Object



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

def console(args)
  options = {}
  optparse = Morpheus::Cli::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

#count(args) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/morpheus/cli/instances.rb', line 182

def count(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[options]")
    build_common_options(opts, options, [:query, :remote, :dry_run])
    opts.footer = "Get the number of instances."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
    if options[:dry_run]
      print_dry_run @instances_interface.dry.list(params)
      return
    end
    json_response = @instances_interface.list(params)
    # print number only
    if json_response['meta'] && json_response['meta']['total']
      print cyan, json_response['meta']['total'], reset, "\n"
    else
      print yellow, "unknown", reset, "\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#delenv(args) ⇒ Object



1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
# File 'lib/morpheus/cli/instances.rb', line 1250

def delenv(args)
  options = {}
  optparse = Morpheus::Cli::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



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

def eject(args)
  params = {'server' => true}
  options = {}
  optparse = Morpheus::Cli::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'], params)
      return
    end
    json_response = @instances_interface.eject(instance['id'], params)
    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



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
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
# File 'lib/morpheus/cli/instances.rb', line 1169

def envs(args)
  options = {}
  optparse = Morpheus::Cli::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

#execution_request(args) ⇒ Object



2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
# File 'lib/morpheus/cli/instances.rb', line 2759

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 script or command on an instance." + "\n" +
                  "[id] is required. This is the id or name of an instance." + "\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
    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
    params['instanceId'] = instance['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
    # dry run?
    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"])
    else
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#firewall_disable(args) ⇒ Object



1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
# File 'lib/morpheus/cli/instances.rb', line 1873

def firewall_disable(args)
  options = {}
  optparse = Morpheus::Cli::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



1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
# File 'lib/morpheus/cli/instances.rb', line 1904

def firewall_enable(args)
  options = {}
  optparse = Morpheus::Cli::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



730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'lib/morpheus/cli/instances.rb', line 730

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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('--refresh [status]', String, "Refresh until status is reached. Default status is running.") do |val|
      if val.to_s.empty?
        options[:refresh_until_status] = "running,failed"
      else
        options[:refresh_until_status] = val.to_s.downcase
      end
    end
    opts.on('--refresh-interval seconds', String, "Refresh interval. Default is 5 seconds.") do |val|
      options[:refresh_interval] = val.to_f
    end
    # 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])
    opts.footer = "Get details about an instance.\n" + 
                  "[instance] is required. This is the name or id of an instance. Supports 1-N [instance] arguments."
  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



41
42
43
# File 'lib/morpheus/cli/instances.rb', line 41

def handle(args)
  handle_subcommand(args)
end

#history(args) ⇒ Object



2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
# File 'lib/morpheus/cli/instances.rb', line 2450

def history(args)
  raw_args = args.dup
  options = {}
  #options[:show_output] = true
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    # opts.on( '-n', '--node NODE_ID', "Scope history to specific Container or VM" ) do |node_id|
    #   options[:node_id] = node_id.to_i
    # end
    opts.on( nil, '--events', "Display sub processes (events)." ) do
      options[:show_events] = true
    end
    opts.on( nil, '--output', "Display process output." ) do
      options[:show_output] = true
    end
    opts.on('--process-id ID', String, "Display details about a specfic process only." ) do |val|
      options[:process_id] = val
    end
    opts.on('--event-id ID', String, "Display details about a specfic process event only." ) do |val|
      options[:event_id] = val
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List historical processes for a specific instance.\n" + 
                  "[instance] is required. This is the name or id of an instance."
  end
  optparse.parse!(args)

  # shortcut to other actions
  if options[:process_id]
    return history_details(raw_args)
  elsif options[:event_id]
    return history_event_details(raw_args)
  end

  if args.count != 1
    puts optparse
    return 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 = {}
    params.merge!(parse_list_options(options))
    # params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    if options[:dry_run]
      print_dry_run @instances_interface.dry.history(instance['id'], params)
      return
    end
    json_response = @instances_interface.history(instance['id'], params)
    if options[:json]
      puts as_json(json_response, options, "processes")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "processes")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['processes'], options)
      return 0
    else

      title = "Instance History: #{instance['name']}"
      subtitles = []
      if params[:query]
        subtitles << "Search: #{params[:query]}".strip
      end
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      if json_response['processes'].empty?
        print "#{cyan}No process history found.#{reset}\n\n"
      else
        history_records = []
        json_response["processes"].each do |process|
          row = {
            id: process['id'],
            eventId: nil,
            uniqueId: process['uniqueId'],
            name: process['displayName'],
            description: process['description'],
            processType: process['processType'] ? (process['processType']['name'] || process['processType']['code']) : process['processTypeName'],
            createdBy: process['createdBy'] ? (process['createdBy']['displayName'] || process['createdBy']['username']) : '',
            startDate: format_local_dt(process['startDate']),
            duration: format_process_duration(process),
            status: format_process_status(process),
            error: format_process_error(process),
            output: format_process_output(process)
          }
          history_records << row
          process_events = process['events'] || process['processEvents']
          if options[:show_events]
            if process_events
              process_events.each do |process_event|
                event_row = {
                  id: process['id'],
                  eventId: process_event['id'],
                  uniqueId: process_event['uniqueId'],
                  name: process_event['displayName'], # blank like the UI
                  description: process_event['description'],
                  processType: process_event['processType'] ? (process_event['processType']['name'] || process_event['processType']['code']) : process['processTypeName'],
                  createdBy: process_event['createdBy'] ? (process_event['createdBy']['displayName'] || process_event['createdBy']['username']) : '',
                  startDate: format_local_dt(process_event['startDate']),
                  duration: format_process_duration(process_event),
                  status: format_process_status(process_event),
                  error: format_process_error(process_event),
                  output: format_process_output(process_event)
                }
                history_records << event_row
              end
            else
              
            end
          end
        end
        columns = [
          {:id => {:display_name => "PROCESS ID"} },
          :name, 
          :description, 
          {:processType => {:display_name => "PROCESS TYPE"} },
          {:createdBy => {:display_name => "CREATED BY"} },
          {:startDate => {:display_name => "START DATE"} },
          {:duration => {:display_name => "ETA/DURATION"} },
          :status, 
          :error
        ]
        if options[:show_events]
          columns.insert(1, {:eventId => {:display_name => "EVENT ID"} })
        end
        if options[:show_output]
          columns << :output
        end
        # custom pretty table columns ...
        if options[:include_fields]
          columns = options[:include_fields]
        end
        print cyan
        print as_pretty_table(history_records, columns, options)
        #print_results_pagination(json_response)
        print_results_pagination(json_response, {:label => "process", :n_label => "processes"})
        print reset, "\n"
        return 0
      end
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#history_details(args) ⇒ Object



2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
# File 'lib/morpheus/cli/instances.rb', line 2601

def history_details(args)
  options = {}
  process_id = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [process-id]")
    opts.on('--process-id ID', String, "Display details about a specfic event." ) do |val|
      options[:process_id] = val
    end
    opts.add_hidden_option('process-id')
    build_common_options(opts, options, [:query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display history details for a specific process.\n" + 
                  "[instance] is required. This is the name or id of an instance.\n" +
                  "[process-id] is required. This is the id of the process."
  end
  optparse.parse!(args)
  if args.count == 2
    process_id = args[1]
  elsif args.count == 1 && options[:process_id]
    process_id = options[:process_id]
  else
    puts_error optparse
    return 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    params = {}
    params.merge!(parse_list_options(options))
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    if options[:dry_run]
      print_dry_run @instances_interface.dry.history_details(instance['id'], process_id, params)
      return
    end
    json_response = @instances_interface.history_details(instance['id'], process_id, params)
    if options[:json]
      puts as_json(json_response, options, "process")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "process")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['process'], options)
      return 0
    else
      process = json_response["process"]
      title = "Instance History Details"
      subtitles = []
      subtitles << " Process ID: #{process_id}"
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      print_process_details(process)

      print_h2 "Process Events"
      process_events = process['events'] || process['processEvents'] || []
      history_records = []
      if process_events.empty?
        puts "#{cyan}No events found.#{reset}"
      else      
        process_events.each do |process_event|
          event_row = {
                  id: process_event['id'],
                  eventId: process_event['id'],
                  uniqueId: process_event['uniqueId'],
                  name: process_event['displayName'], # blank like the UI
                  description: process_event['description'],
                  processType: process_event['processType'] ? (process_event['processType']['name'] || process_event['processType']['code']) : process['processTypeName'],
                  createdBy: process_event['createdBy'] ? (process_event['createdBy']['displayName'] || process_event['createdBy']['username']) : '',
                  startDate: format_local_dt(process_event['startDate']),
                  duration: format_process_duration(process_event),
                  status: format_process_status(process_event),
                  error: format_process_error(process_event),
                  output: format_process_output(process_event)
                }
          history_records << event_row
        end
        columns = [
          {:id => {:display_name => "EVENT ID"} },
          :name, 
          :description, 
          {:processType => {:display_name => "PROCESS TYPE"} },
          {:createdBy => {:display_name => "CREATED BY"} },
          {:startDate => {:display_name => "START DATE"} },
          {:duration => {:display_name => "ETA/DURATION"} },
          :status, 
          :error,
          :output
        ]
        print cyan
        print as_pretty_table(history_records, columns, options)
        print_results_pagination({size: process_events.size, total: process_events.size})
        print reset, "\n"
        return 0
      end
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#history_event_details(args) ⇒ Object



2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
# File 'lib/morpheus/cli/instances.rb', line 2701

def history_event_details(args)
  options = {}
  process_event_id = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [event-id]")
    opts.on('--event-id ID', String, "Display details about a specfic event." ) do |val|
      options[:event_id] = val
    end
    opts.add_hidden_option('event-id')
    build_common_options(opts, options, [:query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display history details for a specific process event.\n" + 
                  "[instance] is required. This is the name or id of an instance.\n" +
                  "[event-id] is required. This is the id of the process event."
  end
  optparse.parse!(args)
  if args.count == 2
    process_event_id = args[1]
  elsif args.count == 1 && options[:event_id]
    process_event_id = options[:event_id]
  else
    puts_error optparse
    return 1
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    params = {}
    params.merge!(parse_list_options(options))
    if options[:dry_run]
      print_dry_run @instances_interface.dry.history_event_details(instance['id'], process_event_id, params)
      return
    end
    json_response = @instances_interface.history_event_details(instance['id'], process_event_id, params)
    if options[:json]
      puts as_json(json_response, options, "processEvent")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "processEvent")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['processEvent'], options)
      return 0
    else
      process_event = json_response['processEvent'] || json_response['event']
      title = "Instance History Event"
      subtitles = []
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      print_process_event_details(process_event)
      print reset, "\n"
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#import_snapshot(args) ⇒ Object



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

def import_snapshot(args)
  options = {}
  storage_provider_id = nil
  optparse = Morpheus::Cli::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



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

def list(args)
  options = {}
  optparse = Morpheus::Cli::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, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List instances."
  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

    params.merge!(parse_list_options(options))

    if options[:dry_run]
      print_dry_run @instances_interface.dry.list(params)
      return
    end
    json_response = @instances_interface.list(params)
    if options[:json]
      puts as_json(json_response, options, "instances")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "instances")
      return 0
    elsif options[:csv]
      # merge stats to be nice here..
      if json_response['instances']
        all_stats = json_response['stats'] || {}
        if all_stats
          json_response['instances'].each do |it|
            it['stats'] ||= all_stats[it['id'].to_s] || all_stats[it['id']]
          end
        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
      subtitles += parse_list_subtitles(options)
      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'] || {} 
        if all_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
        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 => {:max_width => 50}}, :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



976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
# File 'lib/morpheus/cli/instances.rb', line 976

def list_containers(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])
  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



2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
# File 'lib/morpheus/cli/instances.rb', line 2399

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



2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
# File 'lib/morpheus/cli/instances.rb', line 2317

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']
    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



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

def logs(args)
  options = {}
  optparse = Morpheus::Cli::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, :query, :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 = {}
    params.merge!(parse_list_options(options))
    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



1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
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
# File 'lib/morpheus/cli/instances.rb', line 1820

def remove(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '-B', '--keep-backups', "Preserve copy of backups" ) do
      query_params[:keepBackups] = 'on'
    end
    opts.on('--preserve-volumes [on|off]', ['on','off'], "Preserve Volumes. Default is off. Applies to certain types only.") do |val|
      query_params[:preserveVolumes] = val
    end
    opts.on('--releaseEIPs [on|off]', ['on','off'], "Release EIPs. Default is on. Applies to Amazon only.") do |val|
      query_params[:releaseEIPs] = val
    end
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'on'
    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
    # JD: removeVolumes to maintain the old behavior with pre-3.5.2 appliances, remove me later
    if query_params[:preserveVolumes].nil?
      query_params[:removeVolumes] = 'on'
    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



1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
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
1780
1781
1782
1783
# File 'lib/morpheus/cli/instances.rb', line 1709

def resize(args)
  options = {}
  optparse = Morpheus::Cli::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



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
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
# File 'lib/morpheus/cli/instances.rb', line 1353

def restart(args)
  params = {'server' => true, 'muteMonitoring' => true}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--muteMonitoring [on|off]', String, "Mute monitoring. Default is on.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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'], params)
      return 0
    end
    json_response = @instances_interface.restart(instance['id'], params)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print green, "Restarting 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



1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
# File 'lib/morpheus/cli/instances.rb', line 1529

def restart_service(args)
  params = {'server' => false, 'muteMonitoring' => true}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--muteMonitoring [on|off]', String, "Mute monitoring. Default is on.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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'], params)
      return 0
    end
    json_response = @instances_interface.restart(instance['id'], params)
    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



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
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
# File 'lib/morpheus/cli/instances.rb', line 2028

def run_workflow(args)
  options = {}
  optparse = Morpheus::Cli::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_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 2 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 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 = {}
  params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if 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
      print_green_success "Running workflow #{workflow['name']} on instance #{instance['name']} ..."
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#scaling(args) ⇒ Object



2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
# File 'lib/morpheus/cli/instances.rb', line 2141

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



2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
# File 'lib/morpheus/cli/instances.rb', line 2196

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



1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
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
# File 'lib/morpheus/cli/instances.rb', line 1935

def security_groups(args)
  options = {}
  optparse = Morpheus::Cli::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



1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
# File 'lib/morpheus/cli/instances.rb', line 1209

def setenv(args)
  options = {}

  optparse = Morpheus::Cli::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



1320
1321
1322
1323
1324
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
# File 'lib/morpheus/cli/instances.rb', line 1320

def start(args)
  params = {'server' => true}
  options = {}
  optparse = Morpheus::Cli::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'], params)
      return 0
    end
    json_response = @instances_interface.start(instance['id'], params)
    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



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

def start_service(args)
  params = {'server' => true}
  options = {}
  optparse = Morpheus::Cli::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'], params)
      return 0
    end
    json_response = @instances_interface.start(instance['id'], params)
    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



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

def stats(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])
  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



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

def status_check(args)
  out = ""
  options = {}
  optparse = Morpheus::Cli::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



1282
1283
1284
1285
1286
1287
1288
1289
1290
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
# File 'lib/morpheus/cli/instances.rb', line 1282

def stop(args)
  params = {'server' => true, 'muteMonitoring' => false}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--muteMonitoring [on|off]', String, "Mute monitoring. Default is off.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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'], params)
      return
    end
    json_response = @instances_interface.stop(instance['id'], params)
    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



1460
1461
1462
1463
1464
1465
1466
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
# File 'lib/morpheus/cli/instances.rb', line 1460

def stop_service(args)
  params = {'server' => false, 'muteMonitoring' => false}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--muteMonitoring [on|off]', String, "Mute monitoring. Default is off.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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'], params)
      return 0
    end
    json_response = @instances_interface.stop(instance['id'], params)
    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



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

def suspend(args)
  params = {'server' => true, 'muteMonitoring' => false}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--muteMonitoring [on|off]', String, "Mute monitoring. Default is off.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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'], params)
      return
    end
    json_response = @instances_interface.suspend(instance['id'], params)
    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



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
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
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
# File 'lib/morpheus/cli/instances.rb', line 354

def update(args)
  usage = "Usage: morpheus instances update [name] [options]"
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name") do |val|
      params['displayName'] = val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('--environment VALUE', String, "Environment") do |val|
      params['instanceContext'] = val
    end
    opts.on('--group GROUP', String, "Group Name or ID") do |val|
      options[:group] = val
    end
    opts.on('--metadata LIST', String, "Metadata in the format 'name:value, name:value'") do |val|
      options[:metadata] = val
    end
    opts.on('--tags LIST', String, "Tags") do |val|
      params['tags'] = val
      # params['tags'] = val.split(',').collect {|it| it.to_s.strip }.compact.uniq
    end
    opts.on('--power-schedule-type ID', String, "Power Schedule Type ID") do |val|
      params['powerScheduleType'] = val == "null" ? nil : val
    end
    opts.on('--created-by ID', String, "Created By User ID") do |val|
      params['createdById'] = val
    end
    build_common_options(opts, options, [:options, :payload, :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])
    return 1 if instance.nil?
    new_group = nil
    if options[:group]
      new_group = find_group_by_name_or_id_for_provisioning(options[:group])
      return 1 if new_group.nil?
      params['site'] = {'id' => new_group['id']}
    end
    if options[:metadata]
      if options[:metadata] == "[]" || options[:metadata] == "null"
        params['metadata'] = []
      else
        # parse string into format name:value, name:value
        # merge IDs from current metadata
        # todo: should allow quoted semicolons..
         = options[:metadata].split(",").select {|it| !it.to_s.empty? }
         = .collect do |it|
           = it.split(":")
          row = {}
          row['name'] = [0].to_s.strip
          row['value'] = [1].to_s.strip
           = (instance['metadata'] || []).find { |m| m['name'] == it['name'] }
          if 
            row['id'] = ['id']
          end
          row
        end
        params['metadata'] = 
      end
    end
    params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support args and option parameters on top of payload
      if !params.empty?
        payload['instance'] ||= {}
        payload['instance'].deep_merge!(params)
      end
    else
      if params.empty?
        print_red_alert "Specify atleast one option to update"
        puts optparse
        exit 1
      end
      payload = {}
      payload['instance'] = params
    end

    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([])
      get([instance['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_notes(args) ⇒ Object



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

def update_notes(args)
  usage = "Usage: morpheus instances update-notes [name] [options]"
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--notes VALUE', String, "Notes content (Markdown)") do |val|
      params['notes'] = val
    end
    opts.on('--file FILE', "File containing the notes content. This can be used instead of --notes") do |filename|
      full_filename = File.expand_path(filename)
      if File.exists?(full_filename)
        params['notes'] = File.read(full_filename)
      else
        print_red_alert "File not found: #{full_filename}"
        return 1
      end
      # use the filename as the name by default.
      if !params['name']
        params['name'] = File.basename(full_filename)
      end
    end
    opts.on(nil, '--clear', "Clear current notes") do |val|
      params['notes'] = ""
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count != 1
    puts_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 1 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
    new_group = nil
    params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support args and option parameters on top of payload
      if !params.empty?
        payload['instance'] ||= {}
        payload['instance'].deep_merge!(params)
      end
    else
      if params['notes'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'notes', 'type' => 'code-editor', 'fieldLabel' => 'Notes', 'required' => true, 'description' => 'Notes (Markdown)'}], options[:options])
        params['notes'] = v_prompt['notes']
      end
      payload = {}
      payload['instance'] = params
    end

    if options[:dry_run]
      print_dry_run @instances_interface.dry.update_notes(instance["id"], payload)
      return
    end
    json_response = @instances_interface.update_notes(instance["id"], payload)

    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Updated notes for instance #{instance['name']}"
      #list([])
      get([instance['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end