Class: Morpheus::Cli::ServicePlanCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProvisioningHelper

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

Methods included from AccountsHelper

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

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_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, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #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

Instance Method Details

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



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

def _get(plan_id, options = {})
  params = {}
  begin
    @service_plans_interface.setopts(options)

    if !(plan_id.to_s =~ /\A\d{1,}\Z/)
      plan = find_service_plan(plan_id)

      if !plan
        print_red_alert "Service plan #{plan_id} not found"
        exit 1
      end
      plan_id = plan['id']
    end

    if options[:dry_run]
      print_dry_run @service_plans_interface.dry.get(plan_id)
      return
    end
    json_response = @service_plans_interface.get(plan_id)

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

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

    service_plan = json_response['servicePlan']
    print cyan
    description_cols = {
        "ID" => lambda {|it| it['id']},
        "Name" => lambda {|it| it['name'] || (it['accountIntegration'] ? 'Pending' : 'Not Set')},
        "Active" => lambda {|it| format_boolean(it['active'])},
        "Visibility" => lambda {|it| (it['visibility'] || '').capitalize},
        "Code" => lambda {|it| it['code']},
        "Display Order" => lambda {|it| it['sortOrder']},
        "Provision Type" => lambda {|it| it['provisionType'] ? it['provisionType']['name'] : ''},
        "Storage" => lambda {|it| printable_byte_size(it, it['maxStorage'], 'storageSizeType', 'GB')}
    }

    provision_type = service_plan['provisionType'] || {}

    description_cols['Customize Root Volume'] = lambda {|it| format_boolean(it['customMaxStorage'])} if provision_type['rootDiskCustomizable']
    description_cols['Customize Extra Volumes'] = lambda {|it| format_boolean(it['customMaxDataStorage'])} if provision_type['customizeVolume']
    description_cols['Add Volumes'] = lambda {|it| format_boolean(it['addVolumes'])} if provision_type['addVolumes']
    description_cols['Max Disks Allowed'] = lambda {|it| it['maxDisks'] || 0} if provision_type['addVolumes']
    description_cols['Memory'] = lambda {|it| printable_byte_size(it, it['maxMemory'], 'memorySizeType')}
    description_cols['Custom Max Memory'] = lambda {|it| format_boolean(it['customMaxMemory'])}
    description_cols['Core Count'] = lambda {|it| it['maxCores']}
    description_cols['Custom Cores'] = lambda {|it| format_boolean(it['customCores'])}
    description_cols['Cores Per Socket'] = lambda {|it| it['coresPerSocket']} if provision_type['hasConfigurableCpuSockets'] && service_plan['customCores']

    ranges = (service_plan['config'] ? service_plan['config']['ranges'] : nil) || {}

    if (ranges['minStorage'] && ranges['minStorage'] != '') || (ranges['maxStorage'] && ranges['maxStorage'] != '')
      description_cols['Custom Storage Range'] = lambda {|it|
        get_range(
            ranges['minStorage'] && ranges['minStorage'] != '' ? "#{ranges['minStorage']} #{(it['config'] && it['config']['storageSizeType'] ? it['config']['storageSizeType'] : 'GB').upcase}" : nil,
            ranges['maxStorage'] && ranges['maxStorage'] != '' ? "#{ranges['maxStorage']} #{(it['config'] && it['config']['storageSizeType'] ? it['config']['storageSizeType'] : 'GB').upcase}" : nil,
        )
      }
    end
    if (ranges['minMemory'] && ranges['minMemory'] != '') || (ranges['maxMemory'] && ranges['maxMemory'] != '')
      description_cols['Custom Memory Range'] = lambda {|it|
        get_range(
            ranges['minMemory'] && ranges['minMemory'] != '' ? printable_byte_size(it, ranges['minMemory'], 'memorySizeType') : nil,
            ranges['maxMemory'] && ranges['maxMemory'] != '' ? printable_byte_size(it, ranges['maxMemory'], 'memorySizeType') : nil
        )
      }
    end
    if (ranges['minCores'] && ranges['minCores'] != '') || (ranges['maxCores'] && ranges['maxCores'] != '')
      description_cols['Custom Cores Range'] = lambda {|it|
        get_range(
            ranges['minCores'] && ranges['minCores'] != '' ? ranges['minCores'] : nil,
            ranges['maxCores'] && ranges['maxCores'] != '' ? ranges['maxCores'] : nil
        )
      }
    end

    print_description_list(description_cols, service_plan)

    print_h2 "Price Sets"
    price_sets = service_plan['priceSets']

    if price_sets && !price_sets.empty?
      rows = price_sets.collect do |it|
        {
            id: it['id'],
            unit: (it['priceUnit'] || '').capitalize,
            name: it['name']
        }
      end
      columns = [
          :id, :unit, :name
      ]
      print as_pretty_table(rows, columns, options)
    else
      print cyan,"No price sets.",reset,"\n"
    end

    print_permissions(service_plan['permissions'], ['plans', 'groupDefaults'])
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#activate(args) ⇒ Object



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

def activate(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[plan]")
    build_common_options(opts, options, [:json, :dry_run, :remote, :auto_confirm])
    opts.footer = "Activate service plan.\n" +
        "[plan] is required. Service plan ID, name or code"
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    plan = find_service_plan(args[0])

    if !plan
      print_red_alert "Service plan #{args[0]} not found"
      return 1
    end

    # if plan['active'] == true
    #   print_green_success "Service plan #{plan['name']} already actived."
    #   return 0
    # end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to activate the service plan '#{plan['name']}'?", options)
      return 9, "aborted command"
    end

    @service_plans_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @service_plans_interface.dry.activate(plan['id'], params)
      return
    end

    json_response = @service_plans_interface.activate(plan['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Service plan #{plan['name']} activated"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



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

def add(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on("--name NAME", String, "Service plan name") do |val|
      params['name'] = val.to_s
    end
    opts.on("--code CODE", String, "Service plan code, unique identifier") do |val|
      params['code'] = val.to_s
    end
    opts.on('-t', '--provision-type [TYPE]', String, "Provision type ID or code") do |val|
      options[:provisionType] = val
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      params['description'] = val.to_s
    end
    opts.on('--active [on|off]', String, "Can be used to enable / disable the plan. Default is on") do |val|
      params['active'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--editable [on|off]', String, "Can be used to enable / disable the editability of the service plan. Default is on") do |val|
      params['editable'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--storage [AMOUNT]', String, "Storage size is required. Assumes GB unless optional modifier specified, ex: 512MB" ) do |val|
      bytes = parse_bytes_param(val, '--storage', 'GB')
      params['maxStorage'] = bytes[:bytes]
      (params['config'] ||= {})['storageSizeType'] = bytes[:unit].downcase
    end
    opts.on('--memory [AMOUNT]', String, "Memory size is required. Assumes MB unless optional modifier specified, ex: 1GB" ) do |val|
      bytes = parse_bytes_param(val, '--memory', 'MB')
      params['maxMemory'] = bytes[:bytes]
      (params['config'] ||= {})['memorySizeType'] = bytes[:unit].downcase
    end
    opts.on('--cores [NUMBER]', Integer, "Core count. Default is 1" ) do |val|
      params['maxCores'] = val.to_i || 1
    end
    opts.on('--disks [NUMBER]', Integer, "Max disks allowed" ) do |val|
      params['maxDisks'] = val.to_i || 1
    end
    opts.on('--custom-cores [on|off]', String, "Can be used to enable / disable customizable cores. Default is on") do |val|
      params['customCores'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--custom-storage [on|off]', String, "Can be used to enable / disable customizable storage. Default is on") do |val|
      params['customMaxStorage'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--custom-volumes [on|off]', String, "Can be used to enable / disable customizable extra volumes. Default is on") do |val|
      params['customMaxDataStorage'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--custom-memory [on|off]', String, "Can be used to enable / disable customizable memory. Default is on") do |val|
      params['customMaxMemory'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--add-volumes [on|off]', String, "Can be used to enable / disable ability to add volumes. Default is on") do |val|
      params['addVolumes'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--sort-order NUMBER', Integer, "Sort order") do |val|
      params['sortOrder'] = val.to_i
    end
    opts.on('--price-sets [LIST]', Array, 'Price set(s), comma separated list of price set IDs') do |list|
      params['priceSets'] = list.collect {|it| it.to_s.strip.empty? || !it.to_i ? nil : it.to_s.strip}.compact.uniq.collect {|it| {'id' => it.to_i}}
    end
    opts.on('--min-storage NUMBER', String, "Min storage. Assumes GB unless optional modifier specified, ex: 512MB") do |val|
      # Storage doesn't get converted to bytes
      bytes = parse_bytes_param(val, '--min-storage', 'GB')
      ((params['config'] ||= {})['ranges'] ||= {})['minStorage'] = bytes[:number]
      (params['config'] ||= {})['storageSizeType'] = bytes[:unit].downcase
    end
    opts.on('--max-storage NUMBER', String, "Max storage. Assumes GB unless optional modifier specified, ex: 512MB") do |val|
      # Storage doesn't get converted to bytes
      bytes = parse_bytes_param(val, '--max-storage', 'GB')
      ((params['config'] ||= {})['ranges'] ||= {})['maxStorage'] = bytes[:number]
      (params['config'] ||= {})['storageSizeType'] = bytes[:unit].downcase
    end
    opts.on('--min-memory NUMBER', String, "Min memory. Assumes MB unless optional modifier specified, ex: 1GB") do |val|
      # Memory does get converted to bytes
      bytes = parse_bytes_param(val, '--min-memory', 'MB')
      ((params['config'] ||= {})['ranges'] ||= {})['minMemory'] = bytes[:bytes]
      (params['config'] ||= {})['memorySizeType'] = bytes[:unit].downcase
    end
    opts.on('--max-memory NUMBER', String, "Max memory. Assumes MB unless optional modifier specified, ex: 1GB") do |val|
      # Memory does get converted to bytes
      bytes = parse_bytes_param(val, '--max-memory', 'MB')
      ((params['config'] ||= {})['ranges'] ||= {})['maxMemory'] = bytes[:bytes]
      (params['config'] ||= {})['memorySizeType'] = bytes[:unit].downcase
    end
    opts.on('--min-cores NUMBER', String, "Min cores") do |val|
      ((params['config'] ||= {})['ranges'] ||= {})['minCores'] = val.to_i
    end
    opts.on('--max-cores NUMBER', String, "Max cores") do |val|
      ((params['config'] ||= {})['ranges'] ||= {})['maxCores'] = val.to_i
    end
    add_perms_options(opts, options, ['plans', 'groupDefaults'])
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Create service plan"
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    if options[:payload]
      payload = parse_payload(options, 'servicePlan')
    else
      apply_options(params, options)

      # name
      params['name'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Service Plan Name', 'required' => true, 'description' => 'Service Plan Name.'}],options[:options],@api_client,{}, options[:no_prompt])['name']

      # code
      params['code'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'code', 'type' => 'text', 'fieldLabel' => 'Service Plan Code', 'required' => true, 'defaultValue' => params['name'].gsub(/[^0-9a-z ]/i, '').gsub(' ', '.').downcase, 'description' => 'Service Plan Code.'}],options[:options],@api_client,{}, options[:no_prompt])['code']

      # provision type
      options[:provisionType] = options[:provisionType] || (args.count > 1 ? args[1] : nil)
      provision_types = @service_plans_interface.provision_types()['provisionTypes']

      if options[:provisionType].nil? && !options[:no_prompt]
        provision_type_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'provisionType', 'type' => 'select', 'fieldLabel' => 'Provision Type', 'selectOptions' => provision_types.collect {|it| {'name' => it['name'], 'value' => it['id']}}, 'required' => true, 'description' => 'Select Provision Type.'}],options[:options],@api_client,{}, options[:no_prompt], true)['provisionType']

        if !provision_type_id.nil?
          provision_type = provision_types.find {|it| it['id'] == provision_type_id}
        end
      else
        provision_type = provision_types.find {|it| it['name'] == options[:provisionType] || it['code'] == options[:provisionType] || it['id'] == options[:provisionType].to_i}

        if provision_type.nil?
          print_red_alert "Provision type #{options[:provisionType]} not found"
          exit 1
        end
      end

      params['provisionType'] = {'id' => provision_type['id']} if !provision_type.nil?

      # storage is required
      if params['maxStorage'].nil?
        if options[:no_prompt]
          print_red_alert "Storage size is required"
          exit 1
        end
        while params['maxStorage'].nil? do
          begin
            bytes = parse_bytes_param(
                Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'storage', 'type' => 'text', 'fieldLabel' => 'Storage (GB) [can use MB modifier]', 'required' => true, 'description' => 'Storage (GB)'}],options[:options],@api_client,{}, options[:no_prompt])['storage'],
                'storage',
                'GB'
            )
            params['maxStorage'] = bytes[:bytes]
            # (params['config'] ||= {})['storageSizeType'] = bytes[:unit].downcase
          rescue
            print "Invalid Value... Please try again.\n"
          end
        end
      end

      # memory is required
      if params['maxMemory'].nil?
        if options[:no_prompt]
          print_red_alert "Memory size is required"
          exit 1
        end
        while params['maxMemory'].nil? do
          begin
            bytes = parse_bytes_param(
                Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'memory', 'type' => 'text', 'fieldLabel' => 'Memory (MB) [can use GB modifier]', 'required' => true, 'description' => 'Memory (MB)'}],options[:options],@api_client,{}, options[:no_prompt])['memory'],
                'memory',
                'MB'
            )
            params['maxMemory'] = bytes[:bytes]
            # (params['config'] ||= {})['memorySizeType'] = bytes[:unit].downcase
          rescue
            print "Invalid Value... Please try again.\n"
          end
        end
      end

      # price sets
      if params['priceSets'].nil? && !options[:no_prompt]
        price_sets = []
        while Morpheus::Cli::OptionTypes.confirm("Add #{price_sets.empty? ? '' : 'another '}price set?", {:default => false}) do
          price_unit = prompt_price_unit(options)

          avail_price_sets ||= @price_sets_interface.list({'priceUnit' => price_unit, 'max' => 10000})['priceSets'].collect {|it| {'name' => it['name'], 'value' => it['id'], 'priceUnit' => it['priceUnit']}}

          if price_set_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'priceSet', 'type' => 'select', 'fieldLabel' => 'Price Set', 'selectOptions' => avail_price_sets, 'required' => false, 'description' => 'Select Price.'}],options[:options],@api_client,{}, options[:no_prompt], true)['priceSet']
            price_set = avail_price_sets.find {|it| it['value'] == price_set_id}
            price_sets << {'id' => price_set['value'], 'priceUnit' => price_set['priceUnit']}
            avail_price_sets.reject! {|it| it['value'] == price_set_id}
          end

          if avail_price_sets.empty?
            break
          end
        end
        params['priceSets'] = price_sets if !price_sets.empty?
      end

      # permissions
      if !options[:no_prompt]
        perms = prompt_permissions(options, ['plans', 'groupDefaults'])
        params['visibility'] = perms.delete('resourcePool')['visibility']
        params['permissions'] = perms
      end
      payload = {'servicePlan' => params}
    end

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

    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Service plan created"
        _get(json_response['id'], options)
      else
        print_red_alert "Error creating service plan: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/morpheus/cli/service_plans_command.rb', line 13

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @service_plans_interface = @api_client.service_plans
  @provision_types_interface = @api_client.provision_types
  @options_interface = @api_client.options
  @accounts_interface = @api_client.accounts
  @price_sets_interface = @api_client.price_sets
end

#deactivate(args) ⇒ Object



686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/morpheus/cli/service_plans_command.rb', line 686

def deactivate(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[plan]")
    build_common_options(opts, options, [:json, :dry_run, :remote, :auto_confirm])
    opts.footer = "Deactivate service plan.\n" +
        "[plan] is required. Service plan ID, name or code"
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    plan = find_service_plan(args[0])

    if !plan
      print_red_alert "Service plan #{args[0]} not found"
      return 1
    end

    # if plan['active'] == false
    #   print_green_success "Service plan #{plan['name']} already deactivated."
    #   return 0
    # end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to deactivate the service plan '#{plan['name']}'?", options)
      return 9, "aborted command"
    end

    @service_plans_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @service_plans_interface.dry.deactivate(plan['id'], params)
      return
    end

    json_response = @service_plans_interface.deactivate(plan['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Service plan #{plan['name']} deactivated"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/morpheus/cli/service_plans_command.rb', line 103

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[plan]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Get details about a service plan.\n" +
        "[plan] is required. Service plan ID, name or code"
  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)
  return _get(args[0], options)
end

#handle(args) ⇒ Object



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

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



26
27
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
99
100
101
# File 'lib/morpheus/cli/service_plans_command.rb', line 26

def list(args)
  options = {}
  params = {'includeZones': true}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('-t', '--provision-type VALUE', String, "Filter by provision type ID or code") do |val|
      options[:provisionType] = val
    end
    opts.on('-i', '--include-inactive [on|off]', String, "Can be used to enable / disable inactive filter. Default is on") do |val|
      params['includeInactive'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    build_standard_list_options(opts, options)
    opts.footer = "List service plans."
  end
  optparse.parse!(args)
  #verify_args!(args:args, optparse:optparse, count:0)
  connect(options)

  
  params.merge!(parse_list_options(options))

  if !options[:provisionType].nil?
    type = find_provision_type(options[:provisionType])

    if type.nil?
      print_red_alert "Provision type #{options[:provisionType]} not found"
      exit 1
    end
    params['provisionTypeId'] = type['id']
  end

  @service_plans_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @service_plans_interface.dry.list(params)
    return
  end
  json_response = @service_plans_interface.list(params)
  plans = json_response['servicePlans']
  render_response(json_response, options, 'servicePlans') do
    title = "Morpheus Service Plans"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    if plans.empty?
      print cyan,"No service plans found.",reset,"\n"
    else
      rows = plans.collect do |it|
        {
            id: (it['active'] ? cyan : yellow) + it['id'].to_s,
            name: it['name'],
            type: it['provisionType'] ? it['provisionType']['name'] : '',
            active: format_boolean(it['active']),
            cores: it['maxCores'],
            memory: format_bytes(it['maxMemory']),
            clouds: it['zones'] ? truncate_string(it['zones'].collect {|it| it['name']}.join(', '), 30) : '',
            visibility: (it['visibility'] || '').capitalize,
            tenants: it['tenants'] || 'Global',
            price_sets: (it['priceSets'] ? it['priceSets'].count : 0).to_s + cyan
        }
      end
      columns = [
          :id, :name, :type, :active, :cores, :memory, :clouds, :visibility, :tenants, {"PRICE SETS" => :price_sets}
      ]
      columns.delete(:active) if !params['includeInactive']
      print as_pretty_table(rows, columns, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  if plans.empty?
    return 1,  "0 plans found"
  else
    return 0, nil
  end
end

#update(args) ⇒ Object



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

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[plan]")
    opts.on("--name NAME", String, "Service plan name") do |val|
      params['name'] = val.to_s
    end
    opts.on("--code CODE", String, "Service plan code, unique identifier") do |val|
      params['code'] = val.to_s
    end
    opts.on('-t', "--provision-type [TYPE]", String, "Provision type ID or code") do |val|
      options[:provisionType] = val
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      params['description'] = val.to_s
    end
    opts.on('--active [on|off]', String, "Can be used to enable / disable the plan. Default is on") do |val|
      params['active'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--storage [AMOUNT]', String, "Storage size is required. Assumes GB unless optional modifier specified, ex: 512MB" ) do |val|
      bytes = parse_bytes_param(val, '--storage', 'GB')
      params['maxStorage'] = bytes[:bytes]
      (params['config'] ||= {})['storageSizeType'] = bytes[:unit].downcase
    end
    opts.on('--memory [AMOUNT]', String, "Memory size is required. Assumes MB unless optional modifier specified, ex: 1GB" ) do |val|
      bytes = parse_bytes_param(val, '--memory', 'MB')
      params['maxMemory'] = bytes[:bytes]
      (params['config'] ||= {})['memorySizeType'] = bytes[:unit].downcase
    end
    opts.on('--cores [NUMBER]', Integer, "Core count. Default is 1" ) do |val|
      params['maxCores'] = val.to_i || 1
    end
    opts.on('--disks [NUMBER]', Integer, "Max disks allowed" ) do |val|
      params['maxDisks'] = val.to_i || 1
    end
    opts.on('--custom-cores [on|off]', String, "Can be used to enable / disable customizable cores. Default is on") do |val|
      params['customCores'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--custom-storage [on|off]', String, "Can be used to enable / disable customizable storage. Default is on") do |val|
      params['customMaxStorage'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--custom-volumes [on|off]', String, "Can be used to enable / disable customizable extra volumes. Default is on") do |val|
      params['customMaxDataStorage'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--custom-memory [on|off]', String, "Can be used to enable / disable customizable memory. Default is on") do |val|
      params['customMaxMemory'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--add-volumes [on|off]', String, "Can be used to enable / disable ability to add volumes. Default is on") do |val|
      params['addVolumes'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--sort-order NUMBER', Integer, "Sort order") do |val|
      params['sortOrder'] = val.to_i
    end
    opts.on('--price-sets [LIST]', Array, 'Price set(s), comma separated list of price set IDs') do |list|
      params['priceSets'] = list.collect {|it| it.to_s.strip.empty? || !it.to_i ? nil : it.to_s.strip}.compact.uniq.collect {|it| {'id' => it.to_i}}
    end
    opts.on('--min-storage NUMBER', String, "Min storage. Assumes GB unless optional modifier specified, ex: 512MB") do |val|
      # Storage doesn't get converted to bytes
      bytes = parse_bytes_param(val, '--min-storage', 'GB')
      ((params['config'] ||= {})['ranges'] ||= {})['minStorage'] = bytes[:number]
      (params['config'] ||= {})['storageSizeType'] = bytes[:unit].downcase
    end
    opts.on('--max-storage NUMBER', String, "Max storage. Assumes GB unless optional modifier specified, ex: 512MB") do |val|
      # Storage doesn't get converted to bytes
      bytes = parse_bytes_param(val, '--max-storage', 'GB')
      ((params['config'] ||= {})['ranges'] ||= {})['maxStorage'] = bytes[:number]
      (params['config'] ||= {})['storageSizeType'] = bytes[:unit].downcase
    end
    opts.on('--min-memory NUMBER', String, "Min memory. Assumes MB unless optional modifier specified, ex: 1GB") do |val|
      # Memory does get converted to bytes
      bytes = parse_bytes_param(val, '--min-memory', 'MB')
      ((params['config'] ||= {})['ranges'] ||= {})['minMemory'] = bytes[:bytes]
      (params['config'] ||= {})['memorySizeType'] = bytes[:unit].downcase
    end
    opts.on('--max-memory NUMBER', String, "Max memory. Assumes MB unless optional modifier specified, ex: 1GB") do |val|
      # Memory does get converted to bytes
      bytes = parse_bytes_param(val, '--max-memory', 'MB')
      ((params['config'] ||= {})['ranges'] ||= {})['maxMemory'] = bytes[:bytes]
      (params['config'] ||= {})['memorySizeType'] = bytes[:unit].downcase
    end
    opts.on('--min-cores NUMBER', String, "Min cores") do |val|
      ((params['config'] ||= {})['ranges'] ||= {})['minCores'] = val.to_i
    end
    opts.on('--max-cores NUMBER', String, "Max cores") do |val|
      ((params['config'] ||= {})['ranges'] ||= {})['maxCores'] = val.to_i
    end
    add_perms_options(opts, options, ['plans', 'groupDefaults'])
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Update service plan.\n[plan] is required. Service plan ID, name or code"
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    plan = find_service_plan(args[0])

    if plan.nil?
      print_red_alert "Service plan #{args[0]} not found"
      exit 1
    end

    if options[:payload]
      payload = parse_payload(options, 'servicePlan')
    else
      apply_options(params, options)

      # provision type
      options[:provisionType] = options[:provisionType] || (args.count > 1 ? args[1] : nil)

      if !options[:provisionType].nil?
        provision_types = @service_plans_interface.provision_types()['provisionTypes']
        provision_type = provision_types.find {|it| it['name'] == options[:provisionType] || it['code'] == options[:provisionType] || it['id'] == options[:provisionType].to_i}

        if provision_type.nil?
          print_red_alert "Provision type #{options[:provisionType]} not found"
          exit 1
        end
        params['provisionType'] = {'id' => provision_type['id']} if !provision_type.nil?
      end

      # perms
      resource_perms = {}
      resource_perms['all'] = true if options[:groupAccessAll]
      resource_perms['sites'] = options[:groupAccessList].collect {|site_id| {'id' => site_id.to_i}} if !options[:groupAccessList].nil?

      if !resource_perms.empty? || !options[:tenants].nil?
        params['permissions'] = {}
        params['permissions']['resourcePermissions'] = resource_perms if !resource_perms.empty?
        params['permissions']['tenantPermissions'] = {'accounts' => options[:tenants]} if !options[:tenants].nil?
      end

      # visibility
      params['visibility'] = options[:visibility] if !options[:visibility].nil?

      payload = {'servicePlan' => params}
    end

    if payload.empty? || !payload['servicePlan'] || payload['servicePlan'].empty?
      raise_command_error "Specify at least one option to update.\n#{optparse}"
      # print_green_success "Nothing to update"
      # return 0
    end

    @service_plans_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @service_plans_interface.dry.update(plan['id'], payload)
      return
    end
    json_response = @service_plans_interface.update(plan['id'], payload)

    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Service plan updated"
        _get(plan['id'], options)
      else
        print_red_alert "Error updating service plan: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end