Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_wait.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_wait
13 short_description: Wait for a BIG-IP condition before continuing
14 description:
15 - With this module, you can wait for BIG-IP to be "ready", meaning the BIG-IP is ready
16 to accept configuration.
17 - This module can take into account situations where the device is in the middle
18 of rebooting due to a configuration change.
19 version_added: "1.0.0"
20 options:
21 type:
22 description:
23 - The type of the BIG-IP.
24 - Defaults to C(standard), the other choice is C(vcmp).
25 - This choice defines which module or service Ansible looks for to establish
26 that the device has recovered, so ensure to specify the correct choice,
27 especially when running this against VCMP.
28 type: str
29 default: standard
30 choices:
31 - standard
32 - vcmp
33 timeout:
34 description:
35 - Maximum number of seconds to wait.
36 - When used without other conditions, it is equivalent of just sleeping.
37 - The default timeout is deliberately set to 2 hours because there is no individual
38 REST API.
39 type: int
40 default: 7200
41 delay:
42 description:
43 - Number of seconds to wait before starting to poll.
44 type: int
45 default: 0
46 sleep:
47 description:
48 - Number of seconds to sleep between checks. Before version 2.3 this was hardcoded to 1 second.
49 type: int
50 default: 1
51 msg:
52 description:
53 - This overrides the normal error message from a failure to meet the required conditions.
54 type: str
55 extends_documentation_fragment: f5networks.f5_modules.f5_rest_cli
56 author:
57 - Tim Rupp (@caphrim007)
58 - Wojciech Wypior (@wojtek0806)
59 '''
60
61 EXAMPLES = r'''
62 - name: Wait for BIG-IP to be ready to take configuration
63 bigip_wait:
64 provider:
65 password: secret
66 server: lb.mydomain.com
67 user: admin
68 delegate_to: localhost
69
70 - name: Wait a maximum of 300 seconds for BIG-IP to be ready to take configuration
71 bigip_wait:
72 timeout: 300
73 provider:
74 password: secret
75 server: lb.mydomain.com
76 user: admin
77 delegate_to: localhost
78
79 - name: Wait for BIG-IP to be ready, don't start checking for 10 seconds
80 bigip_wait:
81 delay: 10
82 provider:
83 password: secret
84 server: lb.mydomain.com
85 user: admin
86 delegate_to: localhost
87 '''
88
89 RETURN = r'''
90 # only common fields returned
91 '''
92
93 import copy
94 import datetime
95 import signal
96 import time
97
98 from ansible.module_utils.basic import AnsibleModule
99 from ansible.module_utils.connection import exec_command
100
101 from ..module_utils.bigip import F5RestClient
102 from ..module_utils.common import (
103 F5ModuleError, AnsibleF5Parameters, is_cli, f5_argument_spec
104 )
105 from ..module_utils.teem import send_teem
106
107
108 def hard_timeout(module, want, start):
109 elapsed = datetime.datetime.utcnow() - start
110 module.fail_json(
111 msg=want.msg or "Timeout when waiting for BIG-IP", elapsed=elapsed.seconds
112 )
113
114
115 class Parameters(AnsibleF5Parameters):
116 returnables = [
117 'elapsed'
118 ]
119
120 def to_return(self):
121 result = {}
122 try:
123 for returnable in self.returnables:
124 result[returnable] = getattr(self, returnable)
125 result = self._filter_params(result)
126 except Exception:
127 raise
128 return result
129
130 @property
131 def delay(self):
132 if self._values['delay'] is None:
133 return None
134 return int(self._values['delay'])
135
136 @property
137 def timeout(self):
138 if self._values['timeout'] is None:
139 return None
140 return int(self._values['timeout'])
141
142 @property
143 def sleep(self):
144 if self._values['sleep'] is None:
145 return None
146 return int(self._values['sleep'])
147
148
149 class Changes(Parameters):
150 pass
151
152
153 class BaseManager(object):
154 def __init__(self, *args, **kwargs):
155 self.module = kwargs.get('module', None)
156 self.client = F5RestClient(**self.module.params)
157 self.have = None
158 self.want = Parameters(params=self.module.params)
159 self.changes = Parameters()
160
161 def _announce_deprecations(self, result):
162 warnings = result.pop('__warnings', [])
163 for warning in warnings:
164 self.module.deprecate(
165 msg=warning['msg'],
166 version=warning['version']
167 )
168
169 def execute(self):
170 if self.want.delay >= self.want.timeout:
171 raise F5ModuleError(
172 "The delay should not be greater than or equal to the timeout."
173 )
174 if self.want.delay + self.want.sleep >= self.want.timeout:
175 raise F5ModuleError(
176 "The combined delay and sleep should not be greater than or equal to the timeout."
177 )
178 signal.signal(
179 signal.SIGALRM,
180 lambda sig, frame: hard_timeout(self.module, self.want, start)
181 )
182
183 # setup handler before scheduling signal, to eliminate a race
184 signal.alarm(int(self.want.timeout))
185
186 start = datetime.datetime.utcnow()
187 if self.want.delay:
188 time.sleep(float(self.want.delay))
189 end = start + datetime.timedelta(seconds=int(self.want.timeout))
190
191 self.wait_for_device(start, end)
192
193 elapsed = datetime.datetime.utcnow() - start
194 self.changes.update({'elapsed': elapsed.seconds})
195 return False
196
197 def _wait_for_module_provisioning(self):
198 # To prevent things from running forever, the hack is to check
199 # for mprov's status twice. If mprov is finished, then in most
200 # cases (not ASM) the provisioning is probably ready.
201 nops = 0
202 # Sleep a little to let provisioning settle and begin properly
203 time.sleep(5)
204 while nops < 4:
205 try:
206 if not self._is_mprov_running_on_device():
207 nops += 1
208 else:
209 nops = 0
210 except Exception:
211 # This can be caused by restjavad restarting.
212 pass
213 time.sleep(10)
214
215 def _wait_for_rest_interface(self):
216 nops = 0
217 # Sleep a little to let daemons settle and begin checking if REST interface is available.
218 time.sleep(5)
219 while nops < 4:
220 if not self._rest_endpoints_ready():
221 nops += 1
222 else:
223 break
224 time.sleep(10)
225
226
227 class V1Manager(BaseManager):
228 def exec_module(self):
229 result = dict()
230
231 changed = self.execute()
232
233 changes = self.changes.to_return()
234 result.update(**changes)
235 result.update(dict(changed=changed))
236 self._announce_deprecations(result)
237 return result
238
239 def wait_for_device(self, start, end):
240 while datetime.datetime.utcnow() < end:
241 time.sleep(int(self.want.sleep))
242 # First we check if SSH connection is ready by repeatedly attempting to run a simple command
243 rc, out, err = exec_command(self.module, 'date')
244 if rc != 0:
245 continue
246 if self._device_is_rebooting():
247 # Wait for the reboot to happen and then start from the beginning
248 # of the waiting.
249 continue
250 if self.want.type == "standard":
251 if self._is_mprov_running_on_device():
252 self._wait_for_module_provisioning()
253 elif self.want.type == "vcmp":
254 self._is_vcmpd_running_on_device()
255 if not self._rest_endpoints_ready():
256 self._wait_for_rest_interface()
257 break
258 else:
259 elapsed = datetime.datetime.utcnow() - start
260 self.module.fail_json(
261 msg=self.want.msg or "Timeout when waiting for BIG-IP", elapsed=elapsed.seconds
262 )
263
264 def _is_mprov_running_on_device(self):
265 cmd = "ps aux | grep '[m]prov'"
266 rc, out, err = exec_command(self.module, cmd)
267 if rc != 0:
268 raise F5ModuleError(err)
269 if out:
270 return True
271 return False
272
273 def _is_vcmpd_running_on_device(self):
274 cmd = "ps aux | grep '[v]cmpd'"
275 rc, out, err = exec_command(self.module, cmd)
276 if rc != 0:
277 raise F5ModuleError(err)
278 if out:
279 return True
280 return False
281
282 def _rest_endpoints_ready(self):
283 cmd = "curl -o /dev/null -s -w\'%{http_code}\\n\' -u admin: http://localhost:8100/mgmt/tm/sys/available"
284 rc, out, err = exec_command(self.module, cmd)
285 if rc != 0:
286 raise F5ModuleError(err)
287 if out == '200':
288 return True
289 return False
290
291 def _device_is_rebooting(self):
292 cmd = 'runlevel'
293 rc, out, err = exec_command(self.module, cmd)
294 if rc != 0:
295 raise F5ModuleError(err)
296 if out.split(' ')[1] == '6':
297 return True
298 return False
299
300
301 class V2Manager(BaseManager):
302 def exec_module(self):
303 start = datetime.datetime.now().isoformat()
304
305 result = dict()
306
307 changed = self.execute()
308
309 changes = self.changes.to_return()
310 result.update(**changes)
311 result.update(dict(changed=changed))
312 self._announce_deprecations(result)
313 send_teem(start, self.client, self.module, None)
314 return result
315
316 def wait_for_device(self, start, end):
317 while datetime.datetime.utcnow() < end:
318 time.sleep(int(self.want.sleep))
319 try:
320 # The first test verifies that the REST API is available; this is done
321 # by repeatedly trying to login to it.
322 self.client = self._get_client_connection()
323 if not self.client:
324 continue
325
326 if self._device_is_rebooting():
327 # Wait for the reboot to happen and then start from the beginning
328 # of the waiting.
329 continue
330
331 if self.want.type == "standard":
332 if self._is_mprov_running_on_device():
333 self._wait_for_module_provisioning()
334 elif self.want.type == "vcmp":
335 self._is_vcmpd_running_on_device()
336 if not self._rest_endpoints_ready():
337 self._wait_for_rest_interface()
338 break
339 except Exception as ex:
340 if 'Failed to validate the SSL' in str(ex):
341 raise F5ModuleError(str(ex))
342
343 # The types of exception's we're handling here are "REST API is not
344 # ready" exceptions.
345 #
346 # For example,
347 #
348 # Typically caused by device starting up:
349 #
350 # icontrol.exceptions.iControlUnexpectedHTTPError: 404 Unexpected Error:
351 # Not Found for uri: https://localhost:10443/mgmt/tm/sys/
352 # icontrol.exceptions.iControlUnexpectedHTTPError: 503 Unexpected Error:
353 # Service Temporarily Unavailable for uri: https://localhost:10443/mgmt/tm/sys/
354 #
355 #
356 # Typically caused by a device being down
357 #
358 # requests.exceptions.SSLError: HTTPSConnectionPool(host='localhost', port=10443):
359 # Max retries exceeded with url: /mgmt/tm/sys/ (Caused by SSLError(
360 # SSLError("bad handshake: SysCallError(-1, 'Unexpected EOF')",),))
361 #
362 #
363 # Typically caused by device still booting
364 #
365 # raise SSLError(e, request=request)\nrequests.exceptions.SSLError:
366 # HTTPSConnectionPool(host='localhost', port=10443): Max retries
367 # exceeded with url: /mgmt/shared/authn/login (Caused by
368 # SSLError(SSLError(\"bad handshake: SysCallError(-1, 'Unexpected EOF')\",),)),
369 continue
370 else:
371 elapsed = datetime.datetime.utcnow() - start
372 self.module.fail_json(
373 msg=self.want.msg or "Timeout when waiting for BIG-IP", elapsed=elapsed.seconds
374 )
375
376 def _get_client_connection(self):
377 return F5RestClient(**self.module.params)
378
379 def _device_is_rebooting(self):
380 params = {
381 "command": "run",
382 "utilCmdArgs": '-c "runlevel"'
383 }
384 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
385 self.client.provider['server'],
386 self.client.provider['server_port']
387 )
388 resp = self.client.api.post(uri, json=params)
389 try:
390 response = resp.json()
391 except ValueError as ex:
392 raise F5ModuleError(str(ex))
393
394 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
395 raise F5ModuleError(resp.content)
396
397 if 'commandResult' in response and '6' in response['commandResult']:
398 return True
399 return False
400
401 def _is_mprov_running_on_device(self):
402 params = {
403 "command": "run",
404 "utilCmdArgs": '-c "ps aux | grep \'[m]prov\'"'
405 }
406 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
407 self.client.provider['server'],
408 self.client.provider['server_port']
409 )
410 resp = self.client.api.post(uri, json=params)
411 try:
412 response = resp.json()
413 except ValueError as ex:
414 raise F5ModuleError(str(ex))
415
416 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
417 raise F5ModuleError(resp.content)
418
419 if 'commandResult' in response:
420 return True
421 return False
422
423 def _is_vcmpd_running_on_device(self):
424 params = {
425 "command": "run",
426 "utilCmdArgs": '-c "ps aux | grep \'[v]cmpd\'"'
427 }
428 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
429 self.client.provider['server'],
430 self.client.provider['server_port']
431 )
432 resp = self.client.api.post(uri, json=params)
433 try:
434 response = resp.json()
435 except ValueError as ex:
436 raise F5ModuleError(str(ex))
437
438 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
439 raise F5ModuleError(resp.content)
440
441 if 'commandResult' in response:
442 return True
443 return False
444
445 def _rest_endpoints_ready(self):
446 uri = "https://{0}:{1}/mgmt/tm/sys/available".format(
447 self.client.provider['server'],
448 self.client.provider['server_port']
449 )
450 resp = self.client.api.get(uri)
451 try:
452 response = resp.json()
453 except ValueError as ex:
454 raise F5ModuleError(str(ex))
455
456 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
457 return True
458 return False
459
460
461 class ModuleManager(object):
462 def __init__(self, *args, **kwargs):
463 self.kwargs = kwargs
464 self.module = kwargs.get('module', None)
465
466 def exec_module(self):
467 if is_cli(self.module):
468 manager = self.get_manager('v1')
469 else:
470 manager = self.get_manager('v2')
471 result = manager.exec_module()
472 return result
473
474 def get_manager(self, type):
475 if type == 'v1':
476 return V1Manager(**self.kwargs)
477 elif type == 'v2':
478 return V2Manager(**self.kwargs)
479
480
481 class ArgumentSpec(object):
482 def __init__(self):
483 self.supports_check_mode = True
484 argument_spec = dict(
485 type=dict(
486 choices=['standard', 'vcmp'],
487 default='standard'
488 ),
489 timeout=dict(default=7200, type='int'),
490 delay=dict(default=0, type='int'),
491 sleep=dict(default=1, type='int'),
492 msg=dict(),
493 )
494 # required to add CLI to choices and ssh_keyfile as per documentation
495 provider_update = dict(
496 transport=dict(
497 type='str',
498 default='rest',
499 choices=['cli', 'rest']
500 ),
501 ssh_keyfile=dict(
502 type='path'
503 ),
504
505 )
506 new_spec = copy.deepcopy(f5_argument_spec)
507 self.argument_spec = {}
508 self.argument_spec.update(new_spec)
509 self.argument_spec['provider']['options'].update(provider_update)
510 self.argument_spec.update(argument_spec)
511
512
513 def main():
514 spec = ArgumentSpec()
515
516 module = AnsibleModule(
517 argument_spec=spec.argument_spec,
518 supports_check_mode=spec.supports_check_mode
519 )
520
521 try:
522 mm = ModuleManager(module=module)
523 results = mm.exec_module()
524 module.exit_json(**results)
525 except F5ModuleError as ex:
526 module.fail_json(msg=str(ex))
527
528
529 if __name__ == '__main__':
530 main()