Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_profile_udp.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_profile_udp
13 short_description: Manage UDP profiles on a BIG-IP
14 description:
15 - Manage UDP profiles on a BIG-IP system. There are many UDP profiles, each with their
16 own adjustments to the standard C(udp) profile. Users of this module should be aware
17 that many of the available options have no module default. Instead, the default is
18 assigned by the BIG-IP system itself which, in most cases, is acceptable.
19 version_added: "1.0.0"
20 options:
21 name:
22 description:
23 - Specifies the name of the profile.
24 type: str
25 required: True
26 parent:
27 description:
28 - Specifies the profile from which this profile inherits settings.
29 - When creating a new profile, if this parameter is not specified, the default
30 is the system-supplied C(udp) profile.
31 type: str
32 idle_timeout:
33 description:
34 - Specifies the length of time a connection is idle (has no traffic) before
35 the connection is eligible for deletion.
36 - When creating a new profile, if this parameter is not specified, the remote
37 device will choose a default value appropriate for the profile, based on its
38 C(parent) profile.
39 - When a number is specified, indicates the number of seconds the UDP
40 connection can remain idle before the system deletes it.
41 - When C(indefinite), specifies UDP connections can remain idle
42 indefinitely.
43 - When C(0) or C(immediate), specifies you do not want the UDP connection to
44 remain idle, and it is therefore immediately eligible for deletion.
45 type: str
46 datagram_load_balancing:
47 description:
48 - When C(true), specifies the system load balances UDP traffic
49 packet-by-packet.
50 type: bool
51 partition:
52 description:
53 - Device partition to manage resources on.
54 type: str
55 default: Common
56 state:
57 description:
58 - When C(present), ensures the profile exists.
59 - When C(absent), ensures the profile is removed.
60 type: str
61 choices:
62 - present
63 - absent
64 default: present
65 extends_documentation_fragment: f5networks.f5_modules.f5
66 author:
67 - Tim Rupp (@caphrim007)
68 '''
69
70 EXAMPLES = r'''
71 - name: Create a TCP profile
72 bigip_profile_tcp:
73 name: foo
74 parent: udp
75 idle_timeout: 300
76 datagram_load_balancing: false
77 state: present
78 provider:
79 user: admin
80 password: secret
81 server: lb.mydomain.com
82 delegate_to: localhost
83 '''
84
85 RETURN = r'''
86 parent:
87 description: The new parent of the resource.
88 returned: changed
89 type: str
90 sample: udp
91 idle_timeout:
92 description: The new idle timeout of the resource.
93 returned: changed
94 type: int
95 sample: 100
96 datagram_load_balancing:
97 description: The new datagram load balancing setting of the resource.
98 returned: changed
99 type: bool
100 sample: true
101 '''
102 from datetime import datetime
103
104 from ansible.module_utils.basic import (
105 AnsibleModule, env_fallback
106 )
107
108 from ..module_utils.bigip import F5RestClient
109 from ..module_utils.common import (
110 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
111 )
112 from ..module_utils.icontrol import tmos_version
113 from ..module_utils.teem import send_teem
114
115
116 class Parameters(AnsibleF5Parameters):
117 api_map = {
118 'datagramLoadBalancing': 'datagram_load_balancing',
119 'idleTimeout': 'idle_timeout',
120 'defaultsFrom': 'parent',
121 }
122
123 api_attributes = [
124 'datagramLoadBalancing',
125 'idleTimeout',
126 'defaultsFrom',
127 ]
128
129 returnables = [
130 'datagram_load_balancing',
131 'idle_timeout',
132 'parent',
133 ]
134
135 updatables = [
136 'datagram_load_balancing',
137 'idle_timeout',
138 'parent',
139 ]
140
141 @property
142 def idle_timeout(self):
143 if self._values['idle_timeout'] is None:
144 return None
145 if self._values['idle_timeout'] == 'indefinite':
146 return self._values['idle_timeout']
147 if self._values['idle_timeout'] in ['0', 'immediate']:
148 return 'immediate'
149 return int(self._values['idle_timeout'])
150
151
152 class ApiParameters(Parameters):
153 @property
154 def datagram_load_balancing(self):
155 if self._values['datagram_load_balancing'] is None:
156 return None
157 if self._values['datagram_load_balancing'] == 'enabled':
158 return True
159 return False
160
161
162 class ModuleParameters(Parameters):
163 @property
164 def parent(self):
165 if self._values['parent'] is None:
166 return None
167 result = fq_name(self.partition, self._values['parent'])
168 return result
169
170
171 class Changes(Parameters):
172 def to_return(self):
173 result = {}
174 try:
175 for returnable in self.returnables:
176 result[returnable] = getattr(self, returnable)
177 result = self._filter_params(result)
178 except Exception:
179 pass
180 return result
181
182
183 class UsableChanges(Changes):
184 @property
185 def datagram_load_balancing(self):
186 if self._values['datagram_load_balancing'] is None:
187 return None
188 if self._values['datagram_load_balancing']:
189 return 'enabled'
190 return 'disabled'
191
192
193 class ReportableChanges(Changes):
194 @property
195 def datagram_load_balancing(self):
196 if self._values['datagram_load_balancing'] is None:
197 return None
198 if self._values['datagram_load_balancing'] == 'enabled':
199 return True
200 return False
201
202
203 class Difference(object):
204 def __init__(self, want, have=None):
205 self.want = want
206 self.have = have
207
208 def compare(self, param):
209 try:
210 result = getattr(self, param)
211 return result
212 except AttributeError:
213 return self.__default(param)
214
215 def __default(self, param):
216 attr1 = getattr(self.want, param)
217 try:
218 attr2 = getattr(self.have, param)
219 if attr1 != attr2:
220 return attr1
221 except AttributeError:
222 return attr1
223
224
225 class ModuleManager(object):
226 def __init__(self, *args, **kwargs):
227 self.module = kwargs.get('module', None)
228 self.client = F5RestClient(**self.module.params)
229 self.want = ModuleParameters(params=self.module.params)
230 self.have = ApiParameters()
231 self.changes = UsableChanges()
232
233 def _set_changed_options(self):
234 changed = {}
235 for key in Parameters.returnables:
236 if getattr(self.want, key) is not None:
237 changed[key] = getattr(self.want, key)
238 if changed:
239 self.changes = UsableChanges(params=changed)
240
241 def _update_changed_options(self):
242 diff = Difference(self.want, self.have)
243 updatables = Parameters.updatables
244 changed = dict()
245 for k in updatables:
246 change = diff.compare(k)
247 if change is None:
248 continue
249 else:
250 if isinstance(change, dict):
251 changed.update(change)
252 else:
253 changed[k] = change
254 if changed:
255 self.changes = UsableChanges(params=changed)
256 return True
257 return False
258
259 def should_update(self):
260 result = self._update_changed_options()
261 if result:
262 return True
263 return False
264
265 def exec_module(self):
266 start = datetime.now().isoformat()
267 version = tmos_version(self.client)
268 changed = False
269 result = dict()
270 state = self.want.state
271
272 if state == "present":
273 changed = self.present()
274 elif state == "absent":
275 changed = self.absent()
276
277 reportable = ReportableChanges(params=self.changes.to_return())
278 changes = reportable.to_return()
279 result.update(**changes)
280 result.update(dict(changed=changed))
281 self._announce_deprecations(result)
282 send_teem(start, self.client, self.module, version)
283 return result
284
285 def _announce_deprecations(self, result):
286 warnings = result.pop('__warnings', [])
287 for warning in warnings:
288 self.client.module.deprecate(
289 msg=warning['msg'],
290 version=warning['version']
291 )
292
293 def present(self):
294 if self.exists():
295 return self.update()
296 else:
297 return self.create()
298
299 def exists(self):
300 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/udp/{2}".format(
301 self.client.provider['server'],
302 self.client.provider['server_port'],
303 transform_name(self.want.partition, self.want.name)
304 )
305 resp = self.client.api.get(uri)
306 try:
307 response = resp.json()
308 except ValueError as ex:
309 raise F5ModuleError(str(ex))
310
311 if resp.status == 404 or 'code' in response and response['code'] == 404:
312 return False
313 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
314 return True
315
316 errors = [401, 403, 409, 500, 501, 502, 503, 504]
317
318 if resp.status in errors or 'code' in response and response['code'] in errors:
319 if 'message' in response:
320 raise F5ModuleError(response['message'])
321 else:
322 raise F5ModuleError(resp.content)
323
324 def update(self):
325 self.have = self.read_current_from_device()
326 if not self.should_update():
327 return False
328 if self.module.check_mode:
329 return True
330 self.update_on_device()
331 return True
332
333 def remove(self):
334 if self.module.check_mode:
335 return True
336 self.remove_from_device()
337 if self.exists():
338 raise F5ModuleError("Failed to delete the resource.")
339 return True
340
341 def create(self):
342 self._set_changed_options()
343 if self.module.check_mode:
344 return True
345 self.create_on_device()
346 return True
347
348 def create_on_device(self):
349 params = self.changes.api_params()
350 params['name'] = self.want.name
351 params['partition'] = self.want.partition
352 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/udp/".format(
353 self.client.provider['server'],
354 self.client.provider['server_port']
355 )
356 resp = self.client.api.post(uri, json=params)
357 try:
358 response = resp.json()
359 except ValueError as ex:
360 raise F5ModuleError(str(ex))
361
362 if 'code' in response and response['code'] in [400, 403, 404]:
363 if 'message' in response:
364 raise F5ModuleError(response['message'])
365 else:
366 raise F5ModuleError(resp.content)
367 return response['selfLink']
368
369 def update_on_device(self):
370 params = self.changes.api_params()
371 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/udp/{2}".format(
372 self.client.provider['server'],
373 self.client.provider['server_port'],
374 transform_name(self.want.partition, self.want.name)
375 )
376 resp = self.client.api.patch(uri, json=params)
377 try:
378 response = resp.json()
379 except ValueError as ex:
380 raise F5ModuleError(str(ex))
381
382 if 'code' in response and response['code'] in [400, 404]:
383 if 'message' in response:
384 raise F5ModuleError(response['message'])
385 else:
386 raise F5ModuleError(resp.content)
387
388 def absent(self):
389 if self.exists():
390 return self.remove()
391 return False
392
393 def remove_from_device(self):
394 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/udp/{2}".format(
395 self.client.provider['server'],
396 self.client.provider['server_port'],
397 transform_name(self.want.partition, self.want.name)
398 )
399 response = self.client.api.delete(uri)
400 if response.status == 200:
401 return True
402 raise F5ModuleError(response.content)
403
404 def read_current_from_device(self):
405 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/udp/{2}".format(
406 self.client.provider['server'],
407 self.client.provider['server_port'],
408 transform_name(self.want.partition, self.want.name)
409 )
410 resp = self.client.api.get(uri)
411 try:
412 response = resp.json()
413 except ValueError as ex:
414 raise F5ModuleError(str(ex))
415
416 if 'code' in response and response['code'] == 400:
417 if 'message' in response:
418 raise F5ModuleError(response['message'])
419 else:
420 raise F5ModuleError(resp.content)
421 return ApiParameters(params=response)
422
423
424 class ArgumentSpec(object):
425 def __init__(self):
426 self.supports_check_mode = True
427 argument_spec = dict(
428 name=dict(required=True),
429 parent=dict(),
430 idle_timeout=dict(),
431 datagram_load_balancing=dict(type='bool'),
432 state=dict(
433 default='present',
434 choices=['present', 'absent']
435 ),
436 partition=dict(
437 default='Common',
438 fallback=(env_fallback, ['F5_PARTITION'])
439 )
440 )
441 self.argument_spec = {}
442 self.argument_spec.update(f5_argument_spec)
443 self.argument_spec.update(argument_spec)
444
445
446 def main():
447 spec = ArgumentSpec()
448
449 module = AnsibleModule(
450 argument_spec=spec.argument_spec,
451 supports_check_mode=spec.supports_check_mode,
452 )
453
454 try:
455 mm = ModuleManager(module=module)
456 results = mm.exec_module()
457 module.exit_json(**results)
458 except F5ModuleError as ex:
459 module.fail_json(msg=str(ex))
460
461
462 if __name__ == '__main__':
463 main()