Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_profile_http_compression.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_http_compression
13 short_description: Manage HTTP compression profiles on a BIG-IP
14 description:
15 - Manage HTTP compression profiles on a BIG-IP device.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the compression 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(httpcompression) profile.
28 type: str
29 description:
30 description:
31 - Description of the HTTP compression profile.
32 type: str
33 buffer_size:
34 description:
35 - Maximum number of compressed bytes the system buffers before inserting
36 a Content-Length header (which specifies the compressed size) into the response.
37 - When creating a new profile, if this parameter is not specified, the default
38 is provided by the parent profile.
39 type: int
40 gzip_level:
41 description:
42 - Specifies the degree to which the system compresses the content.
43 - Higher compression levels cause the compression process to be slower.
44 - Valid values are between 1 (least compression and fastest) to 9 (most
45 compression and slowest).
46 type: int
47 choices:
48 - 1
49 - 2
50 - 3
51 - 4
52 - 5
53 - 6
54 - 7
55 - 8
56 - 9
57 gzip_memory_level:
58 description:
59 - Number of kilobytes of memory the system uses for internal compression
60 buffers when compressing a server response.
61 type: int
62 choices:
63 - 1
64 - 2
65 - 4
66 - 8
67 - 16
68 - 32
69 - 64
70 - 128
71 - 256
72 gzip_window_size:
73 description:
74 - Number of kilobytes in the window size the system uses when compressing
75 a server response.
76 type: int
77 choices:
78 - 1
79 - 2
80 - 4
81 - 8
82 - 16
83 - 32
84 - 64
85 - 128
86 partition:
87 description:
88 - Device partition to manage resources on.
89 type: str
90 default: Common
91 state:
92 description:
93 - When C(present), ensures the profile exists.
94 - When C(absent), ensures the profile is removed.
95 type: str
96 choices:
97 - present
98 - absent
99 default: present
100 content_type_include:
101 description: Specifies the list of the content types that are allowed.
102 type: list
103 elements: str
104 version_added: "1.15.0"
105 extends_documentation_fragment: f5networks.f5_modules.f5
106 author:
107 - Tim Rupp (@caphrim007)
108 '''
109
110 EXAMPLES = r'''
111 - name: Create an HTTP compression profile
112 bigip_profile_http_compression:
113 name: profile1
114 description: Custom HTTP Compression Profile
115 buffer_size: 131072
116 gzip_level: 6
117 gzip_memory_level: 16k
118 gzip_window_size: 64k
119 provider:
120 password: secret
121 server: lb.mydomain.com
122 user: admin
123 delegate_to: localhost
124 '''
125
126 RETURN = r'''
127 description:
128 description: The new description of the resource.
129 returned: changed
130 type: str
131 sample: My custom profile
132 buffer_size:
133 description: The new buffer size of the profile.
134 returned: changed
135 type: int
136 sample: 4096
137 gzip_memory_level:
138 description: The new GZIP memory level of the profile, in KB.
139 returned: changed
140 type: int
141 sample: 16
142 gzip_level:
143 description: The new GZIP level of the profile. Smaller is less compression.
144 returned: changed
145 type: int
146 sample: 2
147 gzip_window_size:
148 description: The new GZIP window size of the profile, in KB.
149 returned: changed
150 type: int
151 sample: 64
152 '''
153 from datetime import datetime
154
155 from ansible.module_utils.basic import (
156 AnsibleModule, env_fallback
157 )
158
159 from ..module_utils.bigip import F5RestClient
160 from ..module_utils.common import (
161 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
162 )
163 from ..module_utils.icontrol import tmos_version
164 from ..module_utils.teem import send_teem
165
166
167 class Parameters(AnsibleF5Parameters):
168 api_map = {
169 'bufferSize': 'buffer_size',
170 'defaultsFrom': 'parent',
171 'gzipMemoryLevel': 'gzip_memory_level',
172 'gzipLevel': 'gzip_level',
173 'gzipWindowSize': 'gzip_window_size',
174 'contentTypeInclude': 'content_type_include',
175 }
176
177 api_attributes = [
178 'description',
179 'bufferSize',
180 'defaultsFrom',
181 'gzipMemoryLevel',
182 'gzipLevel',
183 'gzipWindowSize',
184 'contentTypeInclude',
185 ]
186
187 returnables = [
188 'description',
189 'buffer_size',
190 'gzip_memory_level',
191 'gzip_level',
192 'gzip_window_size',
193 'content_type_include',
194 ]
195
196 updatables = [
197 'description',
198 'buffer_size',
199 'gzip_memory_level',
200 'gzip_level',
201 'gzip_window_size',
202 'parent',
203 'content_type_include'
204 ]
205
206
207 class ApiParameters(Parameters):
208 @property
209 def description(self):
210 if self._values['description'] in [None, 'none']:
211 return None
212 return self._values['description']
213
214 @property
215 def gzip_memory_level(self):
216 if self._values['gzip_memory_level'] is None:
217 return None
218 return self._values['gzip_memory_level'] / 1024
219
220 @property
221 def gzip_window_size(self):
222 if self._values['gzip_window_size'] is None:
223 return None
224 return self._values['gzip_window_size'] / 1024
225
226
227 class ModuleParameters(Parameters):
228 @property
229 def parent(self):
230 if self._values['parent'] is None:
231 return None
232 result = fq_name(self.partition, self._values['parent'])
233 return result
234
235
236 class Changes(Parameters):
237 def to_return(self):
238 result = {}
239 try:
240 for returnable in self.returnables:
241 result[returnable] = getattr(self, returnable)
242 result = self._filter_params(result)
243 except Exception:
244 pass
245 return result
246
247
248 class UsableChanges(Changes):
249 @property
250 def gzip_memory_level(self):
251 if self._values['gzip_memory_level'] is None:
252 return None
253 return self._values['gzip_memory_level'] * 1024
254
255 @property
256 def gzip_window_size(self):
257 if self._values['gzip_window_size'] is None:
258 return None
259 return self._values['gzip_window_size'] * 1024
260
261
262 class ReportableChanges(Changes):
263 @property
264 def gzip_memory_level(self):
265 if self._values['gzip_memory_level'] is None:
266 return None
267 return self._values['gzip_memory_level'] / 1024
268
269 @property
270 def gzip_window_size(self):
271 if self._values['gzip_window_size'] is None:
272 return None
273 return self._values['gzip_window_size'] / 1024
274
275
276 class Difference(object):
277 def __init__(self, want, have=None):
278 self.want = want
279 self.have = have
280
281 def compare(self, param):
282 try:
283 result = getattr(self, param)
284 return result
285 except AttributeError:
286 return self.__default(param)
287
288 def __default(self, param):
289 attr1 = getattr(self.want, param)
290 try:
291 attr2 = getattr(self.have, param)
292 if attr1 != attr2:
293 return attr1
294 except AttributeError:
295 return attr1
296
297
298 class ModuleManager(object):
299 def __init__(self, *args, **kwargs):
300 self.module = kwargs.get('module', None)
301 self.client = F5RestClient(**self.module.params)
302 self.want = ModuleParameters(params=self.module.params)
303 self.have = ApiParameters()
304 self.changes = UsableChanges()
305
306 def _set_changed_options(self):
307 changed = {}
308 for key in Parameters.returnables:
309 if getattr(self.want, key) is not None:
310 changed[key] = getattr(self.want, key)
311 if changed:
312 self.changes = UsableChanges(params=changed)
313
314 def _update_changed_options(self):
315 diff = Difference(self.want, self.have)
316 updatables = Parameters.updatables
317 changed = dict()
318 for k in updatables:
319 change = diff.compare(k)
320 if change is None:
321 continue
322 else:
323 if isinstance(change, dict):
324 changed.update(change)
325 else:
326 changed[k] = change
327 if changed:
328 self.changes = UsableChanges(params=changed)
329 return True
330 return False
331
332 def should_update(self):
333 result = self._update_changed_options()
334 if result:
335 return True
336 return False
337
338 def exec_module(self):
339 start = datetime.now().isoformat()
340 version = tmos_version(self.client)
341 changed = False
342 result = dict()
343 state = self.want.state
344
345 if state == "present":
346 changed = self.present()
347 elif state == "absent":
348 changed = self.absent()
349
350 reportable = ReportableChanges(params=self.changes.to_return())
351 changes = reportable.to_return()
352 result.update(**changes)
353 result.update(dict(changed=changed))
354 self._announce_deprecations(result)
355 send_teem(start, self.client, self.module, version)
356 return result
357
358 def _announce_deprecations(self, result):
359 warnings = result.pop('__warnings', [])
360 for warning in warnings:
361 self.client.module.deprecate(
362 msg=warning['msg'],
363 version=warning['version']
364 )
365
366 def present(self):
367 if self.exists():
368 return self.update()
369 else:
370 return self.create()
371
372 def exists(self):
373 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http-compression/{2}".format(
374 self.client.provider['server'],
375 self.client.provider['server_port'],
376 transform_name(self.want.partition, self.want.name)
377 )
378 resp = self.client.api.get(uri)
379 try:
380 response = resp.json()
381 except ValueError as ex:
382 raise F5ModuleError(str(ex))
383
384 if resp.status == 404 or 'code' in response and response['code'] == 404:
385 return False
386 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
387 return True
388
389 errors = [401, 403, 409, 500, 501, 502, 503, 504]
390
391 if resp.status in errors or 'code' in response and response['code'] in errors:
392 if 'message' in response:
393 raise F5ModuleError(response['message'])
394 else:
395 raise F5ModuleError(resp.content)
396
397 def update(self):
398 self.have = self.read_current_from_device()
399 if not self.should_update():
400 return False
401 if self.module.check_mode:
402 return True
403 self.update_on_device()
404 return True
405
406 def remove(self):
407 if self.module.check_mode:
408 return True
409 self.remove_from_device()
410 if self.exists():
411 raise F5ModuleError("Failed to delete the resource.")
412 return True
413
414 def create(self):
415 self._set_changed_options()
416 if self.module.check_mode:
417 return True
418 self.create_on_device()
419 return True
420
421 def create_on_device(self):
422 params = self.changes.api_params()
423 params['name'] = self.want.name
424 params['partition'] = self.want.partition
425 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http-compression/".format(
426 self.client.provider['server'],
427 self.client.provider['server_port']
428 )
429 resp = self.client.api.post(uri, json=params)
430 try:
431 response = resp.json()
432 except ValueError as ex:
433 raise F5ModuleError(str(ex))
434
435 if 'code' in response and response['code'] in [400, 403, 404]:
436 if 'message' in response:
437 raise F5ModuleError(response['message'])
438 else:
439 raise F5ModuleError(resp.content)
440
441 def update_on_device(self):
442 params = self.changes.api_params()
443 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http-compression/{2}".format(
444 self.client.provider['server'],
445 self.client.provider['server_port'],
446 transform_name(self.want.partition, self.want.name)
447 )
448 resp = self.client.api.patch(uri, json=params)
449 try:
450 response = resp.json()
451 except ValueError as ex:
452 raise F5ModuleError(str(ex))
453
454 if 'code' in response and response['code'] in [400, 404]:
455 if 'message' in response:
456 raise F5ModuleError(response['message'])
457 else:
458 raise F5ModuleError(resp.content)
459
460 def absent(self):
461 if self.exists():
462 return self.remove()
463 return False
464
465 def remove_from_device(self):
466 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http-compression/{2}".format(
467 self.client.provider['server'],
468 self.client.provider['server_port'],
469 transform_name(self.want.partition, self.want.name)
470 )
471 resp = self.client.api.delete(uri)
472 if resp.status == 200:
473 return True
474 raise F5ModuleError(resp.content)
475
476 def read_current_from_device(self): # lgtm [py/similar-function]
477 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/http-compression/{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.get(uri)
483 try:
484 response = resp.json()
485 except ValueError as ex:
486 raise F5ModuleError(str(ex))
487
488 if 'code' in response and response['code'] == 400:
489 if 'message' in response:
490 raise F5ModuleError(response['message'])
491 else:
492 raise F5ModuleError(resp.content)
493 return ApiParameters(params=response)
494
495
496 class ArgumentSpec(object):
497 def __init__(self):
498 self.supports_check_mode = True
499 argument_spec = dict(
500 name=dict(required=True),
501 parent=dict(),
502 buffer_size=dict(type='int'),
503 description=dict(),
504 gzip_level=dict(
505 type='int',
506 choices=[1, 2, 3, 4, 5, 6, 7, 8, 9]
507 ),
508 gzip_memory_level=dict(
509 type='int',
510 choices=[1, 2, 4, 8, 16, 32, 64, 128, 256]
511 ),
512 gzip_window_size=dict(
513 type='int',
514 choices=[1, 2, 4, 8, 16, 32, 64, 128]
515 ),
516 state=dict(
517 default='present',
518 choices=['present', 'absent']
519 ),
520 partition=dict(
521 default='Common',
522 fallback=(env_fallback, ['F5_PARTITION'])
523 ),
524 content_type_include=dict(
525 elements='str',
526 type='list'
527 )
528 )
529 self.argument_spec = {}
530 self.argument_spec.update(f5_argument_spec)
531 self.argument_spec.update(argument_spec)
532
533
534 def main():
535 spec = ArgumentSpec()
536
537 module = AnsibleModule(
538 argument_spec=spec.argument_spec,
539 supports_check_mode=spec.supports_check_mode,
540 )
541
542 try:
543 mm = ModuleManager(module=module)
544 results = mm.exec_module()
545 module.exit_json(**results)
546 except F5ModuleError as ex:
547 module.fail_json(msg=str(ex))
548
549
550 if __name__ == '__main__':
551 main()