Class: Morpheus::Cli::Migrations

Inherits:
Object
  • Object
show all
Includes:
CliCommand, ProcessesHelper, RestCommand
Defined in:
lib/morpheus/cli/commands/migrations.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProcessesHelper

#api_client, #format_process_duration, #format_process_error, #format_process_output, #format_process_status, #handle_history_command, included, #print_process_details, #print_process_event_details, #processes_interface, #wait_for_process_execution

Methods included from RestCommand

#_get, #_get_type, #connect, #get, #get_type, #handle, included, #list, #list_types, #registered_interfaces, #remove, #render_response_for_get_type, #rest_arg, #rest_column_definitions, #rest_find_by_name_or_id, #rest_has_name, #rest_has_type, #rest_interface, #rest_interface_name, #rest_key, #rest_label, #rest_label_plural, #rest_list_column_definitions, #rest_list_key, #rest_name, #rest_object_key, #rest_option_context_map, #rest_perms_config, #rest_type_arg, #rest_type_column_definitions, #rest_type_find_by_name_or_id, #rest_type_interface, #rest_type_interface_name, #rest_type_key, #rest_type_label, #rest_type_label_plural, #rest_type_list_column_definitions, #rest_type_list_key, #rest_type_name, #rest_type_object_key

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

#add(args) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/morpheus/cli/commands/migrations.rb', line 84

def add(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    build_option_type_options(opts, options, add_migration_option_types)
    build_standard_add_options(opts, options)
    opts.footer = "Create a new migration plan.\n"
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:0, max:1)
  options[:options]['name'] = args[0] if args[0]
  connect(options)
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({rest_object_key => parse_passed_options(options)})
  else
    params.deep_merge!(parse_passed_options(options))
    # prompt for option types
    # skip config if using interactive prompt
    add_option_types = add_migration_option_types
    # handle some option types in a special way
    servers_option_type = add_option_types.find {|it| it['fieldName'] == 'servers' } # || {'switch' => 'servers', 'fieldName' => 'servers', 'fieldLabel' => 'Virtual Machines', 'type' => 'multiSelect', 'optionSource' => 'searchServers', 'required' => true, 'description' => 'Virtual Machines to be migrated, comma separated list of server names or IDs.'}
    add_option_types.reject! {|it| it['fieldName'] == 'servers' }
    # prompt
    v_prompt = Morpheus::Cli::OptionTypes.prompt(add_option_types, options[:options], @api_client, options[:params])
    params.deep_merge!(v_prompt)
    # convert checkbox "on" and "off" to true and false
    params.booleanize!

    # prompt for servers
    server_ids = nil
    if params['sourceServerIds']
      server_ids = parse_id_list(params.delete('sourceServerIds'))
    elsif params['servers']
      server_ids = parse_id_list(params.delete('servers'))
    end
    
    if server_ids
      # lookup each value as an id or name and collect id
      # server_ids = server_ids.collect {|it| find_server_by_name_or_id(it)}.compact.collect {|it| it['id']}
      # available_servers = @api_client.options.options_for_source("searchServers", {'cloudId' => params['sourceCloudId'], 'max' => 1000})['data']
      available_servers = @api_client.migrations.source_servers({'sourceCloudId' => params['sourceCloudId'], 'max' => 5000})['sourceServers']
      bad_ids = []
      server_ids = server_ids.collect {|server_id| 
        found_option = available_servers.find {|it| it['id'].to_s == server_id.to_s || it['name'] == server_id.to_s }
        if found_option
          found_option['value'] || found_option['id']
        else
          bad_ids << server_id
        end
      }
      if bad_ids.size > 0
        raise_command_error "No such server found for: #{bad_ids.join(', ')}"
      end
    else
      # prompt for servers
      # servers_option_type = {'fieldName' => 'servers', 'fieldLabel' => 'Virtual Machines', 'type' => 'multiSelect', 'optionSource' => 'searchServers', 'description' => 'Select virtual machine servers to be migrated.', 'required' => true}
      api_params = {'cloudId' => params['sourceCloudId']}
      # server_ids = Morpheus::Cli::OptionTypes.prompt([servers_option_type], options[:options], @api_client, {'cloudId' => params['sourceCloudId'], 'max' => 1000})['servers']
      server_ids = Morpheus::Cli::OptionTypes.prompt([servers_option_type], options[:options], @api_client, {'sourceCloudId' => params['sourceCloudId'], 'max' => 5000})['servers']
      # todo: Add prompt for Add more servers?
      # while self.confirm("Add more #{servers_option_type['fieldLabel']}?", {:default => false}) do
      #   more_ids = Morpheus::Cli::OptionTypes.prompt([servers_option_type.merge({'required' => false})], {}, @api_client, api_params)['servers']
      #   server_ids += more_ids
      # end
    end
    server_ids.uniq!
    params['sourceServerIds'] = server_ids

    # prompt for datastores
    datastore_mappings = []
    source_datastores = @api_client.migrations.source_storage({'sourceCloudId' => params['sourceCloudId'], 'sourceServerIds' => params['sourceServerIds'].join(",")})['sourceStorage']
    source_datastores.each do |datastore|
      target_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => "datastore.#{datastore['id']}", 'fieldLabel' => "Datastore #{datastore['name']}", 'type' => 'select', 'required' => true, 'defaultFirstOption' => true, 'description' => "Datastore destination for datastore #{datastore['name']} [#{datastore['id']}]", 'optionSource' => lambda {|api_client, api_params| 
        api_client.migrations.target_storage(api_params)['targetStorage'].collect {|it| {'name' => it['name'], 'value' => it['id']} }
      } }], options[:options], @api_client, {'targetCloudId' => params['targetCloudId'], 'targetPoolId' => params['targetPoolId']})["datastore"]["#{datastore['id']}"]
      datastore_mappings << {'sourceDatastore' => {'id' => datastore['id']}, 'destinationDatastore' => {'id' => target_id}}
    end
    params['datastores'] = datastore_mappings
    params.delete('datastore') # remove options passed in as -O datastore.id=

    # prompt for networks
    network_mappings = []
    source_networks = @api_client.migrations.source_networks({'sourceCloudId' => params['sourceCloudId'], 'sourceServerIds' => params['sourceServerIds'].join(",")})['sourceNetworks']
    source_networks.each do |network|
      target_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => "network.#{network['id']}", 'fieldLabel' => "Network #{network['name']}", 'type' => 'select', 'required' => true, 'defaultFirstOption' => true, 'description' => "Network destination for network #{network['name']} [#{network['id']}]", 'optionSource' => lambda {|api_client, api_params| 
        api_client.migrations.target_networks(api_params)['targetNetworks'].collect {|it| {'name' => it['name'], 'value' => it['id']} }
      } }], options[:options], @api_client, {'targetCloudId' => params['targetCloudId'], 'targetPoolId' => params['targetPoolId']})["network"]["#{network['id']}"]
      network_mappings << {'sourceNetwork' => {'id' => network['id']}, 'destinationNetwork' => {'id' => target_id}}
    end
    params['networks'] = network_mappings
    params.delete('network') # remove options passed in as -O network.id=

    payload.deep_merge!({rest_object_key => params})
  end
  @migrations_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @migrations_interface.dry.create(payload)
    return 0, nil
  end
  json_response = @migrations_interface.create(payload)
  migration = json_response[rest_object_key]
  render_response(json_response, options, rest_object_key) do
    print_green_success "Added migration #{migration['name']}"
    return _get(migration["id"], {}, options)
  end
  return 0, nil
end

#history(args) ⇒ Object



73
74
75
76
77
78
79
80
81
82
# File 'lib/morpheus/cli/commands/migrations.rb', line 73

def history(args)
  handle_history_command(args, "migration", "Migration", "migrationPlan") do |id|
    record = rest_find_by_name_or_id(id)
    if record.nil?
      # raise_command_error "#{rest_name} not found for '#{id}'"
      return 1, "#{rest_name} not found for '#{id}'"
    end
    record
  end 
end

#render_response_for_get(json_response, options) ⇒ Object

set_rest_has_type false set_rest_type :migration_types



18
19
20
21
22
23
24
25
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
# File 'lib/morpheus/cli/commands/migrations.rb', line 18

def render_response_for_get(json_response, options)
  render_response(json_response, options, rest_object_key) do
    record = json_response[rest_object_key]
    print_h1 rest_label, [], options
    print cyan
    print_description_list(rest_column_definitions(options), record, options)
    # show Migration Configuration
    # config = record['config']
    # if config && !config.empty?
    #   print_h2 "Virtual Machines"
    #   print_description_list(config.keys, config)
    # end
    # Datastores
    datastores = record['datastores']
    print_h2 "Datastores", options
    if datastores && datastores.size > 0
      columns = [
        {"Source" => lambda {|it| it['sourceDatastore'] ? "#{it['sourceDatastore']['name']} [#{it['sourceDatastore']['id']}]" : "" } },
        {"Destination" => lambda {|it| it['destinationDatastore'] ? "#{it['destinationDatastore']['name']} [#{it['destinationDatastore']['id']}]" : "" } },
      ]
      print as_pretty_table(datastores, columns, options)
    else
      print cyan,"No datatores in migration",reset,"\n"
    end
    # Networks
    print_h2 "Networks", options
    networks = record['networks']
    if networks && networks.size > 0
      columns = [
        {"Source" => lambda {|it| it['sourceNetwork'] ? "#{it['sourceNetwork']['name']} [#{it['sourceNetwork']['id']}]" : "" } },
        {"Destination" => lambda {|it| it['destinationNetwork'] ? "#{it['destinationNetwork']['name']} [#{it['destinationNetwork']['id']}]" : "" } },
      ]
      print as_pretty_table(networks, columns, options)
    else
      print cyan,"No networks found in migration",reset,"\n"
    end
    # Virtual Machines
    print_h2 "Virtual Machines", options
    servers = record['servers']
    if servers && servers.size > 0
      columns = [
        # {"ID" => lambda {|it| it['sourceServer'] ? it['sourceServer']['id'] : "" } },
        # {"Name" => lambda {|it| it['sourceServer'] ? it['sourceServer']['name'] : "" } },
        {"Source" => lambda {|it| it['sourceServer'] ? "#{it['sourceServer']['name']} [#{it['sourceServer']['id']}]" : "" } },
        {"Destination" => lambda {|it| it['destinationServer'] ? "#{it['destinationServer']['name']} [#{it['destinationServer']['id']}]" : "" } },
        {"Status" => lambda {|it| format_migration_server_status(it) } }
      ]
      print as_pretty_table(servers, columns, options)
    else
      print cyan,"No virtual machines found in migration",reset,"\n"
    end
    print reset,"\n"
  end
end

#run(args) ⇒ Object



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

def run(args)
  options = {}
  params = {}
  payload = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[migration]")
    build_standard_post_options(opts, options, [:auto_confirm])
    opts.footer = "Runs a migration plan to transition it from pending to scheduled for execution.\n[migration] is required. This is the name or id of a migration.\n"
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  migration = find_migration_by_name_or_id(args[0])
  return 1 if migration.nil?
  parse_payload(options) do |payload|
  end
  servers = migration['servers']
  print cyan, "The following #{servers.size == 1 ? 'server' : servers.size.to_s + ' servers'} will be migrated:", "\n"
  puts ""
  print as_pretty_table(servers, {"Virtual Machine" => lambda {|it| it['sourceServer'] ? "#{it['sourceServer']['name']} [#{it['sourceServer']['id']}]" : "" } }, options)
  puts ""
  confirm!("Are you sure you want to execute the migration plan?", options)
  execute_api(@migrations_interface, :run, [migration['id']], options, 'migration') do |json_response|
    print_green_success "Running migration #{migration['name']}"
  end
end

#update(args) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/morpheus/cli/commands/migrations.rb', line 197

def update(args)
  options = {}
  params = {}
  payload = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[migration] [options]")
    build_option_type_options(opts, options, update_migration_option_types)
    build_standard_update_options(opts, options)
    opts.footer = "Update a migration plan.\n[migration] is required. This is the name or id of a migration plan.\n"
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  migration = find_migration_by_name_or_id(args[0])
  return 1 if migration.nil?
  payload = {}
  if options[:payload]
    payload = options[:payload]
    payload.deep_merge!({rest_object_key => parse_passed_options(options)})
  else
    params.deep_merge!(parse_passed_options(options))
    # prompt for option types
    # skip config if using interactive prompt
    update_option_types = update_migration_option_types
    # handle some option types in a special way
    servers_option_type = update_option_types.find {|it| it['fieldName'] == 'servers' } # || {'switch' => 'servers', 'fieldName' => 'servers', 'fieldLabel' => 'Virtual Machines', 'type' => 'multiSelect', 'optionSource' => 'searchServers', 'required' => true, 'description' => 'Virtual Machines to be migrated, comma separated list of server names or IDs.'}
    update_option_types.reject! {|it| it['fieldName'] == 'servers' }
    # prompt (edit uses no_prompt)
    # need these parameters for prompting..
    default_api_params = {}
    default_api_params['sourceCloudId'] = migration['sourceCloud']['id'] if migration['sourceCloud']
    default_api_params['targetCloudId'] = migration['targetCloud']['id'] if migration['targetCloud']
    default_api_params['targetGroupId'] = migration['targetGroup']['id'] if migration['targetGroup']
    default_api_params['targetPoolId'] = "pool-" + migration['targetPool']['id'].to_s if migration['targetPool']
    options[:params] = default_api_params.merge(options[:options])
    v_prompt = Morpheus::Cli::OptionTypes.no_prompt(update_option_types, options[:options], @api_client, options[:params])
    params.deep_merge!(v_prompt)
    # convert checkbox "on" and "off" to true and false
    params.booleanize!

    # prompt for servers
    server_ids = nil
    if params['sourceServerIds']
      server_ids = parse_id_list(params.delete('sourceServerIds'))
    elsif params['servers']
      server_ids = parse_id_list(params.delete('servers'))
    end

    if server_ids
      # lookup each value as an id or name and collect id
      # server_ids = server_ids.collect {|it| find_server_by_name_or_id(it)}.compact.collect {|it| it['id']}
      # available_servers = @api_client.options.options_for_source("searchServers", {'cloudId' => params['sourceCloudId'], 'max' => 1000})['data']
      available_servers = @api_client.migrations.source_servers({'sourceCloudId' => params['sourceCloudId'], 'max' => 5000})['sourceServers']
      bad_ids = []
      server_ids = server_ids.collect {|server_id| 
        found_option = available_servers.find {|it| it['id'].to_s == server_id.to_s || it['name'] == server_id.to_s }
        if found_option
          found_option['value'] || found_option['id']
        else
          bad_ids << server_id
        end
      }
      if bad_ids.size > 0
        raise_command_error "No such server found for: #{bad_ids.join(', ')}"
      end
      server_ids.uniq!
      params['sourceServerIds'] = server_ids
    else
      # no prompt for update
    end
    
    source_server_ids = params['sourceServerIds'] || migration['servers'].collect {|it| it['sourceServer'] ? it['sourceServer']['id'] : nil }.compact
    source_cloud_id = params['sourceCloudId'] || (migration['sourceCloud'] ? migration['sourceCloud']['id'] : nil)
    target_cloud_id = params['targetCloudId'] || (migration['targetCloud'] ? migration['targetCloud']['id'] : nil)
    target_pool_id = params['targetPoolId'] || (migration['targetPool'] ? migration['targetPool']['id'] : nil)

    # prompt for datastores
    if options[:options]['datastore'].is_a?(Hash)
      datastore_mappings = []
      source_datastores = @api_client.migrations.source_storage({'sourceCloudId' => source_cloud_id, 'sourceServerIds' => source_server_ids.join(",")})['sourceStorage']
      source_datastores.each do |datastore|
        found_mapping = migration['datastores'].find {|it| it['sourceDatastore'] && it['sourceDatastore']['id'] == datastore['id'] }
        default_value = found_mapping && found_mapping['destinationDatastore'] ? found_mapping['destinationDatastore']['name'] : nil
        target_id = Morpheus::Cli::OptionTypes.no_prompt([{'fieldName' => "datastore.#{datastore['id']}", 'fieldLabel' => "Datastore #{datastore['name']}", 'type' => 'select', 'description' => "Datastore destination for datastore #{datastore['name']} [#{datastore['id']}]", 'defaultValue' => default_value, 'optionSource' => lambda {|api_client, api_params| 
          api_client.migrations.target_storage(api_params)['targetStorage'].collect {|it| {'name' => it['name'], 'value' => it['id']} }
        } }], options[:options], @api_client, {'targetCloudId' => target_cloud_id, 'targetPoolId' => target_pool_id})["datastore"]["#{datastore['id']}"]
        datastore_mappings << {'sourceDatastore' => {'id' => datastore['id']}, 'destinationDatastore' => {'id' => target_id}}
      end
      params['datastores'] = datastore_mappings
      params.delete('datastore') # remove options passed in as -O datastore.id=
    end

    # prompt for networks
    if options[:options]['network'].is_a?(Hash)
      network_mappings = []
      source_networks = @api_client.migrations.source_networks({'sourceCloudId' => source_cloud_id, 'sourceServerIds' => source_server_ids.join(",")})['sourceNetworks']
      source_networks.each do |network|
        found_mapping = migration['networks'].find {|it| it['sourceNetwork'] && it['sourceNetwork']['id'] == network['id'] }
        default_value = found_mapping && found_mapping['destinationNetwork'] ? found_mapping['destinationNetwork']['name'] : nil
        target_id = Morpheus::Cli::OptionTypes.no_prompt([{'fieldName' => "network.#{network['id']}", 'fieldLabel' => "Network #{network['name']}", 'type' => 'select', 'description' => "Network destination for network #{network['name']} [#{network['id']}]", 'defaultValue' => default_value, 'optionSource' => lambda {|api_client, api_params| 
          api_client.migrations.target_networks(api_params)['targetNetworks'].collect {|it| {'name' => it['name'], 'value' => it['id']} }
        } }], options[:options], @api_client, {'targetCloudId' => target_cloud_id, 'targetPoolId' => target_pool_id})["network"]["#{network['id']}"]
        network_mappings << {'sourceNetwork' => {'id' => network['id']}, 'destinationNetwork' => {'id' => target_id}}
      end
      params['networks'] = network_mappings
      params.delete('network') # remove options passed in as -O network.id=
    end

    if params.empty? # || options[:no_prompt]
      raise_command_error "Specify at least one option to update.\n#{optparse}"
    end
    payload.deep_merge!({rest_object_key => params})      
  end
  @migrations_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @migrations_interface.dry.update(migration['id'], payload)
    return
  end
  json_response = @migrations_interface.update(migration['id'], payload)
  migration = json_response[rest_object_key]
  render_response(json_response, options, rest_object_key) do
    print_green_success "Updated migration #{migration['name']}"
    return _get(migration["id"], {}, options)
  end
  return 0, nil
end