Debian Codegraph @

ansible_collections/ibm/storage_virtualize/plugins/modules/ibm_svc_manage_migration.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2021 IBM CORPORATION
5 # Author(s): Rohit kumar <[email protected]>
6 # Shilpi Jain <[email protected]>
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12 DOCUMENTATION = '''
13 ---
14 module: ibm_svc_manage_migration
15 short_description: This module manages volume migration between clusters on IBM Storage Virtualize family systems
16 description:
17 - Ansible interface to manage the migration commands.
18 version_added: "1.6.0"
19 options:
20 type_of_migration:
21 description:
22 - Specifies the type of migration whether it is migration across pools or migration across clusters
23 choices: [across_pools, across_clusters]
24 default: across_clusters
25 type: str
26 version_added: '1.11.0'
27 new_pool:
28 description:
29 - Specifies the pool on which the volume has to be migrated.
30 - Valid only when I(type_of_migration=across_pools).
31 type: str
32 version_added: '1.11.0'
33 source_volume:
34 description:
35 - Specifies the name/UID of the existing source volume to be used in migration.
36 - Required when I(state=initiate) or I(state=cleanup) or I(type_of_migration=across_pools).
37 type: str
38 target_volume:
39 description:
40 - Specifies the name/UID of the volume to be created on the target system.
41 - Required when I(state=initiate).
42 type: str
43 clustername:
44 description:
45 - The hostname or management IP of the Storage Virtualize system.
46 type: str
47 required: true
48 remote_cluster:
49 description:
50 - Specifies the name of the remote cluster.
51 - Required when I(state=initiate).
52 type: str
53 domain:
54 description:
55 - Domain for the Storage Virtualize system.
56 - Valid when hostname is used for the parameter I(clustername).
57 type: str
58 username:
59 description:
60 - REST API username for the Storage Virtualize system.
61 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user on the local system.
62 type: str
63 remote_username:
64 description:
65 - REST API username for the partner Storage Virtualize system.
66 - The parameters I(remote_username) and I(remote_password) are required if not using I(remote_token) to authenticate a user on the partner system.
67 - Valid when C(state=initiate).
68 type: str
69 password:
70 description:
71 - REST API password for the Storage Virtualize system.
72 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user on the local system.
73 type: str
74 remote_password:
75 description:
76 - REST API password for the partner Storage Virtualize system.
77 - The parameters I(remote_username) and I(remote_password) are required if not using I(remote_token) to authenticate a user on the partner system.
78 - Valid when I(state=initiate).
79 type: str
80 relationship_name:
81 description:
82 - Name of the migration relationship. Required when I(state=initiate) or I(state=switch).
83 type: str
84 state:
85 description:
86 - Specifies the different states of the migration process when I(type_of_migration=across_clusters).
87 - C(initiate), creates a volume on remote cluster; optionally used to replicate hosts, and to create and start a migration relationship.
88 - C(switch), switches the migration relationship direction allowing write access on the target volume.
89 - C(cleanup), deletes the source volume and migration relationship after a 'switch'.
90 choices: [initiate, switch, cleanup]
91 type: str
92 token:
93 description:
94 - The authentication token to verify a user on the Storage Virtualize system.
95 - To generate a token, use the ibm_svc_auth module.
96 type: str
97 remote_token:
98 description:
99 - The authentication token to verify a user on the partner Storage Virtualize system.
100 - To generate a token, use the ibm_svc_auth module.
101 Valid when I(state=initiate).
102 type: str
103 remote_pool:
104 description:
105 - Specifies the pool on which the volume on Partner Storage Virtualize system should get created.
106 - Required when I(state=initiate).
107 type: str
108 validate_certs:
109 description:
110 - Validates certification.
111 default: false
112 type: bool
113 remote_validate_certs:
114 description:
115 - Validates certification for partner Storage Virtualize system.
116 - Valid when I(state=initiate).
117 default: false
118 type: bool
119 replicate_hosts:
120 description:
121 - Replicates the hosts mapped to a source volume on the source system, to the target system, and maps the hosts to the target volume. The
122 user can use ibm_svc_host and ibm_svc_vol_map modules to create and map hosts to the target volume for an
123 existing migration relationship.
124 - Valid when I(state=initiate).
125 default: false
126 type: bool
127 log_path:
128 description:
129 - Path of debug log file.
130 type: str
131 author:
132 - Rohit Kumar(@rohitk-github)
133 - Shilpi Jain(@Shilpi-J)
134 notes:
135 - This module supports C(check_mode).
136 - This module supports both volume migration across pools and volume migration across clusters.
137 - In case, user does not specify type_of_migration, the module shall proceed with migration across clusters by default.
138 - In case of I(type_of_migration=across_pools), the only parameters allowed are I(new_pool) and I(source_volume) along with cluster credentials.
139 '''
140
141 EXAMPLES = '''
142 - name: Create a target volume
143 Create a relationship
144 Replicate hosts from source volume to target volume
145 Start a relationship
146 ibm.storage_virtualize.ibm_svc_manage_migration:
147 source_volume: "src_vol"
148 target_volume: "target_vol"
149 clustername: "{{ source_cluster }}"
150 remote_cluster: "{{ remote_cluster }}"
151 token: "{{ source_cluster_token }}"
152 state: initiate
153 replicate_hosts: true
154 remote_token: "{{ partner_cluster_token }}"
155 relationship_name: "migrate_vol"
156 log_path: /tmp/ansible.log
157 remote_pool: "{{ remote_pool }}"
158 - name: Switch replication direction
159 ibm.storage_virtualize.ibm_svc_manage_migration:
160 relationship_name: "migrate_vol"
161 clustername: "{{ source_cluster }}"
162 token: "{{ source_cluster_token }}"
163 state: switch
164 log_path: /tmp/ansible.log
165 - name: Delete source volume and migration relationship
166 ibm.storage_virtualize.ibm_svc_manage_migration:
167 clustername: "{{ source_cluster }}"
168 state: cleanup
169 source_volume: "src_vol"
170 token: "{{ source_cluster_token }}"
171 log_path: /tmp/ansible.log
172 - name: Migration an existing vol from pool0 to pool1
173 ibm.storage_virtualize.ibm_svc_manage_migration:
174 clustername: "{{ source_cluster }}"
175 token: "{{ source_cluster_token }}"
176 log_path: /tmp/ansible.log
177 type_of_migration: across_pools
178 source_volume: vol1
179 new_pool: pool1
180 '''
181
182 RETURN = '''#'''
183
184 from traceback import format_exc
185 from ansible.module_utils.basic import AnsibleModule
186 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
187 from ansible.module_utils._text import to_native
188
189
190 class IBMSVCMigrate(object):
191 def __init__(self):
192 argument_spec = svc_argument_spec()
193
194 argument_spec.update(
195 dict(
196 type_of_migration=dict(type='str', required=False, default='across_clusters',
197 choices=['across_clusters', 'across_pools']),
198 new_pool=dict(type='str', required=False),
199 source_volume=dict(type='str', required=False),
200 target_volume=dict(type='str', required=False),
201 state=dict(type='str',
202 choices=['initiate', 'switch', 'cleanup']),
203 remote_pool=dict(type='str', required=False),
204 replicate_hosts=dict(type='bool', default=False),
205 relationship_name=dict(type='str', required=False),
206 remote_cluster=dict(type='str', required=False),
207 remote_token=dict(type='str', required=False, no_log=True),
208 remote_validate_certs=dict(type='bool', default=False),
209 remote_username=dict(type='str', required=False),
210 remote_password=dict(type='str', required=False, no_log=True)
211 )
212 )
213
214 self.module = AnsibleModule(argument_spec=argument_spec,
215 supports_check_mode=True)
216 self.existing_rel_data = ""
217 self.source_vdisk_data = ""
218 self.hosts_iscsi_flag = False
219
220 # logging setup
221 log_path = self.module.params['log_path']
222 log = get_logger(self.__class__.__name__, log_path)
223 self.log = log.info
224
225 # Required when migration across clusters
226 self.state = self.module.params['state']
227
228 # Required when migration across pools
229 self.new_pool = self.module.params['new_pool']
230
231 # Optional
232 self.type_of_migration = self.module.params['type_of_migration']
233 self.source_volume = self.module.params['source_volume']
234 self.remote_pool = self.module.params['remote_pool']
235 self.target_volume = self.module.params['target_volume']
236 self.relationship_name = self.module.params['relationship_name']
237 self.remote_username = self.module.params['remote_username']
238 self.replicate_hosts = self.module.params['replicate_hosts']
239 self.remote_password = self.module.params['remote_password']
240 self.remote_token = self.module.params['remote_token']
241 self.remote_cluster = self.module.params['remote_cluster']
242 self.remote_validate_certs = self.module.params['remote_validate_certs']
243
244 self.restapi = IBMSVCRestApi(
245 module=self.module,
246 clustername=self.module.params['clustername'],
247 domain=self.module.params['domain'],
248 username=self.module.params['username'],
249 password=self.module.params['password'],
250 validate_certs=self.module.params['validate_certs'],
251 log_path=log_path,
252 token=self.module.params['token']
253 )
254
255 def get_existing_vdisk(self):
256 self.log("Entering function get_existing_vdisk")
257 cmd = 'lsvdisk'
258 cmdargs = {}
259 cmdopts = {'bytes': True}
260 cmdargs = [self.source_volume]
261 remote_vdisk_data = ""
262 existing_vdisk_data = self.restapi.svc_obj_info(cmd, cmdopts, cmdargs)
263 if self.target_volume:
264 cmdargs = [self.target_volume]
265 remote_restapi = self.construct_remote_rest()
266 remote_vdisk_data = remote_restapi.svc_obj_info(cmd, cmdopts, cmdargs)
267 return existing_vdisk_data, remote_vdisk_data
268
269 def basic_checks(self):
270 self.log("Entering function basic_checks()")
271 valid_params = {}
272 valid_params['initiate'] = ['source_volume', 'remote_cluster', 'target_volume', 'replicate_hosts',
273 'remote_username', 'remote_password', 'relationship_name',
274 'remote_token', 'remote_pool', 'remote_validate_certs']
275 valid_params['switch'] = ['relationship_name']
276 valid_params['cleanup'] = ['source_volume']
277 param_list = set(valid_params['initiate'] + valid_params['switch'] + valid_params['cleanup'])
278
279 # Check for missing mandatory parameter
280 for param in valid_params[self.state]:
281 param_value = getattr(self, param)
282 if not param_value:
283 if self.state == "initiate":
284 if param == 'remote_validate_certs' or param == 'replicate_hosts':
285 continue
286 if (param == 'remote_username' or param == 'remote_password'):
287 if not self.remote_username or not self.remote_password:
288 if self.remote_token:
289 continue
290 else:
291 self.module.fail_json(msg="You must pass in either pre-acquired remote_token or "
292 "remote_username/remote_password to generate new token.")
293 elif param == 'remote_token':
294 if (self.remote_username and self.remote_password):
295 if not self.remote_token:
296 continue
297 self.module.fail_json(msg="Missing mandatory parameter [%s]." % param)
298
299 # Check for invalid parameters
300 for param in param_list:
301 if self.state == 'initiate':
302 if getattr(self, param):
303 if param not in valid_params['initiate']:
304 self.module.fail_json(msg="Invalid parameter [%s] for state 'initiate'" % param)
305 if self.state == 'switch':
306 if getattr(self, param):
307 if param not in valid_params['switch']:
308 self.module.fail_json(msg="Invalid parameter [%s] for state 'switch'" % param)
309 elif self.state == 'cleanup':
310 if getattr(self, param):
311 if param not in valid_params['cleanup']:
312 self.module.fail_json(msg="Invalid parameter [%s] for state 'cleanup'" % param)
313
314 def get_source_hosts(self):
315 self.log("Entering function get_source_hosts")
316 cmd = 'lsvdiskhostmap'
317 cmdargs = {}
318 cmdopts = {}
319 cmdargs = [self.source_volume]
320 sourcevolume_hosts = self.restapi.svc_obj_info(cmd, cmdopts, cmdargs)
321 return sourcevolume_hosts
322
323 def replicate_source_hosts(self, hosts_data):
324 self.log("Entering function replicate_source_hosts()")
325 merged_result = []
326 hosts_wwpn = {}
327 hosts_iscsi = {}
328 host_list = []
329
330 if self.module.check_mode:
331 self.changed = True
332 return
333
334 self.log("creating vdiskhostmaps on target system")
335
336 if isinstance(hosts_data, list):
337 for d in hosts_data:
338 merged_result.append(d)
339 elif hosts_data:
340 merged_result = [hosts_data]
341
342 for host in merged_result:
343 host_list.append(host['host_name'])
344
345 for host in host_list:
346 host_wwpn_list = []
347 host_iscsi_list = []
348 self.log("for host %s", host)
349 data = self.restapi.svc_obj_info(cmd='lshost', cmdopts=None, cmdargs=[host])
350 nodes_data = data['nodes']
351 for node in nodes_data:
352 if 'WWPN' in node.keys():
353 host_wwpn_list.append(node['WWPN'])
354 hosts_wwpn[host] = host_wwpn_list
355 elif 'iscsi_name' in node.keys():
356 host_iscsi_list.append(node['iscsi_name'])
357 hosts_iscsi[host] = host_iscsi_list
358 if hosts_wwpn or hosts_iscsi:
359 self.create_remote_hosts(hosts_wwpn, hosts_iscsi)
360
361 def create_remote_hosts(self, hosts_wwpn, hosts_iscsi):
362 self.log("Entering function create_remote_hosts()")
363
364 if self.module.check_mode:
365 self.changed = True
366 return
367 # Make command
368 remote_hosts_list = []
369 source_host_list = []
370 remote_hosts_list = self.return_remote_hosts()
371 if hosts_iscsi:
372 for host, iscsi_vals in hosts_iscsi.items():
373 source_host_list.append(host)
374 if hosts_wwpn:
375 for host, wwpn_vals in hosts_wwpn.items():
376 source_host_list.append(host)
377
378 cmd = 'mkhost'
379 for host, wwpn in hosts_wwpn.items():
380 if host not in remote_hosts_list:
381 cmdopts = {'name': host, 'force': True}
382 wwpn = ':'.join([str(elem) for elem in wwpn])
383 cmdopts['fcwwpn'] = wwpn
384 remote_restapi = self.construct_remote_rest()
385 remote_restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
386
387 for host, iscsi in hosts_iscsi.items():
388 if host not in remote_hosts_list:
389 cmdopts = {'name': host, 'force': True}
390 iscsi = ','.join([str(elem) for elem in iscsi])
391 cmdopts['iscsiname'] = iscsi
392 remote_restapi = self.construct_remote_rest()
393 remote_restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
394 if source_host_list:
395 self.map_host_vol_remote(source_host_list)
396
397 def map_host_vol_remote(self, host_list):
398 remote_restapi = self.construct_remote_rest()
399 if self.module.check_mode:
400 self.changed = True
401 return
402 for host in host_list:
403 # Run command
404 cmd = 'mkvdiskhostmap'
405 cmdopts = {'force': True}
406 cmdopts['host'] = host
407
408 cmdargs = [self.target_volume]
409 result = remote_restapi.svc_run_command(cmd, cmdopts, cmdargs)
410 self.log("create vdiskhostmap result %s", result)
411
412 if 'message' in result:
413 self.changed = True
414 self.log("create vdiskhostmap result message %s", result['message'])
415 else:
416 self.module.fail_json(msg="Failed to create vdiskhostmap.")
417
418 def vdisk_create(self, data):
419 if not self.remote_pool:
420 self.module.fail_json(msg="You must pass in "
421 "remote_pool to the module.")
422
423 if self.module.check_mode:
424 self.changed = True
425 return
426 self.log("creating vdisk '%s'", self.source_volume)
427 size = int(data[0]['capacity'])
428 # Make command
429 cmd = 'mkvolume'
430 cmdopts = {}
431 if self.remote_pool:
432 cmdopts['pool'] = self.remote_pool
433 cmdopts['name'] = self.target_volume
434 cmdopts['size'] = size
435 cmdopts['unit'] = "b"
436 self.log("creating vdisk command %s opts %s", cmd, cmdopts)
437 # Run command
438 remote_restapi = self.construct_remote_rest()
439 result = remote_restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
440 self.log("create vdisk result %s", result)
441
442 if 'message' in result:
443 self.changed = True
444 self.log("create vdisk result message %s", result['message'])
445 else:
446 self.module.fail_json(msg="Failed to create volume [%s]" % self.source_volume)
447
448 def verify_remote_volume_mapping(self):
449 self.log("Entering function verify_remote_volume_mapping")
450 cmd = 'lsvdiskhostmap'
451 cmdargs = {}
452 cmdopts = {}
453 cmdargs = [self.target_volume]
454 remote_hostmap_data = ""
455 remote_restapi = self.construct_remote_rest()
456 remote_hostmap_data = remote_restapi.svc_obj_info(cmd, cmdopts, cmdargs)
457 if remote_hostmap_data:
458 self.module.fail_json(msg="The target volume has hostmappings, Migration relationship cannot be created.")
459
460 def return_remote_hosts(self):
461 self.log("Entering function return_remote_hosts")
462 cmd = 'lshost'
463 remote_hosts = []
464 cmdopts = {}
465 cmdargs = None
466 remote_hosts_data = []
467 remote_restapi = self.construct_remote_rest()
468 remote_hosts_data = remote_restapi.svc_obj_info(cmd, cmdopts, cmdargs)
469 self.log(len(remote_hosts_data))
470 for host in remote_hosts_data:
471 remote_hosts.append(host['name'])
472 return remote_hosts
473
474 def verify_target(self):
475 self.log("Entering function verify_target()")
476 source_data, target_data = self.get_existing_vdisk()
477 if source_data:
478 if source_data[0]['RC_name']:
479 self.module.fail_json(msg="Source Volume [%s] is already in a relationship." % self.source_volume)
480 if target_data:
481 if target_data[0]['RC_name']:
482 self.module.fail_json(msg="Target Volume [%s] is already in a relationship." % self.target_volume)
483 if target_data[0]['mdisk_grp_name'] != self.remote_pool:
484 self.module.fail_json(msg="Target Volume [%s] exists on a different pool." % self.target_volume)
485 if not source_data:
486 self.module.fail_json(msg="Source Volume [%s] does not exist." % self.source_volume)
487 elif source_data and target_data:
488 source_size = int(source_data[0]['capacity'])
489 remote_size = int(target_data[0]['capacity'])
490 if source_size != remote_size:
491 self.module.fail_json(msg="Remote Volume size is different than that of source volume.")
492 else:
493 self.log("Target volume already exists, verifying volume mappings now..")
494 self.verify_remote_volume_mapping()
495 elif source_data and not target_data:
496 self.vdisk_create(source_data)
497 self.log("Target volume successfully created")
498 self.changed = True
499
500 def discover_partner_system(self):
501 cmd = 'lspartnership'
502 cmdopts = {}
503 cmdargs = [self.remote_cluster]
504 partnership_data = self.restapi.svc_obj_info(cmd, cmdopts, cmdargs)
505 if partnership_data:
506 system_location = partnership_data['location']
507 if system_location == 'local':
508 self.module.fail_json(msg="The relationship could not be created as migration relationships are only allowed to be created to a remote system.")
509 self.partnership_exists = True
510 remote_socket = partnership_data['console_IP']
511 return remote_socket.split(':')[0]
512 else:
513 msg = "The partnership with remote cluster [%s] does not exist." % self.remote_cluster
514 self.module.fail_json(msg=msg)
515
516 def construct_remote_rest(self):
517 remote_ip = self.discover_partner_system()
518 self.remote_restapi = IBMSVCRestApi(
519 module=self.module,
520 domain='',
521 clustername=remote_ip,
522 username=self.module.params['remote_username'],
523 password=self.module.params['remote_password'],
524 validate_certs=self.module.params['remote_validate_certs'],
525 log_path=self.module.params['log_path'],
526 token=self.module.params['remote_token']
527 )
528 return self.remote_restapi
529
530 def create_relationship(self):
531 if self.module.check_mode:
532 self.changed = True
533 return
534 self.log("Creating remote copy '%s'", self.relationship_name)
535
536 # Make command
537 cmd = 'mkrcrelationship'
538 cmdopts = {}
539 if self.remote_cluster:
540 cmdopts['cluster'] = self.remote_cluster
541 if self.source_volume:
542 cmdopts['master'] = self.source_volume
543 cmdopts['aux'] = self.target_volume
544 cmdopts['name'] = self.relationship_name
545 cmdopts['migration'] = True
546
547 # Run command
548 self.log("Command %s opts %s", cmd, cmdopts)
549 if not self.existing_rel_data:
550 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
551 self.log("create remote copy result %s", result)
552
553 if 'message' in result:
554 self.changed = True
555 self.log("Succeeded to create remote copy result message %s", result['message'])
556 else:
557 msg = "Failed to create migration relationship [%s]" % self.relationship_name
558 self.module.fail_json(msg=msg)
559
560 def source_vol_relationship(self, volume):
561 """
562 Check if the source volume is associated to any migration relationship.
563 Returns:
564 None if no matching instances
565 """
566
567 source_vdisk_data, target_vdisk_data = self.get_existing_vdisk()
568 if not source_vdisk_data:
569 msg = "Source volume [%s] does not exist" % self.source_volume
570 self.module.exit_json(msg=msg)
571 self.log('Trying to get the remote copy relationship')
572 relationship_name = source_vdisk_data[0]['RC_name']
573 if not relationship_name:
574 self.module.fail_json(msg="Volume [%s] cannot be deleted. No Migration relationship is configured with the volume." % self.source_volume)
575 existing_rel_data = self.restapi.svc_obj_info(cmd='lsrcrelationship', cmdopts=None, cmdargs=[relationship_name])
576 if existing_rel_data['copy_type'] != 'migration':
577 self.module.fail_json(msg="Volume [%s] cannot be deleted. No Migration relationship is configured with the volume." % self.source_volume)
578
579 def existing_rc(self):
580 """
581 Find the relationships such as Metro Mirror, Global Mirror relationships visible to the system.
582
583 Returns:
584 None if no matching instances or a list including all the matching
585 instances
586 """
587 self.log('Trying to get the remote copy relationship %s', self.relationship_name)
588 self.existing_rel_data = self.restapi.svc_obj_info(cmd='lsrcrelationship', cmdopts=None, cmdargs=[self.relationship_name])
589 return self.existing_rel_data
590
591 def verify_existing_rel(self, rel_data):
592 if self.existing_rel_data:
593 master_volume, aux_volume = rel_data['master_vdisk_name'], rel_data['aux_vdisk_name']
594 primary, remotecluster, rel_type = rel_data['primary'], rel_data['aux_cluster_name'], rel_data['copy_type']
595 if rel_type != 'migration':
596 self.module.fail_json(msg="Remote Copy relationship [%s] already exists and is not a migration relationship" % self.relationship_name)
597 if self.source_volume != master_volume:
598 self.module.fail_json(msg="Migration relationship [%s] already exists with a different source volume" % self.relationship_name)
599 if self.target_volume != aux_volume:
600 self.module.fail_json(msg="Migration relationship [%s] already exists with a different target volume" % self.relationship_name)
601 if primary != 'master':
602 self.module.fail_json(msg="Migration relationship [%s] replication direction is incorrect" % self.relationship_name)
603 if remotecluster != self.remote_cluster:
604 self.module.fail_json(msg="Migration relationship [%s] is configured with a different partner system" % self.relationship_name)
605
606 def start_relationship(self):
607 """Start the migration relationship copy process."""
608 cmdopts = {}
609 if self.module.check_mode:
610 self.changed = True
611 return
612 result = self.restapi.svc_run_command(cmd='startrcrelationship', cmdopts=cmdopts, cmdargs=[self.relationship_name])
613
614 if result == '':
615 self.changed = True
616 self.log("succeeded to start the remote copy %s", self.relationship_name)
617 elif 'message' in result:
618 self.changed = True
619 self.log("start the rcrelationship %s with result message %s", self.relationship_name, result['message'])
620 else:
621 msg = "Failed to start the rcrelationship [%s]" % self.relationship_name
622 self.module.fail_json(msg=msg)
623
624 def switch(self):
625 """Switch the replication direction."""
626 cmdopts = {}
627 cmdopts['primary'] = 'aux'
628 if self.existing_rel_data:
629 rel_type = self.existing_rel_data['copy_type']
630 if rel_type != 'migration':
631 self.module.fail_json(msg="Remote Copy relationship [%s] is not a migration relationship." % self.relationship_name)
632 if self.module.check_mode:
633 self.changed = True
634 return
635 result = self.restapi.svc_run_command(cmd='switchrcrelationship', cmdopts=cmdopts, cmdargs=[self.relationship_name])
636 self.log("switch the rcrelationship %s with result %s", self.relationship_name, result)
637 if result == '':
638 self.changed = True
639 self.log("succeeded to switch the remote copy %s", self.relationship_name)
640 elif 'message' in result:
641 self.changed = True
642 self.log("switch the rcrelationship %s with result message %s", self.relationship_name, result['message'])
643 else:
644 msg = "Failed to switch the rcrelationship [%s]" % self.relationship_name
645 self.module.fail_json(msg=msg)
646
647 def delete(self):
648 """Use the rmvolume command to delete the source volume and the existing migration relationship."""
649 if self.module.check_mode:
650 self.changed = True
651 return
652 cmd = 'rmvolume'
653 cmdopts = {}
654 cmdopts['removehostmappings'] = True
655 cmdargs = [self.source_volume]
656 if self.module.check_mode:
657 self.changed = True
658 return
659 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
660
661 # Any error will have been raised in svc_run_command
662 # Command does not output anything when successful.
663 if result == '':
664 self.changed = True
665 self.log("succeeded to delete the source volume %s and associated host mappings and migration relationship", self.source_volume)
666 self.changed = True
667 elif 'message' in result:
668 self.changed = True
669 self.log("delete the source volume %s with result message %s",
670 self.source_volume, result['message'])
671 else:
672 self.module.fail_json(
673 msg="Failed to delete the volume [%s]" % self.source_volume)
674
675 def basic_checks_migrate_vdisk(self):
676 self.log("Entering function basic_checks_migrate_vdisk()")
677 invalid_params = {}
678
679 # Check for missing parameters
680 missing = [item[0] for item in [('new_pool', self.new_pool), ('source_volume', self.source_volume)] if not item[1]]
681 if missing:
682 self.module.fail_json(
683 msg='Missing mandatory parameter: [{0}] for migration across pools'.format(', '.join(missing))
684 )
685
686 invalid_params['across_pools'] = ['state', 'relationship_name', 'remote_cluster', 'remote_username',
687 'remote_password', 'remote_token', 'remote_pool', 'remote_validate_certs',
688 'replicate_hosts']
689 param_list = set(invalid_params['across_pools'])
690
691 # Check for invalid parameters
692 for param in param_list:
693 if self.type_of_migration == 'across_pools':
694 if getattr(self, param):
695 if param in invalid_params['across_pools']:
696 self.module.fail_json(msg="Invalid parameter [%s] for volume migration 'across_pools'" % param)
697
698 def migrate_pools(self):
699 self.basic_checks_migrate_vdisk()
700
701 if self.module.check_mode:
702 self.changed = True
703 return
704
705 source_data, target_data = self.get_existing_vdisk()
706 if not source_data:
707 msg = "Source volume [%s] does not exist" % self.source_volume
708 self.module.fail_json(msg=msg)
709 elif source_data[0]['mdisk_grp_name'] != self.new_pool:
710 cmd = 'migratevdisk'
711 cmdopts = {}
712 cmdopts['mdiskgrp'] = self.new_pool
713 cmdopts['vdisk'] = self.source_volume
714 self.log("Command %s opts %s", cmd, cmdopts)
715 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
716
717 if result == '':
718 self.changed = True
719 else:
720 self.module.fail_json(msg="Failed to migrate volume in different pool.")
721 else:
722 msg = "No modifications done. New pool [%s] is same" % self.new_pool
723 self.module.exit_json(msg=msg, changed=False)
724
725 def apply(self):
726 changed = False
727 msg = None
728 if self.type_of_migration == 'across_pools':
729 self.migrate_pools()
730 msg = "Source Volume migrated successfully to new pool [%s]." % self.new_pool
731 changed = True
732 else:
733 self.basic_checks()
734 if self.state == 'initiate' or self.state == 'switch':
735 existing_rc_data = self.existing_rc()
736 if not existing_rc_data:
737 if self.state == 'initiate':
738 self.verify_target()
739 self.create_relationship()
740 if self.replicate_hosts:
741 hosts_data = self.get_source_hosts()
742 self.replicate_source_hosts(hosts_data)
743 self.start_relationship()
744 changed = True
745 msg = "Migration Relationship [%s] has been started." % self.relationship_name
746 elif self.state == 'switch':
747 msg = "Relationship [%s] does not exist." % self.relationship_name
748 changed = False
749 self.module.fail_json(msg=msg)
750 elif self.state == 'initiate':
751 self.verify_existing_rel(existing_rc_data)
752 self.start_relationship()
753 msg = "Migration Relationship [%s] has been started." % self.relationship_name
754 changed = True
755 elif self.state == 'switch':
756 self.switch()
757 msg = "Migration Relationship [%s] successfully switched." % self.relationship_name
758 changed = True
759 elif self.state == 'cleanup':
760 self.source_vol_relationship(self.source_volume)
761 self.delete()
762 msg = "Source Volume [%s] deleted successfully." % self.source_volume
763 changed = True
764 if self.module.check_mode:
765 msg = "skipping changes due to check mode."
766 self.module.exit_json(msg=msg, changed=changed)
767
768
769 def main():
770 v = IBMSVCMigrate()
771 try:
772 v.apply()
773 except Exception as e:
774 v.log("Exception in apply(): \n%s", format_exc())
775 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
776
777
778 if __name__ == '__main__':
779 main()