Debian Codegraph @

ansible_collections/dellemc/powerflex/plugins/modules/sdt.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # Copyright: (c) 2024, Dell Technologies
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """ Ansible module for managing SDT on Dell Technologies PowerFlex"""
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 DOCUMENTATION = r"""
13 module: sdt
14 version_added: '2.6.0'
15 short_description: Manage SDT (also called NVMe Target) on Dell PowerFlex
16 description:
17 - Managing SDT (also called NVMe Target) on PowerFlex storage system includes
18 creating new SDT, getting details of SDT, managing IP or role of SDT,
19 modifying attributes of SDT, and deleting SDT.
20 - Support only for Powerflex 4.5 versions and above.
21 author:
22 - Yuhao Liu (@RayLiu7) <[email protected]>
23 extends_documentation_fragment:
24 - dellemc.powerflex.powerflex
25 options:
26 discovery_port:
27 description:
28 - Discovery port of the SDT.
29 type: int
30 maintenance_mode:
31 description:
32 - Maintenance mode state of the SDT.
33 choices: ['active', 'inactive']
34 type: str
35 nvme_port:
36 description:
37 - NVMe port of the SDT.
38 type: int
39 protection_domain_name:
40 description:
41 - The name of the protection domain.
42 type: str
43 sdt_ip_list:
44 description:
45 - Dictionary of IPs and their roles for the SDT.
46 - At least one IP-role is mandatory while creating a SDT.
47 - IP-roles can be updated as well.
48 type: list
49 elements: dict
50 suboptions:
51 ip:
52 description:
53 - IP address of the SDT.
54 type: str
55 required: true
56 role:
57 description:
58 - Role assigned to the SDT IP address.
59 choices: ['StorageOnly', 'HostOnly', 'StorageAndHost']
60 type: str
61 required: true
62 sdt_name:
63 description:
64 - The name of the SDT.
65 - Mandatory for all operations.
66 - It is unique across the PowerFlex array.
67 required: true
68 type: str
69 sdt_new_name:
70 description:
71 - SDT new name, can only be used for renaming the SDT.
72 - Only used for updates. Ignored during creation.
73 type: str
74 state:
75 description:
76 - State of the SDT.
77 choices: ['present', 'absent']
78 default: present
79 type: str
80 storage_port:
81 description:
82 - Storage port of the SDT.
83 type: int
84 attributes:
85 check_mode:
86 description: Runs task to validate without performing action on the target
87 machine.
88 support: full
89 diff_mode:
90 description: Runs the task to report the changes made or to be made.
91 support: full
92 notes:
93 - IP addresses, and IP address roles must be configured for each SDT.
94 - You can assign both storage and host roles to the same target IP addresses.
95 - Alternatively, assign the storage role to one target IP address, and add
96 another target IP address for the host role.
97 - Both roles must be configured on each NVMe target.
98 """
99
100 EXAMPLES = r"""
101 - name: Create SDT
102 dellemc.powerflex.sdt:
103 hostname: "{{ hostname }}"
104 username: "{{ username }}"
105 password: "{{ password }}"
106 validate_certs: "{{ validate_certs }}"
107 sdt_name: "sdt_example"
108 sdt_ip_list:
109 - ip: "172.169.xx.xx"
110 role: "StorageAndHost"
111 - ip: "172.169.yy.yy"
112 role: "StorageAndHost"
113 protection_domain_name: "PD1"
114 storage_port: 12200
115 nvme_port: 4420
116 discovery_port: 8009
117 state: "present"
118
119 - name: Rename SDT
120 dellemc.powerflex.sdt:
121 hostname: "{{ hostname }}"
122 username: "{{ username }}"
123 password: "{{ password }}"
124 validate_certs: "{{ validate_certs }}"
125 sdt_name: "sdt_example"
126 sdt_new_name: "sdt_new_example"
127 state: "present"
128
129 - name: Modify SDT port
130 dellemc.powerflex.sdt:
131 hostname: "{{ hostname }}"
132 username: "{{ username }}"
133 password: "{{ password }}"
134 validate_certs: "{{ validate_certs }}"
135 sdt_name: "sdt_example"
136 nvme_port: 4421
137 discovery_port: 8008
138 state: "present"
139
140 - name: Change maintenance mode
141 dellemc.powerflex.sdt:
142 hostname: "{{ hostname }}"
143 username: "{{ username }}"
144 password: "{{ password }}"
145 validate_certs: "{{ validate_certs }}"
146 sdt_name: "sdt_example"
147 maintenance_mode: "active"
148 state: "present"
149
150 - name: Set IP and role to SDT
151 dellemc.powerflex.sdt:
152 hostname: "{{ hostname }}"
153 username: "{{ username }}"
154 password: "{{ password }}"
155 validate_certs: "{{ validate_certs }}"
156 sdt_name: "sdt_example"
157 sdt_ip_list:
158 - ip: "172.169.xx.xx"
159 role: "StorageAndHost"
160 - ip: "172.169.zz.zz"
161 role: "StorageAndHost"
162 state: "present"
163
164 - name: Remove SDT
165 dellemc.powerflex.sdt:
166 hostname: "{{ hostname }}"
167 username: "{{ username }}"
168 password: "{{ password }}"
169 validate_certs: "{{ validate_certs }}"
170 sdt_name: "sdt_example"
171 state: "absent"
172 """
173
174 RETURN = r"""
175 changed:
176 description: Whether or not the resource has changed.
177 returned: always
178 type: bool
179 sample: 'false'
180 sdt_details:
181 description: Details of the SDT.
182 returned: When SDT exists
183 type: dict
184 contains:
185 authenticationError:
186 description: Indicates authentication error.
187 type: str
188 certificateInfo:
189 description: Information about certificate.
190 type: dict
191 contains:
192 issuer:
193 description: Issuer of the certificate.
194 type: str
195 subject:
196 description: Subject of the certificate.
197 type: str
198 thumbprint:
199 description: Thumbprint of the certificate.
200 type: str
201 validFrom:
202 description: Date and time the certificate is valid from.
203 type: str
204 validFromAsn1Format:
205 description: Valid from date in ASN.1 format.
206 type: str
207 validTo:
208 description: Date and time the certificate is valid to.
209 type: str
210 validToAsn1Format:
211 description: Valid to date in ASN.1 format.
212 type: str
213 discoveryPort:
214 description: Discovery port.
215 type: int
216 faultSetId:
217 description: Fault set ID.
218 type: str
219 id:
220 description: SDS ID.
221 type: str
222 ipList:
223 description: SDS IP list.
224 type: list
225 contains:
226 ip:
227 description: IP present in the SDS.
228 type: str
229 role:
230 description: Role of the SDS IP.
231 type: str
232 links:
233 description: SDS links.
234 type: list
235 contains:
236 href:
237 description: SDS instance URL.
238 type: str
239 rel:
240 description: SDS's relationship with different entities.
241 type: str
242 maintenanceState:
243 description: Maintenance state.
244 type: str
245 mdmConnectionState:
246 description: MDM connection state.
247 type: str
248 membershipState:
249 description: Membership state.
250 type: str
251 name:
252 description: Name of the SDS.
253 type: str
254 nvmePort:
255 description: NVMe port.
256 type: int
257 persistentDiscoveryControllersNum:
258 description: Number of persistent discovery controllers.
259 type: int
260 protectionDomainId:
261 description: Protection Domain ID.
262 type: str
263 protectionDomainName:
264 description: Protection Domain Name.
265 type: str
266 sdtState:
267 description: SDS state.
268 type: str
269 softwareVersionInfo:
270 description: SDS software version information.
271 type: str
272 storagePort:
273 description: Storage port.
274 type: int
275 systemId:
276 description: System ID.
277 type: str
278 sample: {
279 "authenticationError": "None",
280 "certificateInfo": {
281 "issuer": "/GN=MDM/CN=CA-804696a4dbe1d90f/L=Hopkinton/ST=Massachusetts/C=US/O=EMC/OU=ASD",
282 "subject": "/GN=sdt-comp-0/CN=host41/L=Hopkinton/ST=Massachusetts/C=US/O=EMC/OU=ASD",
283 "thumbprint": "07:1E:FC:48:03:42:E6:45:14:1D:AA:97:1F:4F:B9:B2:B4:11:99:09",
284 "validFrom": "Oct 8 02:35:00 2024 GMT",
285 "validFromAsn1Format": "241008023500Z",
286 "validTo": "Oct 7 03:35:00 2034 GMT",
287 "validToAsn1Format": "341007033500Z"
288 },
289 "discoveryPort": 8009,
290 "faultSetId": null,
291 "id": "917d28ed00000000",
292 "ipList": [
293 {
294 "ip": "172.169.xx.xx",
295 "role": "StorageAndHost"
296 },
297 {
298 "ip": "172.169.yy.yy",
299 "role": "StorageAndHost"
300 }
301 ],
302 "links": [
303 {
304 "href": "/api/instances/Sdt::917d28ed00000000",
305 "rel": "self"
306 },
307 {
308 "href": "/api/instances/Sdt::917d28ed00000000/relationships/Statistics",
309 "rel": "/api/Sdt/relationship/Statistics"
310 },
311 {
312 "href": "/api/instances/ProtectionDomain::b4787fa100000000",
313 "rel": "/api/parent/relationship/protectionDomainId"
314 }
315 ],
316 "maintenanceState": "NoMaintenance",
317 "mdmConnectionState": "Connected",
318 "membershipState": "Joined",
319 "name": "Sdt-pf460-svm-1",
320 "nvmePort": 4420,
321 "persistentDiscoveryControllersNum": 0,
322 "protectionDomainId": "b4787fa100000000",
323 "protectionDomainName": "PD1",
324 "sdtState": "Normal",
325 "softwareVersionInfo": "R4_5.2100.0",
326 "storagePort": 12200,
327 "systemId": "804696a4dbe1d90f"
328 }
329 """
330
331 from ansible.module_utils.basic import AnsibleModule
332 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell import (
333 utils,
334 )
335 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base import (
336 PowerFlexBase,
337 )
338 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.configuration import (
339 Configuration,
340 )
341 import copy
342
343 LOG = utils.get_logger("sdt")
344
345 SDT_IP_LIST_INVALID_ERROR_MSG = "Provide valid values for sdt_ip_list as 'ip' and 'role' for Create or Modify operations."
346 SDT_NAME_INVALID_ERROR_MSG = (
347 "Provide valid value for name for the creation or modification of the SDT."
348 )
349 PD_INVALID_ERROR_MSG = "Protection Domain is a mandatory parameter for creating an SDT. Enter a valid value."
350
351
352 class PowerFlexSDT(PowerFlexBase):
353 """Class with SDT operations"""
354
355 def __init__(self):
356 """Define all parameters required by this module"""
357 self.module_params = utils.get_powerflex_gateway_host_parameters()
358 self.module_params.update(get_powerflex_sdt_parameters())
359
360 # initialize the Ansible module
361 ansible_module_params = {
362 "argument_spec": get_powerflex_sdt_parameters(),
363 "supports_check_mode": True,
364 }
365 super().__init__(AnsibleModule, ansible_module_params)
366
367 self.result.update({"changed": False, "sdt_details": {}, "diff": {}})
368
369 def validate_ip_parameter(self, sdt_ip_list):
370 """Validate the input parameters"""
371
372 if sdt_ip_list is None or len(sdt_ip_list) == 0:
373 error_msg = SDT_IP_LIST_INVALID_ERROR_MSG
374 LOG.error(error_msg)
375 self.module.fail_json(msg=error_msg)
376
377 def get_sdt_details(self, sdt_name=None, sdt_id=None):
378 """Get SDT details
379 :param sdt_name: Name of the SDT
380 :type sdt_name: str
381 :param sdt_id: ID of the SDT
382 :type sdt_id: str
383 :return: Details of SDT if it exists
384 :rtype: dict
385 """
386
387 id_or_name = sdt_id if sdt_id else sdt_name
388
389 try:
390 if sdt_name:
391 sdt_details = self.powerflex_conn.sdt.get(
392 filter_fields={"name": sdt_name}
393 )
394 else:
395 sdt_details = self.powerflex_conn.sdt.get(filter_fields={"id": sdt_id})
396
397 if len(sdt_details) == 0:
398 msg = "SDT with identifier '%s' not found" % id_or_name
399 LOG.info(msg)
400 return None
401
402 return sdt_details[0]
403
404 except Exception as e:
405 error_msg = "Failed to get the SDT '%s' with error '%s'" % (
406 id_or_name,
407 str(e),
408 )
409 LOG.error(error_msg)
410 self.module.fail_json(msg=error_msg)
411
412 def get_diff_after(self, sdt_params, sdt_details):
413 """Get diff between playbook input and sdt details
414 :param sdt_params: Dictionary of parameters input from playbook
415 :param sdt_params: Dictionary of sdt details
416 :return: Dictionary of parameters of differences"""
417
418 if sdt_params["state"] == "absent":
419 return {}
420 else:
421 diff_dict = {}
422 if sdt_details is None:
423 diff_dict = {
424 "discovery_port": sdt_params["discovery_port"],
425 "nvme_port": sdt_params["nvme_port"],
426 "protection_domain_name": sdt_params["protection_domain_name"],
427 "sdt_ip_list": sdt_params["sdt_ip_list"],
428 "sdt_name": sdt_params["sdt_name"],
429 "storage_port": sdt_params["storage_port"],
430 }
431 else:
432 diff_dict = copy.deepcopy(sdt_details)
433 modify_dict = self.is_sdt_modify_required(sdt_params, diff_dict)
434 for key in modify_dict.keys():
435 diff_dict[key] = modify_dict[key]
436 return diff_dict
437
438 def is_sdt_modify_required(self, sdt_params, sdt_details):
439 """
440 Check if the SDT needs to be modified.
441 :param sdt_params: Dictionary of parameters input from playbook
442 :param sdt_details: Dictionary of sdt details
443 :return: Dictionary of parameters of differences
444 """
445 modify_dict = self.to_modify(
446 sdt_details=sdt_details,
447 sdt_new_name=sdt_params["sdt_new_name"],
448 storage_port=sdt_params["storage_port"],
449 nvme_port=sdt_params["nvme_port"],
450 discovery_port=sdt_params["discovery_port"],
451 maintenance_mode=sdt_params["maintenance_mode"],
452 )
453 if sdt_params["sdt_ip_list"]:
454 ips_to_add, ips_to_remove, roles_to_update = self.classify_ip_list_change(
455 sdt_params["sdt_ip_list"], sdt_details["ipList"]
456 )
457 if ips_to_add or ips_to_remove or roles_to_update:
458 modify_dict["ipList"] = sdt_params["sdt_ip_list"]
459 return modify_dict
460
461 def get_protection_domain(
462 self, protection_domain_name=None, protection_domain_id=None
463 ):
464 """Get the details of a protection domain in a given PowerFlex storage
465 system"""
466 return Configuration(self.powerflex_conn, self.module).get_protection_domain(
467 protection_domain_name=protection_domain_name,
468 protection_domain_id=protection_domain_id,
469 )
470
471 def validate_create(self, protection_domain_id, sdt_ip_list, sdt_name):
472
473 if sdt_name is None or len(sdt_name.strip()) == 0:
474 error_msg = SDT_NAME_INVALID_ERROR_MSG
475 LOG.error(error_msg)
476 self.module.fail_json(msg=error_msg)
477
478 if protection_domain_id is None:
479 error_msg = PD_INVALID_ERROR_MSG
480 LOG.error(error_msg)
481 self.module.fail_json(msg=error_msg)
482
483 self.validate_ip_parameter(sdt_ip_list)
484
485 def create_sdt(
486 self,
487 protection_domain_id,
488 sdt_ip_list,
489 sdt_name,
490 storage_port=None,
491 nvme_port=None,
492 discovery_port=None,
493 ):
494 """Create SDT
495 :param protection_domain_id: ID of the Protection Domain
496 :type protection_domain_id: str
497 :param sdt_ip_list: List of one or more IP addresses and
498 their roles
499 :type sdt_ip_list: list[dict]
500 :param sdt_name: SDT name
501 :type sdt_name: str
502 :param storage_port: Storage port of SDT
503 :type storage_port: int
504 :param nvme_port: NVMe port of SDT
505 :type nvme_port: int
506 :param discovery_port: Discovery port of SDT
507 :type discovery_port: int
508 :return: dict
509 """
510 try:
511
512 # Restructure IP-role parameter format
513 self.validate_create(
514 protection_domain_id=protection_domain_id,
515 sdt_ip_list=sdt_ip_list,
516 sdt_name=sdt_name,
517 )
518
519 if not self.module.check_mode:
520 create_params = (
521 "protection_domain_id: %s,"
522 " sdt_ip_list: %s,"
523 " sdt_name: %s,"
524 " storage_port: %s,"
525 " nvme_port: %s,"
526 " discovery_port: %s"
527 % (
528 protection_domain_id,
529 sdt_ip_list,
530 sdt_name,
531 storage_port,
532 nvme_port,
533 discovery_port,
534 )
535 )
536 LOG.info("Creating SDT with params: %s", create_params)
537
538 self.powerflex_conn.sdt.create(
539 protection_domain_id=protection_domain_id,
540 sdt_ips=sdt_ip_list,
541 sdt_name=sdt_name,
542 storage_port=storage_port,
543 nvme_port=nvme_port,
544 discovery_port=discovery_port,
545 )
546 return self.get_sdt_details(sdt_name=sdt_name)
547
548 except Exception as e:
549 error_msg = f"Create SDT {sdt_name} operation failed with error {str(e)}"
550 LOG.error(error_msg)
551 self.module.fail_json(msg=error_msg)
552
553 def to_modify(
554 self,
555 sdt_details,
556 sdt_new_name,
557 storage_port,
558 nvme_port,
559 discovery_port,
560 maintenance_mode,
561 ):
562 """
563 :param sdt_details: Details of the SDT
564 :type sdt_details: dict
565 :param sdt_new_name: New name of SDT
566 :type sdt_new_name: str
567 :param storage_port: Storage port of SDT
568 :type storage_port: int
569 :param nvme_port: NVMe port of SDT
570 :type nvme_port: int
571 :param discovery_port: Discovery port of SDT
572 :type discovery_port: int
573 :param maintenance_mode: Maintenance mode of SDT
574 :type maintenance_mode: str
575 :return: Dictionary containing the attributes of SDT which are to be
576 updated
577 :rtype: dict
578 """
579 modify_dict = {}
580
581 if sdt_new_name is not None and sdt_new_name != sdt_details["name"]:
582 modify_dict["name"] = sdt_new_name
583
584 if storage_port is not None and storage_port != sdt_details["storagePort"]:
585 modify_dict["storagePort"] = storage_port
586 if nvme_port is not None and nvme_port != sdt_details["nvmePort"]:
587 modify_dict["nvmePort"] = nvme_port
588 if (
589 discovery_port is not None
590 and discovery_port != sdt_details["discoveryPort"]
591 ):
592 modify_dict["discoveryPort"] = discovery_port
593
594 if maintenance_mode is not None:
595 if (
596 maintenance_mode == "active"
597 and sdt_details["maintenanceState"] != "InMaintenance"
598 ):
599 modify_dict["maintenanceState"] = "active"
600 if (
601 maintenance_mode == "inactive"
602 and sdt_details["maintenanceState"] != "NoMaintenance"
603 ):
604 modify_dict["maintenanceState"] = "inactive"
605
606 return modify_dict
607
608 def modify_sdt_attributes(self, sdt_id, modify_dict):
609 """
610 Modify SDT attributes
611 :param sdt_id: SDT ID
612 :type sdt_id: str
613 :param modify_dict: Dictionary containing the attributes of SDT
614 which are to be updated
615 :type modify_dict: dict
616 :return: Boolean indicating if the operation is successful
617 """
618 try:
619 msg = (
620 "Dictionary containing attributes which are to be"
621 " updated is '%s'." % (str(modify_dict))
622 )
623 LOG.info(msg)
624
625 if not self.module.check_mode:
626 if "name" in modify_dict:
627 self.powerflex_conn.sdt.rename(sdt_id, modify_dict["name"])
628 msg = (
629 "The name of the SDT is updated to '%s' successfully."
630 % modify_dict["name"]
631 )
632 LOG.info(msg)
633
634 if "storagePort" in modify_dict:
635 self.powerflex_conn.sdt.set_storage_port(
636 sdt_id, modify_dict["storagePort"]
637 )
638 msg = (
639 "The storage port is updated to '%s' successfully."
640 % modify_dict["storagePort"]
641 )
642 LOG.info(msg)
643
644 if "nvmePort" in modify_dict:
645 self.powerflex_conn.sdt.set_nvme_port(
646 sdt_id, modify_dict["nvmePort"]
647 )
648 msg = (
649 "The nvme port is updated to '%s' successfully."
650 % modify_dict["nvmePort"]
651 )
652 LOG.info(msg)
653
654 if "discoveryPort" in modify_dict:
655 self.powerflex_conn.sdt.set_discovery_port(
656 sdt_id, modify_dict["discoveryPort"]
657 )
658 msg = (
659 "The discovery port is updated to '%s' successfully."
660 % modify_dict["discoveryPort"]
661 )
662 LOG.info(msg)
663
664 if "maintenanceState" in modify_dict:
665 mode_map = {
666 "active": self.powerflex_conn.sdt.enter_maintenance_mode,
667 "inactive": self.powerflex_conn.sdt.exit_maintenance_mode,
668 }
669 mode_func = mode_map.get(modify_dict["maintenanceState"])
670 if mode_func:
671 mode_func(sdt_id)
672 msg = (
673 "The maintenance mode is updated to '%s' successfully."
674 % modify_dict["maintenanceState"]
675 )
676 LOG.info(msg)
677
678 return True
679 except Exception as e:
680 error_msg = "Failed to update the SDT '%s' with error '%s'" % (
681 sdt_id,
682 str(e),
683 )
684 LOG.error(error_msg)
685 self.module.fail_json(msg=error_msg)
686
687 def classify_ip_list_change(self, sdt_ip_list, sdt_details_ip_list):
688 # identify IPs to add or remove or roles to update
689
690 ips_to_add = []
691 ips_to_remove = []
692 roles_to_update = []
693
694 # Check if any new IPs need to be added
695 for ip_source in sdt_ip_list:
696 if not any(
697 ip_dest["ip"] == ip_source["ip"] for ip_dest in sdt_details_ip_list
698 ):
699 ips_to_add.append(ip_source)
700
701 # Check if any IPs need to be removed
702 for ip_source in sdt_details_ip_list:
703 if not any(ip_dest["ip"] == ip_source["ip"] for ip_dest in sdt_ip_list):
704 ips_to_remove.append(ip_source)
705
706 # Check if any IPs need to have their roles updated
707 for ip_source in sdt_ip_list:
708 for ip_dest in sdt_details_ip_list:
709 if (
710 ip_dest["ip"] == ip_source["ip"]
711 and ip_dest["role"] != ip_source["role"]
712 ):
713 roles_to_update.append(ip_source)
714
715 return ips_to_add, ips_to_remove, roles_to_update
716
717 def add_ip(self, sdt_details, sdt_ip_list):
718 """Add IP to SDT
719 :param sdt_details: Details of the SDT
720 :type sdt_details: str
721 :param sdt_ip_list: List of one or more IP addresses and
722 their roles
723 :type sdt_ip_list: list[dict]
724 :return: Boolean indicating if add IP operation is successful
725 """
726 try:
727 if not self.module.check_mode:
728 for ip in sdt_ip_list:
729 LOG.info("IP to add: %s", ip["ip"])
730 self.powerflex_conn.sdt.add_ip(
731 sdt_id=sdt_details["id"], ip=ip["ip"], role=ip["role"]
732 )
733 LOG.info("IP added successfully.")
734 return True
735 except Exception as e:
736 error_msg = "Add IP to SDT '%s' operation failed with " "error '%s'" % (
737 sdt_details["name"],
738 str(e),
739 )
740 LOG.error(error_msg)
741 self.module.fail_json(msg=error_msg)
742
743 def remove_ip(self, sdt_details, sdt_ip_list):
744 """Remove IP from SDT
745 :param sdt_details: Details of the SDT
746 :type sdt_details: str
747 :param sdt_ip_list: List of one or more IP addresses and
748 their roles.
749 :type sdt_ip_list: list[dict]
750 :return: Boolean indicating if remove IP operation is successful
751 """
752 try:
753 if not self.module.check_mode:
754 for ip in sdt_ip_list:
755 LOG.info("IP to remove: %s", ip["ip"])
756 self.powerflex_conn.sdt.remove_ip(
757 sdt_id=sdt_details["id"], ip=ip["ip"]
758 )
759 LOG.info("IP removed successfully.")
760 return True
761 except Exception as e:
762 error_msg = (
763 "Remove IP from SDT '%s' operation failed with "
764 "error '%s'" % (sdt_details["name"], str(e))
765 )
766 LOG.error(error_msg)
767 self.module.fail_json(msg=error_msg)
768
769 def update_role(self, sdt_details, sdt_ip_list):
770 """Update IP's role for an SDT
771 :param sdt_details: Details of the SDT
772 :type sdt_details: str
773 :param sdt_ip_list: List of one or more IP addresses and
774 their roles
775 :type sdt_ip_list: list[dict]
776 :return: Boolean indicating if update role operation is successful
777 """
778 try:
779 if not self.module.check_mode:
780 for ip in sdt_ip_list:
781 LOG.info("ip role to update: %s", ip)
782 self.powerflex_conn.sdt.set_ip_role(
783 sdt_id=sdt_details["id"], ip=ip["ip"], role=ip["role"]
784 )
785 msg = "The role '%s' for IP '%s' is updated " "successfully." % (
786 ip["role"],
787 ip["ip"],
788 )
789 LOG.info(msg)
790 return True
791 except Exception as e:
792 error_msg = (
793 "Update role of IP for SDT '%s' operation failed "
794 "with error '%s'" % (sdt_details["name"], str(e))
795 )
796 LOG.error(error_msg)
797 self.module.fail_json(msg=error_msg)
798
799 def delete_sdt(self, sdt_details):
800 """Delete SDT
801 :param sdt_details: Details of SDT
802 :type sdtsdt_details_id: str
803 :return: dict
804 """
805 try:
806 if not self.module.check_mode:
807 self.powerflex_conn.sdt.delete(sdt_details["id"])
808 return None
809 return self.get_sdt_details(sdt_id=sdt_details["id"])
810 except Exception as e:
811 error_msg = "Delete SDT '%s' operation failed with error '%s'" % (
812 sdt_details["name"],
813 str(e),
814 )
815 LOG.error(error_msg)
816 self.module.fail_json(msg=error_msg)
817
818 def show_output(self, sdt_id):
819 """Show SDT details
820 :param sdt_id: ID of the SDT
821 :type sdt_id: str
822 :return: Details of SDT
823 :rtype: dict
824 """
825
826 try:
827 sdt_details = self.powerflex_conn.sdt.get(filter_fields={"id": sdt_id})
828
829 if len(sdt_details) == 0:
830 msg = "SDT with identifier '%s' not found" % sdt_id
831 LOG.error(msg)
832 return None
833
834 # Append protection domain name
835 if (
836 "protectionDomainId" in sdt_details[0]
837 and sdt_details[0]["protectionDomainId"]
838 ):
839 pd_details = self.get_protection_domain(
840 protection_domain_id=sdt_details[0]["protectionDomainId"]
841 )
842 sdt_details[0]["protectionDomainName"] = pd_details["name"]
843
844 return sdt_details[0]
845
846 except Exception as e:
847 error_msg = "Failed to get the SDT '%s' with error '%s'" % (sdt_id, str(e))
848 LOG.error(error_msg)
849 self.module.fail_json(msg=error_msg)
850
851 def validate_names(self, sdt_params):
852 params = [sdt_params["sdt_name"], sdt_params["sdt_new_name"]]
853 for param in params:
854 if param is not None and len(param.strip()) == 0:
855 error_msg = SDT_NAME_INVALID_ERROR_MSG
856 LOG.error(error_msg)
857 self.module.fail_json(msg=error_msg)
858
859
860 def get_powerflex_sdt_parameters():
861 """This method provide parameters required for the SDT module on
862 PowerFlex"""
863 return dict(
864 sdt_name=dict(required=True),
865 sdt_new_name=dict(),
866 protection_domain_name=dict(),
867 sdt_ip_list=dict(
868 type="list",
869 elements="dict",
870 options=dict(
871 ip=dict(required=True),
872 role=dict(
873 required=True, choices=["StorageAndHost", "StorageOnly", "HostOnly"]
874 ),
875 ),
876 ),
877 storage_port=dict(type="int"),
878 nvme_port=dict(type="int"),
879 discovery_port=dict(type="int"),
880 maintenance_mode=dict(type="str", choices=["active", "inactive"]),
881 state=dict(type="str", choices=["present", "absent"], default="present"),
882 )
883
884
885 class SDTExitHandler:
886 """SDT Handler to manage the output."""
887
888 def handle(self, sdt_obj, sdt_details):
889 if sdt_details:
890 sdt_obj.result["sdt_details"] = sdt_obj.show_output(
891 sdt_id=sdt_details["id"]
892 )
893 else:
894 sdt_obj.result["sdt_details"] = None
895 sdt_obj.module.exit_json(**sdt_obj.result)
896
897
898 class SDTDeleteHandler:
899 """SDT Handler to process the delete operation."""
900
901 def handle(self, sdt_obj, sdt_params, sdt_details):
902 if sdt_params["state"] == "absent" and sdt_details:
903 sdt_details = sdt_obj.delete_sdt(sdt_details)
904 sdt_obj.result["changed"] = True
905
906 SDTExitHandler().handle(sdt_obj, sdt_details)
907
908
909 class SDTChangeIPListHandler:
910 """SDT Handler to process the IP list change operation."""
911
912 def handle(self, sdt_obj, sdt_params, sdt_details, create_sdt_flag, sdt_ip_list):
913 if (
914 sdt_params["state"] == "present"
915 and sdt_ip_list
916 and sdt_details
917 and not create_sdt_flag
918 ):
919 sdt_obj.validate_ip_parameter(sdt_ip_list)
920 ips_to_add, ips_to_remove, roles_to_update = (
921 sdt_obj.classify_ip_list_change(sdt_ip_list, sdt_details["ipList"])
922 )
923
924 if ips_to_add:
925 sdt_obj.add_ip(sdt_details, ips_to_add)
926 if roles_to_update:
927 sdt_obj.update_role(sdt_details, roles_to_update)
928 if ips_to_remove:
929 sdt_obj.remove_ip(sdt_details, ips_to_remove)
930
931 if ips_to_add or roles_to_update or ips_to_remove:
932 sdt_obj.result["changed"] = True
933
934 SDTDeleteHandler().handle(sdt_obj, sdt_params, sdt_details)
935
936
937 class SDTModifyHandler:
938 """SDT Handler to process the attribute modify operation."""
939
940 def handle(self, sdt_obj, sdt_params, sdt_details, create_sdt_flag, sdt_ip_list):
941 if sdt_params["state"] == "present" and sdt_details and not create_sdt_flag:
942 modify_dict = sdt_obj.to_modify(
943 sdt_details=sdt_details,
944 sdt_new_name=sdt_params["sdt_new_name"],
945 storage_port=sdt_params["storage_port"],
946 nvme_port=sdt_params["nvme_port"],
947 discovery_port=sdt_params["discovery_port"],
948 maintenance_mode=sdt_params["maintenance_mode"],
949 )
950 if modify_dict:
951 sdt_obj.modify_sdt_attributes(
952 sdt_id=sdt_details["id"], modify_dict=modify_dict
953 )
954 sdt_obj.result["changed"] = True
955
956 SDTChangeIPListHandler().handle(
957 sdt_obj, sdt_params, sdt_details, create_sdt_flag, sdt_ip_list
958 )
959
960
961 class SDTCreateHandler:
962 """SDT Handler to process the create operation."""
963
964 def handle(self, sdt_obj, sdt_params, sdt_details, protection_domain_id):
965 create_sdt_flag = False
966 sdt_ip_list = copy.deepcopy(sdt_params["sdt_ip_list"])
967 if sdt_params["state"] == "present" and not sdt_details:
968 sdt_details = sdt_obj.create_sdt(
969 sdt_name=sdt_params["sdt_name"],
970 protection_domain_id=protection_domain_id,
971 sdt_ip_list=sdt_ip_list,
972 storage_port=sdt_params["storage_port"],
973 nvme_port=sdt_params["nvme_port"],
974 discovery_port=sdt_params["discovery_port"],
975 )
976 sdt_obj.result["changed"] = True
977 create_sdt_flag = True
978
979 SDTModifyHandler().handle(
980 sdt_obj, sdt_params, sdt_details, create_sdt_flag, sdt_ip_list
981 )
982
983
984 class SDTHandler:
985 """SDT Handler to preprocess the operation."""
986
987 def handle(self, sdt_obj, sdt_params):
988 sdt_obj.validate_names(sdt_params=sdt_params)
989 sdt_details = sdt_obj.get_sdt_details(sdt_params["sdt_name"])
990 protection_domain_id = None
991 if sdt_params["protection_domain_name"]:
992 protection_domain_id = sdt_obj.get_protection_domain(
993 protection_domain_name=sdt_params["protection_domain_name"]
994 )["id"]
995
996 before_dict = {}
997 diff_dict = {}
998 diff_dict = sdt_obj.get_diff_after(sdt_params, sdt_details)
999 if sdt_details is None:
1000 before_dict = {}
1001 else:
1002 before_dict = sdt_details
1003 if sdt_obj.module._diff:
1004 sdt_obj.result["diff"] = dict(before=before_dict, after=diff_dict)
1005
1006 SDTCreateHandler().handle(
1007 sdt_obj, sdt_params, sdt_details, protection_domain_id
1008 )
1009
1010
1011 def main():
1012 """Create PowerFlex SDT object and perform action on it
1013 based on user input from playbook."""
1014 obj = PowerFlexSDT()
1015 SDTHandler().handle(obj, obj.module.params)
1016
1017
1018 if __name__ == "__main__":
1019 main()