Debian Codegraph @

ansible_collections/dellemc/powerflex/plugins/modules/nvme_host.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 NVMe hosts on Dell Technologies PowerFlex"""
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 DOCUMENTATION = r"""
13 module: nvme_host
14 version_added: '2.6.0'
15 short_description: Manage NVMe hosts on Dell PowerFlex
16 description:
17 - Managing NVMe hosts on PowerFlex storage system includes creating, getting details of NVMe hosts
18 , modifying and deleting NVMe hosts.
19
20 author:
21 - Peter Cao (@P-Cao) <[email protected]>
22
23 extends_documentation_fragment:
24 - dellemc.powerflex.powerflex
25
26 options:
27 max_num_paths:
28 description:
29 - Maximum number of paths per volume. Used to create or modify the NVMe host.
30 type: str
31 max_num_sys_ports:
32 description:
33 - Maximum number of ports per protection domain. Used to create or modify the NVMe host.
34 type: str
35 nqn:
36 description:
37 - NQN of the NVMe host. Used to create, get or modify the NVMe host.
38 - To retrieve NQN of NVMe host, use command :command:`cat /etc/nvme/hostnqn`
39 type: str
40 nvme_host_name:
41 description:
42 - Name of the NVMe host.
43 - Specify either I(nvme_host_name), I(nqn) for create, get or rename operation.
44 type: str
45 nvme_host_new_name:
46 description:
47 - New name of the NVMe host. Used to rename the NVMe host.
48 - Only used for updates. Ignored during creation.
49 type: str
50 state:
51 description:
52 - State of the NVMe host.
53 choices: ['present', 'absent']
54 default: present
55 type: str
56 attributes:
57 check_mode:
58 description: Runs task to validate without performing action on the target
59 machine.
60 support: full
61 diff_mode:
62 description: Runs the task to report the changes made or to be made.
63 support: full
64 """
65
66 EXAMPLES = r"""
67 - name: Create NVMe host
68 dellemc.powerflex.nvme_host:
69 hostname: "{{ hostname }}"
70 username: "{{ username }}"
71 password: "{{ password }}"
72 validate_certs: "{{ validate_certs }}"
73 nqn: "{{ nqn }}"
74 nvme_host_name: "{{ nvme_host_name }}"
75 state: "present"
76
77 - name: Rename nvme_host using NVMe host id
78 dellemc.powerflex.nvme_host:
79 hostname: "{{ hostname }}"
80 username: "{{ username }}"
81 password: "{{ password }}"
82 validate_certs: "{{ validate_certs }}"
83 nvme_host_name: "{{ nvme_host_name }}"
84 nvme_host_new_name: "{{ nvme_host_new_name }}"
85 state: "present"
86
87 - name: Set maximum number of paths per volume and maximum Number of Ports Per Protection Domain of nvme_host
88 dellemc.powerflex.nvme_host:
89 hostname: "{{ hostname }}"
90 username: "{{ username }}"
91 password: "{{ password }}"
92 validate_certs: "{{ validate_certs }}"
93 nvme_host_name: "{{ nvme_host_name }}"
94 max_num_paths: "{{ max_num_paths }}"
95 max_num_sys_ports: "{{ max_num_sys_ports }}"
96 state: "present"
97
98 - name: Remove nvme_host
99 dellemc.powerflex.nvme_host:
100 hostname: "{{ hostname }}"
101 username: "{{ username }}"
102 password: "{{ password }}"
103 validate_certs: "{{ validate_certs }}"
104 nvme_host_name: "{{ nvme_host_name }}"
105 state: "absent"
106 """
107
108 RETURN = r"""
109 changed:
110 description: Whether or not the resource has changed.
111 returned: always
112 type: bool
113 sample: 'false'
114
115 nvme_host_details:
116 description: Details of the NVMe host.
117 returned: When NVMe host exists
118 type: dict
119 contains:
120 hostOsFullType:
121 description: Full type of the host OS.
122 type: str
123 hostType:
124 description: Type of the host.
125 type: str
126 id:
127 description: ID of the NVMe host.
128 type: str
129 installedSoftwareVersionInfo:
130 description: Installed software version information.
131 type: str
132 kernelBuildNumber:
133 description: Kernel build number.
134 type: str
135 kernelVersion:
136 description: Kernel version.
137 type: str
138 links:
139 description: Links related to the NVMe host.
140 type: list
141 contains:
142 href:
143 description: Hyperlink reference.
144 type: str
145 rel:
146 description: Relation type.
147 type: str
148 max_num_paths:
149 description: Maximum number of paths per volume. Used to create or modify the NVMe host.
150 type: int
151 max_num_sys_ports:
152 description: Maximum number of ports per protection domain. Used to create or modify the NVMe host.
153 type: int
154 mdmConnectionState:
155 description: MDM connection state.
156 type: str
157 mdmIpAddressesCurrent:
158 description: Current MDM IP addresses.
159 type: list
160 name:
161 description: Name of the NVMe host.
162 type: str
163 nqn:
164 description: NQN of the NVMe host. Used to create, get or modify the NVMe host.
165 type: str
166 osType:
167 description: OS type.
168 type: str
169 peerMdmId:
170 description: Peer MDM ID.
171 type: str
172 perfProfile:
173 description: Performance profile.
174 type: str
175 sdcAgentActive:
176 description: Whether the SDC agent is active.
177 type: bool
178 sdcApproved:
179 description: Whether an SDC has approved access to the system.
180 type: bool
181 sdcApprovedIps:
182 description: SDC approved IPs.
183 type: list
184 sdcGuid:
185 description: SDC GUID.
186 type: str
187 sdcIp:
188 description: SDC IP address.
189 type: str
190 sdcIps:
191 description: SDC IP addresses.
192 type: list
193 sdcType:
194 description: SDC type.
195 type: str
196 sdrId:
197 description: SDR ID.
198 type: str
199 sdtId:
200 description: SDT ID.
201 type: str
202 softwareVersionInfo:
203 description: Software version information.
204 type: str
205 systemId:
206 description: ID of the system.
207 type: str
208 versionInfo:
209 description: Version information.
210 type: str
211 sample: {
212 "hostOsFullType": "Generic",
213 "systemId": "264ec85b3855280f",
214 "name": "name",
215 "sdcApproved": null,
216 "sdcAgentActive": null,
217 "mdmIpAddressesCurrent": null,
218 "sdcIp": null,
219 "sdcIps": null,
220 "osType": null,
221 "perfProfile": null,
222 "peerMdmId": null,
223 "sdtId": null,
224 "mdmConnectionState": null,
225 "softwareVersionInfo": null,
226 "socketAllocationFailure": null,
227 "memoryAllocationFailure": null,
228 "versionInfo": null,
229 "sdcType": null,
230 "nqn": "nqn.org.nvmexpress:uuid",
231 "maxNumPaths": 6,
232 "maxNumSysPorts": 10,
233 "sdcGuid": null,
234 "installedSoftwareVersionInfo": null,
235 "kernelVersion": null,
236 "kernelBuildNumber": null,
237 "sdcApprovedIps": null,
238 "hostType": "NVMeHost",
239 "sdrId": null,
240 "id": "1040d67200010000",
241 "links": [
242 {
243 "rel": "self",
244 "href": "/api/instances/Host::1040d67200010000"
245 },
246 {
247 "rel": "/api/Host/relationship/Volume",
248 "href": "/api/instances/Host::1040d67200010000/relationships/Volume"
249 },
250 {
251 "rel": "/api/Host/relationship/NvmeController",
252 "href": "/api/instances/Host::1040d67200010000/relationships/NvmeController"
253 },
254 {
255 "rel": "/api/parent/relationship/systemId",
256 "href": "/api/instances/System::264ec85b3855280f"
257 }
258 ]
259 }
260 """
261
262 from ansible.module_utils.basic import AnsibleModule
263 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \
264 import PowerFlexBase
265 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell import (
266 utils,
267 )
268
269 LOG = utils.get_logger("nvme")
270
271
272 class PowerFlexNVMeHost(PowerFlexBase):
273 """Class with NVMe host operations"""
274
275 def __init__(self):
276 """Define all parameters required by this module"""
277 required_one_of = [["nvme_host_name", "nqn"]]
278
279 ansible_module_params = {
280 'argument_spec': get_powerflex_nvme_host_parameters(),
281 'supports_check_mode': True,
282 'required_one_of': required_one_of
283 }
284 super().__init__(AnsibleModule, ansible_module_params)
285
286 self.result = dict(
287 changed=False,
288 nvme_host_details={},
289 diff={}
290 )
291
292 def validate_parameters(self, nvme_host_params):
293 """Validate the input parameters
294 :param nvme_host_params: The dict of NVMe host parameters
295 :type nvme_host_params: dict
296 """
297
298 host_identifiers = ["nvme_host_name", "nqn",
299 "max_num_paths", "max_num_sys_ports"]
300 for param in host_identifiers:
301 if (
302 nvme_host_params[param] is not None
303 and len(nvme_host_params[param].strip()) == 0
304 ):
305 msg = f"Provide valid {param}"
306 LOG.error(msg)
307 self.module.fail_json(msg=msg)
308
309 def get_nvme_host(self, nvme_host_id=None, nvme_host_name=None, nqn=None):
310 """Get the NVMe host Details
311 :param nvme_host_name: The name of the NVMe host
312 :param nvme_host_di: The ID of the NVMe host
313 :return: The dict containing NVMe host details
314 """
315 id_name_map = {
316 "id": nvme_host_id,
317 "nqn": nqn,
318 "name": nvme_host_name
319 }
320 id_name = next(((key, value) for key, value in id_name_map.items() if value), None)
321
322 try:
323 filter_field = None
324 filter_value = None
325
326 if id_name:
327 filter_field, filter_value = id_name
328
329 all_host_details = self.powerflex_conn.sdc.get()
330 # Assign names to unnamed NVMe hosts and find the target host
331 for nvme_host in all_host_details:
332 if nvme_host.get("name") is None:
333 nvme_host["name"] = f"NVMeHost:{nvme_host['id']}"
334
335 if filter_field is None or filter_value is None:
336 return all_host_details[0] if all_host_details else None
337
338 nvme_host_details = [
339 host_entity for host_entity in all_host_details
340 if host_entity.get(filter_field) == filter_value and host_entity.get('hostType') == 'NVMeHost'
341 ]
342
343 return nvme_host_details[0] if nvme_host_details else None
344
345 except Exception as e:
346 errormsg = "Failed to get NVMe host with error: %s" % str(e)
347 LOG.error(errormsg)
348 self.module.fail_json(msg=errormsg)
349
350 def create_nvme_host(self, nvme_host_params):
351 """Create the NVMe host
352 :param nvme_host_params: The dict of NVMe host parameters
353 :type nvme_host_params: dict
354 :return: The dict containing NVMe host details
355 """
356 try:
357 if not nvme_host_params['nqn']:
358 errormsg = "nqn is required for creating NVMe host"
359 LOG.error(errormsg)
360 self.module.fail_json(msg=errormsg)
361
362 if self.module._diff:
363 self.result.update({"diff": {"before": {}, "after":
364 {"nqn": nvme_host_params.get('nqn'),
365 "nvme_host_name": nvme_host_params.get('nvme_host_name'),
366 "max_num_paths": nvme_host_params.get('max_num_paths'),
367 "max_num_sys_ports": nvme_host_params.get('max_num_sys_ports')}}})
368 if not self.module.check_mode:
369 msg = (f"Creating NVMe host with nqn: {nvme_host_params['nqn']}")
370 LOG.info(msg)
371 self.powerflex_conn.host.create(
372 nqn=nvme_host_params['nqn'],
373 name=nvme_host_params['nvme_host_name'],
374 max_num_paths=nvme_host_params['max_num_paths'],
375 max_num_sys_ports=nvme_host_params['max_num_sys_ports'],
376 )
377 return self.get_nvme_host(nqn=nvme_host_params['nqn'])
378
379 except Exception as e:
380 errormsg = "Create NVMe host operation failed with " "error %s" % str(e)
381 LOG.error(errormsg)
382 self.module.fail_json(msg=errormsg)
383
384 def delete_nvme_host(self, nvme_host_details):
385 """Remove the NVMe host
386 :param nvme_host_id: The ID of the NVMe host
387 :type nvme_host_id: str
388 :return: The dict containing NVMe host details
389 """
390 try:
391 nvme_host_id = nvme_host_details['id']
392 if self.module._diff:
393 self.result.update({"diff": {"before": nvme_host_details, "after": {}}})
394
395 if not self.module.check_mode:
396 LOG.info(msg=f"Deleting NVMe host {nvme_host_id}")
397 self.powerflex_conn.sdc.delete(nvme_host_id)
398 return None
399 return self.get_nvme_host(nvme_host_id=nvme_host_id)
400
401 except Exception as e:
402 errormsg = f"Failed to remove NVMe host {nvme_host_id} with error {str(e)}"
403 LOG.error(errormsg)
404 self.module.fail_json(msg=errormsg)
405
406 def modify_nvme_host(self, nvme_host_details, nvme_host_params):
407 """
408 Modifies the NVMe host with the given details.
409
410 Args:
411 nvme_host_details (dict): The details of the NVMe host.
412 nvme_host_params (dict): The parameters for modification.
413
414 Returns:
415 bool: True if the NVMe host was modified, False otherwise.
416
417 Raises:
418 Exception: If there was an error renaming the NVMe host or modifying its properties.
419 """
420 modified, modified_fields, before_dict, after_dict = False, [], {}, {}
421 version_check = self._get_api_version_and_check()
422
423 modification_funcs = {
424 "nvme_host_new_name": {
425 "field": "name",
426 "modify_func": lambda: self.powerflex_conn.sdc.rename(sdc_id=nvme_host_details["id"], name=nvme_host_params['nvme_host_new_name']),
427 "condition": nvme_host_params['nvme_host_new_name'] and nvme_host_params['nvme_host_new_name'] != nvme_host_details["name"],
428 },
429 "max_num_paths": {
430 "field": "maxNumPaths",
431 "modify_func": lambda: self.powerflex_conn.host.modify_max_num_paths(host_id=nvme_host_details["id"],
432 max_num_paths=nvme_host_params['max_num_paths']),
433 "condition": nvme_host_params['max_num_paths'] and nvme_host_params['max_num_paths'] != str(nvme_host_details["maxNumPaths"]),
434 },
435 "max_num_sys_ports": {
436 "field": "maxNumSysPorts",
437 "modify_func": lambda: self.powerflex_conn.host.modify_max_num_sys_ports(host_id=nvme_host_details["id"],
438 max_num_sys_ports=nvme_host_params['max_num_sys_ports']),
439 "condition": nvme_host_params['max_num_sys_ports'] and nvme_host_params['max_num_sys_ports'] != str(nvme_host_details["maxNumSysPorts"]),
440 },
441 }
442
443 for k, v in modification_funcs.items():
444 if v["condition"]:
445 before_dict[v["field"]] = nvme_host_details[v["field"]]
446 after_dict[v["field"]] = nvme_host_params[k]
447 try:
448 if not self.module.check_mode:
449 v["modify_func"]()
450 modified_fields.append(v["field"])
451 modified = True
452 except Exception as e:
453 self.handle_exception("modify", v["field"], e, version_check, nvme_host_details, modified_fields)
454
455 if self.module._diff and modified:
456 self.result.update({"diff": {"before": before_dict, "after": after_dict}})
457
458 return modified, self.get_nvme_host(nvme_host_id=nvme_host_details['id'])
459
460 def handle_exception(self, operation, field, ex, version_check, nvme_host_details, modified_fields):
461 """
462 Handles exceptions that occur during the modification of NVMe host fields.
463
464 Args:
465 operation (str): The operation being performed.
466 field (str): The field being modified.
467 ex (Exception): The exception that occurred.
468 version_check (bool): Whether the version check is enabled.
469 nvme_host_details (dict): The details of the NVMe host.
470 modified_fields (list): The list of modified fields.
471
472 Returns:
473 None
474
475 Raises:
476 Exception: If the modification fails.
477
478 """
479 version_support_err = f"Updating the NVMe host {field} is not supported in PowerFlex versions earlier than 4.6"
480 ex_msg = version_support_err if version_check and field != "name" else str(ex)
481 msg = f"Successfully modified the following fields: {', '.join(modified_fields)}" if modified_fields else ""
482 errormsg = f"Failed to {operation} NVMe host {nvme_host_details['id']} {field} with error {ex_msg}. {msg}"
483 LOG.error(errormsg)
484 self.module.fail_json(msg=errormsg)
485
486 def _get_api_version_and_check(self):
487 """
488 Get the API version and check if it is less than version 4.6.
489
490 Returns:
491 bool: True if the API version is less than version 4.6, False otherwise.
492 """
493 api_version = self.powerflex_conn.system.get()[0]['mdmCluster']['master']['versionInfo']
494 version_check = utils.is_version_less(utils.parse_version(api_version), '4.6')
495 return version_check
496
497
498 def get_powerflex_nvme_host_parameters():
499 """This method provide parameters for the Ansible NVMe host module on
500 PowerFlex"""
501 return dict(
502 nqn=dict(type="str"),
503 nvme_host_name=dict(type="str"),
504 nvme_host_new_name=dict(type="str"),
505 max_num_paths=dict(type="str"),
506 max_num_sys_ports=dict(type="str"),
507 state=dict(default="present", type="str", choices=["present", "absent"]),
508 )
509
510
511 class NVMeHostExitHandler():
512 def handle(self, nvme_host_obj, nvme_host_details):
513 if nvme_host_details:
514 nvme_host_obj.result['nvme_host_details'] = nvme_host_details
515 else:
516 nvme_host_obj.result['nvme_host_details'] = {}
517 nvme_host_obj.module.exit_json(**nvme_host_obj.result)
518
519
520 class NVMeHostDeleteHandler():
521 def handle(self, nvme_host_obj, nvme_host_params, nvme_host_details):
522 if nvme_host_params['state'] == 'absent' and nvme_host_details:
523 nvme_host_details = nvme_host_obj.delete_nvme_host(nvme_host_details)
524 nvme_host_obj.result['changed'] = True
525
526 NVMeHostExitHandler().handle(nvme_host_obj, nvme_host_details)
527
528
529 class NVMeHostModifyHandler():
530 def handle(self, nvme_host_obj, nvme_host_params, nvme_host_details, create_flag=False):
531 if not create_flag and nvme_host_params['state'] == 'present' and nvme_host_details:
532 changed, nvme_host_details = nvme_host_obj.modify_nvme_host(nvme_host_details, nvme_host_params)
533 # if created or modified, set changed to true
534 nvme_host_obj.result['changed'] |= changed
535
536 NVMeHostDeleteHandler().handle(nvme_host_obj, nvme_host_params, nvme_host_details)
537
538
539 class NVMeHostCreateHandler():
540 def handle(self, nvme_host_obj, nvme_host_params, nvme_host_details):
541 create_flag = False
542 if nvme_host_params['state'] == 'present' and not nvme_host_details:
543 nvme_host_details = nvme_host_obj.create_nvme_host(nvme_host_params)
544 nvme_host_obj.result['changed'] = True
545 create_flag = True
546
547 NVMeHostModifyHandler().handle(nvme_host_obj, nvme_host_params, nvme_host_details, create_flag)
548
549
550 class NVMeHostHandler():
551 def handle(self, nvme_host_obj, nvme_host_params):
552 nvme_host_obj.validate_parameters(nvme_host_params=nvme_host_params)
553 nvme_host_details = nvme_host_obj.get_nvme_host(nvme_host_name=nvme_host_params['nvme_host_name'],
554 nqn=nvme_host_params['nqn'])
555 NVMeHostCreateHandler().handle(nvme_host_obj, nvme_host_params, nvme_host_details)
556
557
558 def main():
559 """Create PowerFlex NVMe host and perform actions on it
560 based on user input from playbook"""
561 obj = PowerFlexNVMeHost()
562 NVMeHostHandler().handle(obj, obj.module.params)
563
564
565 if __name__ == "__main__":
566 main()