Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_message_routing_protocol
13 short_description: Manage the generic message parser profile.
14 description:
15 - Manages the generic message parser profile for use with the message routing framework.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the generic parser profile.
21 required: True
22 type: str
23 description:
24 description:
25 - The user-defined description of the generic parser profile.
26 type: str
27 parent:
28 description:
29 - The parent template of this parser profile. Once this value has been set, it cannot be changed.
30 - When creating a new profile, if this parameter is not specified,
31 the default is the system-supplied C(genericmsg) profile.
32 type: str
33 disable_parser:
34 description:
35 - When C(true), the generic message parser is disabled, ignoring all incoming packets and not directly
36 send message data.
37 - This mode supports iRule script protocol implementations that generates messages from the incoming transport
38 stream and sends outgoing messages on the outgoing transport stream.
39 type: bool
40 max_egress_buffer:
41 description:
42 - Specifies the maximum size of the send buffer in bytes. If the number of bytes in the send buffer for a
43 connection exceeds this value, the generic message protocol will stop receiving outgoing messages from the
44 router until the size of the size of the buffer drops below this setting.
45 - The accepted range is between 0 and 4294967295 inclusive.
46 type: int
47 max_msg_size:
48 description:
49 - Specifies the maximum size of a received message. If a message exceeds this size, the connection will be reset.
50 - The accepted range is between 0 and 4294967295 inclusive.
51 type: int
52 msg_terminator:
53 description:
54 - The string of characters used to terminate a message. If the message-terminator is not specified,
55 the generic message parser will not separate the input stream into messages.
56 type: str
57 no_response:
58 description:
59 - When set, matching of responses to requests is disabled.
60 type: bool
61 partition:
62 description:
63 - Device partition to create route object on.
64 type: str
65 default: Common
66 state:
67 description:
68 - When C(present), ensures the route exists.
69 - When C(absent), ensures the route is removed.
70 type: str
71 choices:
72 - present
73 - absent
74 default: present
75 notes:
76 - Requires BIG-IP >= 14.0.0
77 extends_documentation_fragment: f5networks.f5_modules.f5
78 author:
79 - Wojciech Wypior (@wojtek0806)
80 '''
81
82 EXAMPLES = r'''
83 - name: Create a generic parser
84 bigip_message_routing_protocol:
85 name: foo
86 description: 'This is parser'
87 no_response: true
88 provider:
89 password: secret
90 server: lb.mydomain.com
91 user: admin
92 delegate_to: localhost
93
94 - name: Modify a generic parser
95 bigip_message_routing_protocol:
96 name: foo
97 no_response: false
98 max_egress_buffer: 10000
99 max_msg_size: 2000
100 provider:
101 password: secret
102 server: lb.mydomain.com
103 user: admin
104 delegate_to: localhost
105
106 - name: Remove generic parser
107 bigip_message_routing_protocol:
108 name: foo
109 state: absent
110 provider:
111 password: secret
112 server: lb.mydomain.com
113 user: admin
114 delegate_to: localhost
115 '''
116
117 RETURN = r'''
118 description:
119 description: The user-defined description of the parser profile.
120 returned: changed
121 type: str
122 sample: My description
123 parent:
124 description: The parent template of this parser profile.
125 returned: changed
126 type: str
127 sample: /Common/genericmsg
128 disable_parser:
129 description: Disables generic message parser.
130 returned: changed
131 type: bool
132 sample: true
133 max_egress_buffer:
134 description: The maximum size of the send buffer in bytes.
135 returned: changed
136 type: int
137 sample: 10000
138 max_msg_size:
139 description: The maximum size of a received message.
140 returned: changed
141 type: int
142 sample: 4000
143 msg_terminator:
144 description: The string of characters used to terminate a message.
145 returned: changed
146 type: str
147 sample: '%%%%'
148 no_response:
149 description: Disables matching of responses to requests.
150 returned: changed
151 type: bool
152 sample: true
153 '''
154 import traceback
155 from datetime import datetime
156
157 try:
158 from packaging.version import Version
159 except ImportError:
160 HAS_PACKAGING = False
161 Version = None
162 PACKAGING_IMPORT_ERROR = traceback.format_exc()
163 else:
164 HAS_PACKAGING = True
165 PACKAGING_IMPORT_ERROR = None
166
167 from ansible.module_utils.basic import (
168 AnsibleModule, missing_required_lib, env_fallback
169 )
170
171 from ..module_utils.bigip import F5RestClient
172 from ..module_utils.common import (
173 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
174 )
175 from ..module_utils.compare import cmp_str_with_none
176 from ..module_utils.icontrol import tmos_version
177 from ..module_utils.teem import send_teem
178
179
180 class Parameters(AnsibleF5Parameters):
181 api_map = {
182 'defaultsFrom': 'parent',
183 'disableParser': 'disable_parser',
184 'maxEgressBuffer': 'max_egress_buffer',
185 'maxMessageSize': 'max_msg_size',
186 'messageTerminator': 'msg_terminator',
187 'noResponse': 'no_response',
188
189 }
190
191 api_attributes = [
192 'description',
193 'defaultsFrom',
194 'disableParser',
195 'maxEgressBuffer',
196 'maxMessageSize',
197 'messageTerminator',
198 'noResponse',
199 ]
200
201 returnables = [
202 'description',
203 'parent',
204 'disable_parser',
205 'max_egress_buffer',
206 'max_msg_size',
207 'msg_terminator',
208 'no_response',
209 ]
210
211 updatables = [
212 'description',
213 'parent',
214 'disable_parser',
215 'max_egress_buffer',
216 'max_msg_size',
217 'msg_terminator',
218 'no_response',
219 ]
220
221 @property
222 def no_response(self):
223 return flatten_boolean(self._values['no_response'])
224
225 @property
226 def disable_parser(self):
227 return flatten_boolean(self._values['disable_parser'])
228
229
230 class ApiParameters(Parameters):
231 pass
232
233
234 class ModuleParameters(Parameters):
235 @property
236 def parent(self):
237 if self._values['parent'] is None:
238 return None
239 result = fq_name(self.partition, self._values['parent'])
240 return result
241
242 @property
243 def max_msg_size(self):
244 if self._values['max_msg_size'] is None:
245 return None
246 if 0 <= self._values['max_msg_size'] <= 4294967295:
247 return self._values['max_msg_size']
248 raise F5ModuleError(
249 "Valid 'max_msg_size' must be in range 0 - 4294967295."
250 )
251
252 @property
253 def max_egress_buffer(self):
254 if self._values['max_egress_buffer'] is None:
255 return None
256 if 0 <= self._values['max_egress_buffer'] <= 4294967295:
257 return self._values['max_egress_buffer']
258 raise F5ModuleError(
259 "Valid 'max_egress_buffer' must be in range 0 - 4294967295."
260 )
261
262
263 class Changes(Parameters):
264 def to_return(self):
265 result = {}
266 try:
267 for returnable in self.returnables:
268 result[returnable] = getattr(self, returnable)
269 result = self._filter_params(result)
270 except Exception:
271 raise
272 return result
273
274
275 class UsableChanges(Changes):
276 pass
277
278
279 class ReportableChanges(Changes):
280 pass
281
282
283 class Difference(object):
284 def __init__(self, want, have=None):
285 self.want = want
286 self.have = have
287
288 def compare(self, param):
289 try:
290 result = getattr(self, param)
291 return result
292 except AttributeError:
293 return self.__default(param)
294
295 def __default(self, param):
296 attr1 = getattr(self.want, param)
297 try:
298 attr2 = getattr(self.have, param)
299 if attr1 != attr2:
300 return attr1
301 except AttributeError:
302 return attr1
303
304 @property
305 def parent(self):
306 if self.want.parent is None:
307 return None
308 if self.want.parent != self.have.parent:
309 raise F5ModuleError(
310 "The parent router profile cannot be changed."
311 )
312
313 @property
314 def description(self):
315 return cmp_str_with_none(self.want.description, self.have.description)
316
317 @property
318 def msg_terminator(self):
319 return cmp_str_with_none(self.want.msg_terminator, self.have.msg_terminator)
320
321
322 class ModuleManager(object):
323 def __init__(self, *args, **kwargs):
324 self.module = kwargs.get('module', None)
325 self.client = F5RestClient(**self.module.params)
326 self.want = ModuleParameters(params=self.module.params)
327 self.have = ApiParameters()
328 self.changes = UsableChanges()
329
330 def _set_changed_options(self):
331 changed = {}
332 for key in Parameters.returnables:
333 if getattr(self.want, key) is not None:
334 changed[key] = getattr(self.want, key)
335 if changed:
336 self.changes = UsableChanges(params=changed)
337
338 def _update_changed_options(self):
339 diff = Difference(self.want, self.have)
340 updatables = Parameters.updatables
341 changed = dict()
342 for k in updatables:
343 change = diff.compare(k)
344 if change is None:
345 continue
346 else:
347 if isinstance(change, dict):
348 changed.update(change)
349 else:
350 changed[k] = change
351 if changed:
352 self.changes = UsableChanges(params=changed)
353 return True
354 return False
355
356 def _announce_deprecations(self, result):
357 warnings = result.pop('__warnings', [])
358 for warning in warnings:
359 self.client.module.deprecate(
360 msg=warning['msg'],
361 version=warning['version']
362 )
363
364 def version_less_than_14(self, version):
365 if Version(version) < Version('14.0.0'):
366 return True
367 return False
368
369 def exec_module(self):
370 start = datetime.now().isoformat()
371 version = tmos_version(self.client)
372 if self.version_less_than_14(version):
373 raise F5ModuleError('Message routing is not supported on TMOS version below 14.x')
374 changed = False
375 result = dict()
376 state = self.want.state
377
378 if state == "present":
379 changed = self.present()
380 elif state == "absent":
381 changed = self.absent()
382
383 reportable = ReportableChanges(params=self.changes.to_return())
384 changes = reportable.to_return()
385 result.update(**changes)
386 result.update(dict(changed=changed))
387 self._announce_deprecations(result)
388 send_teem(start, self.client, self.module, version)
389 return result
390
391 def present(self):
392 if self.exists():
393 return self.update()
394 else:
395 return self.create()
396
397 def absent(self):
398 if self.exists():
399 return self.remove()
400 return False
401
402 def should_update(self):
403 result = self._update_changed_options()
404 if result:
405 return True
406 return False
407
408 def update(self):
409 self.have = self.read_current_from_device()
410 if not self.should_update():
411 return False
412 if self.module.check_mode:
413 return True
414 self.update_on_device()
415 return True
416
417 def remove(self):
418 if self.module.check_mode:
419 return True
420 self.remove_from_device()
421 if self.exists():
422 raise F5ModuleError("Failed to delete the resource.")
423 return True
424
425 def create(self):
426 self._set_changed_options()
427 if self.module.check_mode:
428 return True
429 self.create_on_device()
430 return True
431
432 def exists(self):
433 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/protocol/{2}".format(
434 self.client.provider['server'],
435 self.client.provider['server_port'],
436 transform_name(self.want.partition, self.want.name)
437 )
438 resp = self.client.api.get(uri)
439 try:
440 response = resp.json()
441 except ValueError as ex:
442 raise F5ModuleError(str(ex))
443
444 if resp.status == 404 or 'code' in response and response['code'] == 404:
445 return False
446 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
447 return True
448
449 errors = [401, 403, 409, 500, 501, 502, 503, 504]
450
451 if resp.status in errors or 'code' in response and response['code'] in errors:
452 if 'message' in response:
453 raise F5ModuleError(response['message'])
454 else:
455 raise F5ModuleError(resp.content)
456
457 def create_on_device(self):
458 params = self.changes.api_params()
459 params['name'] = self.want.name
460 params['partition'] = self.want.partition
461 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/protocol/".format(
462 self.client.provider['server'],
463 self.client.provider['server_port'],
464 )
465 resp = self.client.api.post(uri, json=params)
466 try:
467 response = resp.json()
468 except ValueError as ex:
469 raise F5ModuleError(str(ex))
470
471 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
472 return True
473 raise F5ModuleError(resp.content)
474
475 def update_on_device(self):
476 params = self.changes.api_params()
477 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/protocol/{2}".format(
478 self.client.provider['server'],
479 self.client.provider['server_port'],
480 transform_name(self.want.partition, self.want.name)
481 )
482 resp = self.client.api.patch(uri, json=params)
483 try:
484 response = resp.json()
485 except ValueError as ex:
486 raise F5ModuleError(str(ex))
487
488 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
489 return True
490 raise F5ModuleError(resp.content)
491
492 def remove_from_device(self):
493 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/protocol/{2}".format(
494 self.client.provider['server'],
495 self.client.provider['server_port'],
496 transform_name(self.want.partition, self.want.name)
497 )
498 response = self.client.api.delete(uri)
499 if response.status == 200:
500 return True
501 raise F5ModuleError(response.content)
502
503 def read_current_from_device(self):
504 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/protocol/{2}".format(
505 self.client.provider['server'],
506 self.client.provider['server_port'],
507 transform_name(self.want.partition, self.want.name)
508 )
509 resp = self.client.api.get(uri)
510 try:
511 response = resp.json()
512 except ValueError as ex:
513 raise F5ModuleError(str(ex))
514
515 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
516 return ApiParameters(params=response)
517 raise F5ModuleError(resp.content)
518
519
520 class ArgumentSpec(object):
521 def __init__(self):
522 self.supports_check_mode = True
523 argument_spec = dict(
524 name=dict(required=True),
525 description=dict(),
526 parent=dict(),
527 disable_parser=dict(type='bool'),
528 max_egress_buffer=dict(type='int'),
529 max_msg_size=dict(type='int'),
530 msg_terminator=dict(),
531 no_response=dict(type='bool'),
532 partition=dict(
533 default='Common',
534 fallback=(env_fallback, ['F5_PARTITION'])
535 ),
536 state=dict(
537 default='present',
538 choices=['present', 'absent']
539 )
540
541 )
542 self.argument_spec = {}
543 self.argument_spec.update(f5_argument_spec)
544 self.argument_spec.update(argument_spec)
545
546
547 def main():
548 spec = ArgumentSpec()
549
550 module = AnsibleModule(
551 argument_spec=spec.argument_spec,
552 supports_check_mode=spec.supports_check_mode,
553 )
554
555 if not HAS_PACKAGING:
556 module.fail_json(
557 msg=missing_required_lib('packaging'),
558 exception=PACKAGING_IMPORT_ERROR
559 )
560
561 try:
562 mm = ModuleManager(module=module)
563 results = mm.exec_module()
564 module.exit_json(**results)
565 except F5ModuleError as ex:
566 module.fail_json(msg=str(ex))
567
568
569 if __name__ == '__main__':
570 main()