Debian Codegraph @

ansible_collections/community/general/plugins/modules/pmem.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2022, Masayoshi Mizuma <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 author:
10 - Masayoshi Mizuma (@mizumm)
11 module: pmem
12 short_description: Configure Intel Optane Persistent Memory modules
13 version_added: 4.5.0
14 description:
15 - This module allows Configuring Intel Optane Persistent Memory modules (PMem) using C(ipmctl) and C(ndctl) command line
16 tools.
17 requirements:
18 - C(ipmctl) and C(ndctl) command line tools
19 - xmltodict
20 extends_documentation_fragment:
21 - community.general._attributes
22 attributes:
23 check_mode:
24 support: none
25 diff_mode:
26 support: none
27 options:
28 appdirect:
29 description:
30 - Percentage of the total capacity to use in AppDirect Mode (V(0)-V(100)).
31 - Create AppDirect capacity utilizing hardware interleaving across the requested PMem modules if applicable given the
32 specified target.
33 - Total of O(appdirect), O(memorymode) and O(reserved) must be V(100).
34 type: int
35 appdirect_interleaved:
36 description:
37 - Create AppDirect capacity that is interleaved any other PMem modules.
38 type: bool
39 default: true
40 memorymode:
41 description:
42 - Percentage of the total capacity to use in Memory Mode (V(0)-V(100)).
43 type: int
44 reserved:
45 description:
46 - Percentage of the capacity to reserve (V(0)-V(100)). O(reserved) is not mapped into the system physical address space
47 and is presented as reserved capacity with Show Device and Show Memory Resources Commands.
48 - O(reserved) is set automatically if this is not configured.
49 type: int
50 socket:
51 description:
52 - This enables to set the configuration for each socket by using the socket ID.
53 - Total of O(appdirect), O(memorymode) and O(reserved) must be V(100) within one socket.
54 type: list
55 elements: dict
56 suboptions:
57 id:
58 description: The socket ID of the PMem module.
59 type: int
60 required: true
61 appdirect:
62 description:
63 - Percentage of the total capacity to use in AppDirect Mode (V(0)-V(100)) within the socket ID.
64 type: int
65 required: true
66 appdirect_interleaved:
67 description:
68 - Create AppDirect capacity that is interleaved any other PMem modules within the socket ID.
69 type: bool
70 default: true
71 memorymode:
72 description:
73 - Percentage of the total capacity to use in Memory Mode (V(0)-V(100)) within the socket ID.
74 type: int
75 required: true
76 reserved:
77 description:
78 - Percentage of the capacity to reserve (V(0)-V(100)) within the socket ID.
79 type: int
80 namespace:
81 description:
82 - This enables to set the configuration for the namespace of the PMem.
83 type: list
84 elements: dict
85 suboptions:
86 mode:
87 description:
88 - The mode of namespace. The detail of the mode is in the man page of ndctl-create-namespace.
89 type: str
90 required: true
91 choices: ['raw', 'sector', 'fsdax', 'devdax']
92 type:
93 description:
94 - The type of namespace. The detail of the type is in the man page of ndctl-create-namespace.
95 type: str
96 choices: ['pmem', 'blk']
97 size:
98 description:
99 - The size of namespace. This option supports the suffixes V(k) or V(K) or V(KB) for KiB, V(m) or V(M) or V(MB)
100 for MiB, V(g) or V(G) or V(GB) for GiB and V(t) or V(T) or V(TB) for TiB.
101 - This option is required if multiple namespaces are configured.
102 - If this option is not set, all of the available space of a region is configured.
103 type: str
104 namespace_append:
105 description:
106 - Enable to append the new namespaces to the system.
107 - The default is V(false) so the all existing namespaces not listed in O(namespace) are removed.
108 type: bool
109 default: false
110 """
111
112 RETURN = r"""
113 reboot_required:
114 description: Indicates that the system reboot is required to complete the PMem configuration.
115 returned: success
116 type: bool
117 sample: true
118 result:
119 description:
120 - Shows the value of AppDirect, Memory Mode and Reserved size in bytes.
121 - If O(socket) argument is provided, shows the values in each socket with C(socket) which contains the socket ID.
122 - If O(namespace) argument is provided, shows the detail of each namespace.
123 returned: success
124 type: list
125 elements: dict
126 contains:
127 appdirect:
128 description: AppDirect size in bytes.
129 type: int
130 memorymode:
131 description: Memory Mode size in bytes.
132 type: int
133 reserved:
134 description: Reserved size in bytes.
135 type: int
136 socket:
137 description: The socket ID to be configured.
138 type: int
139 namespace:
140 description: The list of the detail of namespace.
141 type: list
142 sample:
143 [
144 {
145 "appdirect": 111669149696,
146 "memorymode": 970662608896,
147 "reserved": 3626500096,
148 "socket": 0
149 },
150 {
151 "appdirect": 111669149696,
152 "memorymode": 970662608896,
153 "reserved": 3626500096,
154 "socket": 1
155 }
156 ]
157 """
158
159 EXAMPLES = r"""
160 - name: Configure the Pmem as AppDirect 10, Memory Mode 70, and the Reserved 20 percent.
161 community.general.pmem:
162 appdirect: 10
163 memorymode: 70
164
165 - name: Configure the Pmem as AppDirect 10, Memory Mode 80, and the Reserved 10 percent.
166 community.general.pmem:
167 appdirect: 10
168 memorymode: 80
169 reserved: 10
170
171 - name: Configure the Pmem as AppDirect with not interleaved 10, Memory Mode 70, and the Reserved 20 percent.
172 community.general.pmem:
173 appdirect: 10
174 appdirect_interleaved: false
175 memorymode: 70
176
177 - name: Configure the Pmem each socket.
178 community.general.pmem:
179 socket:
180 - id: 0
181 appdirect: 10
182 appdirect_interleaved: false
183 memorymode: 70
184 reserved: 20
185 - id: 1
186 appdirect: 10
187 memorymode: 80
188 reserved: 10
189
190 - name: Configure the two namespaces.
191 community.general.pmem:
192 namespace:
193 - size: 1GB
194 type: pmem
195 mode: raw
196 - size: 320MB
197 type: pmem
198 mode: sector
199 """
200
201 import json
202 import traceback
203
204 from ansible.module_utils.basic import AnsibleModule, human_to_bytes, missing_required_lib
205
206 XMLTODICT_LIBRARY_IMPORT_ERROR: str | None
207 try:
208 import xmltodict
209 except ImportError:
210 HAS_XMLTODICT_LIBRARY = False
211 XMLTODICT_LIBRARY_IMPORT_ERROR = traceback.format_exc()
212 else:
213 HAS_XMLTODICT_LIBRARY = True
214 XMLTODICT_LIBRARY_IMPORT_ERROR = None
215
216
217 class PersistentMemory:
218 def __init__(self):
219 module = AnsibleModule(
220 argument_spec=dict(
221 appdirect=dict(type="int"),
222 appdirect_interleaved=dict(type="bool", default=True),
223 memorymode=dict(type="int"),
224 reserved=dict(type="int"),
225 socket=dict(
226 type="list",
227 elements="dict",
228 options=dict(
229 id=dict(required=True, type="int"),
230 appdirect=dict(required=True, type="int"),
231 appdirect_interleaved=dict(type="bool", default=True),
232 memorymode=dict(required=True, type="int"),
233 reserved=dict(type="int"),
234 ),
235 ),
236 namespace=dict(
237 type="list",
238 elements="dict",
239 options=dict(
240 mode=dict(required=True, type="str", choices=["raw", "sector", "fsdax", "devdax"]),
241 type=dict(type="str", choices=["pmem", "blk"]),
242 size=dict(type="str"),
243 ),
244 ),
245 namespace_append=dict(type="bool", default=False),
246 ),
247 required_together=(["appdirect", "memorymode"],),
248 required_one_of=(["appdirect", "memorymode", "socket", "namespace"],),
249 mutually_exclusive=(
250 ["appdirect", "socket"],
251 ["memorymode", "socket"],
252 ["appdirect", "namespace"],
253 ["memorymode", "namespace"],
254 ["socket", "namespace"],
255 ["appdirect", "namespace_append"],
256 ["memorymode", "namespace_append"],
257 ["socket", "namespace_append"],
258 ),
259 )
260
261 if not HAS_XMLTODICT_LIBRARY:
262 module.fail_json(msg=missing_required_lib("xmltodict"), exception=XMLTODICT_LIBRARY_IMPORT_ERROR)
263
264 self.ipmctl_exec = module.get_bin_path("ipmctl", True)
265 self.ndctl_exec = module.get_bin_path("ndctl", True)
266
267 self.appdirect = module.params["appdirect"]
268 self.interleaved = module.params["appdirect_interleaved"]
269 self.memmode = module.params["memorymode"]
270 self.reserved = module.params["reserved"]
271 self.socket = module.params["socket"]
272 self.namespace = module.params["namespace"]
273 self.namespace_append = module.params["namespace_append"]
274
275 self.module = module
276 self.changed = False
277 self.result = []
278
279 def pmem_run_command(self, command, returnCheck=True):
280 # in case command[] has number
281 cmd = [str(part) for part in command]
282
283 self.module.log(msg=f"pmem_run_command: execute: {cmd}")
284
285 rc, out, err = self.module.run_command(cmd)
286
287 self.module.log(msg=f"pmem_run_command: result: {out}")
288
289 if returnCheck and rc != 0:
290 self.module.fail_json(msg=f"Error while running: {cmd}", rc=rc, out=out, err=err)
291
292 return out
293
294 def pmem_run_ipmctl(self, command, returnCheck=True):
295 command = [self.ipmctl_exec] + command
296
297 return self.pmem_run_command(command, returnCheck)
298
299 def pmem_run_ndctl(self, command, returnCheck=True):
300 command = [self.ndctl_exec] + command
301
302 return self.pmem_run_command(command, returnCheck)
303
304 def pmem_is_dcpmm_installed(self):
305 # To check this system has dcpmm
306 command = ["show", "-system", "-capabilities"]
307 return self.pmem_run_ipmctl(command)
308
309 def pmem_get_region_align_size(self, region):
310 aligns = []
311 for rg in region:
312 if rg["align"] not in aligns:
313 aligns.append(rg["align"])
314
315 return aligns
316
317 def pmem_get_available_region_size(self, region):
318 available_size = []
319 for rg in region:
320 available_size.append(rg["available_size"])
321
322 return available_size
323
324 def pmem_get_available_region_type(self, region):
325 types = []
326 for rg in region:
327 if rg["type"] not in types:
328 types.append(rg["type"])
329
330 return types
331
332 def pmem_argument_check(self):
333 def namespace_check(self):
334 command = ["list", "-R"]
335 out = self.pmem_run_ndctl(command)
336 if not out:
337 return "Available region(s) is not in this system."
338 region = json.loads(out)
339
340 aligns = self.pmem_get_region_align_size(region)
341 if len(aligns) != 1:
342 return "Not supported the regions whose alignment size is different."
343
344 available_size = self.pmem_get_available_region_size(region)
345 types = self.pmem_get_available_region_type(region)
346 for ns in self.namespace:
347 if ns["size"]:
348 try:
349 size_byte = human_to_bytes(ns["size"])
350 except ValueError:
351 return "The format of size: NNN TB|GB|MB|KB|T|G|M|K|B"
352
353 if size_byte % aligns[0] != 0:
354 return f"size: {ns['size']} should be align with {aligns[0]}"
355
356 is_space_enough = False
357 for i, avail in enumerate(available_size):
358 if avail > size_byte:
359 available_size[i] -= size_byte
360 is_space_enough = True
361 break
362
363 if is_space_enough is False:
364 return f"There is not available region for size: {ns['size']}"
365
366 ns["size_byte"] = size_byte
367
368 elif len(self.namespace) != 1:
369 return "size option is required to configure multiple namespaces"
370
371 if ns["type"] not in types:
372 return f"type {ns['type']} is not supported in this system. Supported type: {types}"
373
374 return None
375
376 def percent_check(self, appdirect, memmode, reserved=None):
377 if appdirect is None or (appdirect < 0 or appdirect > 100):
378 return "appdirect percent should be from 0 to 100."
379 if memmode is None or (memmode < 0 or memmode > 100):
380 return "memorymode percent should be from 0 to 100."
381
382 if reserved is None:
383 if appdirect + memmode > 100:
384 return "Total percent should be less equal 100."
385 else:
386 if reserved < 0 or reserved > 100:
387 return "reserved percent should be from 0 to 100."
388 if appdirect + memmode + reserved != 100:
389 return "Total percent should be 100."
390
391 def socket_id_check(self):
392 command = ["show", "-o", "nvmxml", "-socket"]
393 out = self.pmem_run_ipmctl(command)
394 sockets_dict = xmltodict.parse(out, dict_constructor=dict)["SocketList"]["Socket"]
395 socket_ids = []
396 for sl in sockets_dict:
397 socket_ids.append(int(sl["SocketID"], 16))
398
399 for skt in self.socket:
400 if skt["id"] not in socket_ids:
401 return f"Invalid socket number: {skt['id']}"
402
403 return None
404
405 if self.namespace:
406 return namespace_check(self)
407 elif self.socket is None:
408 return percent_check(self, self.appdirect, self.memmode, self.reserved)
409 else:
410 ret = socket_id_check(self)
411 if ret is not None:
412 return ret
413
414 for skt in self.socket:
415 ret = percent_check(self, skt["appdirect"], skt["memorymode"], skt["reserved"])
416 if ret is not None:
417 return ret
418
419 return None
420
421 def pmem_remove_namespaces(self):
422 command = ["list", "-N"]
423 out = self.pmem_run_ndctl(command)
424
425 # There's nothing namespaces in this system. Nothing to do.
426 if not out:
427 return
428
429 namespaces = json.loads(out)
430
431 # Disable and destroy all namespaces
432 for ns in namespaces:
433 command = ["disable-namespace", ns["dev"]]
434 self.pmem_run_ndctl(command)
435
436 command = ["destroy-namespace", ns["dev"]]
437 self.pmem_run_ndctl(command)
438
439 return
440
441 def pmem_delete_goal(self):
442 # delete the goal request
443 command = ["delete", "-goal"]
444 self.pmem_run_ipmctl(command)
445
446 def pmem_init_env(self):
447 if self.namespace is None or (self.namespace and self.namespace_append is False):
448 self.pmem_remove_namespaces()
449 if self.namespace is None:
450 self.pmem_delete_goal()
451
452 def pmem_get_capacity(self, skt=None):
453 command = ["show", "-d", "Capacity", "-u", "B", "-o", "nvmxml", "-dimm"]
454 if skt:
455 command += ["-socket", skt["id"]]
456 out = self.pmem_run_ipmctl(command)
457
458 dimm_list = xmltodict.parse(out, dict_constructor=dict)["DimmList"]["Dimm"]
459 capacity = 0
460 for entry in dimm_list:
461 for key, v in entry.items():
462 if key == "Capacity":
463 capacity += int(v.split()[0])
464
465 return capacity
466
467 def pmem_create_memory_allocation(self, skt=None):
468 def build_ipmctl_creation_opts(self, skt=None):
469 ipmctl_opts = []
470
471 if skt:
472 appdirect = skt["appdirect"]
473 memmode = skt["memorymode"]
474 reserved = skt["reserved"]
475 socket_id = skt["id"]
476 ipmctl_opts += ["-socket", socket_id]
477 else:
478 appdirect = self.appdirect
479 memmode = self.memmode
480 reserved = self.reserved
481
482 if reserved is None:
483 res = 100 - memmode - appdirect
484 ipmctl_opts += [f"memorymode={memmode}", f"reserved={res}"]
485 else:
486 ipmctl_opts += [f"memorymode={memmode}", f"reserved={reserved}"]
487
488 if self.interleaved:
489 ipmctl_opts += ["PersistentMemoryType=AppDirect"]
490 else:
491 ipmctl_opts += ["PersistentMemoryType=AppDirectNotInterleaved"]
492
493 return ipmctl_opts
494
495 def is_allocation_good(self, ipmctl_out, command):
496 ignore_error = "Do you want to continue? [y/n] Error: Invalid data input."
497
498 errmsg = ""
499 rc = True
500 for line in ipmctl_out.splitlines():
501 if line.startswith("WARNING"):
502 errmsg = f"{line} (command: {command})"
503 rc = False
504 break
505 elif "Error" in line:
506 if not line.startswith(ignore_error):
507 errmsg = f"{line} (command: {command})"
508 rc = False
509 break
510
511 return rc, errmsg
512
513 def get_allocation_result(self, goal, skt=None):
514 ret = {"appdirect": 0, "memorymode": 0}
515
516 if skt:
517 ret["socket"] = skt["id"]
518
519 out = xmltodict.parse(goal, dict_constructor=dict)["ConfigGoalList"]["ConfigGoal"]
520 for entry in out:
521 # Probably it is a bug of ipmctl to show the socket goal
522 # which isn't specified by the -socket option.
523 # Anyway, filter the noise out here:
524 if skt and skt["id"] != int(entry["SocketID"], 16):
525 continue
526
527 for key, v in entry.items():
528 if key == "MemorySize":
529 ret["memorymode"] += int(v.split()[0])
530 elif key == "AppDirect1Size" or key == "AapDirect2Size":
531 ret["appdirect"] += int(v.split()[0])
532
533 capacity = self.pmem_get_capacity(skt)
534 ret["reserved"] = capacity - ret["appdirect"] - ret["memorymode"]
535
536 return ret
537
538 reboot_required = False
539
540 ipmctl_opts = build_ipmctl_creation_opts(self, skt)
541
542 # First, do dry run ipmctl create command to check the error and warning.
543 command = ["create", "-goal"] + ipmctl_opts
544 out = self.pmem_run_ipmctl(command, returnCheck=False)
545 rc, errmsg = is_allocation_good(self, out, command)
546 if rc is False:
547 return reboot_required, {}, errmsg
548
549 # Run actual creation here
550 command = ["create", "-u", "B", "-o", "nvmxml", "-force", "-goal"] + ipmctl_opts
551 goal = self.pmem_run_ipmctl(command)
552 ret = get_allocation_result(self, goal, skt)
553 reboot_required = True
554
555 return reboot_required, ret, ""
556
557 def pmem_config_namespaces(self, namespace):
558 command = ["create-namespace", "-m", namespace["mode"]]
559 if namespace["type"]:
560 command += ["-t", namespace["type"]]
561 if "size_byte" in namespace:
562 command += ["-s", namespace["size_byte"]]
563
564 self.pmem_run_ndctl(command)
565
566 return None
567
568
569 def main():
570 pmem = PersistentMemory()
571
572 pmem.pmem_is_dcpmm_installed()
573
574 error = pmem.pmem_argument_check()
575 if error:
576 pmem.module.fail_json(msg=error)
577
578 pmem.pmem_init_env()
579 pmem.changed = True
580
581 if pmem.namespace:
582 for ns in pmem.namespace:
583 pmem.pmem_config_namespaces(ns)
584
585 command = ["list", "-N"]
586 out = pmem.pmem_run_ndctl(command)
587 all_ns = json.loads(out)
588
589 pmem.result = all_ns
590 reboot_required = False
591 elif pmem.socket is None:
592 reboot_required, ret, errmsg = pmem.pmem_create_memory_allocation()
593 if errmsg:
594 pmem.module.fail_json(msg=errmsg)
595 pmem.result.append(ret)
596 else:
597 for skt in pmem.socket:
598 skt_reboot_required, skt_ret, skt_errmsg = pmem.pmem_create_memory_allocation(skt)
599
600 if skt_errmsg:
601 pmem.module.fail_json(msg=skt_errmsg)
602
603 if skt_reboot_required:
604 reboot_required = True
605
606 pmem.result.append(skt_ret)
607
608 pmem.module.exit_json(changed=pmem.changed, reboot_required=reboot_required, result=pmem.result)
609
610
611 if __name__ == "__main__":
612 main()