Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, 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_http2
13 short_description: Manage HTTP2 profiles on a BIG-IP
14 description:
15 - Manage HTTP2 profiles on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the profile.
21 type: str
22 required: True
23 parent:
24 description:
25 - Specifies the profile from which this profile inherits settings.
26 - When creating a new profile, if this parameter is not specified, the default
27 is the system-supplied C(http2) profile.
28 type: str
29 description:
30 description:
31 - Description of the profile.
32 type: str
33 streams:
34 description:
35 - Specifies the number of outstanding concurrent requests allowed on a single HTTP/2 connection.
36 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
37 - The valid value range is C(1 - 256).
38 type: int
39 idle_timeout:
40 description:
41 - Specifies the number of seconds an HTTP/2 connection is idly left open before being shut down.
42 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
43 type: int
44 insert_header:
45 description:
46 - Specifies whether an HTTP header indicating the use of HTTP/2 should be inserted into the request
47 that goes to the server.
48 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
49 type: bool
50 insert_header_name:
51 description:
52 - Specifies the name of the HTTP header controlled by C(insert_header) parameter.
53 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
54 type: str
55 enforce_tls_requirements:
56 description:
57 - Specifies whether the system requires TLS for communications between specified senders and recipients.
58 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
59 type: bool
60 activation_modes:
61 description:
62 - Specifies what will cause an incoming connection to be handled as a HTTP/2 connection.
63 - The C(alpn) and C(always) are mutually exclusive.
64 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
65 type: list
66 elements: str
67 choices:
68 - alpn
69 - always
70 frame_size:
71 description:
72 - Specifies the size of data frames, in bytes, that HTTP/2 sends to the client.
73 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
74 - The valid value range in bytes is C(1024 - 16384).
75 type: int
76 write_size:
77 description:
78 - Specifies the total size of combined data frames, in bytes, that HTTP/2 sends in a single write.
79 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
80 - The valid value range in bytes is C(2048 - 32768).
81 type: int
82 receive_window:
83 description:
84 - Specifies the way the HTTP/2 profile performs flow control.
85 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
86 - The valid value range in kilobytes is C(16 - 128).
87 type: int
88 header_table_size:
89 description:
90 - Specifies the size of the header table, in bytes.
91 - When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.
92 - The valid value range in bytes is C(0 - 65535).
93 type: int
94 partition:
95 description:
96 - Device partition to manage resources on.
97 type: str
98 default: Common
99 state:
100 description:
101 - When C(present), ensures the profile exists.
102 - When C(absent), ensures the profile is removed.
103 type: str
104 choices:
105 - present
106 - absent
107 default: present
108 extends_documentation_fragment: f5networks.f5_modules.f5
109 author:
110 - Wojciech Wypior (@wojtek0806)
111 '''
112
113 EXAMPLES = r'''
114 - name: Create HTTP2 profile
115 bigip_profile_http2:
116 name: my_profile
117 insert_header: true
118 insert_header_name: FOO
119 state: present
120 provider:
121 user: admin
122 password: secret
123 server: lb.mydomain.com
124 delegate_to: localhost
125
126 - name: Remove HTTP profile
127 bigip_profile_http2:
128 name: my_profile
129 state: absent
130 provider:
131 server: lb.mydomain.com
132 user: admin
133 password: secret
134 delegate_to: localhost
135
136 - name: Add HTTP profile set activation modes
137 bigip_profile_http:
138 name: my_profile
139 activation_modes:
140 - always
141 provider:
142 password: secret
143 server: lb.mydomain.com
144 user: admin
145 delegate_to: localhost
146 '''
147
148 RETURN = r'''
149 description:
150 description: Description of the profile.
151 returned: changed
152 type: str
153 sample: My profile
154 insert_header_name:
155 description: Specifies the name of the HTTP2 header.
156 returned: changed
157 type: str
158 sample: X-HTTP2
159 streams:
160 description: The number of outstanding concurrent requests allowed on a single HTTP/2 connection.
161 returned: changed
162 type: int
163 sample: 30
164 enforce_tls_requirements:
165 description: Specifies whether the system requires TLS for communications.
166 returned: changed
167 type: bool
168 sample: true
169 frame_size:
170 description: The size of the data frames.
171 returned: changed
172 type: int
173 sample: 30
174 activation_modes:
175 description: Specifies HTTP/2 connection handling modes.
176 returned: changed
177 type: list
178 sample: ['always']
179 '''
180 from datetime import datetime
181
182 from ansible.module_utils.basic import (
183 AnsibleModule, env_fallback
184 )
185
186 from ..module_utils.bigip import F5RestClient
187 from ..module_utils.common import (
188 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name, is_empty_list
189 )
190 from ..module_utils.icontrol import tmos_version
191 from ..module_utils.teem import send_teem
192
193
194 class Parameters(AnsibleF5Parameters):
195 api_map = {
196 'activationModes': 'activation_modes',
197 'concurrentStreamsPerConnection': 'streams',
198 'connectionIdleTimeout': 'idle_timeout',
199 'defaultsFrom': 'parent',
200 'enforceTlsRequirements': 'enforce_tls_requirements',
201 'frameSize': 'frame_size',
202 'headerTableSize': 'header_table_size',
203 'insertHeader': 'insert_header',
204 'insertHeaderName': 'insert_header_name',
205 'receiveWindow': 'receive_window',
206 'writeSize': 'write_size',
207 }
208
209 api_attributes = [
210 'activationModes',
211 'concurrentStreamsPerConnection',
212 'connectionIdleTimeout',
213 'description',
214 'defaultsFrom',
215 'enforceTlsRequirements',
216 'frameSize',
217 'headerTableSize',
218 'insertHeader',
219 'insertHeaderName',
220 'receiveWindow',
221 'writeSize',
222 ]
223
224 returnables = [
225 'activation_modes',
226 'streams',
227 'description',
228 'idle_timeout',
229 'parent',
230 'enforce_tls_requirements',
231 'frame_size',
232 'header_table_size',
233 'insert_header',
234 'insert_header_name',
235 'receive_window',
236 'write_size',
237 ]
238
239 updatables = [
240 'activation_modes',
241 'streams',
242 'description',
243 'idle_timeout',
244 'parent',
245 'enforce_tls_requirements',
246 'frame_size',
247 'header_table_size',
248 'insert_header',
249 'insert_header_name',
250 'receive_window',
251 'write_size',
252 ]
253
254
255 class ApiParameters(Parameters):
256 pass
257
258
259 class ModuleParameters(Parameters):
260 @property
261 def parent(self):
262 if self._values['parent'] is None:
263 return None
264 result = fq_name(self.partition, self._values['parent'])
265 return result
266
267 @property
268 def streams(self):
269 streams = self._values['streams']
270 if streams is None:
271 return None
272 if streams < 1 or streams > 256:
273 raise F5ModuleError(
274 "Streams value must be between 1 and 256"
275 )
276 return self._values['streams']
277
278 @property
279 def receive_window(self):
280 window = self._values['receive_window']
281 if window is None:
282 return None
283 if window < 16 or window > 128:
284 raise F5ModuleError(
285 "Receive Window value must be between 16 and 128"
286 )
287 return self._values['receive_window']
288
289 @property
290 def header_table_size(self):
291 header = self._values['header_table_size']
292 if header is None:
293 return None
294 if header < 0 or header > 65535:
295 raise F5ModuleError(
296 "Header Table Size value must be between 0 and 65535"
297 )
298 return self._values['header_table_size']
299
300 @property
301 def write_size(self):
302 write = self._values['write_size']
303 if write is None:
304 return None
305 if write < 2048 or write > 32768:
306 raise F5ModuleError(
307 "Write Size value must be between 2048 and 32768"
308 )
309 return self._values['write_size']
310
311 @property
312 def frame_size(self):
313 frame = self._values['frame_size']
314 if frame is None:
315 return None
316 if frame < 1024 or frame > 16384:
317 raise F5ModuleError(
318 "Write Size value must be between 1024 and 16384"
319 )
320 return self._values['frame_size']
321
322 @property
323 def enforce_tls_requirements(self):
324 result = flatten_boolean(self._values['enforce_tls_requirements'])
325 if result is None:
326 return None
327 if result == 'yes':
328 return 'enabled'
329 return 'disabled'
330
331 @property
332 def insert_header(self):
333 result = flatten_boolean(self._values['insert_header'])
334 if result is None:
335 return None
336 if result == 'yes':
337 return 'enabled'
338 return 'disabled'
339
340 @property
341 def activation_modes(self):
342 value = self._values['activation_modes']
343 if value is None:
344 return None
345 if is_empty_list(value):
346 raise F5ModuleError(
347 "Activation Modes cannot be empty, please provide a value"
348 )
349 return value
350
351
352 class Changes(Parameters):
353 def to_return(self):
354 result = {}
355 try:
356 for returnable in self.returnables:
357 result[returnable] = getattr(self, returnable)
358 result = self._filter_params(result)
359 except Exception:
360 pass
361 return result
362
363
364 class UsableChanges(Changes):
365 pass
366
367
368 class ReportableChanges(Changes):
369 @property
370 def insert_header(self):
371 if self._values['insert_header'] is None:
372 return None
373 elif self._values['insert_header'] == 'enabled':
374 return 'yes'
375 return 'no'
376
377 @property
378 def enforce_tls_requirements(self):
379 if self._values['enforce_tls_requirements'] is None:
380 return None
381 elif self._values['enforce_tls_requirements'] == 'enabled':
382 return 'yes'
383 return 'no'
384
385
386 class Difference(object):
387 def __init__(self, want, have=None):
388 self.want = want
389 self.have = have
390
391 def compare(self, param):
392 try:
393 result = getattr(self, param)
394 return result
395 except AttributeError:
396 return self.__default(param)
397
398 def __default(self, param):
399 attr1 = getattr(self.want, param)
400 try:
401 attr2 = getattr(self.have, param)
402 if attr1 != attr2:
403 return attr1
404 except AttributeError:
405 return attr1
406
407 @property
408 def description(self):
409 if self.want.description is None:
410 return None
411 if self.want.description == '':
412 if self.have.description is None or self.have.description == "none":
413 return None
414 if self.want.description != self.have.description:
415 return self.want.description
416
417
418 class ModuleManager(object):
419 def __init__(self, *args, **kwargs):
420 self.module = kwargs.get('module', None)
421 self.client = F5RestClient(**self.module.params)
422 self.want = ModuleParameters(params=self.module.params)
423 self.have = ApiParameters()
424 self.changes = UsableChanges()
425
426 def _set_changed_options(self):
427 changed = {}
428 for key in Parameters.returnables:
429 if getattr(self.want, key) is not None:
430 changed[key] = getattr(self.want, key)
431 if changed:
432 self.changes = UsableChanges(params=changed)
433
434 def _update_changed_options(self):
435 diff = Difference(self.want, self.have)
436 updatables = Parameters.updatables
437 changed = dict()
438 for k in updatables:
439 change = diff.compare(k)
440 if change is None:
441 continue
442 else:
443 if isinstance(change, dict):
444 changed.update(change)
445 else:
446 changed[k] = change
447 if changed:
448 self.changes = UsableChanges(params=changed)
449 return True
450 return False
451
452 def exec_module(self):
453 start = datetime.now().isoformat()
454 version = tmos_version(self.client)
455 changed = False
456 result = dict()
457 state = self.want.state
458
459 if state == "present":
460 changed = self.present()
461 elif state == "absent":
462 changed = self.absent()
463 reportable = ReportableChanges(params=self.changes.to_return())
464 changes = reportable.to_return()
465 result.update(**changes)
466 result.update(dict(changed=changed))
467 self._announce_deprecations(result)
468 send_teem(start, self.client, self.module, version)
469 return result
470
471 def _announce_deprecations(self, result):
472 warnings = result.pop('__warnings', [])
473 for warning in warnings:
474 self.client.module.deprecate(
475 msg=warning['msg'],
476 version=warning['version']
477 )
478
479 def present(self):
480 if self.exists():
481 return self.update()
482 else:
483 return self.create()
484
485 def absent(self):
486 if self.exists():
487 return self.remove()
488 return False
489
490 def update(self):
491 self.have = self.read_current_from_device()
492 if not self.should_update():
493 return False
494 if self.module.check_mode:
495 return True
496 self.update_on_device()
497 return True
498
499 def should_update(self):
500 result = self._update_changed_options()
501 if result:
502 return True
503 return False
504
505 def remove(self):
506 if self.module.check_mode:
507 return True
508 self.remove_from_device()
509 if self.exists():
510 raise F5ModuleError("Failed to delete the resource.")
511 return True
512
513 def create(self):
514 self._set_changed_options()
515 if self.module.check_mode:
516 return True
517 self.create_on_device()
518 return True
519
520 def exists(self):
521 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http2/{2}".format(
522 self.client.provider['server'],
523 self.client.provider['server_port'],
524 transform_name(self.want.partition, self.want.name)
525 )
526 resp = self.client.api.get(uri)
527 try:
528 response = resp.json()
529 except ValueError as ex:
530 raise F5ModuleError(str(ex))
531
532 if resp.status == 404 or 'code' in response and response['code'] == 404:
533 return False
534 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
535 return True
536
537 errors = [401, 403, 409, 500, 501, 502, 503, 504]
538
539 if resp.status in errors or 'code' in response and response['code'] in errors:
540 if 'message' in response:
541 raise F5ModuleError(response['message'])
542 else:
543 raise F5ModuleError(resp.content)
544
545 def create_on_device(self):
546 params = self.changes.api_params()
547 params['name'] = self.want.name
548 params['partition'] = self.want.partition
549 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http2/".format(
550 self.client.provider['server'],
551 self.client.provider['server_port']
552 )
553 resp = self.client.api.post(uri, json=params)
554 try:
555 response = resp.json()
556 except ValueError as ex:
557 raise F5ModuleError(str(ex))
558
559 if 'code' in response and response['code'] in [400, 403, 404]:
560 if 'message' in response:
561 raise F5ModuleError(response['message'])
562 else:
563 raise F5ModuleError(resp.content)
564 return response['selfLink']
565
566 def update_on_device(self):
567 params = self.changes.api_params()
568 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http2/{2}".format(
569 self.client.provider['server'],
570 self.client.provider['server_port'],
571 transform_name(self.want.partition, self.want.name)
572 )
573 resp = self.client.api.patch(uri, json=params)
574 try:
575 response = resp.json()
576 except ValueError as ex:
577 raise F5ModuleError(str(ex))
578
579 if 'code' in response and response['code'] in [400, 404]:
580 if 'message' in response:
581 raise F5ModuleError(response['message'])
582 else:
583 raise F5ModuleError(resp.content)
584
585 def remove_from_device(self):
586 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http2/{2}".format(
587 self.client.provider['server'],
588 self.client.provider['server_port'],
589 transform_name(self.want.partition, self.want.name)
590 )
591 response = self.client.api.delete(uri)
592 if response.status == 200:
593 return True
594 raise F5ModuleError(response.content)
595
596 def read_current_from_device(self):
597 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http2/{2}".format(
598 self.client.provider['server'],
599 self.client.provider['server_port'],
600 transform_name(self.want.partition, self.want.name)
601 )
602 resp = self.client.api.get(uri)
603 try:
604 response = resp.json()
605 except ValueError as ex:
606 raise F5ModuleError(str(ex))
607
608 if 'code' in response and response['code'] == 400:
609 if 'message' in response:
610 raise F5ModuleError(response['message'])
611 else:
612 raise F5ModuleError(resp.content)
613 return ApiParameters(params=response)
614
615
616 class ArgumentSpec(object):
617 def __init__(self):
618 self.supports_check_mode = True
619 argument_spec = dict(
620 name=dict(required=True),
621 parent=dict(),
622 activation_modes=dict(
623 type='list',
624 elements='str',
625 choices=[
626 'alpn', 'always'
627 ],
628 mutually_exclusive=[['always', 'alpn']],
629 ),
630 description=dict(),
631 enforce_tls_requirements=dict(type='bool'),
632 streams=dict(type='int'),
633 idle_timeout=dict(type='int'),
634 frame_size=dict(type='int'),
635 header_table_size=dict(type='int'),
636 insert_header=dict(type='bool'),
637 insert_header_name=dict(),
638 receive_window=dict(type='int'),
639 write_size=dict(type='int'),
640 state=dict(
641 default='present',
642 choices=['present', 'absent']
643 ),
644 partition=dict(
645 default='Common',
646 fallback=(env_fallback, ['F5_PARTITION'])
647 )
648 )
649 self.argument_spec = {}
650 self.argument_spec.update(f5_argument_spec)
651 self.argument_spec.update(argument_spec)
652
653
654 def main():
655 spec = ArgumentSpec()
656
657 module = AnsibleModule(
658 argument_spec=spec.argument_spec,
659 supports_check_mode=spec.supports_check_mode,
660 )
661
662 try:
663 mm = ModuleManager(module=module)
664 results = mm.exec_module()
665 module.exit_json(**results)
666 except F5ModuleError as ex:
667 module.fail_json(msg=str(ex))
668
669
670 if __name__ == '__main__':
671 main()