Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/module_utils/fortimanager/common.py

raw symbols SCIP
1 # Copyright (c) 2022 Fortinet
2 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8
9 from __future__ import (absolute_import, division, print_function)
10 __metaclass__ = type
11
12
13 # BEGIN STATIC DATA / MESSAGES
14 class FMGRMethods:
15 GET = "get"
16 SET = "set"
17 EXEC = "exec"
18 EXECUTE = "exec"
19 UPDATE = "update"
20 ADD = "add"
21 DELETE = "delete"
22 REPLACE = "replace"
23 CLONE = "clone"
24 MOVE = "move"
25
26
27 BASE_HEADERS = {
28 'Content-Type': 'application/json',
29 'Accept': 'application/json'
30 }
31
32
33 # FMGR RETURN CODES
34 FMGR_RC = {
35 "fmgr_return_codes": {
36 0: {
37 "msg": "OK",
38 "changed": True,
39 "stop_on_success": True
40 },
41 -100000: {
42 "msg": "Module returned without actually running anything. "
43 "Check parameters, and please contact the authors if needed.",
44 "failed": True
45 },
46 -2: {
47 "msg": "Object already exists.",
48 "skipped": True,
49 "changed": False,
50 "good_codes": [0, -2]
51 },
52 -6: {
53 "msg": "Invalid Url. Sometimes this can happen because the path is mapped to a hostname or object that"
54 " doesn't exist. Double check your input object parameters."
55 },
56 -3: {
57 "msg": "Object doesn't exist.",
58 "skipped": True,
59 "changed": False,
60 "good_codes": [0, -3]
61 },
62 -10131: {
63 "msg": "Object dependency failed. Do all named objects in parameters exist?",
64 "changed": False,
65 "skipped": True
66 },
67 -9998: {
68 "msg": "Duplicate object. Try using mode='set', if using add. STOPPING. Use 'ignore_errors=yes' in playbook"
69 "to override and mark successful.",
70 },
71 -20042: {
72 "msg": "Device Unreachable.",
73 "skipped": True
74 },
75 -10033: {
76 "msg": "Duplicate object. Try using mode='set', if using add.",
77 "changed": False,
78 "skipped": True
79 },
80 -10000: {
81 "msg": "Duplicate object. Try using mode='set', if using add.",
82 "changed": False,
83 "skipped": True
84 },
85 -20010: {
86 "msg": "Device already added to FortiManager. Serial number already in use.",
87 "good_codes": [0, -20010],
88 "changed": False,
89 "stop_on_success": True
90 },
91 -20002: {
92 "msg": "Invalid Argument -- Does this Device exist on FortiManager?",
93 "changed": False,
94 "skipped": True,
95 }
96 }
97 }
98
99 DEFAULT_RESULT_OBJ = (-100000, {"msg": "Nothing Happened. Check that handle_response is being called!"})
100 FAIL_SOCKET_MSG = {"msg": "Socket Path Empty! The persistent connection manager is messed up. "
101 "Try again in a few moments."}
102
103
104 # BEGIN ERROR EXCEPTIONS
105 class FMGBaseException(Exception):
106 """Wrapper to catch the unexpected"""
107
108 def __init__(self, msg=None, *args, **kwargs):
109 if msg is None:
110 msg = "An exception occurred within the fortimanager.py httpapi connection plugin."
111 super(FMGBaseException, self).__init__(msg, *args)
112
113 # END ERROR CLASSES
114
115
116 # BEGIN CLASSES
117 class FMGRCommon(object):
118
119 @staticmethod
120 def format_request(method, url, *args, **kwargs):
121 """
122 Formats the payload from the module, into a payload the API handler can use.
123
124 :param url: Connection URL to access
125 :type url: string
126 :param method: The preferred API Request method (GET, ADD, POST, etc....)
127 :type method: basestring
128 :param kwargs: The payload dictionary from the module to be converted.
129
130 :return: Properly formatted dictionary payload for API Request via Connection Plugin.
131 :rtype: dict
132 """
133
134 params = [{"url": url}]
135 if args:
136 for arg in args:
137 params[0].update(arg)
138 if kwargs:
139 keylist = list(kwargs)
140 for k in keylist:
141 kwargs[k.replace("__", "-")] = kwargs.pop(k)
142 if method == "get" or method == "clone":
143 params[0].update(kwargs)
144 else:
145 if kwargs.get("data", False):
146 params[0]["data"] = kwargs["data"]
147 else:
148 params[0]["data"] = kwargs
149 return params
150
151 @staticmethod
152 def split_comma_strings_into_lists(obj):
153 """
154 Splits a CSV String into a list. Also takes a dictionary, and converts any CSV strings in any key, to a list.
155
156 :param obj: object in CSV format to be parsed.
157 :type obj: str or dict
158
159 :return: A list containing the CSV items.
160 :rtype: list
161 """
162 return_obj = ()
163 if isinstance(obj, dict):
164 if len(obj) > 0:
165 for k, v in obj.items():
166 if isinstance(v, str):
167 new_list = list()
168 if "," in v:
169 new_items = v.split(",")
170 for item in new_items:
171 new_list.append(item.strip())
172 obj[k] = new_list
173 return_obj = obj
174 elif isinstance(obj, str):
175 return_obj = obj.replace(" ", "").split(",")
176
177 return return_obj
178
179 @staticmethod
180 def cidr_to_netmask(cidr):
181 """
182 Converts a CIDR Network string to full blown IP/Subnet format in decimal format.
183 Decided not use IP Address module to keep includes to a minimum.
184
185 :param cidr: String object in CIDR format to be processed
186 :type cidr: str
187
188 :return: A string object that looks like this "x.x.x.x/y.y.y.y"
189 :rtype: str
190 """
191 if isinstance(cidr, str):
192 cidr = int(cidr)
193 mask = (0xffffffff >> (32 - cidr)) << (32 - cidr)
194 return (str((0xff000000 & mask) >> 24) + '.'
195 + str((0x00ff0000 & mask) >> 16) + '.'
196 + str((0x0000ff00 & mask) >> 8) + '.'
197 + str((0x000000ff & mask)))
198
199 @staticmethod
200 def paramgram_child_list_override(list_overrides, paramgram, module):
201 """
202 If a list of items was provided to a "parent" paramgram attribute, the paramgram needs to be rewritten.
203 The child keys of the desired attribute need to be deleted, and then that "parent" keys' contents is replaced
204 With the list of items that was provided.
205
206 :param list_overrides: Contains the response from the FortiManager.
207 :type list_overrides: list
208 :param paramgram: Contains the paramgram passed to the modules' local modify function.
209 :type paramgram: dict
210 :param module: Contains the Ansible Module Object being used by the module.
211 :type module: classObject
212
213 :return: A new "paramgram" refactored to allow for multiple entries being added.
214 :rtype: dict
215 """
216 if len(list_overrides) > 0:
217 for list_variable in list_overrides:
218 try:
219 list_variable = list_variable.replace("-", "_")
220 override_data = module.params[list_variable]
221 if override_data:
222 del paramgram[list_variable]
223 paramgram[list_variable] = override_data
224 except BaseException as e:
225 raise FMGBaseException("Error occurred merging custom lists for the paramgram parent: " + str(e))
226 return paramgram
227
228 @staticmethod
229 def syslog(module, msg):
230 try:
231 module.log(msg=msg)
232 except BaseException:
233 pass
234
235
236 # RECURSIVE FUNCTIONS START
237 def prepare_dict(obj):
238 """
239 Removes any keys from a dictionary that are only specific to our use in the module. FortiManager will reject
240 requests with these empty/None keys in it.
241
242 :param obj: Dictionary object to be processed.
243 :type obj: dict
244
245 :return: Processed dictionary.
246 :rtype: dict
247 """
248
249 list_of_elems = ["mode", "adom", "host", "username", "password"]
250
251 if isinstance(obj, dict):
252 obj = dict((key, prepare_dict(value)) for (key, value) in obj.items() if key not in list_of_elems)
253 return obj
254
255
256 def scrub_dict(obj):
257 """
258 Removes any keys from a dictionary that are EMPTY -- this includes parent keys. FortiManager doesn't
259 like empty keys in dictionaries
260
261 :param obj: Dictionary object to be processed.
262 :type obj: dict
263
264 :return: Processed dictionary.
265 :rtype: dict
266 """
267
268 if isinstance(obj, dict):
269 return dict((k, scrub_dict(v)) for k, v in obj.items() if v and scrub_dict(v))
270 else:
271 return obj