Class: Morpheus::Cli::BackupsCommand

Inherits:
Object
  • Object
show all
Includes:
BackupsHelper, CliCommand, OptionSourceHelper, ProvisioningHelper
Defined in:
lib/morpheus/cli/commands/backups_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from OptionSourceHelper

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

Methods included from 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_permissions_v2, #prompt_resize_volumes, #prompt_security_groups, #prompt_service_plan_options, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from BackupsHelper

#backup_job_list_key, #backup_job_object_key, #backup_jobs_interface, #backup_list_key, #backup_object_key, #backup_restore_column_definitions, #backup_restore_list_column_definitions, #backup_result_column_definitions, #backup_result_list_column_definitions, #backups_interface, #find_backup_by_id, #find_backup_by_name, #find_backup_by_name_or_id, #find_backup_job_by_id, #find_backup_job_by_name, #find_backup_job_by_name_or_id, #format_backup_restore_status, #format_backup_result_status, included

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

Instance Method Details

#_get(id, params, options) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/morpheus/cli/commands/backups_command.rb', line 83

def _get(id, params, options)
  if id.to_s !~ /\A\d{1,}\Z/
    record = find_by_name(:backup, id)
    if record.nil?
      return 1, "Backup not found for '#{id}'"
    end
    id = record['id']
  end
  options[:params] = params # parse_options(options, params)
  options.delete(:payload)
  execute_api(@backups_interface, :get, [id], options, 'backup') do |json_response|
    backup = json_response['backup']
    print_h1 "Backup Details", [], options
    print cyan
    columns = backup_column_definitions
    columns.delete("Instance") if backup['instance'].nil?
    columns.delete("Container ID") if backup['containerId'].nil?
    columns.delete("Host") if backup['server'].nil?
    print_description_list(columns, backup, options)
    print reset,"\n"
  end
end

#add(args) ⇒ Object



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

def add(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    opts.on('--source VALUE', String, "Backup Source: instance, host or provider") do |val|
      options[:options]['source'] = val
    end
    opts.on('--instance VALUE', String, "Instance Name or ID") do |val|
      options[:options]['source'] = 'instance'
      options[:options]['instanceId'] = val
    end
    opts.on('--host VALUE', String, "Host Name or ID") do |val|
      options[:options]['source'] = 'server'
      options[:options]['serverId'] = val
    end
    opts.on('--server VALUE', String, "alias for --host") do |val|
      options[:options]['source'] = 'server'
      options[:options]['serverId'] = val
    end
    opts.add_hidden_option('--server')
    opts.on('--name VALUE', String, "Name") do |val|
      options[:options]['name'] = val
    end
    # build_option_type_options(opts, options, add_backup_option_types)
    build_standard_add_many_options(opts, options)
    opts.footer = <<-EOT
Create a new backup.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:0, max:1)
  options[:options]['name'] = args[0] if args[0]
  connect(options)
  parse_payload(options, 'backup') do |payload|
    # v_prompt = Morpheus::Cli::OptionTypes.no_prompt(add_backup_option_types, options[:options], @api_client)
    # v_prompt.deep_compact!.booleanize! # remove empty values and convert checkbox "on" and "off" to true and false
    # params.deep_merge!(v_prompt)
    location_type = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'source', 'fieldLabel' => 'Source', 'type' => 'select', 'selectOptions' => [{'name' => 'Instance', 'value' => 'instance'}, {'name' => 'Host', 'value' => 'server'}, {'name' => 'Provider', 'value' => 'provider'}], 'defaultValue' => 'instance', 'required' => true, 'description' => 'Where is the backup located?'}], options[:options], @api_client)['source']
    params['locationType'] = location_type
    if location_type == 'instance'
      # Instance
      avail_instances = @instances_interface.list({max:10000})['instances'].collect {|it| {'name' => it['name'], 'value' => it['id']}}
      params['instanceId'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'instanceId', 'fieldLabel' => 'Instance', 'type' => 'select', 'selectOptions' => avail_instances, 'required' => true}], options[:options], @api_client)['instanceId']
      # Name
      params['name'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Backup Name'}], options[:options], @api_client)['name']
    elsif location_type == 'server'
      # Server
      avail_servers = @servers_interface.list({max:10000, 'vmHypervisor' => nil, 'containerHypervisor' => nil})['servers'].collect {|it| {'name' => it['name'], 'value' => it['id']}}
      params['serverId'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'serverId', 'fieldLabel' => 'Host', 'type' => 'select', 'selectOptions' => avail_servers, 'required' => true}], options[:options], @api_client)['serverId']
      # Name
      params['name'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Backup Name'}], options[:options], @api_client)['name']
    elsif location_type == 'provider'
      # todo: prompt for provider inputs
      # sourceProviderId
      # storageProvider
    end
    # POST to /create to get available option info for containers, backupTypes, backupProviderTypes, etc.
    payload['backup'].deep_merge!(params)
    create_results = @backups_interface.create_options(payload)

    if location_type == 'instance' || location_type == 'server'
      if location_type == 'instance'
        # Container
        avail_containers = (create_results['containers'] || []).collect {|it| {'name' => it['name'], 'value' => it['id']} }
        if avail_containers.empty?
          raise_command_error "No available containers found for selected instance"
        else
          params['containerId'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'containerId', 'fieldLabel' => 'Container', 'type' => 'select', 'selectOptions' => avail_containers, 'defaultValue' => avail_containers[0] ? avail_containers[0]['name'] : nil, 'required' => true}], options[:options], @api_client)['containerId']
        end
      elsif location_type == 'server'
        
      end
      # Backup Type
      avail_backup_types = (create_results['backupTypes'] || []).collect {|it| {'name' => it['name'], 'value' => it['code']} }
      if avail_backup_types.empty?
        raise_command_error "No available backup types found"
      else
        params['backupType'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'backupType', 'fieldLabel' => 'Backup Type', 'type' => 'select', 'selectOptions' => avail_backup_types, 'defaultValue' => avail_backup_types[0] ? avail_backup_types[0]['name'] : nil, 'required' => true}], options[:options], @api_client)['backupType']  
      end

      # Job / Schedule
      params['jobAction'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobAction', 'fieldLabel' => 'Backup Job Type', 'type' => 'select', 'optionSource' => 'backupJobActions', 'required' => true, 'defaultValue' => 'new'}], options[:options], @api_client)['jobAction']
      if params['jobAction'] == 'new'
        params['jobName'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobName', 'fieldLabel' => 'Job Name', 'type' => 'text', 'required' => false, 'defaultValue' => nil}], options[:options], @api_client)['jobName']
        default_retention_count = (create_results['backup'] && create_results['backup']['retentionCount']) ? create_results['backup']['retentionCount'] : ((create_results['backupSettings'] && create_results['backupSettings']['retentionCount']) ? create_results['backupSettings']['retentionCount'] : nil)
        params['retentionCount'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'retentionCount', 'fieldLabel' => 'Retention Count', 'type' => 'number', 'required' => false, 'defaultValue' => default_retention_count}], options[:options], @api_client)['retentionCount']
        params['jobSchedule'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobSchedule', 'fieldLabel' => 'Backup Schedule', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
          schedules = api_client.options.options_for_source('executeSchedules',{})['data']
          [{"name" => "Manual", "value" => "manual"}] + schedules
        }, 'required' => false}], options[:options], @api_client)['jobSchedule']
        if params['jobSchedule'] == 'manual' || params['jobSchedule'] == ''
          params.delete('jobSchedule')
        end
      elsif params['jobAction'] == 'clone'
        params['jobId'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobId', 'fieldLabel' => 'Backup Job', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
          @backup_jobs_interface.list({max:10000})['jobs'].collect {|backup_job|
            {'name' => backup_job['name'], 'value' => backup_job['id'], 'id' => backup_job['id']}
          }
        }, 'required' => true}], options[:options], @api_client)['jobId']
        params['jobName'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobName', 'fieldLabel' => 'Job Name', 'type' => 'text', 'required' => false, 'defaultValue' => nil}], options[:options], @api_client)['jobName']
      elsif params['jobAction'] == 'addTo'
        params['jobId'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobId', 'fieldLabel' => 'Backup Job', 'type' => 'select', 'optionSource' => lambda { |api_client, api_params| 
          @backup_jobs_interface.list({max:10000})['jobs'].collect {|backup_job|
            {'name' => backup_job['name'], 'value' => backup_job['id'], 'id' => backup_job['id']}
          }
        }, 'required' => true}], options[:options], @api_client)['jobId']
      end
    end
    payload['backup'].deep_merge!(params)
  end
  execute_api(@backups_interface, :create, [], options, 'backup') do |json_response|
    backup = json_response['backup']
    print_green_success "Added backup #{backup['name']}"
    _get(backup["id"], {}, options)
  end
end

#add_job(args) ⇒ Object



438
439
440
# File 'lib/morpheus/cli/commands/backups_command.rb', line 438

def add_job(args)
  Morpheus::Cli::BackupJobsCommand.new.add(args)
end

#connect(opts) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/morpheus/cli/commands/backups_command.rb', line 17

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @backups_interface = @api_client.backups
  @backup_jobs_interface = @api_client.backup_jobs
  @backup_results_interface = @api_client.backup_results
  @backup_restores_interface = @api_client.backup_restores
  @instances_interface = @api_client.instances
  @servers_interface = @api_client.servers
end

#execute(args) ⇒ Object



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

def execute(args)
  options = {}
  params = {}
  payload = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[backup] [options]")
    build_standard_post_options(opts, options)
    opts.footer = <<-EOT
Execute a backup to create a new backup result.
[backup] is required. This is the name or id of a backup.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  backup = find_backup_by_name_or_id(args[0])
  return 1 if backup.nil?
  parse_payload(options) do |payload|
  end
  execute_api(@backups_interface, :execute_backup, [backup['id']], options, 'backup') do |json_response|
    print_green_success "Executing backup #{backup['name']}"
    # should get the result maybe, or could even support refreshing until it is complete...
    # return _get(backup["id"], {}, options)
  end
end

#execute_job(args) ⇒ Object



450
451
452
# File 'lib/morpheus/cli/commands/backups_command.rb', line 450

def execute_job(args)
  Morpheus::Cli::BackupJobsCommand.new.execute(args)
end

#get(args) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/morpheus/cli/commands/backups_command.rb', line 62

def get(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[backup]")
    build_standard_get_options(opts, options)
    opts.footer = <<-EOT
Get details about a specific backup.
[backup] is required. This is the name or id of a backup.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  connect(options)
  parse_options(options, params)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, params, options)
  end
end

#get_job(args) ⇒ Object



434
435
436
# File 'lib/morpheus/cli/commands/backups_command.rb', line 434

def get_job(args)
  Morpheus::Cli::BackupJobsCommand.new.get(args)
end

#get_restore(args) ⇒ Object



474
475
476
# File 'lib/morpheus/cli/commands/backups_command.rb', line 474

def get_restore(args)
  Morpheus::Cli::BackupRestoresCommand.new.get(args)
end

#get_result(args) ⇒ Object



460
461
462
# File 'lib/morpheus/cli/commands/backups_command.rb', line 460

def get_result(args)
  Morpheus::Cli::BackupResultsCommand.new.get(args)
end

#handle(args) ⇒ Object



27
28
29
# File 'lib/morpheus/cli/commands/backups_command.rb', line 27

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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

def list(args)
  options = {}
  params = {}
  ref_ids = []
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search]")
    build_standard_list_options(opts, options)
    opts.footer = "List backups."
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  parse_options(options, params)
  execute_api(@backups_interface, :list, [], options, 'backups') do |json_response|
    backups = json_response['backups']
    print_h1 "Morpheus Backups", parse_list_subtitles(options), options
    if backups.empty?
      print cyan,"No backups found.",reset,"\n"
    else
      print as_pretty_table(backups, backup_list_column_definitions.upcase_keys!, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
end

#list_jobs(args) ⇒ Object

Backup Jobs



430
431
432
# File 'lib/morpheus/cli/commands/backups_command.rb', line 430

def list_jobs(args)
  Morpheus::Cli::BackupJobsCommand.new.list(args)
end

#list_restores(args) ⇒ Object

Backup Restores



470
471
472
# File 'lib/morpheus/cli/commands/backups_command.rb', line 470

def list_restores(args)
  Morpheus::Cli::BackupRestoresCommand.new.list(args)
end

#list_results(args) ⇒ Object

Backup Results



456
457
458
# File 'lib/morpheus/cli/commands/backups_command.rb', line 456

def list_results(args)
  Morpheus::Cli::BackupResultsCommand.new.list(args)
end

#remove(args) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/morpheus/cli/commands/backups_command.rb', line 268

def remove(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[backup] [options]")
    build_standard_remove_options(opts, options)
    opts.footer = <<-EOT
Delete a backup.
[backup] is required. This is the name or id of a backup.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  backup = find_backup_by_name_or_id(args[0])
  return 1 if backup.nil?
  parse_options(options, params)
  confirm!("Are you sure you want to delete the backup #{backup['name']}?", options)
  execute_api(@backups_interface, :destroy, [backup['id']], options) do |json_response|
    print_green_success "Removed backup #{backup['name']}"
  end
end

#remove_job(args) ⇒ Object



446
447
448
# File 'lib/morpheus/cli/commands/backups_command.rb', line 446

def remove_job(args)
  Morpheus::Cli::BackupJobsCommand.new.remove(args)
end

#remove_restore(args) ⇒ Object



478
479
480
# File 'lib/morpheus/cli/commands/backups_command.rb', line 478

def remove_restore(args)
  Morpheus::Cli::BackupRestoresCommand.new.remove(args)
end

#remove_result(args) ⇒ Object



464
465
466
# File 'lib/morpheus/cli/commands/backups_command.rb', line 464

def remove_result(args)
  Morpheus::Cli::BackupResultsCommand.new.remove(args)
end

#restore(args) ⇒ Object



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

def restore(args)
  options = {}
  params = {}
  payload = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[backup] [result] [options]")
    build_standard_post_options(opts, options, [:auto_confirm])
    opts.on('--result ID', String, "Backup Result ID that is being restored") do |val|
      options[:options]['backupResultId'] = val
    end
    opts.on('--restore-instance existing|new', String, "Instance being targeted for the restore, existing to restore the current instance or new to create a new instance. The current instance is targeted by default.") do |val|
      # restoreInstance=existing|new and the flag on the restore object is called 'restoreToNew'
      options[:options]['restoreInstance'] = val
    end
    opts.footer = <<-EOT
Restore a backup, replacing the existing target with the specified backup result.
[backup] is required. This is the name or id of a backup.
--result ID is required. This is the id of a backup result being restored.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, max:1)
  connect(options)
  backup = nil
  backup_result = nil
  if args[0]
    backup = find_backup_by_name_or_id(args[0])
    return 1 if backup.nil?
  else
    # Prompt for backup
    if backup.nil?
      # Backup
      available_backups = @backups_interface.list({max:10000})['backups'].collect {|it| {'name' => it['name'], 'value' => it['id']}}
      backup_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'backupId', 'fieldLabel' => 'Backup', 'type' => 'select', 'selectOptions' => available_backups, 'required' => true}], options[:options], @api_client)['backupId']
      backup = find_backup_by_name_or_id(backup_id)
      return 1 if backup.nil?
    end
  end
  # Prompt for backup result
  if backup_result.nil?
    #available_backup_results = @backup_results_interface.list({backupId: backup['id'], status: ['success', 'succeeded'], max:10000})['results'].collect {|it| {format_backup_result_option_name(it), 'value' => it['id']}}
    available_backup_results = @backup_results_interface.list({backupId: backup['id'], max:10000})['results'].select {|it| it['status'].to_s.downcase == 'succeeded' || it['status'].to_s.downcase == 'success' }.collect {|it| {'name' => format_backup_result_option_name(it), 'value' => it['id']} }
    params['backupResultId'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'backupResultId', 'fieldLabel' => 'Backup Result', 'type' => 'select', 'selectOptions' => available_backup_results, 'required' => true}], options[:options], @api_client)['backupResultId']
    backup_result = @backup_results_interface.get(params['backupResultId'].to_i)['result']
  end
  parse_payload(options, 'restore') do |payload|
    # Prompt for restore configuration
    # todo: These options should be based on backup type
    #       Look at backup_type['restoreExistingEnabled'] and backup_type['restoreNewEnabled']
    # Target Instance
    #if backup_result['instanceId']
    if backup['locationType'] == 'instance'
      instance = backup['instance']
      # could actually fetch the instance.., only need name and id right now though.
      raise_command_error "Backup instance not found" if instance.nil?
      params['restoreInstance'] = prompt_value({'fieldName' => 'restoreInstance', 'fieldLabel' => 'Restore Instance', 'type' => 'select', 'selectOptions' => [{'name' => 'Current Instance', 'value' => 'existing'}, {'name' => 'New Instance', 'value' => 'new'}], 'defaultValue' => 'existing', 'required' => true, 'description' => 'Restore the current instance or a new instance?'}, options)
      if params['restoreInstance'] == 'new'
        # new instance
        config_map = prompt_restore_instance_config(options)
        params['instanceConfig'] = config_map
      else
        # existing instance
        # confirm the instance
        keep_prompting = !options[:no_prompt]
        while keep_prompting
          instance_id = prompt_value({'fieldName' => 'instanceId', 'fieldLabel' => 'Confirm Instance ID', 'type' => 'text', 'required' => true, 'description' => "Enter the current instance ID to confirm that you wish to restore it."}, options)
          if instance_id && instance_id.to_i == instance['id']
            params['instanceId'] = instance_id.to_i
            keep_prompting = false
          elsif instance_id.to_s.downcase == instance['name'].to_s.downcase # allow matching on name too
            params['instanceId'] = instance['id']
            keep_prompting = false
          else
            print_red_alert "The value '#{instance_id}' does not match the existing instance #{instance['name']} [#{instance['id'] rescue ''}]. Please try again."
          end
        end
      end
    elsif backup['locationType'] == 'server'
      # prompt for server type backup restore
    elsif backup['locationType'] == 'storage'
      # prompt for storage type backup restore
    else
      print yellow, "Backup location type is unknown: #{backup['locationType']}",reset,"\n"
    end

    payload['restore'].deep_merge!(params)
  end

  if params['restoreInstance'] != 'new'
    if backup['instance']
      print cyan,"You have selected to restore the existing instance #{backup['instance']['name'] rescue ''} [#{backup['instance']['id'] rescue ''}] with the backup result #{format_backup_result_option_name(backup_result)} [#{backup_result['id']}]",reset,"\n"
    end
    if backup['sourceProviderId']
      print yellow,"#{bold}WARNING!#{reset}#{yellow} Restoring a backup will overwite objects when restored to an existing object store.",reset,"\n"
    else
      print yellow,"#{bold}WARNING!#{reset}#{yellow} Restoring a backup will erase all data when restored to an existing instance.",reset,"\n"
    end
  end
  confirm!("Are you sure you want to restore the backup result?", options)
  execute_api(@backup_restores_interface, :create, [], options, 'restore') do |json_response|
    print_green_success "Restoring backup result ID: #{backup_result['id']} Name: #{backup_result['backup']['name'] rescue ''} Date: (#{format_local_dt(backup_result['dateCreated'])}"
    # should get the restore maybe, or could even support refreshing until it is complete...
    # restore = json_response["restore"]
    # return _get_restore(restore["id"], {}, options)
  end
end

#update(args) ⇒ Object



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

def update(args)
  options = {}
  params = {}
  payload = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[backup] [options]")
    # opts.on('--name NAME', String, "Name") do |val|
    #   options[:options]['name'] = val
    # end
    # opts.on('--job JOB', String, "Name or ID of the Backup Job to associate this backup with") do |val|
    #   options[:options]['jobId'] = val
    # end
    # opts.on('--enabled [on|off]', String, "Can be used to disable") do |val|
    #   options[:options]['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s.empty?
    # end
    build_option_type_options(opts, options, update_backup_option_types)
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Update a backup.
[backup] is required. This is the name or id of a backup.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  backup = find_backup_by_name_or_id(args[0])
  return 1 if backup.nil?
  parse_payload(options, 'backup') do |payload|
    # do not prompt on update
    v_prompt = Morpheus::Cli::OptionTypes.no_prompt(update_backup_option_types, options[:options], @api_client)
    v_prompt.deep_compact!.booleanize! # remove empty values and convert checkbox "on" and "off" to true and false
    params.deep_merge!(v_prompt)
    payload.deep_merge!({'backup' => params})
    if payload['backup'].empty? # || options[:no_prompt]
      raise_command_error "Specify at least one option to update.\n#{optparse}"
    end
  end
  execute_api(@backups_interface, :update, [backup['id']], options, 'backup') do |json_response|
    backup = json_response['backup']
    print_green_success "Updated backup #{backup['name']}"
    return _get(backup["id"], {}, options)
  end
end

#update_job(args) ⇒ Object



442
443
444
# File 'lib/morpheus/cli/commands/backups_command.rb', line 442

def update_job(args)
  Morpheus::Cli::BackupJobsCommand.new.update(args)
end