Debian Codegraph @

ansible_collections/community/hrobot/plugins/module_utils/failover.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c), Felix Fontein <[email protected]>, 2019
4 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
5 # SPDX-License-Identifier: BSD-2-Clause
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 import json
11
12 from ansible_collections.community.hrobot.plugins.module_utils.robot import (
13 BASE_URL,
14 fetch_url_json,
15 )
16
17 try:
18 from urllib.parse import urlencode
19 except ImportError:
20 # Python 2.x fallback:
21 from urllib import urlencode
22
23
24 def get_failover_record(module, ip):
25 '''
26 Get information record of failover IP.
27
28 See https://robot.your-server.de/doc/webservice/en.html#get-failover-failover-ip
29 '''
30 url = "{0}/failover/{1}".format(BASE_URL, ip)
31 result, error = fetch_url_json(module, url)
32 if 'failover' not in result:
33 module.fail_json(msg='Cannot interpret result: {0}'.format(json.dumps(result, sort_keys=True)))
34 return result['failover']
35
36
37 def get_failover(module, ip):
38 '''
39 Get current routing target of failover IP.
40
41 The value ``None`` represents unrouted.
42
43 See https://robot.your-server.de/doc/webservice/en.html#get-failover-failover-ip
44 '''
45 return get_failover_record(module, ip)['active_server_ip']
46
47
48 def set_failover(module, ip, value, timeout=180):
49 '''
50 Set current routing target of failover IP.
51
52 Return a pair ``(value, changed)``. The value ``None`` for ``value`` represents unrouted.
53
54 See https://robot.your-server.de/doc/webservice/en.html#post-failover-failover-ip
55 and https://robot.your-server.de/doc/webservice/en.html#delete-failover-failover-ip
56 '''
57 url = "{0}/failover/{1}".format(BASE_URL, ip)
58 if value is None:
59 result, error = fetch_url_json(
60 module,
61 url,
62 method='DELETE',
63 timeout=timeout,
64 accept_errors=['FAILOVER_ALREADY_ROUTED']
65 )
66 else:
67 headers = {"Content-type": "application/x-www-form-urlencoded"}
68 data = dict(
69 active_server_ip=value,
70 )
71 result, error = fetch_url_json(
72 module,
73 url,
74 method='POST',
75 timeout=timeout,
76 data=urlencode(data),
77 headers=headers,
78 accept_errors=['FAILOVER_ALREADY_ROUTED']
79 )
80 if error is not None:
81 return value, False
82 else:
83 return result['failover']['active_server_ip'], True
84
85
86 def get_failover_state(value):
87 '''
88 Create result dictionary for failover IP's value.
89
90 The value ``None`` represents unrouted.
91 '''
92 return dict(
93 value=value,
94 state='routed' if value else 'unrouted'
95 )