Class: Morpheus::Cli::Clusters

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

Overview

require ‘morpheus/cli/mixins/infrastructure_helper’

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from AccountsHelper

#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_role_type, #format_user_role_names, #get_access_string, included, #print_accounts_table, #print_roles_table, #print_users_table, #roles_interface, #user_groups_interface, #users_interface

Methods included from WhoamiHelper

included, #load_whoami

Methods included from ProcessesHelper

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

Methods included from ProvisioningHelper

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

Methods included from CliCommand

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

Instance Method Details

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



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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/morpheus/cli/clusters.rb', line 174

def _get(arg, options={})
  
  begin
    @clusters_interface.setopts(options)

    if options[:dry_run]
      if arg.to_s =~ /\A\d{1,}\Z/
        print_dry_run @clusters_interface.dry.get(arg.to_i)
      else
        print_dry_run @clusters_interface.dry.list({name:arg})
      end
      return 0
    end
    cluster = find_cluster_by_name_or_id(arg)
    return 1 if cluster.nil?
    json_response = nil
    if arg.to_s =~ /\A\d{1,}\Z/
      json_response = {'cluster' => cluster}  # skip redundant request
    else
      json_response = @clusters_interface.get(cluster['id'])
    end

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end

    cluster = json_response['cluster']
    worker_stats = cluster['workerStats']
    clusterType = find_cluster_type_by_id(cluster['type']['id'])

    print_h1 "Morpheus Cluster"
    print cyan
    description_cols = {
        "ID" => 'id',
        "Name" => 'name',
        "Type" => lambda { |it| it['type']['name'] },
        #"Group" => lambda { |it| it['site']['name'] },
        "Cloud" => lambda { |it| it['zone']['name'] },
        "Location" => lambda { |it| it['location'] },
        "Layout" => lambda { |it| it['layout'] ? it['layout']['name'] : ''},
        "API Url" => 'serviceUrl',
        "Visibility" => lambda { |it| it['visibility'].to_s.capitalize },
        #"Groups" => lambda {|it| it['groups'].collect {|g| g.instance_of?(Hash) ? g['name'] : g.to_s }.join(', ') },
        #"Owner" => lambda {|it| it['owner'].instance_of?(Hash) ? it['owner']['name'] : it['ownerId'] },
        #"Tenant" => lambda {|it| it['account'].instance_of?(Hash) ? it['account']['name'] : it['accountId'] },
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Created By" => lambda {|it| it['createdBy'] ? it['createdBy']['username'] : '' },
        "Enabled" => lambda { |it| format_boolean(it['enabled']) },
        "Status" => lambda { |it| format_cluster_status(it) }
    }
    print_description_list(description_cols, cluster)

    print_h2 "Cluster Details"
    print cyan

    print "Namespaces: #{cluster['namespacesCount']}".center(20) if !cluster['namespacesCount'].nil?
    print "Masters: #{cluster['mastersCount']}".center(20) if !cluster['mastersCount'].nil?
    print "Workers: #{cluster['workersCount']}".center(20) if !clusterType['workersCount'].nil?
    print "Volumes: #{cluster['volumesCount']}".center(20) if !cluster['volumesCount'].nil?
    print "Containers: #{cluster['containersCount']}".center(20) if !cluster['containersCount'].nil?
    print "Services: #{cluster['servicesCount']}".center(20) if !cluster['servicesCount'].nil?
    print "Jobs: #{cluster['jobsCount']}".center(20) if !cluster['jobsCount'].nil?
    print "Pods: #{cluster['podsCount']}".center(20) if !cluster['podsCount'].nil?
    print "Deployments: #{cluster['deploymentsCount']}".center(20) if !cluster['deploymentsCount'].nil?
    print "\n"

    if options[:show_masters]
      masters_json = @clusters_interface.list_masters(cluster['id'], options)
      if masters_json.nil? || masters_json['masters'].empty?
        print_h2 "Masters"
        print yellow,"No masters found.",reset,"\n"
      else
        masters = masters_json['masters']
        print_h2 "Masters"
        rows = masters.collect do |server|
          {
            id: server['id'],
            name: server['name'],
            type: (server['type']['name'] rescue server['type']),
            status: format_server_status(server),
            power: format_server_power_state(server, cyan)
          }
        end
        columns = [:id, :name, :status, :power]
        puts as_pretty_table(rows, columns, options)
      end
    end
    if options[:show_workers]
      workers_json = @clusters_interface.list_workers(cluster['id'], options)
      if workers_json.nil? || workers_json['workers'].empty?
        print_h2 "Workers"
        print yellow,"No workers found.",reset,"\n"
      else
        workers = workers_json['workers']
        print_h2 "Workers"
        rows = workers.collect do |server|
          {
            id: server['id'],
            name: server['name'],
            type: (server['type']['name'] rescue server['type']),
            status: format_server_status(server),
            power: format_server_power_state(server, cyan)
          }
        end
        columns = [:id, :name, :status, :power]
        puts as_pretty_table(rows, columns, options)
      end
    end

    if worker_stats
      print_h2 "Worker Usage"
      print cyan
      # print "CPU Usage: #{worker_stats['cpuUsage']}".center(20)
      # print "Memory: #{worker_stats['usedMemory']}".center(20)
      # print "Storage: #{worker_stats['usedStorage']}".center(20)
      print_stats_usage(worker_stats, {include: [:max_cpu, :avg_cpu, :memory, :storage]})
      print reset,"\n"
    end

    if options[:show_perms]
      permissions = cluster['permissions']
      print_permissions(permissions)
    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?(cluster['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(arg, options)
      end
    end

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

#_list_container_groups(args, options, resource_type) ⇒ Object



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

def _list_container_groups(args, options, resource_type)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    params = {}
    params.merge!(parse_list_options(options))
    params['resourceLevel'] = options[:resourceLevel] if !options[:resourceLevel].nil?
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_container_groups(cluster['id'], resource_type, params)
      return
    end
    json_response = @clusters_interface.list_container_groups(cluster['id'], resource_type, params)

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

    title = "Morpheus Cluster #{resource_type.capitalize}s: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    container_groups = json_response["#{resource_type}s"]
    if container_groups.empty?
      print yellow,"No #{resource_type}s found.",reset,"\n"
    else
      # more stuff to show here
      rows = container_groups.collect do |it|
        stats = it['stats']
        cpu_usage_str = generate_usage_bar((it['totalCpuUsage']).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})
        {
            id: it['id'],
            status: it['status'],
            name: it['name'],
            cpu: cpu_usage_str + cyan,
            memory: memory_usage_str + cyan,
            storage: storage_usage_str + cyan
        }
      end
      columns = [
          :id, :status, :name, :cpu, :memory, :storage
      ]
      print as_pretty_table(rows, columns, options)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#_remove_container_group(args, options, resource_type) ⇒ Object



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

def _remove_container_group(args, options, resource_type)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    container_group_id = args[1]

    if container_group_id.empty?
      raise_command_error "missing required container parameter"
    end

    container_group = find_container_group_by_name_or_id(cluster['id'], resource_type, container_group_id)
    if container_group.nil?
      print_red_alert "#{resource_type.capitalize} not found by id '#{container_group_id}'"
      return 1
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cluster #{resource_type} '#{container_group['name'] || container_group['id']}'?", options)
      return 9, "aborted command"
    end

    params = {}
    params.merge!(parse_list_options(options))

    if !options[:force].nil?
      params['force'] = options[:force]
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.destroy_container_group(cluster['id'], container_group['id'], resource_type, params)
      return
    end
    json_response = @clusters_interface.destroy_container_group(cluster['id'], container_group['id'], resource_type, params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_red_alert "Error removing #{resource_type} #{container_group['name']} from cluster #{cluster['name']}: #{json_response['msg']}" if json_response['success'] == false
      print_green_success "#{resource_type.capitalize} #{container_group['name']} is being removed from cluster #{cluster['name']}..." if json_response['success'] == true
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#_restart_container_group(args, options, resource_type) ⇒ Object



1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
# File 'lib/morpheus/cli/clusters.rb', line 1969

def _restart_container_group(args, options, resource_type)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    container_group_id = args[1]

    if container_group_id.empty?
      raise_command_error "missing required container parameter"
    end

    container_group = find_container_group_by_name_or_id(cluster['id'], resource_type, container_group_id)
    if container_group.nil?
      print_red_alert "#{resource_type.capitalize} not found by id '#{container_group_id}'"
      return 1
    end

    params = {}
    params.merge!(parse_list_options(options))

    if !options[:force].nil?
      params['force'] = options[:force]
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.restart_container_group(cluster['id'], container_group['id'], resource_type, params)
      return
    end
    json_response = @clusters_interface.restart_container_group(cluster['id'], container_group['id'], resource_type, params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_red_alert "Error restarting #{resource_type} #{container_group['name']} from cluster #{cluster['name']}: #{json_response['msg']}" if json_response['success'] == false
      print_green_success "#{resource_type.capitalize} #{container_group['name']} is being restarted for cluster #{cluster['name']}..." if json_response['success'] == true
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

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



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
377
378
# File 'lib/morpheus/cli/clusters.rb', line 347

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

    link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/infrastructure/clusters/#{cluster['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

#add(args) ⇒ Object



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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'lib/morpheus/cli/clusters.rb', line 380

def add(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[name]")
    opts.on( '--name NAME', "Cluster Name" ) do |val|
      options[:name] = val.to_s
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      options[:description] = val.to_s
    end
    opts.on( '--resource-name NAME', "Resource Name" ) do |val|
      options[:resourceName] = val.to_s
    end
    opts.on('--tags LIST', String, "Tags") do |val|
      options[:tags] = val
    end
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options[:group] = val
    end
    opts.on( '-t', '--cluster-type TYPE', "Cluster Type Name or ID" ) do |val|
      options[:clusterType] = val
    end
    opts.on( '-l', '--layout LAYOUT', "Layout Name or ID" ) do |val|
      options[:layout] = val
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options[:visibility] = val
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until status is provisioned,failed. 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('--workflow ID', String, "Workflow") do |val|
      params['taskSetId'] = val.to_i
    end
    add_server_options(opts, options)
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a cluster.\n" +
                  "[name] is required. This is the name of the new cluster."
  end

  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      payload['cluster'] ||= {}
      if options[:options]
        payload['cluster'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end
      if args[0]
        payload['cluster']['name'] = args[0]
      elsif options[:name]
        payload['cluster']['name'] = options[:name]
      end
      # if args[1]
      #   payload['cluster']['description'] = args[1]
      # elsif options[:description]
      #   payload['cluster']['description'] = options[:description]
      # end
      payload['cluster']['server'] ||= {}
      if options[:resourceName]
        payload['cluster']['server']['name'] = options[:resourceName]
      end
      if options[:description]
        payload['cluster']['description'] = options[:description]
      end
    else
      cluster_payload = {}
      server_payload = {"config" => {}}

      # Cluster Type
      cluster_type_id = nil
      cluster_type = options[:clusterType] ? find_cluster_type_by_name_or_id(options[:clusterType]) : nil

      if cluster_type
        cluster_type_id = cluster_type['id']
      else
        available_cluster_types = cluster_types_for_dropdown

        if available_cluster_types.empty?
          print_red_alert "A cluster type is required"
          exit 1
        elsif available_cluster_types.count > 1 && !options[:no_prompt]
          cluster_type_code = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'clusterType', 'type' => 'select', 'fieldLabel' => 'Cluster Type', 'selectOptions' => cluster_types_for_dropdown, 'required' => true, 'description' => 'Select Cluster Type.'}],options[:options],@api_client,{})['clusterType']
        else
          cluster_type_code = available_cluster_types.first['code']
        end
        cluster_type = get_cluster_types.find { |ct| ct['code'] == cluster_type_code }
      end

      cluster_payload['type'] = cluster_type['code'] # {'id' => cluster_type['id']}

      # Cluster Name
      if args.empty? && options[:no_prompt]
        print_red_alert "No cluster name provided"
        exit 1
      elsif !args.empty?
        cluster_payload['name'] = args[0]
      elsif options[:name]
        cluster_payload['name'] = options[:name]
      else
        existing_cluster_names = @clusters_interface.list()['clusters'].collect { |cluster| cluster['name'] }
        while cluster_payload['name'].empty?
          name = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Cluster Name', 'required' => true, 'description' => 'Cluster Name.'}],options[:options],@api_client,{})['name']

          if existing_cluster_names.include?(name)
            print_red_alert "Name must be unique, #{name} already exists"
          else
            cluster_payload['name'] = name
          end
        end
      end

      # Cluster Description
      # if !args.empty? && args.count > 1
      #   cluster_payload['description'] = args[1]
      # elsif options[:description]
      #   cluster_payload['description'] = options[:description]
      # elsif !options[:no_prompt]
      #   cluster_payload['description'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'type' => 'text', 'fieldLabel' => 'Cluster Description', 'required' => false, 'description' => 'Cluster Description.'}],options[:options],@api_client,{})['description']
      # end

      # Resource Name
      resourceName = options[:resourceName]

      if !resourceName
        if options[:no_prompt]
          print_red_alert "No resource name provided"
          exit 1
        else
          resourceName = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'resourceName', 'type' => 'text', 'fieldLabel' => 'Resource Name', 'required' => true, 'description' => 'Resource Name.'}],options[:options],@api_client,{})['resourceName']
        end
      end

      server_payload['name'] = resourceName

      # Resource Description
      description = options[:description] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'type' => 'text', 'fieldLabel' => 'Description', 'required' => false, 'description' => 'Resource Description.'}],options[:options],@api_client,{})['description']
      cluster_payload['description'] = description if description

      tags = options[:tags]

      if !tags && !options[:no_prompt]
        tags = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'tags', 'type' => 'text', 'fieldLabel' => 'Resource Tags', 'required' => false, 'description' => 'Resource Tags.'}],options[:options],@api_client,{})['tags']
      end

      server_payload['tags'] = tags if tags

      # Group / Site
      group = load_group(options)
      cluster_payload['group'] = {'id' => group['id']}

      # Cloud / Zone
      cloud_id = nil
      cloud = options[:cloud] ? find_cloud_by_name_or_id_for_provisioning(group['id'], options[:cloud]) : nil
      if cloud
        # load full cloud
        cloud = @clouds_interface.get(cloud['id'])['zone']
        cloud_id = cloud['id']
      else
        available_clouds = get_available_clouds(group['id'])

        if available_clouds.empty?
          print_red_alert "Group #{group['name']} has no available clouds"
          exit 1
        else
          cloud_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'selectOptions' => available_clouds, 'required' => true, 'description' => 'Select Cloud.'}],options[:options],@api_client,{groupId: group['id']})['cloud']
        end
        cloud = @clouds_interface.get(cloud_id)['zone']
      end

      cloud['zoneType'] = get_cloud_type(cloud['zoneType']['id'])
      cluster_payload['cloud'] = {'id' => cloud['id']}

      # Layout
      layout = options[:layout] ? find_layout_by_name_or_id(options[:layout]) : nil

      if !layout
        available_layouts = layouts_for_dropdown(cloud['id'], cluster_type['id'])

        if !available_layouts.empty?
          if available_layouts.count > 1 && !options[:no_prompt]
            layout_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'layout', 'type' => 'select', 'fieldLabel' => 'Layout', 'selectOptions' => available_layouts, 'required' => true, 'description' => 'Select Layout.'}],options[:options],@api_client,{})['layout']
          else
            layout_id = available_layouts.first['id']
          end
          layout = find_layout_by_name_or_id(layout_id)
        end
      end

      cluster_payload['layout'] = {id: layout['id']}

      # Plan
      provision_type = (layout && layout['provisionType'] ? layout['provisionType'] : nil) || get_provision_type_for_zone_type(cloud['zoneType']['id'])
      service_plan = prompt_service_plan(cloud['id'], provision_type, options)

      if service_plan
        server_payload['plan'] = {'id' => service_plan['id'], 'code' => service_plan['code'], 'options' => prompt_service_plan_options(service_plan, options)}
      end

      # Controller type
      server_types = @server_types_interface.list({max:1, computeTypeId: cluster_type['controllerTypes'].first['id'], zoneTypeId: cloud['zoneType']['id'], useZoneProvisionTypes: true})['serverTypes']
      controller_provision_type = nil
      resource_pool = nil

      if !server_types.empty?
        controller_type = server_types.first
        controller_provision_type = controller_type['provisionType'] ? (@provision_types_interface.get(controller_type['provisionType']['id'])['provisionType'] rescue nil) : nil

        if controller_provision_type && resource_pool = prompt_resource_pool(group, cloud, service_plan, controller_provision_type, options)
            server_payload['config']['resourcePool'] = resource_pool['externalId']
        end
      end

      # Multi-disk / prompt for volumes
      volumes = options[:volumes] || prompt_volumes(service_plan, options.merge({'defaultAddFirstDataVolume': true}), @api_client, {zoneId: cloud['id'], siteId: group['id']})

      if !volumes.empty?
        server_payload['volumes'] = volumes
      end

      # Networks
      # NOTE: You must choose subnets in the same availability zone
      if controller_provision_type && controller_provision_type['hasNetworks'] && cloud['zoneType']['code'] != 'esxi'
        server_payload['networkInterfaces'] = options[:networkInterfaces] || prompt_network_interfaces(cloud['id'], provision_type['id'], (resource_pool['id'] rescue nil), options)
      end

      # Security Groups
      server_payload['securityGroups'] = prompt_security_groups_by_cloud(cloud, provision_type, resource_pool, options)

      # Visibility
      server_payload['visibility'] = options[:visibility] || (Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'visibility', 'fieldLabel' => 'Visibility', 'type' => 'select', 'defaultValue' => 'private', 'required' => true, 'selectOptions' => [{'name' => 'Private', 'value' => 'private'},{'name' => 'Public', 'value' => 'public'}]}], options[:options], @api_client, {})['visibility'])

      # Options / Custom Config
      option_type_list = ((controller_type['optionTypes'].reject { |type| !type['enabled'] || type['fieldComponent'] } rescue []) + layout['optionTypes'] +
        (cluster_type['optionTypes'].reject { |type| !type['enabled'] || !type['creatable'] || type['fieldComponent'] } rescue [])).sort { |type| type['displayOrder'] }

      # remove volume options if volumes were configured
      if !server_payload['volumes'].empty?
        option_type_list = reject_volume_option_types(option_type_list)
      end
      # remove networkId option if networks were configured above
      if !server_payload['networkInterfaces'].empty?
        option_type_list = reject_networking_option_types(option_type_list)
      end

      server_payload.deep_merge!(Morpheus::Cli::OptionTypes.prompt(option_type_list, options[:options], @api_client, {zoneId: cloud['id'], siteId: group['id'], layoutId: layout['id']}))

      # Create User
      if !options[:createUser].nil?
        server_payload['config']['createUser'] = options[:createUser]
      elsif !options[:no_prompt]
        current_user['windowsUsername'] || current_user['linuxUsername']
        server_payload['config']['createUser'] = (current_user['windowsUsername'] || current_user['linuxUsername']) && Morpheus::Cli::OptionTypes.confirm("Create Your User?", {:default => true})
      end

      # User Groups
      userGroup = options[:userGroup] ? find_user_group_by_name_or_id(nil, options[:userGroup]) : nil

      if userGroup
        server_payload['userGroup'] = userGroup
      elsif !options[:no_prompt]
        userGroupId = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'userGroupId', 'fieldLabel' => 'User Group', 'type' => 'select', 'required' => false, 'optionSource' => 'userGroups'}], options[:options], @api_client, {})['userGroupId']

        if userGroupId
          server_payload['userGroup'] = {'id' => userGroupId}
        end
      end

      # Host / Domain
      server_payload['networkDomain'] = options[:domain] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'networkDomain', 'fieldLabel' => 'Network Domain', 'type' => 'select', 'required' => false, 'optionSource' => 'networkDomains'}], options[:options], @api_client, {})['networkDomain']
      server_payload['hostname'] = options[:hostname] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'hostname', 'fieldLabel' => 'Hostname', 'type' => 'text', 'required' => true, 'description' => 'Hostname', 'defaultValue' => resourceName}], options[:options], @api_client)['hostname']

      # Workflow / Automation
      task_set_id = options[:taskSetId] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'taskSet', 'fieldLabel' => 'Workflow', 'type' => 'select', 'required' => false, 'optionSource' => 'taskSets'}], options[:options], @api_client, {'phase' => 'postProvision'})['taskSet']

      if !task_set_id.nil?
        server_payload['taskSet'] = {'id' => task_set_id}
      end

      cluster_payload['server'] = server_payload
      payload = {'cluster' => cluster_payload}
    end
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.create(payload)
      return
    end
    json_response = @clusters_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif json_response['success']
      get_args = [json_response["cluster"]["id"]] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
      get(get_args)
    else
      print_rest_errors(json_response, options)
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_namespace(args) ⇒ Object



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
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
# File 'lib/morpheus/cli/clusters.rb', line 2188

def add_namespace(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster] [name] [options]")
    opts.on("--name NAME", String, "Name of the new namespace") do |val|
      options[:name] = val.to_s
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      options[:description] = val.to_s
    end
    opts.on('--active [on|off]', String, "Enable namespace") do |val|
      options[:active] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    add_perms_options(opts, options)
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a cluster namespace.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster.\n" +
                  "[name] is required. This is the name of the new namespace."
  end

  optparse.parse!(args)
  if args.count < 1 || args.count > 3
    raise_command_error "wrong number of arguments, expected 1 to 3 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload['namespace'] ||= {}
        payload['namespace'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end
    else
      namespace_payload = {'name' => options[:name] || (args.length > 1 ? args[1] : nil) || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'description' => 'Namespace Name', 'required' => true}], options[:options], @api_client)['name']}
      namespace_payload.deep_merge!(prompt_update_namespace(options).reject {|k,v| k.is_a?(Symbol)})
      payload = {"namespace" => namespace_payload}
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.create_namespace(cluster['id'], payload)
      return
    end
    json_response = @clusters_interface.create_namespace(cluster['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      namespace = json_response['namespace']
      print_green_success "Added namespace #{namespace['name']}"
      get_args = [cluster["id"], namespace["id"]] + (options[:remote] ? ["-r",options[:remote]] : [])
      get_namespace(get_args)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_worker(args) ⇒ Object



1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
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
# File 'lib/morpheus/cli/clusters.rb', line 1045

def add_worker(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster] [options]")
    opts.on("--name NAME", String, "Name of the new worker") do |val|
      options[:name] = val.to_s
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      options[:description] = val.to_s
    end
    add_server_options(opts, options)
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Add worker to a cluster.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster.\n" + 
                  "[name] is required. This is the name of the new worker."
  end

  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload['server'] ||= {}
        payload['server'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end
    else
      server_payload = {'config' => {}}

      # If not available add set type return
      layout = find_layout_by_id(cluster['layout']['id'])

      # currently limiting to just worker types
      available_type_sets = layout['computeServers'].reject {|typeSet| !typeSet['dynamicCount']}

      if available_type_sets.empty?
        print_red_alert "Cluster #{cluster['name']} has no available server types to add"
        exit 1
      else
        type_set = available_type_sets[0]
      end

      # find servers within cluster
      server_matches = cluster['servers'].reject {|server| server['typeSet']['id'] != type_set['id']}
      server_type = find_server_type_by_id(server_matches.count > 0 ? server_matches[0]['computeServerType']['id'] : type_set['computeServerType']['id'])
      server_payload['serverType'] = {'id' => server_type['id']}

      # Name
      if options[:name].empty?
        default_name = (server_matches.count ? server_matches[0]['name'] : nil) || cluster['name']
        default_name.delete_prefix!(type_set['namePrefix']) if !type_set['namePrefix'].empty?
        default_name = default_name[0..(default_name.index(type_set['nameSuffix']) - 1)] if !type_set['nameSuffix'].nil? && default_name.index(type_set['nameSuffix'])
        default_name = (type_set['namePrefix'] || '') + default_name + (type_set['nameSuffix'] || '') + '-' + (server_matches.count + 1).to_s
        server_payload['name'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Name', 'required' => true, 'description' => 'Worker Name.', 'defaultValue' => default_name}],options[:options],@api_client,{})['name']
      else
        server_payload['name'] = options[:name]
      end

      # Description
      server_payload['description'] = options[:description] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'description' => 'Worker Description'}], options[:options], @api_client)['description']

      # Cloud
      available_clouds = options_interface.options_for_source('clouds', {groupId: cluster['site']['id'], clusterId: cluster['id'], ownerOnly: true})['data']
      cloud_id = nil

      if options[:cloud]
        cloud = available_clouds.find {|it| it['value'].to_s == options[:cloud].to_s || it['name'].casecmp?(options[:cloud].to_s)}

        if !cloud
          print_red_alert "Cloud #{options[:cloud]} is not a valid option for cluster #{cluster['name']}"
          exit 1
        end
        cloud_id = cloud['value']
      end

      if !cloud_id
        default_cloud = available_clouds.find {|it| it['value'] == cluster['zone']['id']}
        cloud_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'fieldLabel' => 'Cloud', 'type' => 'select', 'selectOptions' => available_clouds, 'description' => 'Cloud', 'required' => true, 'defaultValue' => (default_cloud ? default_cloud['name'] : nil)}], options[:options], @api_client)['cloud']
        cloud_id = (default_cloud && cloud_id == default_cloud['name']) ? default_cloud['value'] : cloud_id
      end

      server_payload['cloud'] = {'id' => cloud_id}
      service_plan = prompt_service_plan(cloud_id, server_type['provisionType'], options)

      if service_plan
        server_payload['plan'] = {'code' => service_plan['code'], 'options' => prompt_service_plan_options(service_plan, options)}
      end

      # resources (zone pools)
      cloud = @clouds_interface.get(cloud_id)['zone']
      cloud['zoneType'] = get_cloud_type(cloud['zoneType']['id'])
      group = @groups_interface.get(cluster['site']['id'])['group']

      if resource_pool = prompt_resource_pool(cluster, cloud, service_plan, server_type['provisionType'], options)
        server_payload['config']['resourcePool'] = resource_pool['externalId']
      end

      # Multi-disk / prompt for volumes
      volumes = options[:volumes] || prompt_volumes(service_plan, options.merge({'defaultAddFirstDataVolume': true}), @api_client, {zoneId: cloud['id'], siteId: group['id']})

      if !volumes.empty?
        server_payload['volumes'] = volumes
      end

      # Networks
      # NOTE: You must choose subnets in the same availability zone
      provision_type = server_type['provisionType'] || {}
      if provision_type && cloud['zoneType']['code'] != 'esxi'
        server_payload['networkInterfaces'] = options[:networkInterfaces] || prompt_network_interfaces(cloud['id'], server_type['provisionType']['id'], (resource_pool['id'] rescue nil), options)
      end

      # Security Groups
      server_payload['securityGroups'] = prompt_security_groups_by_cloud(cloud, provision_type, resource_pool, options)

      # Options / Custom Config
      option_type_list = (server_type['optionTypes'].reject { |type|
        !type['enabled'] || type['fieldComponent'] ||
        (['provisionType.vmware.host', 'provisionType.scvmm.host'].include?(type['code']) && cloud['config']['hideHostSelection'] == 'on') || # should this be truthy?
        (type['fieldContext'] == 'instance.networkDomain' && type['fieldName'] == 'id')
      } rescue [])

      # remove volume options if volumes were configured
      if !server_payload['volumes'].empty?
        option_type_list = reject_volume_option_types(option_type_list)
      end
      # remove networkId option if networks were configured above
      if !server_payload['networkInterfaces'].empty?
        option_type_list = reject_networking_option_types(option_type_list)
      end

      server_payload.deep_merge!(Morpheus::Cli::OptionTypes.prompt(option_type_list, options[:options], @api_client, {zoneId: cloud['id'], siteId: group['id'], layoutId: layout['id']}))

      # Create User
      if !options[:createUser].nil?
        server_payload['config']['createUser'] = options[:createUser]
      elsif !options[:no_prompt]
        server_payload['config']['createUser'] = (current_user['windowsUsername'] || current_user['linuxUsername']) && Morpheus::Cli::OptionTypes.confirm("Create Your User?", {:default => true})
      end

      # User Groups
      userGroup = options[:userGroup] ? find_user_group_by_name_or_id(nil, options[:userGroup]) : nil

      if userGroup
        server_payload['userGroup'] = userGroup
      elsif !options[:no_prompt]
        userGroupId = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'userGroupId', 'fieldLabel' => 'User Group', 'type' => 'select', 'required' => false, 'optionSource' => 'userGroups'}], options[:options], @api_client, {})['userGroupId']

        if userGroupId
          server_payload['userGroup'] = {'id' => userGroupId}
        end
      end

      # Host / Domain
      server_payload['networkDomain'] = options[:domain] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'networkDomain', 'fieldLabel' => 'Network Domain', 'type' => 'select', 'required' => false, 'optionSource' => 'networkDomains'}], options[:options], @api_client, {})['networkDomain']
      server_payload['hostname'] = options[:hostname] || Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'hostname', 'fieldLabel' => 'Hostname', 'type' => 'text', 'required' => true, 'description' => 'Hostname', 'defaultValue' => server_payload['name']}], options[:options], @api_client)['hostname']

      # Workflow / Automation
      if !options[:no_prompt]
        task_set_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'taskSet', 'fieldLabel' => 'Workflow', 'type' => 'select', 'required' => false, 'optionSource' => 'taskSets'}], options[:options], @api_client, {'phase' => 'postProvision', 'taskSetType' => 'provision'})['taskSet']

        if task_set_id
          server_payload['taskSet'] = {'id' => task_set_id}
        end
      end
      payload = {'server' => server_payload}
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.add_server(cluster['id'], payload)
      return
    end
    json_response = @clusters_interface.add_server(cluster['id'], payload)
    if options[:json]
      puts as_json(json_response)
    elsif json_response['success']
      print_green_success "Added worker to cluster #{cluster['name']}"
      #get_args = [json_response["cluster"]["id"]] + (options[:remote] ? ["-r",options[:remote]] : [])
      #get(get_args)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#api_config(args) ⇒ Object



2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
# File 'lib/morpheus/cli/clusters.rb', line 2497

def api_config(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    build_common_options(opts, options, [:query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display API service settings for a cluster."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.api_config(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.api_config(cluster['id'], params)
    
    render_result = render_with_format(json_response, options)
    return 0 if render_result

    title = "Cluster API Config: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options

    service_config = json_response
    print cyan
    description_cols = {
        "Url" => 'serviceUrl',
        "Username" => 'serviceUsername',
        #"Password" => 'servicePassword',
        "Token" => 'serviceToken',
        "Access" => 'serviceAccess',
        "Cert" => 'serviceCert',
        #"Config" => 'serviceConfig',
        "Version" => 'serviceVersion',
    }
    print_description_list(description_cols, service_config)
    print reset,"\n"
    return 0

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

#connect(opts) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/morpheus/cli/clusters.rb', line 31

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @clusters_interface = @api_client.clusters
  @groups_interface = @api_client.groups
  @compute_type_layouts_interface = @api_client.library_compute_type_layouts
  @security_groups_interface = @api_client.security_groups
  #@security_group_rules_interface = @api_client.security_group_rules
  @cloud_resource_pools_interface = @api_client.cloud_resource_pools
  @clouds_interface = @api_client.clouds
  @servers_interface = @api_client.servers
  @server_types_interface = @api_client.server_types
  @options_interface = @api_client.options
  @active_group_id = Morpheus::Cli::Groups.active_group
  @provision_types_interface = @api_client.provision_types
  @service_plans_interface = @api_client.service_plans
  @user_groups_interface = @api_client.user_groups
  @accounts_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).accounts
  @logs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).logs
  #@active_security_group = ::Morpheus::Cli::SecurityGroups.load_security_group_file
end

#count(args) ⇒ Object



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

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

#get(args) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/morpheus/cli/clusters.rb', line 134

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    opts.on( nil, '--hosts', "Display masters and workers" ) do
      options[:show_masters] = true
      options[:show_workers] = true
    end
    opts.on( nil, '--masters', "Display masters" ) do
      options[:show_masters] = true
    end
    opts.on( nil, '--workers', "Display workers" ) do
      options[:show_workers] = true
    end
    opts.on( nil, '--permissions', "Display permissions" ) do
      options[:show_perms] = true
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until status is provisioned,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_until_status] ||= "provisioned,failed"
      if !val.to_s.empty?
        options[:refresh_interval] = val.to_f
      end
    end
    opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
      options[:refresh_until_status] = val.to_s.downcase
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Get details about a cluster."
  end
  optparse.parse!(args)
  if args.count < 1
    raise_command_error "wrong number of arguments, expected 1-N and got (#{args.count}) #{args}\n#{optparse}"
  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_namespace(args) ⇒ Object



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
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
# File 'lib/morpheus/cli/clusters.rb', line 2314

def get_namespace(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster] [namespace]")
    opts.on( nil, '--permissions', "Display permissions" ) do
      options[:show_perms] = true
    end
    build_common_options(opts, options, [:query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a cluster namespace.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster.\n" +
                  "[namespace] is required. This is the name or id of an existing namespace."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    # this finds the namespace in the cluster api response, then fetches it by ID
    namespace = find_namespace_by_name_or_id(cluster['id'], args[1])
    if namespace.nil?
      print_red_alert "Namespace not found for '#{args[1]}'"
      exit 1
    end
    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.get_namespace(cluster['id'], namespace['id'], params)
      return
    end
    json_response = @clusters_interface.get_namespace(cluster['id'], namespace['id'], params)
    
    render_result = render_with_format(json_response, options, 'namespace')
    return 0 if render_result

    print_h1 "Morpheus Cluster Namespace"
    print cyan
    description_cols = {
        "ID" => 'id',
        "Name" => 'name',
        "Description" => 'description',
        "Cluster" => lambda { |it| cluster['name'] },
        "Status" => 'status',
        "Active" => lambda {|it| format_boolean it['active'] }
        # more stuff to show here
    }
    print_description_list(description_cols, namespace)
    print reset,"\n"

    if options[:show_perms]
      permissions = cluster['permissions']
      print_permissions(permissions)
    end

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

#handle(args) ⇒ Object



52
53
54
# File 'lib/morpheus/cli/clusters.rb', line 52

def handle(args)
  handle_subcommand(args)
end

#history(args) ⇒ Object



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
2885
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
2927
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
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
# File 'lib/morpheus/cli/clusters.rb', line 2859

def history(args)
  raw_args = args.dup
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    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 cluster.\n" +
        "[cluster] is required. This is the name or id of an cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    params = {}
    params.merge!(parse_list_options(options))
    # params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.history(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.history(cluster['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 = "Cluster History: #{cluster['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, {: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



3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
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
3049
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
3080
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
# File 'lib/morpheus/cli/clusters.rb', line 3008

def history_details(args)
  options = {}
  process_id = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [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" +
        "[cluster] is required. This is the name or id of a cluster.\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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    params = {}
    params.merge!(parse_list_options(options))
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.history_details(cluster['id'], process_id, params)
      return
    end
    json_response = @clusters_interface.history_details(cluster['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 = "Cluster 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



3110
3111
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
3142
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
# File 'lib/morpheus/cli/clusters.rb', line 3110

def history_event_details(args)
  options = {}
  process_event_id = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [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" +
        "[cluster] is required. This is the name or id of an cluster.\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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.history_event_details(cluster['id'], process_event_id, params)
      return
    end
    json_response = @clusters_interface.history_event_details(cluster['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 = "Cluster History Event"
      subtitles = []
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles, options
      print_process_event_details(process_event)
      print reset, "\n"
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list(args) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/morpheus/cli/clusters.rb', line 56

def list(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List clusters."
  end
  optparse.parse!(args)
  if args.count != 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list(params)
      return
    end
    json_response = @clusters_interface.list(params)
    
    render_result = render_with_format(json_response, options, 'clusters')
    return 0 if render_result

    title = "Morpheus Clusters"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    clusters = json_response['clusters']
    
    if clusters.empty?
      print yellow,"No clusters found.",reset,"\n"
    else
      print_clusters_table(clusters, options)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_containers(args) ⇒ Object



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

def list_containers(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    opts.on("--resource-level LEVEL", String, "Resource Level") do |val|
      options[:resourceLevel] = val.to_s
    end
    opts.on("--worker WORKER", String, "Worker") do |val|
      options[:worker] = val
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List containers for a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    if options[:worker]
      worker = find_host_by_name_or_id(options[:worker])
      return 1 if worker.nil?
      params['workerId'] = worker['id']
    end
    params = {}
    params.merge!(parse_list_options(options))
    params['resourceLevel'] = options[:resourceLevel] if !options[:resourceLevel].nil?
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_containers(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.list_containers(cluster['id'], params)

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

    title = "Morpheus Cluster Containers: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    containers = json_response['containers']
    if containers.empty?
      print yellow,"No containers found.",reset,"\n"
    else
      # more stuff to show here
      rows = containers.collect do |it|
        {
            id: it['id'],
            status: it['status'],
            name: it['name'],
            instance: it['instance'].nil? ? '' : it['instance']['name'],
            type: it['containerType'].nil? ? '' : it['containerType']['name'],
            location: it['ip'],
            cluster: cluster['name']
        }
      end
      columns = [
          :id, :status, :name, :instance, :type, :location, :cluster => lambda { |it| cluster['name'] }
      ]
      print as_pretty_table(rows, columns, options)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_deployments(args) ⇒ Object



2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
# File 'lib/morpheus/cli/clusters.rb', line 2011

def list_deployments(args)
  resource_type = 'deployment'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    opts.on("--resource-level LEVEL", String, "Resource Level") do |val|
      options[:resourceLevel] = val.to_s
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List #{resource_type}s for a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  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)
  _list_container_groups(args, options,resource_type)
end

#list_jobs(args) ⇒ Object



1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
# File 'lib/morpheus/cli/clusters.rb', line 1571

def list_jobs(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List jobs for a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_jobs(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.list_jobs(cluster['id'], params)

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

    title = "Morpheus Cluster Jobs: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    jobs = json_response['jobs']
    if jobs.empty?
      print yellow,"No jobs found.",reset,"\n"
    else
      # more stuff to show here
      rows = jobs.collect do |job|
        {
            id: job['id'],
            status: job['type'],
            namespace: job['namespace'],
            name: job['name'],
            lastRun: format_local_dt(job['lastRun']),
            cluster: cluster['name']
        }
      end
      columns = [
          :id, :status, :namespace, :name, :lastRun, :cluster => lambda { |it| cluster['name'] }
      ]
      print as_pretty_table(rows, columns, options)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_masters(args) ⇒ Object



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
1268
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
1330
1331
1332
1333
1334
1335
1336
1337
# File 'lib/morpheus/cli/clusters.rb', line 1240

def list_masters(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List masters for a cluster.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_masters(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.list_masters(cluster['id'], params)
    
    render_result = render_with_format(json_response, options, 'masters')
    return 0 if render_result

    title = "Morpheus Cluster Masters: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    masters = json_response['masters']
    if masters.empty?
      print yellow,"No masters found.",reset,"\n"
    else
      # more stuff to show here
      
      servers = masters
      multi_tenant = false

      # print_servers_table(servers)
      rows = servers.collect {|server|
        stats = server['stats']

        if !stats['maxMemory']
          stats['maxMemory'] = stats['usedMemory'] + stats['freeMemory']
        end
        cpu_usage_str = !stats ? "" : generate_usage_bar((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]
          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: server['id'],
          tenant: server['account'] ? server['account']['name'] : server['accountId'],
          name: server['name'],
          platform: server['serverOs'] ? server['serverOs']['name'].upcase : 'N/A',
          cloud: server['zone'] ? server['zone']['name'] : '',
          type: server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged',
          nodes: server['containers'] ? server['containers'].size : '',
          status: format_server_status(server, cyan),
          power: format_server_power_state(server, cyan),
          cpu: cpu_usage_str + cyan,
          memory: memory_usage_str + cyan,
          storage: storage_usage_str + cyan
        }
        row
      }
      columns = [:id, :name, :type, :cloud, :nodes, :status, :power]
      if multi_tenant
        columns.insert(4, :tenant)
      end
      columns += [: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(json_response)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_namespaces(args) ⇒ Object



2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
# File 'lib/morpheus/cli/clusters.rb', line 2252

def list_namespaces(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List namespaces for a cluster.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_namespaces(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.list_namespaces(cluster['id'], params)
    
    render_result = render_with_format(json_response, options, 'namespaces')
    return 0 if render_result

    title = "Morpheus Cluster Namespaces: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    namespaces = json_response['namespaces']
    if namespaces.empty?
      print yellow,"No namespaces found.",reset,"\n"
    else
      # more stuff to show here
      rows = namespaces.collect do |ns|
        {
            id: ns['id'],
            name: ns['name'],
            description: ns['description'],
            status: ns['status'],
            active: format_boolean(ns['active']),
            cluster: cluster['name']
        }
      end
      columns = [
          :id, :name, :description, :status, :active #, :cluster => lambda { |it| cluster['name'] }
      ]
      print as_pretty_table(rows, columns, options)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_pods(args) ⇒ Object



2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
# File 'lib/morpheus/cli/clusters.rb', line 2129

def list_pods(args)
  resource_type = 'pod'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    opts.on("--resource-level LEVEL", String, "Resource Level") do |val|
      options[:resourceLevel] = val.to_s
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List #{resource_type}s for a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  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)
  _list_container_groups(args, options, resource_type)
end

#list_services(args) ⇒ Object



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

def list_services(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List services for a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_services(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.list_services(cluster['id'], params)

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

    title = "Morpheus Cluster Services: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    services = json_response['services']
    if services.empty?
      print yellow,"No services found.",reset,"\n"
    else
      # more stuff to show here
      rows = services.collect do |service|
        {
            id: service['id'],
            name: service['name'],
            type: service['type'],
            externalIp: service['externalIp'],
            externalPort: service['externalPort'],
            internalPort: service['internalPort'],
            status: service['status'],
            cluster: cluster['name']
        }
      end
      columns = [
          :id, :name, :type, :externalIp, :externalPort, :internalPort, :status, :cluster => lambda { |it| cluster['name'] }
      ]
      print as_pretty_table(rows, columns, options)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_stateful_sets(args) ⇒ Object



2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
# File 'lib/morpheus/cli/clusters.rb', line 2070

def list_stateful_sets(args)
  resource_type = 'statefulset'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    opts.on("--resource-level LEVEL", String, "Resource Level") do |val|
      options[:resourceLevel] = val.to_s
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List #{resource_type}s for a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  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)
  _list_container_groups(args, options, resource_type)
end

#list_volumes(args) ⇒ Object



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

def list_volumes(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List volumes for a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_volumes(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.list_volumes(cluster['id'], params)

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

    title = "Morpheus Cluster Volumes: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    volumes = json_response['volumes']
    if volumes.empty?
      print yellow,"No volumes found.",reset,"\n"
    else
      # more stuff to show here
      rows = volumes.collect do |ns|
        {
            id: ns['id'],
            name: ns['name'],
            description: ns['description'],
            status: ns['status'],
            active: ns['active'],
            cluster: cluster['name']
        }
      end
      columns = [
          :id, :name, :description, :status, :active, :cluster => lambda { |it| cluster['name'] }
      ]
      print as_pretty_table(rows, columns, options)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_workers(args) ⇒ Object



946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'lib/morpheus/cli/clusters.rb', line 946

def list_workers(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List workers for a cluster.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.list_workers(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.list_workers(cluster['id'], params)
    
    render_result = render_with_format(json_response, options, 'workers')
    return 0 if render_result

    title = "Morpheus Cluster Workers: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    workers = json_response['workers']
    if workers.empty?
      print yellow,"No workers found.",reset,"\n"
    else
      # more stuff to show here
      
      servers = workers
      multi_tenant = false

      # print_servers_table(servers)
      rows = servers.collect {|server|
        stats = server['stats']

        if !stats['maxMemory']
          stats['maxMemory'] = stats['usedMemory'] + stats['freeMemory']
        end
        cpu_usage_str = !stats ? "" : generate_usage_bar((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]
          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: server['id'],
          tenant: server['account'] ? server['account']['name'] : server['accountId'],
          name: server['name'],
          platform: server['serverOs'] ? server['serverOs']['name'].upcase : 'N/A',
          cloud: server['zone'] ? server['zone']['name'] : '',
          type: server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged',
          nodes: server['containers'] ? server['containers'].size : '',
          status: format_server_status(server, cyan),
          power: format_server_power_state(server, cyan),
          cpu: cpu_usage_str + cyan,
          memory: memory_usage_str + cyan,
          storage: storage_usage_str + cyan
        }
        row
      }
      columns = [:id, :name, :type, :cloud, :nodes, :status, :power]
      if multi_tenant
        columns.insert(4, :tenant)
      end
      columns += [: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(json_response)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#logs(args) ⇒ Object



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

def logs(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :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}\n#{optparse}"
  end
  connect(options)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    params = {}
    params.merge!(parse_list_options(options))
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    @logs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @logs_interface.dry.cluster_logs(cluster['id'], params)
      return
    end
    json_response = @logs_interface.cluster_logs(cluster['id'], params)
    render_result = render_with_format(json_response, options, 'data')
    return 0 if render_result

    logs = json_response
    title = "Cluster Logs: #{cluster['name']}"
    subtitles = parse_list_subtitles(options)
    if params[:query]
      subtitles << "Search: #{params[:query]}".strip
    end
    # todo: startMs, endMs, sorts insteaad of sort..etc
    print_h1 title, subtitles, options
    if logs['data'].empty?
      puts "#{cyan}No logs found.#{reset}"
    else
      logs['data'].reverse.each do |log_entry|
        log_level = ''
        case log_entry['level']
        when 'INFO'
          log_level = "#{blue}#{bold}INFO#{reset}"
        when 'DEBUG'
          log_level = "#{white}#{bold}DEBUG#{reset}"
        when 'WARN'
          log_level = "#{yellow}#{bold}WARN#{reset}"
        when 'ERROR'
          log_level = "#{red}#{bold}ERROR#{reset}"
        when 'FATAL'
          log_level = "#{red}#{bold}FATAL#{reset}"
        end
        puts "[#{log_entry['ts']}] #{log_level} - #{log_entry['message'].to_s.strip}"
      end
      print_results_pagination({'meta'=>{'total'=>json_response['total'],'size'=>json_response['data'].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

#remove(args) ⇒ Object



780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
# File 'lib/morpheus/cli/clusters.rb', line 780

def remove(args)
  options = {}
  query_params = {:removeResources => 'on'}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    opts.on('--remove-resources [on|off]', ['on','off'], "Remove Infrastructure. Default is on.") do |val|
      query_params[:removeResources] = val.nil? ? 'on' : val
    end
    opts.on('--preserve-volumes [on|off]', ['on','off'], "Preserve Volumes. Default is off.") do |val|
      query_params[:preserveVolumes] = val.nil? ? 'on' : val
    end
    opts.on('--remove-instances [on|off]', ['on','off'], "Remove Associated Instances. Default is off.") do |val|
      query_params[:removeInstances] = val.nil? ? 'on' : val
    end
    opts.on('--release-eips [on|off]', ['on','off'], "Release EIPs, default is on. Amazon only.") do |val|
      params[:releaseEIPs] = val.nil? ? 'on' : val
    end
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a cluster.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cluster '#{cluster['name']}'?", options)
      return 9, "aborted command"
    end
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.destroy(cluster['id'], query_params)
      return
    end
    json_response = @clusters_interface.destroy(cluster['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Cluster #{cluster['name']} is being removed..."
      #list([])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_container(args) ⇒ Object



1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
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
# File 'lib/morpheus/cli/clusters.rb', line 1760

def remove_container(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [container]")
    opts.on( '-f', '--force', "Force Delete" ) do
      options[:force] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a container within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[container] is required. This is the name or id of an existing container."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    container_id = args[1]

    if container_id.empty?
      raise_command_error "missing required container parameter"
    end

    container = find_container_by_name_or_id(cluster['id'], container_id)
    if container.nil?
      print_red_alert "Container not found by id '#{container_id}'"
      return 1
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cluster container '#{container['name'] || container['id']}'?", options)
      return 9, "aborted command"
    end

    if !options[:force].nil?
        params['force'] = options[:force]
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.destroy_container(cluster['id'], container['id'], params)
      return
    end
    json_response = @clusters_interface.destroy_container(cluster['id'], container['id'], params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_red_alert "Error removing container #{container['name']} from cluster #{cluster['name']}: #{json_response['msg']}" if json_response['success'] == false
      print_green_success "container #{container['name']} is being removed from cluster #{cluster['name']}..." if json_response['success'] == true
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_deployment(args) ⇒ Object



2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
# File 'lib/morpheus/cli/clusters.rb', line 2031

def remove_deployment(args)
  resource_type = 'deployment'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [#{resource_type}]")
    opts.on( '-f', '--force', "Force Delete" ) do
      options[:force] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a #{resource_type} within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[#{resource_type}] is required. This is the name or id of an existing #{resource_type}."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  _remove_container_group(args, options, resource_type)
end

#remove_job(args) ⇒ Object



1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
# File 'lib/morpheus/cli/clusters.rb', line 1633

def remove_job(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [job]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a job within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[job] is required. This is the name or id of an existing job."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    job_id = args[1]

    if job_id.empty?
      raise_command_error "missing required job parameter"
    end

    job = find_job_by_name_or_id(cluster['id'], job_id)
    if job.nil?
      print_red_alert "Job not found by id '#{job_id}'"
      return 1
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cluster job '#{job['name'] || job['id']}'?", options)
      return 9, "aborted command"
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.destroy_job(cluster['id'], job['id'], params)
      return
    end
    json_response = @clusters_interface.destroy_job(cluster['id'], job['id'], params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_red_alert "Error removing job #{job['name']} from cluster #{cluster['name']}: #{json_response['msg']}" if json_response['success'] == false
      print_green_success "Job #{job['name']} is being removed from cluster #{cluster['name']}..." if json_response['success'] == true
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_namespace(args) ⇒ Object



2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
# File 'lib/morpheus/cli/clusters.rb', line 2450

def remove_namespace(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [namespace]")
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a namespace within a cluster."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    namespace = find_namespace_by_name_or_id(cluster['id'], args[1])
    if namespace.nil?
      print_red_alert "Namespace not found by '#{args[1]}'"
      exit 1
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cluster namespace '#{namespace['name']}'?", options)
      return 9, "aborted command"
    end
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.destroy_namespace(cluster['id'], namespace['id'], query_params)
      return
    end
    json_response = @clusters_interface.destroy_namespace(cluster['id'], namespace['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Removed cluster namespace #{namespace['name']}"
      #list([])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_pod(args) ⇒ Object



2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
# File 'lib/morpheus/cli/clusters.rb', line 2149

def remove_pod(args)
  resource_type = 'pod'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [#{resource_type}]")
    opts.on( '-f', '--force', "Force Delete" ) do
      options[:force] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a #{resource_type} within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[#{resource_type}] is required. This is the name or id of an existing #{resource_type}."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  _remove_container_group(args, options, resource_type)
end

#remove_service(args) ⇒ Object



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

def remove_service(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [service]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a service within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[service] is required. This is the name or id of an existing service."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    service_id = args[1]

    if service_id.empty?
      raise_command_error "missing required service parameter"
    end

    service = find_service_by_name_or_id(cluster['id'], service_id)
    if service.nil?
      print_red_alert "Service not found by id '#{service_id}'"
      return 1
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cluster service '#{service['name'] || service['id']}'?", options)
      return 9, "aborted command"
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.destroy_service(cluster['id'], service['id'], params)
      return
    end
    json_response = @clusters_interface.destroy_service(cluster['id'], service['id'], params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_red_alert "Error removing service #{service['name']} from cluster #{cluster['name']}: #{json_response['msg']}" if json_response['success'] == false
      print_green_success "Service #{service['name']} is being removed from cluster #{cluster['name']}..." if json_response['success'] == true
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_stateful_set(args) ⇒ Object



2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
# File 'lib/morpheus/cli/clusters.rb', line 2090

def remove_stateful_set(args)
  resource_type = 'statefulset'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [#{resource_type}]")
    opts.on( '-f', '--force', "Force Delete" ) do
      options[:force] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a #{resource_type} within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[#{resource_type}] is required. This is the name or id of an existing #{resource_type}."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  _remove_container_group(args, options, resource_type)
end

#remove_volume(args) ⇒ Object



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

def remove_volume(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [volume]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a volume within a cluster.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster.\n" +
                  "[volume] is required. This is the name or id of an existing volume."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    volume_id = args[1]

    if volume_id.empty?
      raise_command_error "missing required volume parameter"
    end

    volume = find_volume_by_name_or_id(cluster['id'], volume_id)
    if volume.nil?
      print_red_alert "Volume not found for '#{volume_id}'"
      return 1
    end
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cluster volume '#{volume['name'] || volume['id']}'?", options)
      return 9, "aborted command"
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.destroy_volume(cluster['id'], volume['id'], params)
      return
    end
    json_response = @clusters_interface.destroy_volume(cluster['id'], volume['id'], params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_red_alert "Error removing volume #{volume['name']} from cluster #{cluster['name']}: #{json_response['msg']}" if json_response['success'] == false
      print_green_success "Volume #{volume['name']} is being removed from cluster #{cluster['name']}..." if json_response['success'] == true
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#restart_container(args) ⇒ Object



1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
# File 'lib/morpheus/cli/clusters.rb', line 1820

def restart_container(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [container]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Restart a container within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[container] is required. This is the name or id of an existing container."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    container_id = args[1]

    if container_id.empty?
      raise_command_error "missing required container parameter"
    end

    container = find_container_by_name_or_id(cluster['id'], container_id)
    if container.nil?
      print_red_alert "Container not found by id '#{container_id}'"
      return 1
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.restart_container(cluster['id'], container['id'], params)
      return
    end
    json_response = @clusters_interface.restart_container(cluster['id'], container['id'], params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_red_alert "Error restarting container #{container['name']} for cluster #{cluster['name']}: #{json_response['msg']}" if json_response['success'] == false
      print_green_success "Container #{container['name']} is restarting for cluster #{cluster['name']}..." if json_response['success'] == true
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#restart_deployment(args) ⇒ Object



2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
# File 'lib/morpheus/cli/clusters.rb', line 2052

def restart_deployment(args)
  resource_type = 'deployment'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [#{resource_type}]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Restart a #{resource_type} within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[#{resource_type}] is required. This is the name or id of an existing #{resource_type}."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  _restart_container_group(args, options, resource_type)
end

#restart_pod(args) ⇒ Object



2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
# File 'lib/morpheus/cli/clusters.rb', line 2170

def restart_pod(args)
  resource_type = 'pod'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [#{resource_type}]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Restart a #{resource_type} within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[#{resource_type}] is required. This is the name or id of an existing #{resource_type}."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  _restart_container_group(args, options, resource_type)
end

#restart_stateful_set(args) ⇒ Object



2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
# File 'lib/morpheus/cli/clusters.rb', line 2111

def restart_stateful_set(args)
  resource_type = 'statefulset'
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [#{resource_type}]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Restart a #{resource_type} within a cluster.\n" +
        "[cluster] is required. This is the name or id of an existing cluster.\n" +
        "[#{resource_type}] is required. This is the name or id of an existing #{resource_type}."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  _restart_container_group(args, options, resource_type)
end

#update(args) ⇒ Object



690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
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
# File 'lib/morpheus/cli/clusters.rb', line 690

def update(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster] --name --description --active")
    opts.on("--name NAME", String, "Updates Cluster Name") do |val|
      options[:name] = val.to_s
    end
    opts.on("--description [TEXT]", String, "Updates Cluster Description") do |val|
      options[:description] = val.to_s
    end
    opts.on("--api-url [TEXT]", String, "Updates Cluster API Url") do |val|
      options[:apiUrl] = val.to_s
    end
    opts.on('--active [on|off]', String, "Can be used to enable / disable the cluster. Default is on") do |val|
      options[:active] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on( nil, '--refresh', "Refresh cluster" ) do
      options[:refresh] = true
    end
    opts.on("--tenant ACCOUNT", String, "Account ID or Name" ) do |val|
      options[:tenant] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a cluster.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster."
  end

  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    payload = nil
    cluster = nil

    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload['cluster'] ||= {}
        payload['cluster'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end

      if !payload['cluster'].empty?
        cluster = find_cluster_by_name_or_id(payload['cluster']['id'] || payload['cluster']['name'])
      end
    else
      cluster = find_cluster_by_name_or_id(args[0])
      cluster_payload = {}
      cluster_payload['name'] = options[:name] if !options[:name].empty?
      cluster_payload['description'] = options[:description] if !options[:description].empty?
      cluster_payload['enabled'] = options[:active] if !options[:active].nil?
      cluster_payload['serviceUrl'] = options[:apiUrl] if !options[:apiUrl].nil?
      cluster_payload['refresh'] = options[:refresh] if options[:refresh] == true
      cluster_payload['tenant'] = options[:tenant] if !options[:tenant].nil?
      payload = {"cluster" => cluster_payload}
    end

    if !cluster
      print_red_alert "No clusters available for update"
      exit 1
    end

    has_field_updates = ['name', 'description', 'enabled', 'serviceUrl'].find {|field| payload['cluster'] && !payload['cluster'][field].nil? && payload['cluster'][field] != cluster[field] ? field : nil}

    if !has_field_updates && cluster_payload['refresh'].nil? && cluster_payload['tenant'].nil?
      print_green_success "Nothing to update"
      exit 1
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.update(cluster['id'], payload)
      return
    end
    json_response = @clusters_interface.update(cluster['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif json_response['success']
      get_args = [json_response["cluster"]["id"]] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
      get(get_args)
    else
      print_rest_errors(json_response, options)
    end
  end
end

#update_namespace(args) ⇒ Object



2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
# File 'lib/morpheus/cli/clusters.rb', line 2378

def update_namespace(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster] [namespace] [options]")
    opts.on("--description [TEXT]", String, "Description") do |val|
      options[:description] = val.to_s
    end
    opts.on('--active [on|off]', String, "Enable namespace") do |val|
      options[:active] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    add_perms_options(opts, options)
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a cluster namespace.\n" +
                  "[cluster] is required. This is the name or id of an existing cluster.\n" +
                  "[namespace] is required. This is the name or id of an existing namespace."
  end

  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    namespace = find_namespace_by_name_or_id(cluster['id'], args[1])
    if namespace.nil?
      print_red_alert "Namespace not found by '#{args[1]}'"
      exit 1
    end
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of everything
      if options[:options]
        payload.deep_merge!({'namespace' => options[:options].reject {|k,v| k.is_a?(Symbol) }})
      end
    else
      payload = {'namespace' => prompt_update_namespace(options)}

      # support -O OPTION switch on top of everything
      if options[:options]
        payload.deep_merge!({'namespace' => options[:options].reject {|k,v| k.is_a?(Symbol) }})
      end

      if payload['namespace'].nil? || payload['namespace'].empty?
        raise_command_error "Specify at least one option to update.\n#{optparse}"
      end
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.update_namespace(cluster['id'], namespace['id'], payload)
      return
    end
    json_response = @clusters_interface.update_namespace(cluster['id'], namespace['id'], payload)
    if options[:json]
      puts as_json(json_response)
    elsif !options[:quiet]
      namespace = json_response['namespace']
      print_green_success "Updated namespace #{namespace['name']}"
      get_args = [cluster["id"], namespace["id"]] + (options[:remote] ? ["-r",options[:remote]] : [])
      get_namespace(get_args)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_permissions(args) ⇒ Object



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

def update_permissions(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cluster]")
    add_perms_options(opts, options)
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a clusters permissions.\n" +
        "[cluster] is required. This is the name or id of an existing cluster."
  end

  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload['permissions'] ||= {}
        payload['permissions'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end
    else
      payload = {"permissions" => prompt_permissions(options)}
    end

    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.update_permissions(cluster['id'], payload)
      return
    end
    json_response = @clusters_interface.update_permissions(cluster['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif json_response['success']
      get_args = [json_response["cluster"]["id"], '--permissions'] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
      get(get_args)
    else
      print_rest_errors(json_response, options)
    end
  end
end

#update_wiki(args) ⇒ Object



2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
# File 'lib/morpheus/cli/clusters.rb', line 2781

def update_wiki(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster] [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.exists?(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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.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
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.update_wiki(cluster["id"], payload)
      return
    end
    json_response = @clusters_interface.update_wiki(cluster["id"], payload)

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

#view(args) ⇒ Object



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/morpheus/cli/clusters.rb', line 321

def view(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    opts.on('-w','--wiki', "Open the wiki tab for this cluster") 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 a cluster in a web browser" + "\n" +
                  "[cluster] is required. This is the name or id of a cluster. Supports 1-N [cluster] arguments."
  end
  optparse.parse!(args)
  if args.count < 1
    raise_command_error "wrong number of arguments, expected 1-N and got (#{args.count}) #{args}\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_api_token(args) ⇒ Object



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
2652
2653
2654
2655
2656
2657
2658
# File 'lib/morpheus/cli/clusters.rb', line 2599

def view_api_token(args)
  print_token_only = false
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    build_common_options(opts, options, [:dry_run, :remote])
    opts.on('-t','--token-only', "Print the api token only") do
      print_token_only = true
    end
    opts.footer = "Display api token for a cluster."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.api_config(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.api_config(cluster['id'], params)
    
    render_result = render_with_format(json_response, options)
    return 0 if render_result

    service_config = json_response
    service_token = service_config['serviceToken']

    if print_token_only
      if service_token.to_s.empty?
        print yellow,"No api token found.",reset,"\n"
        return 1
      else
        print cyan,service_token,reset,"\n"
        return 0
      end
    end

    title = "Cluster API Token: #{cluster['name']}"
    subtitles = []
    print_h1 title, subtitles, options
    
    if service_token.to_s.empty?
      print yellow,"No api token found.",reset,"\n\n"
      return 1
    else
      print cyan,service_token,reset,"\n\n"
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#view_kube_config(args) ⇒ Object



2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
# File 'lib/morpheus/cli/clusters.rb', line 2551

def view_kube_config(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    build_common_options(opts, options, [:query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display Kubernetes config for a cluster."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  begin
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?
    params = {}
    params.merge!(parse_list_options(options))
    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.api_config(cluster['id'], params)
      return
    end
    json_response = @clusters_interface.api_config(cluster['id'], params)
    
    render_result = render_with_format(json_response, options)
    return 0 if render_result

    title = "Cluster Kube Config: #{cluster['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options

    service_config = json_response
    service_access = service_config['serviceAccess']
    if service_access.to_s.empty?
      print yellow,"No kube config found.",reset,"\n\n"
      return 1
    else
      print cyan,service_access,reset,"\n\n"
      return 0
    end

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

#view_wiki(args) ⇒ Object



2738
2739
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
# File 'lib/morpheus/cli/clusters.rb', line 2738

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 cluster wiki page in a web browser" + "\n" +
                  "[cluster] is required. This is the name or id of a cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?

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

    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

#wiki(args) ⇒ Object



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

def wiki(args)
  options = {}
  params = {}
  open_wiki_link = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cluster]")
    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 a cluster." + "\n" +
                  "[cluster] is required. This is the name or id of a cluster."
  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
    cluster = find_cluster_by_name_or_id(args[0])
    return 1 if cluster.nil?


    @clusters_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clusters_interface.dry.wiki(cluster["id"], params)
      return
    end
    json_response = @clusters_interface.wiki(cluster["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 "cluster Wiki Page: #{cluster['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([args[0]])
    end

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