Class: Morpheus::Cli::LibraryClusterLayoutsCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, LibraryHelper
Defined in:
lib/morpheus/cli/commands/library_cluster_layouts_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from LibraryHelper

#api_client, #find_container_type_by_id, #find_container_type_by_name, #find_container_type_by_name_or_id, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_option_type_by_id, #find_option_type_by_name, #find_option_type_by_name_or_id, #find_option_type_list_by_id, #find_option_type_list_by_name, #find_option_type_list_by_name_or_id, #find_spec_template_by_id, #find_spec_template_by_name, #find_spec_template_by_name_or_id, #find_spec_template_type_by_id, #find_spec_template_type_by_name_or_code, #find_spec_template_type_by_name_or_code_id, #format_container_type_technology, #format_instance_type_technology, #get_all_spec_template_types, included, #load_balance_protocols_dropdown, #print_container_types_table, #print_instance_types_table, #print_resource_specs_table, #prompt_exposed_ports, #prompt_for_container_types, #prompt_for_option_types, #prompt_for_spec_templates

Methods included from CliCommand

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

Constructor Details

#initializeLibraryClusterLayoutsCommand

Returns a new instance of LibraryClusterLayoutsCommand.



11
12
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 11

def initialize()
end

Instance Method Details

#_get(id, options) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 123

def _get(id, options)
  begin
    @library_cluster_layouts_interface.setopts(options)
    if options[:dry_run]
      if arg.to_s =~ /\A\d{1,}\Z/
        print_dry_run @library_cluster_layouts_interface.dry.get(arg.to_i)
      else
        print_dry_run @library_container_types_interface.dry.list({name:arg})
      end
      return
    end
    layout = find_layout_by_name_or_id(id)
    if layout.nil?
      return 1
    end

    json_response = {'layout' => layout}

    if options[:json]
      puts as_json(json_response, options, "layout")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "layout")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['layout']], options)
      return 0
    end

    print_h1 "Cluster Layout Details"
    print cyan
    description_cols = {
      "ID" => lambda {|it| it['id'] },
      "Name" => lambda {|it| it['name'] },
      "Version" => lambda {|it| it['computeVersion']},
      # "Type" => lambda {|it| it['type'] ? it['type']['name'] : nil},
      "Creatable" => lambda {|it| format_boolean(it['creatable'])},
      "Cloud Type" => lambda {|it| layout_cloud_type(it)},
      "Cluster Type" => lambda {|it| it['groupType'] ? it['groupType']['name'] : nil},
      "Technology" => lambda {|it| it['provisionType'] ? it['provisionType']['code'] : nil},
      "Labels" => lambda {|it| format_list(it['labels'], '') },
      "Minimum Memory" => lambda {|it| printable_byte_size(it['memoryRequirement'])},
      "Workflow" => lambda {|it| it['taskSets'] && it['taskSets'].count > 0 ? it['taskSets'][0]['name'] : nil},
      "Description" => lambda {|it| it['description']},
      "Horizontal Scaling" => lambda {|it| format_boolean(it['hasAutoScale'])},
      "Install Docker" => lambda {|it| it['installContainerRuntime'].nil? ? nil : format_boolean(it['installContainerRuntime'])},
    }

    print_description_list(description_cols, layout)

    if (layout['environmentVariables'] || []).count > 0
      rows = layout['environmentVariables'].collect do |evar|
        {
            name: evar['name'],
            value: evar['defaultValue'],
            masked: format_boolean(evar['masked']),
            label: format_boolean(evar['export'])
        }
      end
      print_h2 "Environment Variables"
      puts as_pretty_table(rows, [:name, :value, :masked, :label])
    end

    if (layout['optionTypes'] || []).count > 0
      rows = layout['optionTypes'].collect do |opt|
        {
            label: opt['fieldLabel'],
            type: opt['type']
        }
      end
      print_h2 "Option Types"
      puts as_pretty_table(rows, [:label, :type])
    end

    ['master', 'worker'].each do |node_type|
      nodes = layout['computeServers'].reject {|it| it['nodeType'] != node_type}.collect do |server|
        container = server['containerType']
        {
            id: container['id'],
            name: container['name'],
            short_name: container['shortName'],
            version: container['containerVersion'],
            category: container['category'],
            count: server['nodeCount'],
            priority: server['priorityOrder']
        }
      end

      if nodes.count > 0
        print_h2 "#{node_type.capitalize} Nodes"
        puts as_pretty_table(nodes, [:id, :name, :short_name, :version, :category, :count, :priority])
      end
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#add(args) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 223

def add(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [options]")
    opts.on('-n', '--name VALUE', String, "Name for this cluster layout") do |val|
      params['name'] = val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      params['labels'] = parse_labels(val)
    end
    opts.on('-D', '--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('-v', '--version VALUE', String, "Version") do |val|
      params['computeVersion'] = val
    end
    opts.on('-c', '--creatable [on|off]', String, "Can be used to enable / disable creatable layout. Default is on") do |val|
      params['creatable'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('-g', '--cluster-type CODE', String, "Cluster type. This is the cluster type code.") do |val|
      options[:clusterTypeCode] = val
    end
    opts.on('-t', '--technology CODE', String, "Technology. This is the provision type code.") do |val|
      options[:provisionTypeCode] = val
    end
    opts.on('-m', '--min-memory NUMBER', String, "Min memory. Assumes MB unless optional modifier specified, ex: 1GB") do |val|
      bytes = parse_bytes_param(val, '--min-memory', 'MB')
      params['memoryRequirement'] = bytes[:bytes]
    end
    opts.on('-w', '--workflow ID', String, "Workflow") do |val|
      options[:taskSetId] = val.to_i
    end
    opts.on('-s', '--auto-scale [on|off]', String, "Can be used to enable / disable horizontal scaling. Default is on") do |val|
      params['hasAutoScale'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--install-docker [on|off]', String, "Install Docker container runtime. Default is off.") do |val|
      params['installContainerRuntime'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--install-container-runtime [on|off]', String, "Install Docker container runtime. Default is off.") do |val|
      params['installContainerRuntime'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.add_hidden_option('--install-container-runtime')
    opts.on('--evars-json JSON', String, 'Environment variables JSON: {"name":"Foo", "value":"Bar", "masked":true, "export":true}' ) do |val|
      begin
        evars = JSON.parse(val.to_s)
        params['environmentVariables'] = evars.kind_of?(Array) ? evars : [evars]
      rescue JSON::ParserError => e
        print_red_alert "Unable to parse evars JSON"
        exit 1
      end
    end
    opts.on('-e', '--evars LIST', Array, "Environment variables list. Comma delimited list of name=value pairs") do |val|
      params['environmentVariables'] = val.collect do |nv|
        parts = nv.split('=')
        {'name' => parts[0].strip, 'value' => (parts.count > 1 ? parts[1].strip : '')}
      end
    end
    opts.on('-o', '--option-types LIST', Array, "Option types, comma separated list of option type IDs") do |val|
      options[:optionTypes] = val
    end
    opts.on('--masters LIST', Array, "List of master. Comma separated container types IDs in format id[/count/priority], ex: 100,101/3/0") do |val|
      options[:masters] = val
    end
    opts.on('--workers LIST', Array, "List of workers. Comma separated container types IDs in format id[/count/priority], ex: 100,101/3/1") do |val|
      options[:workers] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a cluster layout."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  if args[0]
    params['name'] = args[0]
  end
  begin
    if options[:payload]
      payload = options[:payload]
    else
      # support the old -O OPTION switch
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

      # prompt for options
      if params['name'].nil?
        params['name'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Name', 'required' => true}], options[:options], @api_client,{})['name']
      end

      # version
      if params['computeVersion'].nil?
        params['computeVersion'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'computeVersion', 'type' => 'text', 'fieldLabel' => 'Version', 'required' => true}], options[:options], @api_client,{})['computeVersion']
      end

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

      # creatable
      if params['creatable'].nil?
        params['creatable'] = Morpheus::Cli::OptionTypes.confirm("Creatable?", {:default => true}) == true
      end

      # cluster type
      if options[:clusterTypeCode]
        cluster_type = find_cluster_type_by_code(options[:clusterTypeCode])
        if cluster_type.nil?
          print_red_alert "Cluster type #{options[:clusterTypeCode]} not found"
          exit 1
        end
      else
        cluster_type_options = cluster_types.collect {|type| {'name' => type['name'], 'value' => type['code']}}
        cluster_type_code = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'groupType', 'type' => 'select', 'fieldLabel' => 'Cluster Type', 'required' => true, 'selectOptions' => cluster_type_options}], options[:options], @api_client,{}, nil, true)['groupType']
        cluster_type = cluster_types.find {|type| type['code'] == cluster_type_code}
      end

      params['groupType'] = {'id' => cluster_type['id']}

      # technology customSupported, createServer
      if options[:provisionTypeCode]
        provision_type = find_provision_type_by_code(options[:provisionTypeCode])
        if provision_type.nil?
          print_red_alert "Technology #{options[:provisionTypeCode]} not found"
          exit 1
        end
      else
        provision_type_options = provision_types.collect {|type| {'name' => type['name'], 'value' => type['code']}}
        provision_type_code = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'provisionType', 'type' => 'select', 'fieldLabel' => 'Technology', 'required' => true, 'selectOptions' => provision_type_options}], options[:options], @api_client,{}, nil, true)['provisionType']
        provision_type = provision_types.find {|type| type['code'] == provision_type_code}
      end

      params['provisionType'] = {'id' => provision_type['id']}

      # min memory
      if params['memoryRequirement'].nil?
        memory = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'memoryRequirement', 'type' => 'text', 'fieldLabel' => 'Minimum Memory (MB) [can use GB modifier]', 'required' => false, 'description' => 'Memory (MB)'}], options[:options], @api_client,{}, options[:no_prompt])['memoryRequirement']

        if memory
          bytes = parse_bytes_param(memory, 'minimum memory', 'MB')
          params['memoryRequirement'] = bytes[:bytes]
        end
      end

      # workflow
      if options[:taskSetId]
        task_set = @task_sets_interface.get(options[:taskSetId])['taskSet']

        if !task_set
          print_red_alert "Workflow #{options[:taskSetId]} not found"
          exit 1
        end
        params['taskSets'] = [{'id' => task_set['id']}]
      else
        task_set_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'taskSets', 'fieldLabel' => 'Workflow', 'type' => 'select', 'required' => false, 'optionSource' => 'taskSets'}], options[:options], @api_client, {})['taskSets']

        if task_set_id
          params['taskSets'] = [{'id' => task_set_id.to_i}]
        end
      end

      # auto scale
      if params['hasAutoScale'].nil?
        params['hasAutoScale'] = Morpheus::Cli::OptionTypes.confirm("Enable scaling?", {:default => false}) == true
      end

      # install docker
      if params['installContainerRuntime'].nil?
        params['installContainerRuntime'] = Morpheus::Cli::OptionTypes.confirm("Install Docker?", {:default => false}) == true
      end
      
      # evars?
      if params['environmentVariables'].nil?
        evars = []
        while Morpheus::Cli::OptionTypes.confirm("Add #{evars.empty? ? '' : 'another '}environment variable?", {:default => false}) do
          evars << prompt_evar(options)
        end
        params['environmentVariables'] = evars
      end

      # option types
      if options[:optionTypes]
        option_types = []
        options[:optionTypes].each do |option_type_id|
          if @options_types_interface.get(option_type_id.to_i).nil?
            print_red_alert "Option type #{option_type_id} not found"
            exit 1
          else
            option_types << {'id' => option_type_id.to_i}
          end
        end
      elsif !options[:no_prompt]
        avail_type_options = @options_types_interface.list({'max' => 1000})['optionTypes'].collect {|it| {'name' => it['name'], 'value' => it['id']}}
        option_types = []
        while !avail_type_options.empty? && Morpheus::Cli::OptionTypes.confirm("Add #{option_types.empty? ? '' : 'another '}option type?", {:default => false}) do
          option_type_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'optionType', 'type' => 'select', 'fieldLabel' => 'Option Type', 'selectOptions' => avail_type_options, 'required' => false}],options[:options],@api_client,{}, options[:no_prompt], true)['optionType']

          if option_type_id
            option_types << {'id' => option_type_id.to_i}
            avail_type_options.reject! {|it| it['value'] == option_type_id}
          else
            break
          end
        end
      end

      params['optionTypes'] = option_types if option_types

      # nodes
      priority = 0
      ['master', 'worker'].each do |node_type|
        nodes = []
        if cluster_type["has#{node_type.capitalize}s"]
          if options["#{node_type}s".to_sym]
            options["#{node_type}s".to_sym].each do |container_type_id|
              node_count = 1
              if container_type_id.include?('/')
                parts = container_type_id.split('/')
                container_type_id = parts[0]
                node_count = parts[1].to_i if parts.count > 1
                priority = parts[2].to_i if parts.count > 2
              end

              if @library_container_types_interface.get(nil, container_type_id.to_i).nil?
                print_red_alert "Container type #{container_type_id} not found"
                exit 1
              else
                nodes << {'nodeCount' => node_count, 'priorityOrder' => priority, 'containerType' => {'id' => container_type_id.to_i}}
              end
            end
          else
            avail_container_types = @library_container_types_interface.list(nil, {'technology' => provision_type['code'], 'max' => 1000})['containerTypes'].collect {|it| {'name' => it['name'], 'value' => it['id']}}
            while !avail_container_types.empty? && Morpheus::Cli::OptionTypes.confirm("Add #{nodes.empty? ? '' : 'another '}#{node_type} node?", {:default => false}) do
              container_type_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => "#{node_type}ContainerType", 'type' => 'select', 'fieldLabel' => "#{node_type.capitalize} Node", 'selectOptions' => avail_container_types, 'required' => true}],options[:options],@api_client,{}, options[:no_prompt], true)["#{node_type}ContainerType"]
              node_count = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => "#{node_type}NodeCount", 'type' => 'number', 'fieldLabel' => "#{node_type.capitalize} Node Count", 'required' => true, 'defaultValue' => 1}], options[:options], @api_client, {}, options[:no_prompt])["#{node_type}NodeCount"]
              priority = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => "#{node_type}Priority", 'type' => 'number', 'fieldLabel' => "#{node_type.capitalize} Priority", 'required' => true, 'defaultValue' => priority}], options[:options], @api_client, {}, options[:no_prompt])["#{node_type}Priority"]
              nodes << {'nodeCount' => node_count, 'priorityOrder' => priority, 'containerType' => {'id' => container_type_id.to_i}}
              avail_container_types.reject! {|it| it['value'] == container_type_id}
            end
          end
          priority += 1
        end
        params["#{node_type}s"] = nodes
      end
      payload = {'layout' => params}
    end

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

    json_response = @library_cluster_layouts_interface.create(payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "Added Cluster Layout #{params['name']}"
    get([json_response['id']])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#clone(args) ⇒ Object



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

def clone(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[layout]")
    opts.on('-n', '--name VALUE', String, "Name for new cluster layout. Defaults to 'Copy of...'") do |val|
      params['name'] = val
    end
    opts.on('-D', '--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('-v', '--version VALUE', String, "Version") do |val|
      params['computeVersion'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Clone a cluster layout." + "\n" +
        "[layout] is required. This is the name or id of a cluster layout being cloned."
  end
  optparse.parse!(args)

  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end

  connect(options)

  begin
    layout = find_layout_by_name_or_id(args[0])
    if layout.nil?
      return 1
    end

    if options[:payload]
      params = options[:payload]
    else
      # support the old -O OPTION switch
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
    end

    @library_cluster_layouts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @library_cluster_layouts_interface.dry.clone(layout['id'], params)
      return
    end

    json_response = @library_cluster_layouts_interface.clone(layout['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "Added Cluster Layout #{params['name']}"
    get([json_response['id']])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 14

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @library_cluster_layouts_interface = @api_client.library_cluster_layouts
  @library_container_types_interface = @api_client.library_container_types
  @clusters_interface = @api_client.clusters
  @provision_types_interface = @api_client.provision_types
  @options_types_interface = @api_client.option_types
  @task_sets_interface = @api_client.task_sets
end

#get(args) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 100

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[layout]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display cluster layout details." + "\n" +
                  "[layout] is required. This is the name or id of a cluster layout."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  id_list.each do |id|

  end
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end

#handle(args) ⇒ Object



24
25
26
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 24

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 28

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('--technology VALUE', String, "Filter by technology") do |val|
      params['provisionType'] = val
    end
    opts.on('-l', '--labels LABEL', String, "Filter by labels, can match any of the values") do |val|
      add_query_parameter(params, 'labels', parse_labels(val))
    end
    opts.on('--all-labels LABEL', String, "Filter by labels, must match all of the values") do |val|
      add_query_parameter(params, 'allLabels', parse_labels(val))
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List cluster layouts."
  end
  optparse.parse!(args)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  connect(options)
  begin
    # construct payload
    params.merge!(parse_list_options(options))
    @library_cluster_layouts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @library_cluster_layouts_interface.dry.list(params)
      return
    end
    # do it
    json_response = @library_cluster_layouts_interface.list(params)
    # print and/or return result
    # return 0 if options[:quiet]
    if options[:json]
      puts as_json(json_response, options, "layouts")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['layouts'], options)
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "layouts")
      return 0
    end
    layouts = json_response['layouts']
    title = "Morpheus Library - Cluster Layout"
    subtitles = parse_list_subtitles(options)
    print_h1 title, subtitles
    if layouts.empty?
      print cyan,"No cluster layouts found.",reset,"\n"
    else
      rows = layouts.collect do |layout|
        {
            id: layout['id'],
            name: layout['name'],
            cloud_type: layout_cloud_type(layout),
            version: layout['computeVersion'],
            description: layout['description'],
            labels: format_list(layout['labels'], '', 3)
        }
      end
      print as_pretty_table(rows, [:id, :name, :cloud_type, :version, :description, :labels], options)
      print_results_pagination(json_response, {:label => "node type", :n_label => "node types"})
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#remove(args) ⇒ Object



772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 772

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[layout]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a cluster layout." + "\n" +
                  "[layout] is required. This is the name or id of a cluster layout."
  end
  optparse.parse!(args)

  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end

  connect(options)

  begin
    layout = find_layout_by_name_or_id(args[0])
    if layout.nil?
      return 1
    end

    unless Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the cluster layout #{layout['name']}?", options)
      exit
    end

    @library_cluster_layouts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @library_cluster_layouts_interface.dry.destroy(layout['id'])
      return
    end
    json_response = @library_cluster_layouts_interface.destroy(layout['id'])

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      if json_response['success']
        print_green_success "Removed Cluster Layout #{layout['name']}"
      else
        print_red_alert "Error removing cluster layout: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# File 'lib/morpheus/cli/commands/library_cluster_layouts_command.rb', line 493

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [options]")
    opts.on('-n', '--name VALUE', String, "Name for this cluster layout") do |val|
      params['name'] = val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      params['labels'] = parse_labels(val)
    end
    opts.on('-D', '--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('-v', '--version VALUE', String, "Version") do |val|
      params['computeVersion'] = val
    end
    opts.on('-c', '--creatable [on|off]', String, "Can be used to enable / disable creatable layout. Default is on") do |val|
      params['creatable'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('-g', '--cluster-type CODE', String, "Cluster type. This is the cluster type code.") do |val|
      options[:clusterTypeCode] = val
    end
    opts.on('-t', '--technology CODE', String, "Technology. This is the provision type code.") do |val|
      options[:provisionTypeCode] = val
    end
    opts.on('-m', '--min-memory NUMBER', String, "Min memory. Assumes MB unless optional modifier specified, ex: 1GB") do |val|
      bytes = parse_bytes_param(val, '--min-memory', 'MB')
      params['memoryRequirement'] = bytes[:bytes]
    end
    opts.on('-w', '--workflow ID', String, "Workflow") do |val|
      options[:taskSetId] = val.to_i
    end
    opts.on(nil, '--clear-workflow', "Removes workflow from cluster layout") do
      params['taskSets'] = []
    end
    opts.on('-s', '--auto-scale [on|off]', String, "Can be used to enable / disable horizontal scaling. Default is on") do |val|
      params['hasAutoScale'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--install-docker [on|off]', String, "Install Docker container runtime. Default is off.") do |val|
      params['installContainerRuntime'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--install-container-runtime [on|off]', String, "Install Docker container runtime. Default is off.") do |val|
      params['installContainerRuntime'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.add_hidden_option('--install-container-runtime')
    opts.on('--evars-json JSON', String, 'Environment variables JSON: {"name":"Foo", "value":"Bar", "masked":true, "export":true}' ) do |val|
      begin
        evars = JSON.parse(val.to_s)
        params['environmentVariables'] = evars.kind_of?(Array) ? evars : [evars]
      rescue JSON::ParserError => e
        print_red_alert "Unable to parse evars JSON"
        exit 1
      end
    end
    opts.on('-e', '--evars LIST', Array, "Environment variables list. Comma delimited list of name=value pairs") do |val|
      params['environmentVariables'] = val.collect do |nv|
        parts = nv.split('=')
        {'name' => parts[0].strip, 'value' => (parts.count > 1 ? parts[1].strip : '')}
      end
    end
    opts.on(nil, '--clear-evars', "Removes all environment variables") do
      params['environmentVariables'] = []
    end
    opts.on('-o', '--opt-types LIST', Array, "Option types, comma separated list of option type IDs") do |val|
      options[:optionTypes] = val
    end
    opts.on(nil, '--clear-opt-types', "Removes all options") do
      params['optionTypes'] = []
    end
    opts.on('--masters LIST', Array, "List of master. Comma separated container types IDs in format id[/count/priority], ex: 100,101/3/0") do |val|
      options[:masters] = val
    end
    opts.on('--clear-masters', Array, "Removes all master nodes") do
      params['masters'] = []
    end
    opts.on('--workers LIST', Array, "List of workers. Comma separated container types IDs in format id[/count/priority], ex: 100,101/3/1") do |val|
      options[:workers] = val
    end
    opts.on('--clear-workers', Array, "Removes all worker nodes") do
      params['workers'] = []
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a cluster layout." + "\n" +
                  "[layout] is required. This is the name or id of a cluster layout."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end

  begin
    layout = find_layout_by_name_or_id(args[0])
    if layout.nil?
      return 1
    end

    if options[:payload]
      payload = options[:payload]
    else
      # support the old -O OPTION switch
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

      # cluster type
      cluster_type = nil
      if options[:clusterTypeCode]
        cluster_type = find_cluster_type_by_code(options[:clusterTypeCode])
        if cluster_type.nil?
          print_red_alert "Cluster type #{options[:clusterTypeCode]} not found"
          exit 1
        end
        params['groupType'] = {'id' => cluster_type['id']}
      end

      # technology customSupported, createServer
      if options[:provisionTypeCode]
        provision_type = find_provision_type_by_code(options[:provisionTypeCode])
        if provision_type.nil?
          print_red_alert "Technology #{options[:provisionTypeCode]} not found"
          exit 1
        end
        params['provisionType'] = {'id' => provision_type['id']}
      end

      # workflow
      if options[:taskSetId]
        task_set = @task_sets_interface.get(options[:taskSetId])['taskSet']

        if !task_set
          print_red_alert "Workflow #{options[:taskSetId]} not found"
          exit 1
        end
        params['taskSets'] = [{'id' => task_set['id']}]
      end

      # option types
      if options[:optionTypes]
        option_types = []
        options[:optionTypes].each do |option_type_id|
          if @options_types_interface.get(option_type_id.to_i).nil?
            print_red_alert "Option type #{option_type_id} not found"
            exit 1
          else
            option_types << {'id' => option_type_id.to_i}
          end
        end
        params['optionTypes'] = option_types if option_types
      end

      # nodes
      ['master', 'worker'].each do |node_type|
        nodes = []
        if options["#{node_type}s".to_sym]
          cluster_type ||= find_cluster_type_by_code(layout['groupType']['code'])

          if !cluster_type["has#{node_type.capitalize}s"]
            print_red_alert "#{node_type.capitalize}s not support for a #{cluster_type['name']}"
            exit 1
          else
            options["#{node_type}s".to_sym].each do |container_type_id|
              node_count = 1
              priority = nil
              if container_type_id.include?('/')
                parts = container_type_id.split('/')
                container_type_id = parts[0]
                node_count = parts[1].to_i if parts.count > 1
                priority = parts[2].to_i if parts.count > 2
              end

              if @library_container_types_interface.get(nil, container_type_id.to_i).nil?
                print_red_alert "Container type #{container_type_id} not found"
                exit 1
              else
                node = {'nodeCount' => node_count, 'containerType' => {'id' => container_type_id.to_i}}
                node['priorityOrder'] = priority if !priority.nil?
                nodes << node
              end
            end
          end
          params["#{node_type}s"] = nodes
        end
      end

      if params.empty?
        print_green_success "Nothing to update"
        exit 1
      end
      payload = {'layout' => params}
    end

    @library_cluster_layouts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @library_cluster_layouts_interface.dry.update(layout['id'], payload)
      return
    end

    json_response = @library_cluster_layouts_interface.update(layout['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    elsif !options[:quiet]
      if json_response['success']
        print_green_success "Updated cluster Layout #{params['name']}"
        get([layout['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
      else
        print_red_alert "Error updating cluster layout: #{json_response['msg'] || json_response['errors']}"
      end
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end