Class: Morpheus::Cli::Instances

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand, DeploymentsHelper, ExecutionRequestHelper, LogsHelper, OptionSourceHelper, ProcessesHelper, ProvisioningHelper
Defined in:
lib/morpheus/cli/commands/instances.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ExecutionRequestHelper

#api_client, #execution_request_interface, included, #wait_for_execution_request

Methods included from LogsHelper

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

Methods included from ProcessesHelper

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

Methods included from DeploymentsHelper

#deployment_list_key, #deployment_object_key, #deployment_version_list_key, #deployment_version_object_key, #deployments_interface, #find_deployment_by_id, #find_deployment_by_name, #find_deployment_by_name_or_id, #find_deployment_type_by_name, #find_deployment_version_by_id, #find_deployment_version_by_name, #find_deployment_version_by_name_or_id, #format_app_deploy_status, #format_deploy_type, #format_deployment_version_number, included

Methods included from ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_permissions_v2, #prompt_resize_volumes, #prompt_security_groups, #prompt_service_plan_options, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from OptionSourceHelper

#find_available_user_option, #find_cloud_option, #find_group_option, #find_tenant_option, #get_available_user_options, #get_cloud_options, #get_group_options, #get_tenant_options, included, #load_option_source_data, #options_interface, #parse_cloud_id_list, #parse_group_id_list, #parse_option_source_id_list, #parse_project_id_list, #parse_tenant_id_list, #parse_user_id_list

Methods included from AccountsHelper

#account_column_definitions, #account_users_interface, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_interface

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_payload, #build_standard_add_options, #build_standard_api_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_parameter_as_resource_id!, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Constructor Details

#initializeInstances

Returns a new instance of Instances.



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

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

Instance Method Details

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



1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
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
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
# File 'lib/morpheus/cli/commands/instances.rb', line 1331

def _get(id, options={})
  params = {}
  params.merge!(parse_query_options(options))
  # Use details=true to get more details from the appliance
  # if options[:details] || options[:include_containers]  || options[:include_scaling]
  if options[:details] || options[:include_containers]  || options[:include_scaling]
    params['details'] = true
  end
  instance = nil
  if id.to_s !~ /\A\d{1,}\Z/
    instance = find_instance_by_name_or_id(id)
    return 1, "Instance not found by name #{id}" if instance.nil?
    id = instance['id']
  end
  if options[:dry_run]
    print_dry_run @instances_interface.dry.get(id, params)
    return 0, nil
  end
  @instances_interface.setopts(options)
  json_response = @instances_interface.get(id, params)
  render_response(json_response, options, "instance") do
    instance = json_response['instance']
    pricing = instance['instancePrice']
    stats = instance['stats'] || json_response['stats'] || {}
    # load_balancers = json_response['loadBalancers'] || {}
    # metadata tags used to be returned as metadata and are now returned as tags
    # the problem is tags is what we used to call Labels (keywords)
    # the api will change to tags and labels, so handle the old format as long as metadata is returned.
    labels = nil
    tags = nil
    if instance.key?('labels')
      labels = instance['labels']
      tags = instance['tags']
    else
      labels = instance['tags']
      tags = instance['metadata']
    end
    # containers are fetched via separate api call
    containers = nil
    if options[:include_containers]
      # todo: can use instance['containerDetails'] in api 5.2.7/5.3.2
      if instance['containerDetails']
        containers = instance['containerDetails']
      else
        containers = @instances_interface.containers(instance['id'])['containers']
      end
    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", [], options
    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'] : '' },
      "Price" => lambda {|it|
        if pricing
          pricing['price'] ? format_money(pricing['price'], (pricing['currency'] || 'USD')).to_s + ' per ' + pricing['unit'].to_s : ''
        elsif it['hourlyPrice']
          format_money(it['hourlyPrice'], (it['currency'] || 'USD')).to_s + ' per hour'
        end
      },
      "Cost" => lambda {|it| 
        if pricing
          pricing['cost'] ? format_money(pricing['cost'], (pricing['currency'] || 'USD')).to_s + ' per ' + pricing['unit'].to_s : ''
        elsif it['hourlyCost']
          format_money(it['hourlyCost'], (it['currency'] || 'USD')).to_s + ' per hour'
        end
      },
      "Environment" => 'instanceContext',
      "Labels" => lambda {|it| labels ? labels.join(',') : '' },
      "Tags" => lambda {|it| tags ? tags.collect {|m| "#{m['name']}: #{m['value']}" }.join(', ') : '' },
      "Owner" => lambda {|it| 
        if it['owner']
          (it['owner']['username'] || it['owner']['id'])
        else
          it['createdBy'] ? (it['createdBy']['username'] || it['createdBy']['id']) : '' 
        end
      },
      #"Tenant" => lambda {|it| it['tenant'] ? it['tenant']['name'] : '' },
      "Apps" => lambda {|it| anded_list(it['apps'] ? it['apps'].collect {|app| app['name'] } : [])},
      "Date Created" => lambda {|it| format_local_dt(it['dateCreated']) },
      # "Last Updated" => lambda {|it| format_local_dt(it['lastUpdated']) },
      "Power Schedule" => lambda {|it| (it['powerSchedule'] && it['powerSchedule']['type']) ? it['powerSchedule']['type']['name'] : '' },
      "Last Deployment" => lambda {|it| (it['lastDeploy'] ? "#{it['lastDeploy']['deployment']['name']} #{it['lastDeploy']['deploymentVersion']['userVersion']} at #{format_local_dt it['lastDeploy']['deployDate']}" : nil) rescue "" },
      "Expire Date" => lambda {|it| it['expireDate'] ? format_local_dt(it['expireDate']) : '' },
      "Shutdown Date" => lambda {|it| it['shutdownDate'] ? format_local_dt(it['shutdownDate']) : '' },
      "Nodes" => lambda {|it| it['containers'] ? it['containers'].count : 0 },
      "Connection" => lambda {|it| format_instance_connection_string(it) },
      "Locked" => lambda {|it| format_boolean(it['locked']) },
      "Status" => lambda {|it| format_instance_status(it) }
    }
    description_cols.delete("Labels") if labels.nil? || labels.empty?
    description_cols.delete("Apps") if instance['apps'].nil? || instance['apps'].empty?
    description_cols.delete("Power Schedule") if instance['powerSchedule'].nil?
    description_cols.delete("Expire Date") if instance['expireDate'].nil?
    description_cols.delete("Shutdown Date") if instance['shutdownDate'].nil?
    description_cols["Removal Date"] = lambda {|it| format_local_dt(it['removalDate'])} if instance['status'] == 'pendingRemoval'
    description_cols.delete("Last Deployment") if instance['lastDeploy'].nil?
    description_cols.delete("Locked") if instance['locked'] != true
    price_value = (pricing ? pricing['price'] : instance['hourlyPrice']).to_i
    cost_value = (pricing ? pricing['cost'] : instance['hourlyCost']).to_i
    description_cols.delete("Price") if price_value == 0
    description_cols.delete("Cost") if cost_value == 0 || cost_value == price_value
    #description_cols.delete("Environment") if instance['instanceContext'].nil?
    print_description_list(description_cols, instance)

    if instance['statusMessage']
      print_h2 "Status Message", options
      if instance['status'] == 'failed'
        print red, instance['statusMessage'], reset
      else
        print instance['statusMessage']
      end
      print "\n"
    end
    if instance['errorMessage']
      print_h2 "Error Message", options
      print red, instance['errorMessage'], reset, "\n"
    end
    if !instance['notes'].to_s.empty?
      print_h2 "Instance Notes", options
      print cyan, instance['notes'], reset, "\n"
    end
    wiki_page = instance['wikiPage']
    if wiki_page && wiki_page['content']
      print_h2 "Instance Wiki", options
      print cyan, truncate_string(wiki_page['content'], 100), reset, "\n"
      print "  Last updated by #{wiki_page['updatedBy'] ? wiki_page['updatedBy']['username'] : ''} on #{format_local_dt(wiki_page['lastUpdated'])}", reset, "\n"
    end
    if stats
      print_h2 "Instance Usage", options
      print_stats_usage(stats)
    end

    print reset, "\n"

    # if options[:include_lb]
    if current_instance_lb
      print_h2 "Load Balancer", options
      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", options

      if containers.empty?
        print yellow,"No containers found for instance.",reset,"\n"
      else
        containers = containers.sort { |x,y| x['id'] <=> y['id'] }
        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})
          if stats['maxMemory'] && stats['maxMemory'].to_i != 0
            memory_usage_str = memory_usage_str + cyan + format_bytes_short(stats['usedMemory']).strip.rjust(7, ' ')  + " / " + format_bytes_short(stats['maxMemory']).strip
          end
          if stats['maxStorage'] && stats['maxStorage'].to_i != 0
            storage_usage_str = storage_usage_str + cyan + format_bytes_short(stats['usedStorage']).strip.rjust(7, ' ') + " / " + format_bytes_short(stats['maxStorage']).strip
          end
          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'] : '',
            host: container['server'] ? container['server']['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, :host, :location, :cpu, :memory, :storage]
        # 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", options
      if instance_threshold.nil? || instance_threshold.empty?
        print cyan,"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] = default_refresh_interval
      end
      statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
      if !statuses.include?(instance['status'])
        print cyan, "Refreshing in #{options[:refresh_interval] > 1 ? options[:refresh_interval].to_i : options[:refresh_interval]} seconds"
        sleep_with_dots(options[:refresh_interval])
        print "\n"
        _get(instance['id'], options)
      end
    end
  end
  return 0, nil
end

#_list_containers(arg, options) ⇒ Object



1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
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
# File 'lib/morpheus/cli/commands/instances.rb', line 1604

def _list_containers(arg, options)
  params = {}
  begin
    instance = find_instance_by_name_or_id(arg)
    return 1 if instance.nil?
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.containers(instance['id'], params)
      return
    end
    json_response = @instances_interface.containers(instance['id'], params)
    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']
    containers = containers.sort { |x,y| x['id'] <=> y['id'] }
    title = "Instance Containers: #{instance['name']} (#{instance['instanceType']['name']})"
    print_h1 title, [], options
    if containers.empty?
      print cyan,"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})
        if stats['maxMemory'] && stats['maxMemory'].to_i != 0
          memory_usage_str = memory_usage_str + cyan + format_bytes_short(stats['usedMemory']).strip.rjust(7, ' ')  + " / " + format_bytes_short(stats['maxMemory']).strip
        end
        if stats['maxStorage'] && stats['maxStorage'].to_i != 0
          storage_usage_str = storage_usage_str + cyan + format_bytes_short(stats['usedStorage']).strip.rjust(7, ' ') + " / " + format_bytes_short(stats['maxStorage']).strip
        end
        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, :cpu, :memory, :storage]
      # 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



3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
# File 'lib/morpheus/cli/commands/instances.rb', line 3755

def _scaling(arg, options)
  params = {}
  params.merge!(parse_list_options(options))
  instance = find_instance_by_name_or_id(arg)
  return 1 if instance.nil?
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.threshold(instance['id'], params)
    return 0
  end
  json_response = @instances_interface.threshold(instance['id'], params)
  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']
  instance_schedules = json_response['instanceSchedules']
  title = "Instance Scaling: [#{instance['id']}] #{instance['name']} (#{instance['instanceType']['name']})"
  print_h1 title, [], options
  if instance_threshold.empty?
    print cyan,"No scaling settings applied to this instance.",reset,"\n"
  else
    # print_h1 "Threshold Settings", [], options
    print cyan
    print_instance_threshold_description_list(instance_threshold)

    if instance_schedules && instance_schedules.size > 0
      print_h2 "Instance Schedules"
      print as_pretty_table(instance_schedules, instance_schedule_list_column_definitions(options).upcase_keys!, options)
    end
  end
  print reset, "\n"
  return 0

end

#_stats(arg, options) ⇒ Object



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

def _stats(arg, options)
  begin
    instance = find_instance_by_name_or_id(arg)
    @instances_interface.setopts(options)
    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, [], options
    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", options
    print_stats_usage(stats)
    print reset, "\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

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



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

def _view(arg, options={})
  begin
    instance = find_instance_by_name_or_id(arg)
    return 1 if instance.nil?

    link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/provisioning/instances/#{instance['id']}"
    if options[:link_tab]
      link << "#!#{options[:link_tab]}"
    end

    open_command = nil
    if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
      open_command = "start #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /darwin/
      open_command = "open #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
      open_command = "xdg-open #{link}"
    end

    if options[:dry_run]
      puts "system: #{open_command}"
      return 0
    end

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

#action(args) ⇒ Object



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

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 one or many 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
  @instances_interface.setopts(options)
  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



2596
2597
2598
2599
2600
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
# File 'lib/morpheus/cli/commands/instances.rb', line 2596

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



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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/morpheus/cli/commands/instances.rb', line 378

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("--description [TEXT]", String, "Description") do |val|
      options[:description] = val.to_s
    end
    opts.on("--environment ENV", String, "Environment code") do |val|
      options[:environment] = val.to_s
    end
    opts.on('--tags LIST', String, "Metadata tags in the format 'ping=pong,flash=bang'") do |val|
      options[:metadata] = val
    end
    opts.on('--metadata LIST', String, "Metadata tags in the format 'ping=pong,flash=bang'") do |val|
      options[:metadata] = val
    end
    opts.add_hidden_option('--metadata')
    opts.on('--labels LIST', String, "Labels (keywords) in the format 'foo, bar'") do |val|
      options[:labels] = parse_labels(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( '-l', '--layout LAYOUT', "Layout ID" ) do |val|
      options[:layout] = val
    end
    opts.on( '-p', '--plan PLAN', "Service plan ID") do |val|
      options[:service_plan] = val
    end
    opts.on( '--resource-pool ID', String, "Resource pool ID" ) do |val|
      options[:resource_pool] = val
    end
    opts.on("--workflow ID", String, "Automation: Workflow ID") do |val|
      options[:workflow_id] = val
    end
    opts.on("--ports ARRAY", String, "Exposed Ports, JSON formatted list of objects containing name and port") do |val|
      # expects format like --ports '[{"name":"web","port":8080}]'
      ports_array = JSON.parse(val)
      options[:ports] = ports_array
      options[:options]['ports'] = ports_array
    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 DAYS", Integer, "Automation: Shutdown Days") do |val|
      options[:shutdown_days] = val.to_i
    end
    opts.on("--expire-days DAYS", Integer, "Automation: Expiration Days") do |val|
      options[:expire_days] = val.to_i
    end
    opts.on("--create-backup [on|off]", String, "Automation: Create Backups.") do |val|
      options[:create_backup] = ['on','true','1',''].include?(val.to_s.downcase) ? 'on' : 'off'
    end
    opts.on("--security-groups LIST", String, "Security Groups, comma separated list of security group IDs") do |val|
      options[:security_groups] = val.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until status is running,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
    end
    build_standard_add_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

  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]
    # obviously should support every option that prompt supports on top of -- payload as well
    # group, cloud and type for now
    # todo: also support :layout, service_plan, :resource_pool, etc.
    group = nil
    if options[:group]
      group = find_group_by_name_or_id_for_provisioning(options[:group])
      if group.nil?
        return 1, "group not found by #{options[:group]}"
      end
      payload.deep_merge!({"instance" => {"site" => {"id" => group["id"]} } })
    end
    if options[:cloud]
      group_id = group ? group["id"] : ((payload["instance"] && payload["instance"]["site"].is_a?(Hash)) ? payload["instance"]["site"]["id"] : nil)
      cloud = find_cloud_by_name_or_id_for_provisioning(group_id, options[:cloud])
      if cloud.nil?
        return 1, "cloud not found by #{options[:cloud]}"
      end
      payload["zoneId"] = cloud["id"]
      payload.deep_merge!({"instance" => {"cloud" => cloud["name"] } })
    end
      # if options[:cloud]
      #   group_id = group ? group["id"] : ((payload["instance"] && payload["instance"]["site"].is_a?(Hash)) ? payload["instance"]["site"]["id"] : nil)
      #   cloud = find_cloud_by_name_or_id_for_provisioning(group_id, options[:cloud])
      #   if cloud.nil?
      #     return 1, "cloud not found by #{options[:cloud]}"
      #   end
      #   payload["zoneId"] = cloud["id"]
      #   payload.deep_merge!({"instance" => {"cloud" => cloud["name"] } })
      # end
    if options[:instance_type_code]
      # should just use find_instance_type_by_name_or_id
      # note that the api actually will match name name or code
      instance_type = (options[:instance_type_code].to_s =~ /\A\d{1,}\Z/) ? find_instance_type_by_id(options[:instance_type_code]) : find_instance_type_by_code(options[:instance_type_code])
      if instance_type.nil?
        return 1, "instance type not found by #{options[:cloud]}"
      end
      payload.deep_merge!({"instance" => {"type" => instance_type["code"] } })
      payload.deep_merge!({"instance" => {"instanceType" => {"code" => instance_type["code"]} } })
    end
  else
    # use active group by default
    options[:group] ||= @active_group_id
    options[:select_datastore] = true
    options[:name_required] = true
    # 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
  
  payload['instance'] ||= {}
  if options[:instance_name]
    payload['instance']['name'] = options[:instance_name]
  end
  if options[:description] && !payload['instance']['description']
    payload['instance']['description'] = options[:description]
  end
  if options[:environment] && !payload['instance']['instanceContext']
    payload['instance']['instanceContext'] = options[:environment]
  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] if !options[:create_backup].nil?
  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'] ||= {}
    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
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.create(payload)
    return 0
  end

  json_response = @instances_interface.create(payload)
  render_response(json_response, options, "instance") do
    instance_id = json_response["instance"]["id"]
    instance_name = json_response["instance"]["name"]
    print_green_success "Provisioning instance [#{instance_id}] #{instance_name}"
    # print details
    get_args = [instance_id] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
    get(get_args)
  end
  return 0, nil
end

#add_schedule(args) ⇒ Object



3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
# File 'lib/morpheus/cli/commands/instances.rb', line 3959

def add_schedule(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance]")
    # opts.on( '--threshold VALUE', String, "Threshold template to apply scaling settings with. Default is no template (custom)." ) do |val|
    #   options[:threshold] = val
    # end
    build_option_type_options(opts, options, add_instance_schedule_option_types)
    build_option_type_options(opts, options, instance_threshold_option_types)
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Update an existing instance scaling threshold schedule
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  # construct payload
  object_key = 'instanceSchedule'
  payload = parse_payload(options, object_key)
  if !payload
    # payload = {object_key => {}}
    # support -O option but avoid duplicate threshold settings... so -O maxCpu, goes under threshold only
    # could just use options -O threshold.maxCpu instead, which is what the api wants...
    payload = {object_key => parse_passed_options(options, exclude: ['sourceThresholdId'] + instance_threshold_option_types.collect {|i|i['fieldName']})}
    params = {}
    params.deep_merge! Morpheus::Cli::OptionTypes.prompt(add_instance_schedule_option_types, options[:options], @api_client, {})
    source_threshold_id = params.delete('sourceThresholdId')
    customize_threshold_prompt = true
    params['threshold'] ||= {}
    if source_threshold_id.to_s != '' && source_threshold_id.to_s != 'custom'
      #params['threshold']['id']= source_threshold_id
      params['threshold']['sourceThresholdId']= source_threshold_id.to_i
      customize_threshold_prompt = false
    end
    # always parse the threshold options but customize_threshold means prompt also
    if customize_threshold_prompt
      params['threshold'].deep_merge! Morpheus::Cli::OptionTypes.prompt(instance_threshold_option_types, options[:options], @api_client, {})
    else
      params['threshold'].deep_merge! Morpheus::Cli::OptionTypes.no_prompt(instance_threshold_option_types, options[:options], @api_client, {})
    end
    params.booleanize! # convert checkbox "on" and "off" to true and false
    payload[object_key].deep_merge!(params)
    # unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to update the scaling settings for instance '#{instance['name']}' with the above scaling schedule?", options)
    #   return 9, "aborted command"
    # end
  end
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.create_schedule(instance['id'], payload)
    return 0, nil
  end
  json_response = @instances_interface.create_schedule(instance['id'], payload)
  render_response(json_response, options) do
    print_green_success "Added scaling schedule for instance #{instance['name']}"
    #_scaling(instance['id'], options)
  end
  return 0, nil
end

#apply(args) ⇒ Object



4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
# File 'lib/morpheus/cli/commands/instances.rb', line 4948

def apply(args)
  default_refresh_interval = 5
  params, payload, options = {}, {}, {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [options]")
    opts.on( '-p', '--parameter NAME=VALUE', "Template parameter name and value" ) do |val|
      k, v = val.split("=")
      options[:options]['templateParameter'] ||= {}
      options[:options]['templateParameter'][k] = v
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until execution is complete. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
    end
    opts.on(nil, '--no-refresh', "Do not refresh" ) do
      options[:no_refresh] = true
    end
    opts.on(nil, '--no-validate', "Do not validate planned changes before apply" ) do
      options[:no_validate] = true
    end
    opts.on(nil, '--validate-only', "Only validate planned changes, do not execute the apply command." ) do
      options[:validate_only] = true
    end
    build_standard_update_options(opts, options, [:auto_confirm])
    opts.footer = <<-EOT
Apply an instance.
[instance] is required. This is the name or id of an instance.
This is only supported by certain types of instances such as terraform.
By default this executes two requests to validate and then apply the changes.
The first request corresponds to the terraform plan command only.
Use --no-validate to skip this step apply changes in one step.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)

  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  # construct request
  params.merge!(parse_query_options(options))
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!(parse_passed_options(options))
  else
    payload.deep_merge!(parse_passed_options(options))
    # attempt to load prepare-apply to get templateParameter values and prompt for them
    # ok, actually use options/layoutParameters to get the list of parameters
    begin
      prepare_apply_json_response = @instances_interface.prepare_apply(instance["id"])
      config = prepare_apply_json_response['data']
      variable_map = config['templateParameter']
      api_params = {layoutId: instance['layout']['id'], instanceId: instance['id'], zoneId: instance['cloud']['id'], siteId: instance['group']['id']}
      layout_parameters = @options_interface.options_for_source('layoutParameters',api_params)['data']

      if layout_parameters && !layout_parameters.empty?
        variable_option_types = []
        i = 0
        layout_parameters.each do |layout_parameter|
          var_label = layout_parameter['displayName'] || layout_parameter['name']
          var_name = layout_parameter['name']
          var_value = variable_map ? variable_map[var_name] : layout_parameter['defaultValue']
          if var_value.nil? && layout_parameter['defaultValue']
            var_value = layout_parameter['defaultValue']
          end
          var_type = (layout_parameter['passwordType'] || layout_parameter['sensitive']) ? 'password' : 'text'
          option_type = {'fieldContext' => 'templateParameter', 'fieldName' => var_name, 'fieldLabel' => var_label, 'type' => var_type, 'required' => true, 'defaultValue' => (var_value.to_s.empty? ? nil : var_value.to_s), 'displayOrder' => (i+1) }
          variable_option_types << option_type
          i+=1
        end
        blueprint_type_display = format_blueprint_type(instance['layout']['provisionTypeCode'])
        if blueprint_type_display == "terraform"
          blueprint_type_display = "Terraform"
        end
        print_h2 "#{blueprint_type_display} Variables"
        v_prompt = Morpheus::Cli::OptionTypes.prompt(variable_option_types, options[:options], @api_client)
        v_prompt.deep_compact!
        payload.deep_merge!(v_prompt)
      end
    rescue RestClient::Exception => ex
      # if e.response && e.response.code == 404
      Morpheus::Logging::DarkPrinter.puts "Unable to load config for instance apply, skipping parameter prompting" if Morpheus::Logging.debug?
      # print_rest_exception(ex, options)
      # end
    end
  end

  @instances_interface.setopts(options)
  if options[:validate_only]
    # validate only
    if options[:dry_run]
      print_dry_run @instances_interface.dry.validate_apply(instance["id"], params, payload)
      return
    end
    json_response = @instances_interface.validate_apply(instance["id"], params, payload)
    print_green_success "Validating instance #{instance['name']}"
    execution_id = json_response['executionId']
    if !options[:no_refresh]
      #Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_id, "--refresh", options[:refresh_interval].to_s]+ (options[:remote] ? ["-r",options[:remote]] : []))
      validate_execution_request = wait_for_execution_request(execution_id, options)
    end
  elsif options[:no_validate]
    # skip validate, apply only
    if options[:dry_run]
      print_dry_run @instances_interface.dry.apply(instance["id"], params, payload)
      return
    end
    json_response = @instances_interface.apply(instance["id"], params, payload)
    render_response(json_response, options) do
      print_green_success "Applying instance #{instance['name']}"
      execution_id = json_response['executionId']        
      if !options[:no_refresh]
        #Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_id, "--refresh", options[:refresh_interval].to_s]+ (options[:remote] ? ["-r",options[:remote]] : []))
        apply_execution_request = wait_for_execution_request(execution_id, options)
      end
    end
  else
    # validate and then apply
    if options[:dry_run]
      print_dry_run @instances_interface.dry.validate_apply(instance["id"], params, payload)
      print_dry_run @instances_interface.dry.apply(instance["id"], params, payload)
      return
    end
    json_response = @instances_interface.validate_apply(instance["id"], params, payload)
    print_green_success "Validating instance #{instance['name']}"
    execution_id = json_response['executionId']
    validate_execution_request = wait_for_execution_request(execution_id, options)
    if validate_execution_request['status'] != 'complete'
      print_red_alert "Validation failed. Changes will not be applied."
      return 1, "Validation failed. Changes will not be applied."
    else
      unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to apply these changes?")
        return 9, "aborted command"
      end
      json_response = @instances_interface.apply(instance["id"], params, payload)
      render_response(json_response, options) do
        print_green_success "Applying instance #{instance['name']}"
        execution_id = json_response['executionId']        
        if !options[:no_refresh]
          #Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_id, "--refresh", options[:refresh_interval].to_s]+ (options[:remote] ? ["-r",options[:remote]] : []))
          apply_execution_request = wait_for_execution_request(execution_id, options)
        end
      end
    end
  end
  return 0, nil
end

#apply_security_groups(args) ⇒ Object



3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
# File 'lib/morpheus/cli/commands/instances.rb', line 3303

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("[instance] [-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}
    @instances_interface.setopts(options)
    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]] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#backup(args) ⇒ Object



2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
# File 'lib/morpheus/cli/commands/instances.rb', line 2837

def backup(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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
    @instances_interface.setopts(options)
    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
      bad_results = []
      if json_response['results']
        json_response['results'].each do |result_id, result|
          if result['success'] != true
            bad_results << result['msg'] || "Failed to create backup for instance #{result_id}"
          end
        end
      end
      if bad_results.empty?
        print_green_success "Backup initiated."
        return 0
      else
        print_red_alert bad_results.join("\n")
        return 1
      end
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#backups(args) ⇒ Object



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

def backups(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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])
    params = {}
    @instances_interface.setopts(options)
    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
    
    if json_response['backups'] && json_response['backups'][0] && json_response['backups'][0]['backupResults']
      # new format
      print_h1 "Instance Backups: #{instance['name']} (#{instance['instanceType']['name']})", [], options


      backup = json_response['backups'][0]

      description_cols = {
        "Backup ID" => lambda {|it| it['id'] },
        "Name" => lambda {|it| it['name'] },
        "Type" => lambda {|it| it['backupType'] ? (it['backupType']['name'] || it['backupType']['code']) : '' },
        "Storage" => lambda {|it| it['storageProvider'] ? it['storageProvider']['name'] : '' },
        "Schedule" => lambda {|it| it['cronDescription'] || it['cronExpression'] }
      }
      print_description_list(description_cols, backup)

      backup_results = backup ? backup['backupResults'] : nil
      backup_rows = backup_results.collect {|it| 
        status_str = it['status'].to_s.upcase
        # 'START_REQUESTED' //START_REQUESTED, IN_PROGRESS, CANCEL_REQUESTED, CANCELLED, SUCCEEDED, FAILED
        if status_str == 'SUCCEEDED'
          status_str = "#{green}#{status_str.upcase}#{cyan}"
        elsif status_str == 'FAILED'
          status_str = "#{red}#{status_str.upcase}#{cyan}"
        else
          status_str = "#{cyan}#{status_str.upcase}#{cyan}"
        end
        {id: it['id'], startDate: format_local_dt(it['dateCreated']), duration: format_duration_milliseconds(it['durationMillis']), 
          size: format_bytes(it['sizeInMb'], 'MB'), status: status_str }
      }
      print_h1 "Backup Results", [], options
      print cyan
      puts as_pretty_table backup_rows, [
        :id,
        {:startDate => {:display_name => "Started"} },
        :duration,
        :size,
        :status
      ]
      print reset, "\n"
    elsif json_response['backups'].size == 0
      # no backup configured
      print_h1 "Instance Backups: #{instance['name']} (#{instance['instanceType']['name']})", [], options
      print "#{yellow}No backups configured#{reset}\n\n"
    else
      # old format
      print_h1 "Instance Backups: #{instance['name']} (#{instance['instanceType']['name']})", [], options
      backups = json_response['backups']
      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"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#cancel_expiration(args) ⇒ Object



3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
# File 'lib/morpheus/cli/commands/instances.rb', line 3019

def cancel_expiration(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options, [:query]) # query params instead of p
    opts.footer = <<-EOT
Cancel expiration of an instance.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  params.merge!(parse_query_options(options))
  payload = options[:payload] || {}
  payload.deep_merge!(parse_passed_options(options))
  instance = find_instance_by_name_or_id(args[0])
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.cancel_expiration(instance['id'], params, payload)
    return
  end
  json_response = @instances_interface.cancel_expiration(instance['id'], params, payload)
  render_response(json_response, options) do
    print_green_success "Canceled expiration for instance #{instance['name']} ..."
    get([instance['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#cancel_removal(args) ⇒ Object



2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
# File 'lib/morpheus/cli/commands/instances.rb', line 2987

def cancel_removal(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Cancel removal of an instance.
This is a way to undo delete of an instance still pending removal.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  params.merge!(parse_query_options(options))
  payload = options[:payload] || {}
  payload.deep_merge!(parse_passed_options(options))
  instance = find_instance_by_name_or_id(args[0])
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.cancel_removal(instance['id'], params, payload)
    return
  end
  json_response = @instances_interface.cancel_removal(instance['id'], params, payload)
  render_response(json_response, options) do
    print_green_success "Canceled removal for instance #{instance['name']} ..."
    get([instance['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#cancel_shutdown(args) ⇒ Object



3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
# File 'lib/morpheus/cli/commands/instances.rb', line 3050

def cancel_shutdown(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options, [:query]) # query params instead of p
    opts.footer = <<-EOT
Cancel shutdown for an instance.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  params.merge!(parse_query_options(options))
  payload = options[:payload] || {}
  payload.deep_merge!(parse_passed_options(options))
  instance = find_instance_by_name_or_id(args[0])
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.cancel_shutdown(instance['id'], params, payload)
    return
  end
  json_response = @instances_interface.cancel_shutdown(instance['id'], params, payload)
  render_response(json_response, options) do
    print_green_success "Canceled shutdown for instance #{instance['name']} ..."
    get([instance['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#clone(args) ⇒ Object



1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
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
1872
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
1903
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
1934
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
1979
1980
1981
# File 'lib/morpheus/cli/commands/instances.rb', line 1772

def clone(args)
  options = {:options => {}}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] -g GROUP")
    opts.on( '-g', '--group GROUP', "Group Name or ID for the new instance" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID for the new instance" ) do |val|
      options[:cloud] = val
    end
    opts.on('--name VALUE', String, "Name") do |val|
      options[:options]['name'] = val
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      options[:description] = val.to_s
    end
    opts.on("--environment ENV", String, "Environment code") do |val|
      options[:environment] = val.to_s
    end
    opts.on('--tags LIST', String, "Metadata tags in the format 'ping=pong,flash=bang'") do |val|
      options[:metadata] = val
    end
    opts.on('--metadata LIST', String, "Metadata tags in the format 'ping=pong,flash=bang'") do |val|
      options[:metadata] = val
    end
    opts.add_hidden_option('--metadata')
    opts.on('--labels LIST', String, "Labels (keywords) in the format 'foo, bar'") do |val|
      options[:labels] = parse_labels(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( '-l', '--layout LAYOUT', "Layout ID" ) do |val|
    #   options[:layout] = val
    # end
    opts.on( '-p', '--plan PLAN', "Service plan ID") do |val|
      options[:service_plan] = val
    end
    opts.on( '--resource-pool ID', String, "Resource pool ID" ) do |val|
      options[:resource_pool] = val
    end
    opts.on("--workflow ID", String, "Automation: Workflow ID") do |val|
      options[:workflow_id] = val
    end
    opts.on("--ports ARRAY", String, "Exposed Ports, JSON formatted list of objects containing name and port") do |val|
      # expects format like --ports '[{"name":"web","port":8080}]'
      ports_array = JSON.parse(val)
      options[:ports] = ports_array
      options[:options]['ports'] = ports_array
    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 DAYS", Integer, "Automation: Shutdown Days") do |val|
      options[:shutdown_days] = val.to_i
    end
    opts.on("--expire-days DAYS", Integer, "Automation: Expiration Days") do |val|
      options[:expire_days] = val.to_i
    end
    opts.on("--create-backup [on|off]", String, "Automation: Create Backups.") do |val|
      options[:create_backup] = ['on','true','1',''].include?(val.to_s.downcase) ? 'on' : 'off'
    end
    opts.on("--security-groups LIST", String, "Security Groups, comma separated list of security group IDs") do |val|
      options[:security_groups] = val.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
    end
    build_standard_post_options(opts, options, [:auto_confirm])
  end
  optparse.parse!(args)
  if args.count < 1 || args.count > 2
    raise_command_error "wrong number of arguments, expected 1-2 and got (#{args.count}) #{args}\n#{optparse}"
  end

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

    options[:options] ||= {}
    options[:select_datastore] = true
    options[:name_required] = true

    # defaults derived from clone
    options[:default_name] = instance['name'] + '-clone' if instance['name']
    options[:default_description] = instance['description'] if !instance['description'].to_s.empty?
    options[:default_environment] = instance['environment'] if instance['environment']
    options[:default_group] = instance['group']['id'] if instance['group']
    options[:default_cloud] = instance['cloud']['name'] if instance['cloud']
    options[:default_plan] = instance['plan']['name'] if instance['plan']
    options[:default_resource_pool] = instance['config']['resourcePoolId'] if instance['config']
    options[:default_config] = instance['config']
    options[:default_security_group] = instance['config']['securityGroups'][0]['id'] if instance['config'] && (instance['config']['securityGroups'] || []).count > 0
    if instance['labels'] && !instance['labels'].empty?
      options[:default_labels] = (instance['labels'] || []).join(',')
    end
    if instance['tags'] && !instance['tags'].empty?
      options[:current_tags] = instance['tags']
    end

    # immutable derived from clone
    options[:instance_type_code] = instance['instanceType']['code'] if instance['instanceType']
    options[:version] = instance['instanceVersion']
    options[:layout] = instance['layout']['id'] if instance['layout']

    # volume defaults
    options[:options]['volumes'] = instance['volumes']

    # network defaults
    options[:options]['networkInterfaces'] = instance['interfaces']

    # use the -g GROUP or active group by default
    #options[:options]['group'] ||= (options[:group] || @active_group_id)
    # support [new-name] 
    if args[1]
      options[:options]['name'] = args[1]
    end
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) || ['networkInterfaces'].include?(k)} : {}
    payload = {}
    if options[:payload]
      payload = options[:payload]
    else
      new_instance_payload = prompt_new_instance(options)

      # adjust for differences between new and clone payloads
      payload = new_instance_payload.delete('instance')
      payload.deep_merge!(new_instance_payload)
      payload['cloud'] = {'id' => payload.delete('zoneId')}
      payload['group'] = payload.delete('site')
    end
    unless passed_options.empty?
      passed_options.delete('cloud')
      passed_options.delete('group')
      payload.deep_merge!(passed_options)
    end
    
    #payload['instance'] ||= {}
    # if options[:instance_name]
    #   payload['instance']['name'] = options[:instance_name]
    # end
    # if options[:description] && !payload['instance']['description']
    #   payload['instance']['description'] = options[:description]
    # end
    # if options[:environment] && !payload['instance']['instanceContext']
    #   payload['instance']['instanceContext'] = options[:environment]
    # end
  
    #payload[:copies] = options[:copies] if options[:copies] && options[:copies] > 0
    if options[:layout_size] && options[:layout_size] > 0 # aka Scale Factor
      payload[:layoutSize] = options[:layout_size]
    end
    if !options[:create_backup].nil?
      payload[:createBackup] = options[:create_backup]
    end
    if options[:expire_days]
      payload['instance'] ||= {}
      payload['instance']['expireDays'] = options[:expire_days]
    end
    if options[:shutdown_days]
      payload['instance'] ||= {}
      payload['shutdownDays'] = options[:shutdown_days]
    end
    # JD: this actually fixed a customer problem
    # It appears to be important to pass this... not sure if config.createUser is necessary...
    if options[:create_user].nil?
      options[:create_user] = true
    end
    if options.key?(:create_user)
      payload['config'] ||= {}
      payload['config']['createUser'] = options[:create_user]
      payload['createUser'] = options[:create_user]
    end
    if options[:user_group_id]
      payload['instance'] ||= {}
      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
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to clone the instance #{instance['name']} as '#{payload['name']}'?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    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

#clone_image(args) ⇒ Object



4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
# File 'lib/morpheus/cli/commands/instances.rb', line 4701

def clone_image(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on( '--name VALUE', String, "Image Name (Template Name). Default is server name + timestamp" ) do |val|
      options[:options]['templateName'] = val
    end
    opts.on( '--folder VALUE', String, "Folder externalId or '/' to use the root folder" ) do |val|
      options[:options]['zoneFolder'] = val
    end
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Clone to image (template) for an instance
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  # need to GET provision type for hasFolders
  provision_type_code = instance['layout']['provisionTypeCode'] rescue nil
  provision_type = nil
  if provision_type_code
    provision_type = provision_types_interface.list({code:provision_type_code})['provisionTypes'][0]
    if provision_type.nil?
      print_red_alert "Provision Type not found by code #{provision_type_code}"
      exit 1
    end
  else
    provision_type = get_provision_type_for_zone_type(cloud['zoneType']['id'])
  end
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!(parse_passed_options(options))
  else
    payload.deep_merge!(parse_passed_options(options))
    if payload['templateName'].nil?
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'templateName', 'type' => 'text', 'fieldLabel' => 'Image Name', 'description' => 'Choose a name for the new image template. Default is the server name + timestamp'}], options[:options])
      if v_prompt['templateName'].to_s != ''
        payload['templateName'] = v_prompt['templateName']
      end
    end
    #if instance['layout']['provisionTypeCode'] == 'vmware'
    if provision_type && provision_type["hasFolders"]
      if payload['zoneFolder'].nil?
        # vmwareFolders moved from /api/options/vmwareFolders to /api/options/vmware/vmwareFolders
        folder_prompt = nil
        begin
          folder_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'zoneFolder', 'type' => 'select', 'optionSource' => 'vmwareFolders', 'optionSourceType' => 'vmware', 'fieldLabel' => 'Folder', 'description' => "Folder externalId or '/' to use the root folder", 'required' => true}], options[:options], @api_client, {siteId: instance['group']['id'], zoneId: instance['cloud']['id']})
        rescue RestClient::Exception => e
          Morpheus::Logging::DarkPrinter.puts "Failed to load folder options" if Morpheus::Logging.debug?
          begin
            folder_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'zoneFolder', 'type' => 'select', 'optionSource' => 'vmwareFolders', 'fieldLabel' => 'Folder', 'description' => "Folder externalId or '/' to use the root folder", 'required' => true}], options[:options], @api_client, {siteId: instance['group']['id'], zoneId: instance['cloud']['id']})
          rescue RestClient::Exception => e2
            Morpheus::Logging::DarkPrinter.puts "Failed to load folder options from alternative endpoint too" if Morpheus::Logging.debug?
          end
        end
        if folder_prompt && folder_prompt['zoneFolder'].to_s != ''
          payload['zoneFolder'] = folder_prompt['zoneFolder']
        end
      end
    end
  end
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.clone_image(instance['id'], payload)
    return
  end
  json_response = @instances_interface.clone_image(instance['id'], payload)
  render_response(json_response, options) do
    print_green_success "Clone Image initiated."
  end
  return 0, nil
end

#connect(opts) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/morpheus/cli/commands/instances.rb', line 44

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @accounts_interface = @api_client.accounts
  @account_users_interface = @api_client.
  @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
  @library_layouts_interface = @api_client.library_layouts
  @clouds_interface = @api_client.clouds
  @clouds_datastores_interface = @api_client.cloud_datastores
  @servers_interface = @api_client.servers
  @provision_types_interface = @api_client.provision_types
  @options_interface = @api_client.options
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
  @execution_request_interface = @api_client.execution_request
  @deploy_interface = @api_client.deploy
  @deployments_interface = @api_client.deployments
  @snapshots_interface = @api_client.snapshots
end

#console(args) ⇒ Object



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

def console(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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, [: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])
    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 options[:dry_run]
      puts Morpheus::Util.open_url_command(link)
      return 0
    end
    return Morpheus::Util.open_url(link)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#count(args) ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/morpheus/cli/commands/instances.rb', line 303

def count(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[options]")
    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
    opts.on( '--owner USER', "Owner Username or ID" ) do |val|
      options[:owner] = val
    end
    opts.on( '--created-by USER', "Alias for --owner" ) do |val|
      options[:owner] = val
    end
    opts.add_hidden_option('--created-by')
    opts.on( '-s', '--search PHRASE', "Search Phrase" ) do |phrase|
      options[:phrase] = phrase
    end
    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))
    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

     = nil
    if options[:owner]
      created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:owner])
      return if created_by_ids.nil?
      params['createdBy'] = created_by_ids
      # params['ownerId'] = created_by_ids # 4.2.1+
    end
    
    @instances_interface.setopts(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
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#create_linked_clone(args) ⇒ Object



3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
# File 'lib/morpheus/cli/commands/instances.rb', line 3678

def create_linked_clone(args)
  options = {}
  instance = nil
  snapshot_id = nil

  optparse = Morpheus::Cli::OptionParser.new do |opts|
   opts.banner = subcommand_usage("[instance]")
    opts.on("--snapshot ID", String, "Optional snapshot") do |val|
      snapshot_id = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Create a linked clone using the selected snapshot of an Instance." + "\n" +
                  "[snapshotId] is required. This is the id of the snapshot which the clone will refer to."
  end
  
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    options[:options]['instanceId'] = instance['id']
    begin
      snapshot_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'snapshotId', 'type' => 'select', 'fieldLabel' => 'Snapshot', 'optionSource' => 'instanceSnapshots', 'required' => true, 'description' => 'Select Snapshot.'}], {}, @api_client, options[:options])
    
      if !snapshot_prompt['snapshotId'].to_s.empty?
        snapshot_id = snapshot_prompt['snapshotId']
      end
    rescue RestClient::Exception => e
      puts "Failed to load instance snapshots"
    end
    
    @instances_interface.setopts(options)
 
    payload = {}
    if options[:dry_run]
      print_dry_run @instances_interface.dry.create_linked_clone(instance['id'], snapshot_id, payload)
      return
    end
    
    json_response = @instances_interface.create_linked_clone(instance['id'], snapshot_id, payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Linked Clone creation initiated."
    end
    return 0

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

#delenv(args) ⇒ Object



2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
# File 'lib/morpheus/cli/commands/instances.rb', line 2066

def delenv(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] 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])
    @instances_interface.setopts(options)
    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]] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#deploys(args) ⇒ Object



4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
# File 'lib/morpheus/cli/commands/instances.rb', line 4647

def deploys(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [search]")
    build_standard_list_options(opts, options)
    opts.footer = <<-EOT
List deployments for an instance.
[instance] is required. This is the name or id of an instance
[search] is optional. Filters on deployment version identifier
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  connect(options)
  if args.count > 1
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  # @deploy_interface.setopts(options)
  # if options[:dry_run]
  #   print_dry_run @deploy_interface.dry.list(instance['id'], params)
  #   return
  # end
  # json_response = @deploy_interface.list(instance['id'], params)

  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.deploys(instance['id'], params)
    return
  end
  json_response = @instances_interface.deploys(instance['id'], params)

  app_deploys = json_response['appDeploys']
  render_response(json_response, options, 'appDeploys') do
    print_h1 "Instance Deploys", ["#{instance['name']}"] + parse_list_subtitles(options), options
    if app_deploys.empty?
      print cyan,"No deployments found.",reset,"\n"
    else
      print as_pretty_table(app_deploys, app_deploy_column_definitions.upcase_keys!, options)
      if json_response['meta']
        print_results_pagination(json_response)
      else
        print_results_pagination({size:app_deploys.size,total:app_deploys.size.to_i})
      end

    end
    print reset,"\n"
  end
  return 0
end

#eject(args) ⇒ Object



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

def eject(args)
  params = {'server' => true}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Eject 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to eject #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.eject(instances.collect {|it| it['id'] }, params)
      return
    end
    json_response = @instances_interface.eject(instances.collect {|it| it['id'] }, params)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if instances.size == 1
        print_green_success "Ejected instance #{instances[0]['name']}"
      else
        print_green_success "Ejected #{instances.size} instances"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#envs(args) ⇒ Object



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

def envs(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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])
    @instances_interface.setopts(options)
    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']})", [], options
    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
    columns = [:name, :value, :export]
    print_h2 "Imported Envs", options
    print as_pretty_table(envs, columns, options)
    print reset, "\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#execution_request(args) ⇒ Object



4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
# File 'lib/morpheus/cli/commands/instances.rb', line 4566

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.exist?(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
    @execution_request_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execution_request_interface.dry.create(params, payload)
      return 0
    end
    # do it
    json_response = @execution_request_interface.create(params, payload)
    # print and return result
    if options[:quiet]
      return 0
    elsif options[:json]
      puts as_json(json_response, options)
      return 0
    end
    execution_request = json_response['executionRequest']
    print_green_success "Executing request #{execution_request['uniqueId']}"
    if do_refresh
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId'], "--refresh"]+ (options[:remote] ? ["-r",options[:remote]] : []))
    else
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId']]+ (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#extend_expiration(args) ⇒ Object



3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
# File 'lib/morpheus/cli/commands/instances.rb', line 3081

def extend_expiration(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options, [:query]) # query params instead of p
    opts.footer = <<-EOT
Extend expiration for an instance.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  params.merge!(parse_query_options(options))
  payload = options[:payload] || {}
  payload.deep_merge!(parse_passed_options(options))
  instance = find_instance_by_name_or_id(args[0])
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.extend_expiration(instance['id'], params, payload)
    return
  end
  json_response = @instances_interface.extend_expiration(instance['id'], params, payload)
  render_response(json_response, options) do
    print_green_success "Extended expiration for instance #{instance['name']} ..."
    get([instance['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#extend_shutdown(args) ⇒ Object



3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
# File 'lib/morpheus/cli/commands/instances.rb', line 3112

def extend_shutdown(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options, [:query]) # query params instead of p
    opts.footer = <<-EOT
Extend shutdown for an instance.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  params.merge!(parse_query_options(options))
  payload = options[:payload] || {}
  payload.deep_merge!(parse_passed_options(options))
  instance = find_instance_by_name_or_id(args[0])
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.extend_shutdown(instance['id'], params, payload)
    return
  end
  json_response = @instances_interface.extend_shutdown(instance['id'], params, payload)
  render_response(json_response, options) do
    print_green_success "Extended shutdown for instance #{instance['name']} ..."
    get([instance['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  end
  return 0, nil
end

#firewall_disable(args) ⇒ Object



3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
# File 'lib/morpheus/cli/commands/instances.rb', line 3193

def firewall_disable(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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])
    @instances_interface.setopts(options)
    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]] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#firewall_enable(args) ⇒ Object



3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
# File 'lib/morpheus/cli/commands/instances.rb', line 3225

def firewall_enable(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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])
    @instances_interface.setopts(options)
    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]] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
# File 'lib/morpheus/cli/commands/instances.rb', line 1269

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('-a', '--all', "Display all details: containers|vms, and scaling." ) do
      options[:details] = true
      options[:include_containers] = true
      options[:include_scaling] = true
      options[:include_costs]
    end
    opts.on(nil, '--details', "Alias for --all" ) do
      options[:details] = true
      options[:include_containers] = true
      options[:include_scaling] = true
      options[:include_costs]
    end
    opts.add_hidden_option('--details')
    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.add_hidden_option('--nodes')
    opts.on( nil, '--vms', "Alias for --containers" ) do
      options[:include_containers] = true
    end
    # opts.add_hidden_option('--vms')
    opts.on( nil, '--scaling', "Display Instance Scaling Settings" ) do
      options[:include_scaling] = true
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until status is running,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_until_status] ||= "running,failed"
      if !val.to_s.empty?
        options[:refresh_interval] = val.to_f
      end
    end
    opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
      options[:refresh_until_status] = val.to_s.downcase
    end
    # 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_standard_get_options(opts, options)
    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

#get_schedule(args) ⇒ Object



3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
# File 'lib/morpheus/cli/commands/instances.rb', line 3922

def get_schedule(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance] [schedule]")
    # build_standard_list_options(opts, options)
    build_standard_get_options(opts, options) # phrase,max,etc is not supported
    opts.footer = <<-EOT
Get details about an instance scaling threshold schedule.
[instance] is required. This is the name or id of an instance
[schedule] is required. This is id of an instance schedule
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  parse_get_options!(args, options, params)
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.list(instance['id'], args[1], params)
    return 0, nil
  end
  json_response = @instances_interface.get_schedule(instance['id'], args[1], params)
  object_key = 'instanceSchedule'
  render_response(json_response, options, object_key) do
    record = json_response[object_key]
    title = "Instance Schedule Details"
    print_h1 title, options
    columns = instance_schedule_column_definitions(options)
    print print_description_list(columns, record, options)
    print reset,"\n"
  end
  return 0, nil
end

#handle(args) ⇒ Object



66
67
68
# File 'lib/morpheus/cli/commands/instances.rb', line 66

def handle(args)
  handle_subcommand(args)
end

#history(args) ⇒ Object



4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
# File 'lib/morpheus/cli/commands/instances.rb', line 4250

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('--details', "Display more details: memory and storage usage used / max values." ) do
      options[:show_events] = true
      options[:show_output] = true
      options[:details] = 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') if params['phrase']
    @instances_interface.setopts(options)
    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, options
      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, options[:details] ? nil : 20),
            output: format_process_output(process, options[:details] ? nil : 20)
          }
          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, options[:details] ? nil : 20),
                  output: format_process_output(process_event, options[:details] ? nil : 20)
                }
                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



4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
# File 'lib/morpheus/cli/commands/instances.rb', line 4407

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))
    @instances_interface.setopts(options)
    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, options
      print_process_details(process)

      print_h2 "Process Events", options
      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



4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
# File 'lib/morpheus/cli/commands/instances.rb', line 4507

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))
    @instances_interface.setopts(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, options
      print_process_event_details(process_event, options)
      print reset, "\n"
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#import_snapshot(args) ⇒ Object



3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
# File 'lib/morpheus/cli/commands/instances.rb', line 3461

def import_snapshot(args)
  options = {}
  query_params = {}
  storage_provider_id = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  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'].to_s.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
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.import_snapshot(instance['id'], query_params, payload)
      return
    end
    json_response = @instances_interface.import_snapshot(instance['id'], query_params, payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Snapshot import initiated."
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list(args) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
# File 'lib/morpheus/cli/commands/instances.rb', line 70

def list(args)
  options = {}
  params = {}
  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
    opts.on( '--owner USER', "Owner Username or ID" ) do |val|
      options[:owner] = val
    end
    opts.on( '--created-by USER', "Alias for --owner" ) do |val|
      options[:owner] = val
    end
    opts.on('--agent', "Show only Instances with the agent installed" ) do
      params[:agentInstalled] = true
    end
    opts.on('--noagent', "Show only Instances with No agent" ) do
      params[:agentInstalled] = false
    end
    opts.add_hidden_option('--created-by')
    opts.on('--status STATUS', "Filter by status i.e. provisioning,running,starting,stopping") do |val|
      params['status'] = (params['status'] || []) + val.to_s.split(',').collect {|s| s.strip }.select {|s| s != "" }
    end
    opts.on( '--type CODE', String, "Filter by Instance Type code" ) do |val|
      # commas used in names a lot so use --plan one --plan two
      params['instanceType'] ||= []
      params['instanceType'] << val
    end
    opts.on( '--environment CODE', String, "Filter by Environment code(s)" ) do |val|
      # commas used in names a lot so use --plan one --plan two
      params['environment'] ||= []
      params['environment'] << val
    end
    opts.on('--pending-removal', "Include instances pending removal.") do
      options[:showDeleted] = true
    end
    opts.on('--pending-removal-only', "Only instances pending removal.") do
      options[:deleted] = true
    end
    opts.on( '--plan NAME', String, "Filter by Plan name(s)" ) do |val|
      # commas used in names a lot so use --plan one --plan two
      params['plan'] ||= []
      params['plan'] << val
    end
    opts.on( '--plan-id ID', String, "Filter by Plan id(s)" ) do |val|
      params['planId'] = parse_id_list(val)
    end
    opts.on( '--plan-code CODE', String, "Filter by Plan code(s)" ) do |val|
      params['planCode'] = parse_id_list(val)
    end
    opts.on('-l', '--labels LABEL', String, "Filter by labels, can match any of the values") do |val|
      add_query_parameter(params, 'labels', parse_labels(val))
    end
    opts.on('--all-labels LABEL', String, "Filter by labels, must match all of the values") do |val|
      add_query_parameter(params, 'allLabels', parse_labels(val))
    end
    opts.on('--tags Name=Value',String, "Filter by tags (metadata name value pairs).") do |val|
      val.split(",").each do |value_pair|
        k,v = value_pair.strip.split("=")
        options[:tags] ||= {}
        options[:tags][k] ||= []
        options[:tags][k] << (v || '')
      end
    end
    opts.on('--stats', "Display values for memory and storage usage used / max values." ) do
      options[:stats] = true
    end
    opts.on('-a', '--details', "Display all details: plan, stats, etc" ) do
      options[:details] = true
      params['details'] = true # get more data from server this way
    end
    build_standard_list_options(opts, options)
    opts.footer = "List instances."
  end
  optparse.parse!(args)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  connect(options)

  params.merge!(parse_list_options(options))
  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

   = nil
  #todo: user = find_available_user_option(owner_id)

  if options[:owner]
    created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:owner])
    return if created_by_ids.nil?
    params['createdBy'] = created_by_ids
    params['ownerId'] = created_by_ids # 4.2.1+
  end

  params['showDeleted'] = true if options[:showDeleted]
  params['deleted'] = true if options[:deleted]
  if options[:tags]
    options[:tags].each do |k,v|
      params['tags.' + k] = v
    end
  end

  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.list(params)
    return 0
  end
  json_response = @instances_interface.list(params)
  all_stats = json_response['stats'] || {}
  # merge stats into each record just to be nice...
  if options[:include_fields] || options[:all_fields]
    if json_response['instances']
      if all_stats
        json_response['instances'].each do |it|
          it['stats'] ||= all_stats[it['id'].to_s] || all_stats[it['id']]
        end
      end
    end
  end
  render_response(json_response, options, "instances") do
    instances = json_response['instances']

    title = "Morpheus Instances"
    subtitles = []
    if group
      subtitles << "Group: #{group['name']}".strip
    end
    if cloud
      subtitles << "Cloud: #{cloud['name']}".strip
    end
    if host
      subtitles << "Host: #{host['name']}".strip
    end
    if options[:owner]
      subtitles << "Created By: #{options[:owner]}"
    end
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options
    if instances.empty?
      print cyan,"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})
        if options[:details] || options[:stats]
          if stats['maxMemory'] && stats['maxMemory'].to_i != 0
            memory_usage_str = memory_usage_str + cyan + format_bytes_short(stats['usedMemory']).strip.rjust(8, ' ')  + " / " + format_bytes_short(stats['maxMemory']).strip
          end
          if stats['maxStorage'] && stats['maxStorage'].to_i != 0
            storage_usage_str = storage_usage_str + cyan + format_bytes_short(stats['usedStorage']).strip.rjust(8, ' ') + " / " + format_bytes_short(stats['maxStorage']).strip
          end
        end
        row = {
          id: instance['id'],
          name: instance['name'],
          labels: format_list(instance['labels'], '', 3),
          connection: format_instance_connection_string(instance),
          environment: instance['instanceContext'],
          user: (instance['owner'] ? (instance['owner']['username'] || instance['owner']['id']) : (instance['createdBy'].is_a?(Hash) ? instance['createdBy']['username'] : instance['createdBy'])),
          tenant: (instance['owner'] ? (instance['owner']['username'] || instance['owner']['id']) : (instance['createdBy'].is_a?(Hash) ? instance['createdBy']['username'] : instance['createdBy'])),
          nodes: instance['containers'].count,
          status: format_instance_status(instance, cyan),
          type: instance['instanceType']['name'],
          group: instance['group'] ? instance['group']['name'] : nil,
          cloud: instance['cloud'] ? instance['cloud']['name'] : nil,
          plan: instance['plan'] ? instance['plan']['name'] : '',
          version: instance['instanceVersion'] ? instance['instanceVersion'] : '',
          created: format_local_dt(instance['dateCreated']),
          cpu: cpu_usage_str + cyan,
          memory: memory_usage_str + cyan, 
          storage: storage_usage_str + cyan
        }
        row
      }
      columns = [:id, {:name => {:max_width => 50}}, :labels, :group, :cloud, 
          :type, :version, :environment, :plan,
          {:created => {:display_name => "CREATED"}}, 
          # {:tenant => {:display_name => "TENANT"}}, 
          {:user => {:display_name => "OWNER", :max_width => 20}}, 
          :nodes, {:connection => {:max_width => 30}}, :status, :cpu, :memory, :storage]
      # custom pretty table columns ... this is handled in as_pretty_table now(), 
      # todo: remove all these.. and try to always pass rows as the json data itself..
      if options[:details] != true
        columns.delete(:labels)
        columns.delete(:plan)
      end
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
end

#list_containers(args) ⇒ Object



1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
# File 'lib/morpheus/cli/commands/instances.rb', line 1586

def list_containers(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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

#list_schedules(args) ⇒ Object



3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
# File 'lib/morpheus/cli/commands/instances.rb', line 3880

def list_schedules(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_get_options(opts, options) # build_standard_list_options(opts, options) # phrase,max,etc is not supported
    opts.footer = <<-EOT
List instance scaling threshold schedules.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  parse_get_options!(args, options, params) # parse_list_options!(args, options, params) # phrase,max,etc is not supported
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.list_schedules(instance['id'], params)
    return 0, nil
  end
  json_response = @instances_interface.list_schedules(instance['id'], params)
  list_key = 'instanceSchedules'
  render_response(json_response, options, list_key) do
    records = json_response[list_key]
    title = "Morpheus Instance Schedules"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options
    if records.nil? || records.empty?
      print cyan,"No schedules found.",reset,"\n"
    else
      print as_pretty_table(records, instance_schedule_list_column_definitions(options).upcase_keys!, options)
      print_results_pagination(json_response) if json_response['meta']
    end
    print reset,"\n"
  end
  return 0, nil

end

#load_balancer_remove(args) ⇒ Object



4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
# File 'lib/morpheus/cli/commands/instances.rb', line 4200

def load_balancer_remove(args)
  usage = "Usage: morpheus instances lb-remove [instance] [options]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance]")
    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 = {}
    @instances_interface.setopts(options)
    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



4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
# File 'lib/morpheus/cli/commands/instances.rb', line 4118

def load_balancer_update(args)
  raise "Not Yet Implemented"
  usage = "Usage: morpheus instances lb-update [instance] [options]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance]")
    #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
    @instances_interface.setopts(options)
    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

#lock(args) ⇒ Object



4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
# File 'lib/morpheus/cli/commands/instances.rb', line 4779

def lock(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Lock an instance
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!(parse_passed_options(options))
  else
    payload.deep_merge!(parse_passed_options(options))
  end
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.lock(instance['id'], payload)
    return
  end
  json_response = @instances_interface.lock(instance['id'], payload)
  render_response(json_response, options) do
    print_green_success "Locked instance #{instance['name']}"
  end
  return 0, nil
end

#logs(args) ⇒ Object



1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
# File 'lib/morpheus/cli/commands/instances.rb', line 1154

def logs(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    # opts.on('--hosts HOSTS', String, "Filter logs to specific Host ID(s)") do |val|
    #   params['servers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    # opts.on('--servers HOSTS', String, "alias for --hosts") do |val|
    #   params['servers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    # opts.on('--vms HOSTS', String, "alias for --hosts") do |val|
    #   params['servers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    opts.on( '-n', '--node NODE_ID', "Scope logs to specific Container or VM" ) do |node_id|
      options[:node_id] = node_id.to_i
    end
    # opts.on('--container CONTAINER', String, "Filter logs to specific Container ID(s)") do |val|
    #   params['containers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    # opts.on('--nodes HOST', String, "alias for --containers") do |val|
    #   params['containers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    opts.on('--start TIMESTAMP','--start TIMESTAMP', "Start timestamp. Default is 30 days ago.") do |val|
      options[:start] = parse_time(val) #.utc.iso8601
    end
    opts.on('--end TIMESTAMP','--end TIMESTAMP', "End timestamp. Default is now.") do |val|
      options[:end] = parse_time(val) #.utc.iso8601
    end
    # opts.on('--interval TIME','--interval TIME', "Interval of time to include, in seconds. Default is 30 days ago.") do |val|
    #   options[:interval] = parse_time(val).utc.iso8601
    # end
    opts.on('--level VALUE', String, "Log Level. DEBUG,INFO,WARN,ERROR") do |val|
      params['level'] = params['level'] ? [params['level'], val].flatten : [val]
    end
    opts.on('--table', '--table', "Format ouput as a table.") do
      options[:table] = true
    end
    opts.on('-a', '--all', "Display all details: entire message." ) do
      options[:details] = true
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
  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]
      if container_ids.include?(options[:node_id])
        container_ids = [options[:node_id]]
      else
        print_red_alert "Instance does not include node #{options[:node_id]}"
        return 1
      end
    end
    params['level'] = params['level'].collect {|it| it.to_s.upcase }.join('|') if params['level'] # api works with INFO|WARN
    params.merge!(parse_list_options(options))
    params['query'] = params.delete('phrase') if params['phrase']
    params['order'] = params['direction'] unless params['direction'].nil? # old api version expects order instead of direction
    params['startMs'] = (options[:start].to_i * 1000) if options[:start]
    params['endMs'] = (options[:end].to_i * 1000) if options[:end]
    params['interval'] = options[:interval].to_s if options[:interval]
    @logs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @logs_interface.dry.container_logs(container_ids, params)
      return
    end
    json_response = @logs_interface.container_logs(container_ids, params)
    render_result = json_response['logs'] ? render_with_format(json_response, options, 'logs') : render_with_format(json_response, options, 'data')
    return 0 if render_result
    
    title = "Instance Logs: #{instance['name']} (#{instance['instanceType'] ? instance['instanceType']['name'] : ''})"
    subtitles = parse_list_subtitles(options)
    if options[:start]
      subtitles << "Start: #{options[:start]}".strip
    end
    if options[:end]
      subtitles << "End: #{options[:end]}".strip
    end
    if params[:query]
      subtitles << "Search: #{params[:query]}".strip
    end
    if params['servers']
      subtitles << "Servers: #{params['servers']}".strip
    end
    if params['containers']
      subtitles << "Containers: #{params['containers']}".strip
    end
    if params[:query]
      subtitles << "Search: #{params[:query]}".strip
    end
    if params['level']
      subtitles << "Level: #{params['level']}"
    end
    logs = json_response['data'] || json_response['logs']
    print_h1 title, subtitles, options
    if logs.empty?
      print "#{cyan}No logs found.#{reset}\n"
    else
      print format_log_records(logs, options)
      print_results_pagination({'meta'=>{'total'=>(json_response['total']['value'] rescue json_response['total']),'size'=>logs.size,'max'=>(json_response['max'] || options[:max]),'offset'=>(json_response['offset'] || options[:offset] || 0)}})
    end
    print reset, "\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#prepare_apply(args) ⇒ Object



4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
# File 'lib/morpheus/cli/commands/instances.rb', line 4895

def prepare_apply(args)
  params, payload, options = {}, {}, {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [options]")
    build_standard_update_options(opts, options, [:auto_confirm])
    opts.footer = <<-EOT
Prepare to apply an instance.
[instance] is required. This is the name or id of an instance.
Displays the current configuration data used by the apply command.
This is only supported by certain types of instances such as terraform.
EOT
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(', ')}\n#{optparse}"
  end
  connect(options)

  begin
    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
    # construct request
    params.merge!(parse_query_options(options))
    payload = {}
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!(parse_passed_options(options))
    else
      payload.deep_merge!(parse_passed_options(options))
      # raise_command_error "Specify at least one option to update.\n#{optparse}" if payload.empty?
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.prepare_apply(instance["id"], params)
      return
    end
    json_response = @instances_interface.prepare_apply(instance["id"], params)
    render_result = render_with_format(json_response, options)
    return 0 if render_result
    # print_green_success "Prepared to apply instance: #{instance['name']}"
    print_h1 "Prepared Instance: #{instance['name']}"
    instance_config = json_response['data'] 
    # instance_config = json_response if instance_config.nil?
    puts as_yaml(instance_config, options)
    #return get([app['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    print "\n", reset
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#refresh(args) ⇒ Object



4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
# File 'lib/morpheus/cli/commands/instances.rb', line 4847

def refresh(args)
  params, payload, options = {}, {}, {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [options]")
    build_standard_update_options(opts, options, [:auto_confirm])
    opts.footer = <<-EOT
Refresh an instance.
[instance] is required. This is the name or id of an instance.
This is only supported by certain types of instances such as terraform.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)

  begin
    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
    # construct request
    params.merge!(parse_query_options(options))
    payload = {}
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!(parse_passed_options(options))
    else
      payload.deep_merge!(parse_passed_options(options))
      # raise_command_error "Specify at least one option to update.\n#{optparse}" if payload.empty?
    end
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to refresh this instance: #{instance['name']}?")
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.refresh(instance["id"], params, payload)
      return
    end
    json_response = @instances_interface.refresh(instance["id"], params, payload)
    render_response(json_response, options) do
      print_green_success "Refreshing instance #{instance['name']}"
      # return _get(instance['id'], options)
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
# File 'lib/morpheus/cli/commands/instances.rb', line 2928

def remove(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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.nil? ? 'on' : val
    end
    opts.on('--release-ips [on|off]', ['on','off'], "Release Floating IPs. Default is on. Applies to certain types only.") do |val|
      query_params[:releaseFloatingIps] = val.nil? ? 'on' : val
      query_params[:releaseEIPs] = query_params[:releaseFloatingIps] # old parameter before 6.0
    end
    opts.on('--releaseEIPs [on|off]', ['on','off'], "Alias for Release Floating IPs") do |val|
      query_params[:releaseFloatingIps] = val.nil? ? 'on' : val
      query_params[:releaseEIPs] = query_params[:releaseFloatingIps] # old parameter before 6.0
    end
    opts.add_hidden_option('--releaseEIPs')
    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
    @instances_interface.setopts(options)
    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([] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_all_container_snapshots(args) ⇒ Object



3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
# File 'lib/morpheus/cli/commands/instances.rb', line 3575

def remove_all_container_snapshots(args)
  options = {}
  instance = nil
  container_id = nil

  optparse = Morpheus::Cli::OptionParser.new do |opts|
   opts.banner = subcommand_usage("[instance]")
    opts.on("--container ID", String, "Required container") do |val|
      container_id = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Remove all snapshots attached to an instances container." + "\n" +
                  "[containerId] is required. This is the id of the container which removes all attached snapshots."
  end
  
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  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 all snapshots for a container?", options)
      exit 1
    end
    options[:options]['instanceId'] = instance['id']
    begin
      container_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'containerId', 'type' => 'select', 'fieldLabel' => 'Container', 'optionSource' => 'instanceContainers', 'required' => true, 'description' => 'Select Container.'}], {}, @api_client, options[:options])
      
      if !container_prompt['containerId'].to_s.empty?
        container_id = container_prompt['containerId']
      end
    rescue RestClient::Exception => e
      puts "Failed to load instance containers"
    end
    
    @instances_interface.setopts(options)
 
    payload = {}
    if options[:dry_run]
      print_dry_run @instances_interface.dry.remove_all_container_snapshots(instance['id'], container_id, payload)
      return
    end
    
    json_response = @instances_interface.remove_all_container_snapshots(instance['id'], container_id, payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Snapshot delete initiated."
    end
    return 0

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

#remove_all_snapshots(args) ⇒ Object



3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
# File 'lib/morpheus/cli/commands/instances.rb', line 3633

def remove_all_snapshots(args)
  options = {}
  instance = nil

  optparse = Morpheus::Cli::OptionParser.new do |opts|
   opts.banner = subcommand_usage("[instance]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Remove all snapshots attached to an instance." + "\n" +
                  "Warning: This will remove all snapshots across all containers of an instance."
  end
  
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  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 all snapshots for this instance?", options)
      exit 1
    end
    options[:options]['instanceId'] = instance['id']

    @instances_interface.setopts(options)
 
    payload = {}
    if options[:dry_run]
      print_dry_run @instances_interface.dry.remove_all_instance_snapshots(instance['id'], payload)
      return
    end
    
    json_response = @instances_interface.remove_all_instance_snapshots(instance['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Snapshots attaced to instance #{instance['name']} queued for deletion."
    end
    return 0

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

#remove_from_control(args) ⇒ Object



3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
# File 'lib/morpheus/cli/commands/instances.rb', line 3143

def remove_from_control(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name or id]")
    opts.footer = "Remove a brownfield instance from Morpheus. This does not delete the cloud instance, only Morpheus' record of it.\n" +
                  "[name or id] is required. The name or the id of the instance may be listed.\n" +
                  "[name or id] [name or id] [name or id] ...  A list of names or ids, separated by a space, may be used for bulk removal."
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.remove_from_control(instances.collect {|it| it['id'] }, params)
      return
    end
    json_response = @instances_interface.remove_from_control(instances.collect {|it| it['id'] }, params)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      puts json_response
      if json_response['success'] == false
         print_red_alert json_response['msg']
      else
         print_green_success json_response['msg']
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_schedule(args) ⇒ Object



4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
# File 'lib/morpheus/cli/commands/instances.rb', line 4083

def remove_schedule(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [schedule]")
    build_standard_remove_options(opts, options)
    opts.footer = <<-EOT
Delete an existing instance scaling threshold schedule
[instance] is required. This is the name or id of an instance
[schedule] is required. This is id of an instance schedule
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  params.merge!(parse_query_options(options))
  instance = find_instance_by_name_or_id(args[0])
  return 1, "Instance not found for '#{args[0]}'" if instance.nil?
  instance_schedule = find_instance_schedule_by_id(instance['id'], args[1])
  return 1, "Instance schedule not found for '#{args[1]}'" if instance_schedule.nil?
  unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the instance schedule #{instance_schedule['id']}?")
    return 9, "aborted"
  end
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.destroy_schedule(instance['id'], instance_schedule['id'], params)
    return 0, nil
  end
  json_response = @instances_interface.destroy_schedule(instance['id'], instance_schedule['id'], params)
  render_response(json_response, options) do
    print_green_success "Removed instance schedule #{instance_schedule['id']}"
  end
  return 0, nil
end

#resize(args) ⇒ Object



2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
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
# File 'lib/morpheus/cli/commands/instances.rb', line 2740

def resize(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options)
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
  return 1, "instance not found" if instance.nil?
  
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!(parse_passed_options(options))
  else
    payload = {
      "instance" => {:id => instance["id"]}
    }
    payload.deep_merge!(parse_passed_options(options))

    # 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"

    group_id = instance['group']['id']
    cloud_id = instance['cloud']['id']
    layout_id = instance['layout']['id']
    plan_id = instance['plan']['id']
    resource_pool_id = instance['config']['resourcePoolId'] if instance['config']
    current_plan_name = instance['plan']['name']
    current_interfaces = get_instance_interfaces(instance)
    if current_interfaces != false 
      payload['networkInterfaces'] = current_interfaces
    end
    

    # need to GET provision type for some settings...
    provision_type = @provision_types_interface.get(instance['layout']['provisionTypeId'])['provisionType']

    # prompt for service plan
    service_plans_json = @instances_interface.service_plans({zoneId: cloud_id, siteId: group_id, layoutId: layout_id, resourcePoolId: resource_pool_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)"
      #   current_plan_name = plan['name']
      # end
    end
    plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'servicePlan', 'type' => 'select', 'fieldLabel' => 'Plan', 'selectOptions' => service_plans_dropdown, 'required' => true, 'defaultValue' => current_plan_name, '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
    vol_options = options 
    vol_options['siteId'] = group_id
    vol_options['zoneId'] = cloud_id
    volumes = prompt_resize_volumes(current_volumes, service_plan, provision_type, vol_options)
    if !volumes.empty?
      payload["volumes"] = volumes
    end

    # plan customizations
    plan_opts = prompt_service_plan_options(service_plan, options, @api_client, {}, instance)
    if plan_opts && !plan_opts.empty?
      payload['servicePlanOptions'] = plan_opts
    end

    # only amazon supports this option
    # for now, always do this
    payload["deleteOriginalVolumes"] = true
  end
  payload.delete("rootVolume")
  (1..20).each {|i| payload.delete("dataVolume#{i}") }
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.resize(instance['id'], payload)
    return
  end
  json_response = @instances_interface.resize(instance['id'], payload)
  render_response(json_response, options, 'snapshots') do
    print_green_success "Resizing instance #{instance['name']}"
  end
  return 0, nil
  

end

#restart(args) ⇒ Object



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

def restart(args)
  params = {'server' => true, 'muteMonitoring' => true}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('--mute-monitoring [on|off]', String, "Mute monitoring. Default is on.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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
    opts.add_hidden_option('--muteMonitoring') if opts.is_a?(Morpheus::Cli::OptionParser)
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Restart 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_h1 "DRY RUN", [], options
      instances.each do |instance|
        print_dry_run @instances_interface.dry.restart(instance['id'], params)
      end
      return 0
    end
    bad_responses = []
    instances.each do |instance|
      json_response = @instances_interface.restart(instance['id'], params)
      render_result = render_with_format(json_response, options)
      if render_result
        #return 0
      elsif !options[:quiet]
        print green, "Restarting instance #{instance['name']}", reset, "\n"
      end
      if json_response['success'] == false
        bad_responses << json_response
        if !options[:quiet]
          print_rest_errors(json_response)
        end
      end
    end
    if !bad_responses.empty?
      return 1
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#restart_service(args) ⇒ Object



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

def restart_service(args)
  params = {'server' => false, 'muteMonitoring' => true}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('--mute-monitoring [on|off]', String, "Mute monitoring. Default is on.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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
    opts.add_hidden_option('--muteMonitoring')
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Restart service on 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart service on #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_h1 "DRY RUN", [], options
      instances.each do |instance|
        print_dry_run @instances_interface.dry.restart(instance['id'], params)
      end
      return 0
    end
    bad_responses = []
    instances.each do |instance|
      json_response = @instances_interface.restart(instance['id'], params)
      render_result = render_with_format(json_response, options)
      if render_result
        #return 0
      elsif !options[:quiet]
        print green, "Restarting service on instance #{instance['name']}", reset, "\n"
      end
      if json_response['success'] == false
        bad_responses << json_response
        if !options[:quiet]
          print_rest_errors(json_response)
        end
      end
    end
    if !bad_responses.empty?
      return 1
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#revert_to_snapshot(args) ⇒ Object



3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
# File 'lib/morpheus/cli/commands/instances.rb', line 3516

def revert_to_snapshot(args)
  options = {}
  instance = nil
  snapshot_id = nil

  optparse = Morpheus::Cli::OptionParser.new do |opts|
   opts.banner = subcommand_usage("[instance]")
    opts.on("--snapshot ID", String, "Optional snapshot") do |val|
      snapshot_id = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
         build_standard_add_options(opts, options) #, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Revert an Instance to saved Snapshot previously made." + "\n" +
                  "[snapshotId] is required. This is the id of the snapshot to replace the current instance."
  end
  
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  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 revert instance '#{instance['name']}'?", options)
      exit 1
    end
    options[:options]['instanceId'] = instance['id']
    begin
      snapshot_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'snapshotId', 'type' => 'select', 'fieldLabel' => 'Snapshot', 'optionSource' => 'instanceSnapshots', 'required' => true, 'description' => 'Select Snapshot.'}], {}, @api_client, options[:options])
    
      if !snapshot_prompt['snapshotId'].to_s.empty?
        snapshot_id = snapshot_prompt['snapshotId']
      end
    rescue RestClient::Exception => e
      puts "Failed to load instance snapshots"
    end
    
    @instances_interface.setopts(options)
 
    payload = {}
    if options[:dry_run]
      print_dry_run @instances_interface.dry.revert_to_snapshot(instance['id'], snapshot_id, payload)
      return
    end
    
    json_response = @instances_interface.revert_to_snapshot(instance['id'], snapshot_id, payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Snapshot revert initiated."
    end
    return 0

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

#run_workflow(args) ⇒ Object



3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
# File 'lib/morpheus/cli/commands/instances.rb', line 3352

def run_workflow(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [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_or_id(args[1])
  task_types = @tasks_interface.list_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
    @instances_interface.setopts(options)
    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



3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
# File 'lib/morpheus/cli/commands/instances.rb', line 3734

def scaling(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance]")
    build_common_options(opts, options, [:query, :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



3798
3799
3800
3801
# File 'lib/morpheus/cli/commands/instances.rb', line 3798

def scaling_update(args)
  print_error "#{yellow}DEPRECATION WARNING: `instances scaling-update` has been renamed to `instances update-scaling`. Please use `instances update-scaling` instead.#{reset}\n"
  update_scaling(args)
end

#security_groups(args) ⇒ Object



3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
# File 'lib/morpheus/cli/commands/instances.rb', line 3257

def security_groups(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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])
    @instances_interface.setopts(options)
    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']}", [], options
    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



2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
# File 'lib/morpheus/cli/commands/instances.rb', line 2024

def setenv(args)
  options = {}

  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] 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]}
    @instances_interface.setopts(options)
    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]] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#snapshot(args) ⇒ Object



2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
# File 'lib/morpheus/cli/commands/instances.rb', line 2886

def snapshot(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on( '--name VALUE', String, "Snapshot Name. Default is server name + timestamp" ) do |val|
      options[:options]['name'] = val
    end
    opts.on( '--description VALUE', String, "Snapshot Description." ) do |val|
      options[:options]['description'] = val
    end
    build_standard_add_options(opts, options, [:auto_confirm])
    opts.footer = <<-EOT
Create a snapshot for an instance.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to snapshot the instance '#{instance['name']}'?", options)
    exit 1
  end
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({'snapshot' => parse_passed_options(options)})
  else
    payload.deep_merge!({'snapshot' => parse_passed_options(options)})
  end
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.snapshot(instance['id'], payload)
    return
  end
  json_response = @instances_interface.snapshot(instance['id'], payload)
  render_response(json_response, options, 'snapshots') do
    print_green_success "Snapshot initiated."
  end
  return 0, nil
end

#snapshots(args) ⇒ Object



3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
# File 'lib/morpheus/cli/commands/instances.rb', line 3410

def snapshots(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    # no pagination yet
    # build_standard_list_options(opts, options)
    build_standard_get_options(opts, options)
          opts.footer = <<-EOT
List snapshots for an instance.
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    params = {}
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.snapshots(instance['id'], params)
      return
    end
    json_response = @instances_interface.snapshots(instance['id'], params)
    snapshots = json_response['snapshots']      
    render_response(json_response, options, 'snapshots') do
      print_h1 "Snapshots: #{instance['name']} (#{instance['instanceType']['name']})", [], options
      if snapshots.empty?
        print cyan,"No snapshots found",reset,"\n"
      else
        snapshot_column_definitions = {
          "ID" => lambda {|it| it['id'] },
          "Name" => lambda {|it| it['name'] },
          "Description" => lambda {|it| it['description'] },
          # "Type" => lambda {|it| it['snapshotType'] },
          "Date Created" => lambda {|it| format_local_dt(it['snapshotCreated']) },
          "Status" => lambda {|it| format_snapshot_status(it) }
        }
        print cyan
        print as_pretty_table(snapshots, snapshot_column_definitions.upcase_keys!, options)
        print_results_pagination({size: snapshots.size, total: snapshots.size})
      end
      print reset, "\n"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#start(args) ⇒ Object



2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
# File 'lib/morpheus/cli/commands/instances.rb', line 2167

def start(args)
  params = {'server' => true}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Start 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to start #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_h1 "DRY RUN", [], options
      instances.each do |instance|
        print_dry_run @instances_interface.dry.start(instance['id'], params)
      end
      return 0
    end
    bad_responses = []
    instances.each do |instance|
      json_response = @instances_interface.start(instance['id'], params)
      render_result = render_with_format(json_response, options)
      if render_result
        #return 0
      elsif !options[:quiet]
        print green, "Starting instance #{instance['name']}", reset, "\n"
      end
      if json_response['success'] == false
        bad_responses << json_response
        if !options[:quiet]
          print_rest_errors(json_response)
        end
      end
    end
    if !bad_responses.empty?
      return 1
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#start_service(args) ⇒ Object



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

def start_service(args)
  params = {'server' => false}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Start service on 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to start service on #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_h1 "DRY RUN", [], options
      instances.each do |instance|
        print_dry_run @instances_interface.dry.start(instance['id'], params)
      end
      return 0
    end
    bad_responses = []
    instances.each do |instance|
      json_response = @instances_interface.start(instance['id'], params)
      render_result = render_with_format(json_response, options)
      if render_result
        #return 0
      elsif !options[:quiet]
        print green, "Starting service on instance #{instance['name']}", reset, "\n"
      end
      if json_response['success'] == false
        bad_responses << json_response
        if !options[:quiet]
          print_rest_errors(json_response)
        end
      end
    end
    if !bad_responses.empty?
      return 1
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#state(args) ⇒ Object



5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
# File 'lib/morpheus/cli/commands/instances.rb', line 5096

def state(args)
  params, payload, options = {}, {}, {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [options]")
    opts.on('--data', "Display State Data") do
      options[:include_state_data] = true
    end
    opts.on('--specs', "Display Spec Templates") do
      options[:include_spec_templates] = true
    end
    opts.on('--plan', "Display Plan Data") do
      options[:include_plan_data] = true
    end
    opts.on('--input', "Display Input") do
      options[:include_input] = true
    end
    opts.on('--output', "Display Output") do
      options[:include_output] = true
    end
    opts.on('-a','--all', "Display All Details") do
      options[:include_state_data] = true
      options[:include_spec_templates] = true
      options[:include_plan_data] = true
      options[:include_input] = true
      options[:include_output] = true
      options[:details] = true
    end
    build_standard_get_options(opts, options)
    opts.footer = <<-EOT
View state of an instance.
[instance] is required. This is the name or id of an instance.
This is only supported by certain types of apps such as terraform.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
  # construct request
  params.merge!(parse_query_options(options))
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.state(instance["id"], params)
    return
  end
  json_response = @instances_interface.state(instance["id"], params)
  render_result = render_with_format(json_response, options)
  return 0 if render_result
  print_h1 "Instance State: #{instance['name']}", options
  # print_h2 "Workloads", options
  if json_response['workloads'] && !json_response['workloads'].empty?
    workload_columns = {
      "Name" => lambda {|it| it['subRefName'].to_s.empty? ? "#{it['refName']}" : "#{it['refName']} - #{it['subRefName']}" },
      "Last Check" => lambda {|it| format_local_dt(it['stateDate']) },
      "Status" => lambda {|it| format_ok_status(it['status'] || 'ok') },
      "Drift Status" => lambda {|it| it['iacDrift'] ? "Drift" : "No Drift" }
    }
    print as_pretty_table(json_response['workloads'], workload_columns.upcase_keys!, options)
  else
    print cyan,"No workloads found.",reset,"\n"
  end
  if options[:include_state_data]
    print_h2 "State Data", options
    puts json_response['stateData']
  end
  if options[:include_spec_templates]
    print_h2 "Spec Templates", options
    spec_templates_columns = {
      "Resource Spec" => lambda {|it| it['name'] || (it['template'] ? it['template']['name'] : nil) },
      "Attached to Source Template" => lambda {|it| format_boolean(!it['isolated']) },
      "Source Spec Template" => lambda {|it| (it['template'] ? it['template']['name'] : nil) || it['name'] }
    }
    print as_pretty_table(json_response['specs'], spec_templates_columns.upcase_keys!, options)
    # print "\n", reset
  end
  if options[:include_plan_data]
    # print_h2 "Plan Data", options
    if instance['type'] == 'terraform' || instance['layout']['provisionTypeCode'] == 'terraform'
      print_h2 "Terraform Plan", options
    else
      print_h2 "Plan Data", options
    end
    puts json_response['planData']
    # print "\n", reset
  end
  if options[:include_input]
    # print_h2 "Input"
    if json_response['input'] && json_response['input']['variables']
      print_h2 "VARIABLES", options
      input_variable_columns = {
        "Name" => lambda {|it| it['name'] },
        "Value" => lambda {|it| it['value'] }
      }
      print as_pretty_table(json_response['input']['variables'], input_variable_columns.upcase_keys!, options)
    end
    if json_response['input'] && json_response['input']['providers']
      print_h2 "PROVIDERS", options
      input_provider_columns = {
        "Name" => lambda {|it| it['name'] }
      }
      print as_pretty_table(json_response['input']['providers'], input_provider_columns.upcase_keys!, options)
    end
    if json_response['input'] && json_response['input']['data']
      print_h2 "DATA", options
      input_data_columns = {
        "Type" => lambda {|it| it['type'] },
        "Key" => lambda {|it| it['key'] },
        "Name" => lambda {|it| it['name'] }
      }
      print as_pretty_table(json_response['input']['data'], input_data_columns.upcase_keys!, options)
    end
    # print "\n", reset
  end
  if options[:include_output]
    # print_h2 "Output", options
    if json_response['output'] && json_response['output']['outputs']
      print_h2 "OUTPUTS", options
      input_variable_columns = {
        "Name" => lambda {|it| it['name'] },
        "Value" => lambda {|it| it['value'] }
      }
      print as_pretty_table(json_response['output']['outputs'], input_variable_columns.upcase_keys!, options)
    end
    # print "\n", reset
  end
  print "\n", reset
  return 0
end

#stats(args) ⇒ Object



1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# File 'lib/morpheus/cli/commands/instances.rb', line 1009

def stats(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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



976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
# File 'lib/morpheus/cli/commands/instances.rb', line 976

def status_check(args)
  out = ""
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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



2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
# File 'lib/morpheus/cli/commands/instances.rb', line 2099

def stop(args)
  params = {'server' => true, 'muteMonitoring' => false}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('--mute-monitoring [on|off]', String, "Mute monitoring. Default is off.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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
    opts.add_hidden_option('--muteMonitoring') if opts.is_a?(Morpheus::Cli::OptionParser)
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Stop 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_h1 "DRY RUN", [], options
      instances.each do |instance|
        print_dry_run @instances_interface.dry.stop(instance['id'], params)
      end
      return 0
    end
    bad_responses = []
    instances.each do |instance|
      json_response = @instances_interface.stop(instance['id'], params)
      render_result = render_with_format(json_response, options)
      if render_result
        #return 0
      elsif !options[:quiet]
        print green, "Stopping instance #{instance['name']}", reset, "\n"
      end
      if json_response['success'] == false
        bad_responses << json_response
        if !options[:quiet]
          print_rest_errors(json_response)
        end
      end
    end
    if !bad_responses.empty?
      return 1
    end
    return 0
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#stop_service(args) ⇒ Object



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
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
# File 'lib/morpheus/cli/commands/instances.rb', line 2401

def stop_service(args)
  params = {'server' => false, 'muteMonitoring' => false}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('--mute-monitoring [on|off]', String, "Mute monitoring. Default is off.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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
    opts.add_hidden_option('--muteMonitoring') if opts.is_a?(Morpheus::Cli::OptionParser)
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Stop service on 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop service on #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_h1 "DRY RUN", [], options
      instances.each do |instance|
        print_dry_run @instances_interface.dry.stop(instance['id'], params)
      end
      return 0
    end
    bad_responses = []
    instances.each do |instance|
      json_response = @instances_interface.stop(instance['id'], params)
      render_result = render_with_format(json_response, options)
      if render_result
        #return 0
      elsif !options[:quiet]
        print green, "Stopping service on instance #{instance['name']}", reset, "\n"
      end
      if json_response['success'] == false
        bad_responses << json_response
        if !options[:quiet]
          print_rest_errors(json_response)
        end
      end
    end
    if !bad_responses.empty?
      return 1
    end
    return 0
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#suspend(args) ⇒ Object

suspend should be server: false by default I guess..



2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
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
# File 'lib/morpheus/cli/commands/instances.rb', line 2295

def suspend(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('--mute-monitoring [on|off]', String, "Mute monitoring. Default is on.") do |val|
      params['muteMonitoring'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    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
    opts.add_hidden_option('--muteMonitoring')
    opts.on('--server [on|off]', String, "Suspend instance server. Default is off.") do |val|
      params['server'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Suspend 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)
  begin
    instance_ids = parse_id_list(args)
    instances = []
    instance_ids.each do |instance_id|
      instance = find_instance_by_name_or_id(instance_id)
      return 1 if instance.nil?
      instances << instance
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to suspend #{instances.size == 1 ? 'instance' : (instances.size.to_s + ' instances')} #{anded_list(instances.collect {|it| it['name'] })}?", options)
      return 9, "aborted command"
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.suspend(instances.collect {|it| it['id'] }, params)
      return
    end
    json_response = @instances_interface.suspend(instances.collect {|it| it['id'] }, params)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if instances.size == 1
        print_green_success "Suspended instance #{instances[0]['name']}"
      else
        print_green_success "Suspended #{instances.size} instances"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#unlock(args) ⇒ Object



4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
# File 'lib/morpheus/cli/commands/instances.rb', line 4813

def unlock(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Unlock an instance
[instance] is required. This is the name or id of an instance
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!(parse_passed_options(options))
  else
    payload.deep_merge!(parse_passed_options(options))
  end
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.unlock(instance['id'], payload)
    return
  end
  json_response = @instances_interface.unlock(instance['id'], payload)
  render_response(json_response, options) do
    print_green_success "Unlocked instance #{instance['name']}"
  end
  return 0, nil
end

#update(args) ⇒ Object



597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/morpheus/cli/commands/instances.rb', line 597

def update(args)
  params, payload, options = {}, {}, {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    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('--labels [LIST]', String, "Labels (keywords) in the format 'foo, bar'") do |val|
      params['labels'] = parse_labels(val)
    end
    opts.on('--tags LIST', String, "Tags in the format 'name:value, name:value'. This will add and remove tags.") do |val|
      options[:tags] = val
    end
    opts.on('--add-tags TAGS', String, "Add Tags in the format 'name:value, name:value'. This will only add/update tags.") do |val|
      options[:add_tags] = val
    end
    opts.on('--remove-tags TAGS', String, "Remove Tags in the format 'name, name:value'. This removes tags, the :value component is optional and must match if passed.") do |val|
      options[:remove_tags] = val
    end
    opts.on('--power-schedule-type ID', String, "Power Schedule Type ID") do |val|
      params['powerScheduleType'] = val == "null" ? nil : val
    end
    opts.on( '--owner USER', "Owner Username or ID" ) do |val|
      options[:owner] = val == 'null' ? nil : val
    end
    opts.on( '--created-by USER', "Alias for --owner" ) do |val|
      options[:owner] = val == 'null' ? nil : val
    end
    opts.add_hidden_option('--created-by')
    # opts.on("--shutdown-days [DAYS]", Integer, "Automation: Shutdown Days") do |val|
    #   params['shutdownDays'] = val.to_s.empty? ? nil : val.to_i
    # end
    # opts.on("--expire-days DAYS", Integer, "Automation: Expiration Days") do |val|
    #   params['expireDays'] = val.to_s.empty? ? nil : val.to_i
    # end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)

  begin
    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?
    if options[:payload]
      payload = options[:payload]
    end
    payload['instance'] ||= {}
    payload.deep_merge!({'instance' => parse_passed_options(options)})

    if options.key?(:owner) && [nil].include?(options[:owner])
      # allow clearing
      params['ownerId'] = nil
    elsif options[:owner]
      owner_id = options[:owner].to_s
      if owner_id.to_s =~ /\A\d{1,}\Z/
        # allow id without lookup
      else
        user = find_available_user_option(owner_id)
        return 1 if user.nil?
        owner_id = user['id']
      end
      params['ownerId'] = owner_id
      #payload['createdById'] = options[:owner].to_i # pre 4.2.1 api
    end
    if options[:group]
      group = find_group_by_name_or_id_for_provisioning(options[:group])
      if group.nil?
        return 1, "group not found"
      end
      payload['instance']['site'] = {'id' => group['id']}
    end
    # metadata tags
    if options[:tags]
      # api version 4.2.5 and later supports tags, older versions expect metadata
      # todo: use tags instead like everywhere else
      # payload['instance']['tags'] = parse_metadata(options[:tags])
      payload['instance']['metadata'] = (options[:tags])
    end
    if options[:add_tags]
      payload['instance']['addTags'] = (options[:add_tags])
    end
    if options[:remove_tags]
      payload['instance']['removeTags'] = (options[:remove_tags])
    end
    if payload['instance'].empty? && params.empty? && options[:owner].nil?
      raise_command_error "Specify at least one option to update.\n#{optparse}"
    end
    if !params.empty?
      payload['instance'].deep_merge!(params)
    end
    payload.delete('instance') if payload['instance'] && payload['instance'].empty?
    raise_command_error "Specify at least one option to update.\n#{optparse}" if payload.empty?
    @instances_interface.setopts(options)
    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']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_network_label(args) ⇒ Object



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

def update_network_label(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [options]")
    opts.on('--network NETWORK', "Network Interface ID" ) do |val|
      options[:network] = val
    end
    opts.on('--label LABEL', "label") do |val|
      options[:label] = val
    end
     opts.footer = "Change the label of a Network Interface.\n" +
                  "Editing an Interface will not apply changes to the physical hardware. The purpose is for a manual override or data correction (mostly for self managed or baremetal servers where cloud sync is not available)\n" +
                  "[name or id] is required. The name or the id of the instance.\n" +
                  "[network] ID of the Network Interface. (optional).\n" +
                  "[label] New Label name for the Network Interface (optional)"
    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?

    network_id = options[:network]
    if network_id != nil && network_id.to_i == 0
      print_red_alert  "network must be an ID/integer above 0, not a name/string value."
      network_id = nil
    end

    if !network_id
      available_networks = get_available_networks(instance)
      network_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'network', 'fieldLabel' => 'Network', 'type' => 'select', 'selectOptions' => available_networks, 'required' => true, 'defaultValue' => available_networks[0], 'description' => "The networks available for relabeling"}], options[:options])
      network_id = network_prompt['network']
    end



    label = options[:label]
    while label.nil? do
      label_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'label', 'fieldLabel' => 'Label', 'type' => 'text', 'required' => true}], options[:options])
      label = label_prompt['label']
    end
    payload = { "name" => label }
    if options[:dry_run]
      print_dry_run @instances_interface.dry.update_network_label(network_id, instance["id"], payload)
      return
    end
    json_response = @instances_interface.update_network_label(network_id, instance["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Updated label for instance #{instance['name']} network #{network_id} to #{label}"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_scaling(args) ⇒ Object



3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
# File 'lib/morpheus/cli/commands/instances.rb', line 3803

def update_scaling(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance]")
    build_option_type_options(opts, options, update_instance_scaling_option_types)
    build_option_type_options(opts, options, instance_threshold_option_types)
    build_standard_update_options(opts, options)
    opts.footer = "Update scaling threshold settings for an instance."
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  # load objects
  instance = find_instance_by_name_or_id(args[0])
  return 1 if instance.nil?
  instance_threshold = @instances_interface.threshold(instance['id'])['instanceThreshold'] || {}
  # construct payload
  object_key = 'instanceThreshold'
  payload = parse_payload(options, object_key)
  if !payload
    # payload = {object_key => {}}
    payload = {object_key => parse_passed_options(options, exclude: ['sourceThresholdId'])}
    params = {}
    params.deep_merge! Morpheus::Cli::OptionTypes.prompt(update_instance_scaling_option_types, options[:options], @api_client, {})
    source_threshold_id = params.delete('sourceThresholdId')
    customize_threshold_prompt = true
    params ||= {}
    if source_threshold_id.to_s != '' && source_threshold_id.to_s != 'custom'
      params['sourceThresholdId']= source_threshold_id.to_i
      customize_threshold_prompt = false
    end
    # always parse the threshold options but customize_threshold means prompt also
    my_option_types = instance_threshold_option_types
    if customize_threshold_prompt
      # preserve all current values by setting the prompt options defaultValue attribute
      my_option_types.each do |opt|
        field_key = opt['fieldName']
        if instance_threshold[field_key] != nil
          opt['defaultValue'] = instance_threshold[field_key]
        end
      end
      params.deep_merge! Morpheus::Cli::OptionTypes.prompt(my_option_types, options[:options], @api_client, {})
    else
      # preserve current values by setting the prompt options defaultValue attribute
      # only prompt for autoUp and autoDown
      my_option_types.each do |opt|
        field_key = opt['fieldName']
        if ['autoUp','autoDown'].include?(field_key)
          if instance_threshold[field_key] != nil
            opt['defaultValue'] = instance_threshold[field_key]
          end
          opt['noPrompt'] = false
        else
          opt['noPrompt'] = true
        end
      end
      params.deep_merge! Morpheus::Cli::OptionTypes.prompt(my_option_types, options[:options], @api_client, {})
    end
    params.booleanize! # convert checkbox "on" and "off" to true and false
    payload[object_key].deep_merge!(params)
  end
  # 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
  @instances_interface.setopts(options)
  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)
  render_response(json_response, options) do
    print_green_success "Updated scaling settings for instance #{instance['name']}"
    # return _get_inventory(integration, integration_inventory["id"], {}, options)
  end
  return 0, nil
end

#update_schedule(args) ⇒ Object



4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
# File 'lib/morpheus/cli/commands/instances.rb', line 4022

def update_schedule(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[instance] [schedule]")
    build_option_type_options(opts, options, update_instance_schedule_option_types)
    build_option_type_options(opts, options, instance_threshold_option_types)
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Update an existing instance scaling threshold schedule.
[instance] is required. This is the name or id of an instance
[schedule] is required. This is id of an instance schedule
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  instance = find_instance_by_name_or_id(args[0])
  return 1, "Instance not found for '#{args[0]}'" if instance.nil?
  instance_schedule = find_instance_schedule_by_id(instance['id'], args[1])
  return 1, "Instance schedule not found for '#{args[1]}'" if instance_schedule.nil?
  # construct payload
  object_key = 'instanceSchedule'
  payload = parse_payload(options, object_key)
  if !payload
    # payload = {object_key => {}}
    # support -O option but avoid duplicate threshold settings... so -O maxCpu, goes under threshold only
    # could just use options -O threshold.maxCpu instead, which is what the api wants...
    payload = {object_key => parse_passed_options(options, exclude: ['sourceThresholdId'] + instance_threshold_option_types.collect {|i|i['fieldName']})}
    params = {}
    params.deep_merge! Morpheus::Cli::OptionTypes.no_prompt(update_instance_schedule_option_types, options[:options], @api_client, {})
    source_threshold_id = params.delete('sourceThresholdId')
    customize_threshold_prompt = true
    params['threshold'] ||= {}
    if source_threshold_id.to_s != '' && source_threshold_id.to_s != 'custom'
      #params['threshold']['id']= source_threshold_id
      params['threshold']['sourceThresholdId']= source_threshold_id.to_i
      customize_threshold_prompt = false
    end
    params['threshold'].deep_merge! Morpheus::Cli::OptionTypes.no_prompt(instance_threshold_option_types, options[:options], @api_client, {})
    params.booleanize! # convert checkbox "on" and "off" to true and false
    payload[object_key].deep_merge!(params)
    if (payload[object_key].keys - ['threshold']).empty? && payload[object_key]['threshold'].empty?
      raise_command_error "Specify at least one option to update.\n#{optparse}"
    end
    # unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to update the scaling settings for instance '#{instance['name']}' with the above scaling schedule?", options)
    #   return 9, "aborted command"
    # end
  end
  @instances_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @instances_interface.dry.update_schedule(instance['id'], instance_schedule['id'], payload)
    return 0, nil
  end
  json_response = @instances_interface.update_schedule(instance['id'], instance_schedule['id'], payload)
  render_response(json_response, options) do
    print_green_success "Updated scaling schedule for instance #{instance['name']}"
    #_scaling(instance['id'], options)
  end
  return 0, nil
end

#update_wiki(args) ⇒ Object



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

def update_wiki(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance] [options]")
    build_option_type_options(opts, options, update_wiki_page_option_types)
    opts.on('--file FILE', "File containing the wiki content. This can be used instead of --content") do |filename|
      full_filename = File.expand_path(filename)
      if File.exist?(full_filename)
        params['content'] = 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 page content") do |val|
      params['content'] = ""
    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?
    # construct payload
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'page' => passed_options}) unless passed_options.empty?
    else
      payload = {
        'page' => {
        }
      }
      # allow arbitrary -O options
      payload.deep_merge!({'page' => passed_options}) unless passed_options.empty?
      # prompt for options
      #params = Morpheus::Cli::OptionTypes.prompt(update_wiki_page_option_types, options[:options], @api_client, options[:params])
      #params = passed_options
      params.deep_merge!(passed_options)

      if params.empty?
        raise_command_error "Specify at least one option to update.\n#{optparse}"
      end

      payload.deep_merge!({'page' => params}) unless params.empty?
    end
    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.update_wiki(instance["id"], payload)
      return
    end
    json_response = @instances_interface.update_wiki(instance["id"], payload)

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

      wiki([instance['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#view(args) ⇒ Object



1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
# File 'lib/morpheus/cli/commands/instances.rb', line 1095

def view(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('-w','--wiki', "Open the wiki tab for this instance") do
      options[:link_tab] = "wiki"
    end
    opts.on('--tab VALUE', String, "Open a specific tab") do |val|
      options[:link_tab] = val.to_s
    end
    build_common_options(opts, options, [:dry_run, :remote])
    opts.footer = "View an instance in a web browser" + "\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
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _view(arg, options)
  end
end

#view_wiki(args) ⇒ Object



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

def view_wiki(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:dry_run, :remote])
    opts.footer = "View instance wiki page in a web browser" + "\n" +
                  "[instance] is required. This is the name or id of an instance."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    instance = find_instance_by_name_or_id(args[0])
    return 1 if instance.nil?

    link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/provisioning/instances/#{instance['id']}#!wiki"

    if options[:dry_run]
      puts Morpheus::Util.open_url_command(link)
      return 0
    end
    return Morpheus::Util.open_url(link)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#wiki(args) ⇒ Object



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
# File 'lib/morpheus/cli/commands/instances.rb', line 720

def wiki(args)
  options = {}
  params = {}
  open_wiki_link = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance]")
    opts.on('--view', '--view', "View wiki page in web browser.") do
      open_wiki_link = true
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "View wiki page details for an instance." + "\n" +
                  "[instance] is required. This is the name or id of an instance."
  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?


    @instances_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @instances_interface.dry.wiki(instance["id"], params)
      return
    end
    json_response = @instances_interface.wiki(instance["id"], params)
    page = json_response['page']

    render_result = render_with_format(json_response, options, 'page')
    return 0 if render_result

    if page

      # my_terminal.exec("wiki get #{page['id']}")

      print_h1 "Instance Wiki Page: #{instance['name']}"
      # print_h1 "Wiki Page Details"
      print cyan

      print_description_list({
        "Page ID" => 'id',
        "Name" => 'name',
        #"Category" => 'category',
        #"Ref Type" => 'refType',
        #"Ref ID" => 'refId',
        #"Owner" => lambda {|it| it['account'] ? it['account']['name'] : '' },
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Created By" => lambda {|it| it['createdBy'] ? it['createdBy']['username'] : '' },
        "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) },
        "Updated By" => lambda {|it| it['updatedBy'] ? it['updatedBy']['username'] : '' }
      }, page)
      print reset,"\n"

      print_h2 "Page Content"
      print cyan, page['content'], reset, "\n"

    else
      print "\n"
      print cyan, "No wiki page found.", reset, "\n"
    end
    print reset,"\n"

    if open_wiki_link
      return view_wiki([instance['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end

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