Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_dpdk_cpus.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import absolute_import, division, print_function
3
4 # Copyright: (c) 2022 Fortinet
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {
15 "status": ["preview"],
16 "supported_by": "community",
17 "metadata_version": "1.1",
18 }
19
20 DOCUMENTATION = """
21 ---
22 module: fortios_dpdk_cpus
23 short_description: Configure CPUs enabled to run engines in each DPDK stage in Fortinet's FortiOS and FortiGate.
24 description:
25 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
26 user to set and modify dpdk feature and cpus category.
27 Examples include all parameters and values need to be adjusted to datasources before usage.
28 Tested with FOS v6.0.0
29 version_added: "2.0.0"
30 author:
31 - Link Zheng (@chillancezen)
32 - Jie Xue (@JieX19)
33 - Hongbin Lu (@fgtdev-hblu)
34 - Frank Shen (@frankshen01)
35 - Miguel Angel Munoz (@mamunozgonzalez)
36 - Nicolas Thomas (@thomnico)
37 notes:
38 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
39
40 - The module supports check_mode.
41
42 requirements:
43 - ansible>=2.16
44 options:
45 access_token:
46 description:
47 - Token-based authentication.
48 Generated from GUI of Fortigate.
49 type: str
50 required: false
51 enable_log:
52 description:
53 - Enable/Disable logging for task.
54 type: bool
55 required: false
56 default: false
57 vdom:
58 description:
59 - Virtual domain, among those defined previously. A vdom is a
60 virtual instance of the FortiGate that can be configured and
61 used as a different unit.
62 type: str
63 default: root
64 member_path:
65 type: str
66 description:
67 - Member attribute path to operate on.
68 - Delimited by a slash character if there are more than one attribute.
69 - Parameter marked with member_path is legitimate for doing member operation.
70 member_state:
71 type: str
72 description:
73 - Add or delete a member under specified attribute path.
74 - When member_state is specified, the state option is ignored.
75 choices:
76 - 'present'
77 - 'absent'
78
79 dpdk_cpus:
80 description:
81 - Configure CPUs enabled to run engines in each DPDK stage.
82 default: null
83 type: dict
84 suboptions:
85 ips_cpus:
86 description:
87 - CPUs enabled to run DPDK IPS engines.
88 type: str
89 isolated_cpus:
90 description:
91 - CPUs isolated to run only the DPDK engines with the exception of processes that have affinity explicitly set by either a user
92 configuration or by their implementation.
93 type: str
94 rx_cpus:
95 description:
96 - CPUs enabled to run DPDK RX engines.
97 type: str
98 tx_cpus:
99 description:
100 - CPUs enabled to run DPDK TX engines.
101 type: str
102 vnp_cpus:
103 description:
104 - CPUs enabled to run DPDK VNP engines.
105 type: str
106 vnpsp_cpus:
107 description:
108 - CPUs enabled to run DPDK VNP slow path.
109 type: str
110 """
111
112 EXAMPLES = """
113 - name: Configure CPUs enabled to run engines in each DPDK stage.
114 fortinet.fortios.fortios_dpdk_cpus:
115 vdom: "{{ vdom }}"
116 dpdk_cpus:
117 ips_cpus: "<your_own_value>"
118 isolated_cpus: "<your_own_value>"
119 rx_cpus: "<your_own_value>"
120 tx_cpus: "<your_own_value>"
121 vnp_cpus: "<your_own_value>"
122 vnpsp_cpus: "<your_own_value>"
123 """
124
125 RETURN = """
126 build:
127 description: Build number of the fortigate image
128 returned: always
129 type: str
130 sample: '1547'
131 http_method:
132 description: Last method used to provision the content into FortiGate
133 returned: always
134 type: str
135 sample: 'PUT'
136 http_status:
137 description: Last result given by FortiGate on last operation applied
138 returned: always
139 type: str
140 sample: "200"
141 mkey:
142 description: Master key (id) used in the last call to FortiGate
143 returned: success
144 type: str
145 sample: "id"
146 name:
147 description: Name of the table used to fulfill the request
148 returned: always
149 type: str
150 sample: "urlfilter"
151 path:
152 description: Path of the table used to fulfill the request
153 returned: always
154 type: str
155 sample: "webfilter"
156 revision:
157 description: Internal revision number
158 returned: always
159 type: str
160 sample: "17.0.2.10658"
161 serial:
162 description: Serial number of the unit
163 returned: always
164 type: str
165 sample: "FGVMEVYYQT3AB5352"
166 status:
167 description: Indication of the operation's result
168 returned: always
169 type: str
170 sample: "success"
171 vdom:
172 description: Virtual domain used
173 returned: always
174 type: str
175 sample: "root"
176 version:
177 description: Version of the FortiGate
178 returned: always
179 type: str
180 sample: "v5.6.3"
181 """
182 from ansible.module_utils.basic import AnsibleModule
183 from ansible.module_utils.connection import Connection
184 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
185 FortiOSHandler,
186 )
187 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
188 check_legacy_fortiosapi,
189 )
190 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
191 schema_to_module_spec,
192 )
193 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
194 check_schema_versioning,
195 )
196 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
197 FAIL_SOCKET_MSG,
198 )
199 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
200 remove_invalid_fields,
201 )
202 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
203 is_same_comparison,
204 )
205 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
206 serialize,
207 )
208 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
209 find_current_values,
210 )
211 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
212 unify_data_format,
213 )
214
215
216 def filter_dpdk_cpus_data(json):
217 option_list = [
218 "ips_cpus",
219 "isolated_cpus",
220 "rx_cpus",
221 "tx_cpus",
222 "vnp_cpus",
223 "vnpsp_cpus",
224 ]
225
226 json = remove_invalid_fields(json)
227 dictionary = {}
228
229 for attribute in option_list:
230 if attribute in json and json[attribute] is not None:
231 dictionary[attribute] = json[attribute]
232
233 return dictionary
234
235
236 def underscore_to_hyphen(data):
237 new_data = None
238 if isinstance(data, list):
239 new_data = []
240 for i, elem in enumerate(data):
241 new_data.append(underscore_to_hyphen(elem))
242 elif isinstance(data, dict):
243 new_data = {}
244 for k, v in data.items():
245 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
246 else:
247 return data
248 return new_data
249
250
251 def dpdk_cpus(data, fos, check_mode=False):
252
253 state = None
254 vdom = data["vdom"]
255 parameters = None
256 state = data.get("state", None)
257 dpdk_cpus_data = data["dpdk_cpus"]
258
259 filtered_data = filter_dpdk_cpus_data(dpdk_cpus_data)
260 converted_data = underscore_to_hyphen(filtered_data)
261
262 # check_mode starts from here
263 if check_mode:
264 diff = {
265 "before": "",
266 "after": filtered_data,
267 }
268 mkeyname = fos.get_mkeyname(None, None)
269 mkey = fos.get_mkey("dpdk", "cpus", filtered_data, vdom=vdom)
270 current_data = fos.get(
271 "dpdk", "cpus", vdom=vdom, mkey=mkey, parameters=parameters
272 )
273 is_existed = (
274 current_data
275 and current_data.get("http_status") == 200
276 and (
277 mkeyname
278 and isinstance(current_data.get("results"), list)
279 and len(current_data["results"]) > 0
280 or not mkeyname
281 and current_data["results"] # global object response
282 )
283 )
284
285 # 2. if it exists and the state is 'present' then compare current settings with desired
286 if state == "present" or state is True or state is None:
287 # for non global modules, mkeyname must exist and it's a new module when mkey is None
288 if mkeyname is not None and mkey is None:
289 return False, True, filtered_data, diff
290
291 # if mkey exists then compare each other
292 # record exits and they're matched or not
293 copied_filtered_data = filtered_data.copy()
294 copied_filtered_data.pop(mkeyname, None)
295 unified_filtered_data = unify_data_format(copied_filtered_data)
296
297 current_data_results = current_data.get("results", {})
298 current_config = (
299 current_data_results[0]
300 if mkeyname
301 and isinstance(current_data_results, list)
302 and len(current_data_results) > 0
303 else current_data_results
304 )
305 if is_existed:
306 unified_current_values = find_current_values(
307 unified_filtered_data,
308 unify_data_format(current_config),
309 )
310
311 is_same = is_same_comparison(
312 serialize(unified_current_values), serialize(unified_filtered_data)
313 )
314
315 return (
316 False,
317 not is_same,
318 filtered_data,
319 {"before": unified_current_values, "after": unified_filtered_data},
320 )
321
322 # record does not exist
323 return False, True, filtered_data, diff
324
325 if state == "absent":
326 if mkey is None:
327 return (
328 False,
329 False,
330 filtered_data,
331 {"before": current_data["results"][0], "after": ""},
332 )
333
334 if is_existed:
335 return (
336 False,
337 True,
338 filtered_data,
339 {"before": current_data["results"][0], "after": ""},
340 )
341 return False, False, filtered_data, {}
342
343 return True, False, {"reason: ": "Must provide state parameter"}, {}
344 # pass post processed data to member operations
345 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
346 data_copy = data.copy()
347 data_copy["dpdk_cpus"] = filtered_data
348 fos.do_member_operation(
349 "dpdk",
350 "cpus",
351 data_copy,
352 )
353
354 return fos.set(
355 "dpdk", "cpus", data=converted_data, vdom=vdom, parameters=parameters
356 )
357
358
359 def is_successful_status(resp):
360 return (
361 "status" in resp
362 and resp["status"] == "success"
363 or "http_status" in resp
364 and resp["http_status"] == 200
365 or "http_method" in resp
366 and resp["http_method"] == "DELETE"
367 and resp["http_status"] == 404
368 )
369
370
371 def fortios_dpdk(data, fos, check_mode):
372
373 if data["dpdk_cpus"]:
374 resp = dpdk_cpus(data, fos, check_mode)
375 else:
376 fos._module.fail_json(msg="missing task body: %s" % ("dpdk_cpus"))
377 if isinstance(resp, tuple) and len(resp) == 4:
378 return resp
379 return (
380 not is_successful_status(resp),
381 is_successful_status(resp)
382 and (resp["revision_changed"] if "revision_changed" in resp else True),
383 resp,
384 {},
385 )
386
387
388 versioned_schema = {
389 "v_range": [["v7.0.0", "v7.0.12"], ["v7.2.1", "v7.2.2"], ["v7.4.0", "v7.6.1"]],
390 "type": "dict",
391 "children": {
392 "rx_cpus": {
393 "v_range": [
394 ["v7.0.0", "v7.0.12"],
395 ["v7.2.1", "v7.2.2"],
396 ["v7.4.0", "v7.6.1"],
397 ],
398 "type": "string",
399 },
400 "vnp_cpus": {
401 "v_range": [
402 ["v7.0.0", "v7.0.12"],
403 ["v7.2.1", "v7.2.2"],
404 ["v7.4.0", "v7.6.1"],
405 ],
406 "type": "string",
407 },
408 "vnpsp_cpus": {"v_range": [["v7.4.2", "v7.6.1"]], "type": "string"},
409 "ips_cpus": {
410 "v_range": [
411 ["v7.0.0", "v7.0.12"],
412 ["v7.2.1", "v7.2.2"],
413 ["v7.4.0", "v7.6.1"],
414 ],
415 "type": "string",
416 },
417 "tx_cpus": {
418 "v_range": [
419 ["v7.0.0", "v7.0.12"],
420 ["v7.2.1", "v7.2.2"],
421 ["v7.4.0", "v7.6.1"],
422 ],
423 "type": "string",
424 },
425 "isolated_cpus": {
426 "v_range": [
427 ["v7.0.2", "v7.0.12"],
428 ["v7.2.1", "v7.2.2"],
429 ["v7.4.0", "v7.6.1"],
430 ],
431 "type": "string",
432 },
433 },
434 }
435
436
437 def main():
438 module_spec = schema_to_module_spec(versioned_schema)
439 mkeyname = None
440 fields = {
441 "access_token": {"required": False, "type": "str", "no_log": True},
442 "enable_log": {"required": False, "type": "bool", "default": False},
443 "vdom": {"required": False, "type": "str", "default": "root"},
444 "member_path": {"required": False, "type": "str"},
445 "member_state": {
446 "type": "str",
447 "required": False,
448 "choices": ["present", "absent"],
449 },
450 "dpdk_cpus": {
451 "required": False,
452 "type": "dict",
453 "default": None,
454 "options": {},
455 },
456 }
457 for attribute_name in module_spec["options"]:
458 fields["dpdk_cpus"]["options"][attribute_name] = module_spec["options"][
459 attribute_name
460 ]
461 if mkeyname and mkeyname == attribute_name:
462 fields["dpdk_cpus"]["options"][attribute_name]["required"] = True
463
464 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
465 check_legacy_fortiosapi(module)
466
467 is_error = False
468 has_changed = False
469 result = None
470 diff = None
471
472 versions_check_result = None
473 if module._socket_path:
474 connection = Connection(module._socket_path)
475 if "access_token" in module.params:
476 connection.set_custom_option("access_token", module.params["access_token"])
477
478 if "enable_log" in module.params:
479 connection.set_custom_option("enable_log", module.params["enable_log"])
480 else:
481 connection.set_custom_option("enable_log", False)
482 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
483 versions_check_result = check_schema_versioning(
484 fos, versioned_schema, "dpdk_cpus"
485 )
486
487 is_error, has_changed, result, diff = fortios_dpdk(
488 module.params, fos, module.check_mode
489 )
490
491 else:
492 module.fail_json(**FAIL_SOCKET_MSG)
493
494 if versions_check_result and versions_check_result["matched"] is False:
495 module.warn(
496 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
497 )
498
499 if not is_error:
500 if versions_check_result and versions_check_result["matched"] is False:
501 module.exit_json(
502 changed=has_changed,
503 version_check_warning=versions_check_result,
504 meta=result,
505 diff=diff,
506 )
507 else:
508 module.exit_json(changed=has_changed, meta=result, diff=diff)
509 else:
510 if versions_check_result and versions_check_result["matched"] is False:
511 module.fail_json(
512 msg="Error in repo",
513 version_check_warning=versions_check_result,
514 meta=result,
515 )
516 else:
517 module.fail_json(msg="Error in repo", meta=result)
518
519
520 if __name__ == "__main__":
521 main()