Debian Codegraph @

ctdb/utils/etcd/ctdb_etcd_lock

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 #
16 # Copyright (C) 2016 Jose A. Rivera <[email protected]>
17 # Copyright (C) 2016 Ira Cooper <[email protected]>
18 """CTDB mutex helper using etcd.
19
20 This script is intended to be run as a mutex helper for CTDB. It will try to
21 connect to an existing etcd cluster and grab an etcd.Lock() to function as
22 CTDB's cluster lock. Please see ctdb/doc/cluster_mutex_helper.txt for
23 details on what we're SUPPOSED to be doing. :) To use this, include
24 the following line in the ctdb.conf:
25
•26 cluster lock = !/usr/libexec/ctdb/ctdb_etcd_lock
27
28 You can also pass "-v", "-vv", or "-vvv" to include verbose output in the
29 CTDB log. Additional "v"s indicate increases in verbosity.
30
31 This mutex helper expects the system Python interpreter to have access to the
32 etcd Python module. It also expects an etcd cluster to be configured and
33 running. To integrate with this, there is an optional config file of the
34 following format:
35
36 key = value
37
38 The following configuration variables (and their defaults) are defined for
39 use by this script:
40
41 port = 2379 # connecting port for the etcd cluster
42 lock_ttl = 9 # seconds for TTL
43 refresh = 2 # seconds between attempts to maintain lock
44 locks_dir = _ctdb # where to store CTDB locks in etcd
45 # The final etcd directory for any given lock looks like:
46 # /_locks/{locks_dir}/{netbios name}/
47
48 In addition, any keyword parameter that can be used to configure an etcd
49 client may be specified and modified here. For more documentation on these
50 parameters, see here: https://github.com/jplana/python-etcd/
51
52 """
53 import signal
54 import time
55 import sys
56 import os
57 import argparse
58 import logging
59 import subprocess
60
61 import etcd
62
63 # Helper Functions ------------------------------------------------------------
64 #
65
66
67 def process_args():
68 '''Process command-line arguments and return them.
69 '''
70 parser = argparse.ArgumentParser(
71 description=__doc__,
72 epilog='',
73 formatter_class=argparse.RawDescriptionHelpFormatter)
74 parser.add_argument('-v', '--verbose',
75 action='count',
76 help='Display verbose output to stderr. '
77 'Default is no output.',
78 default=0,
79 )
80 parser.add_argument('-c', '--config',
81 action='store',
82 help='Configuration file to use. The default behavior '
83 'is to look is the base CTDB configuration '
84 'directory, which can be overwritten by setting '
85 'the CTDB_BASE environment variable, for a file '
86 'called \'etcd\'. Default value is %(default)s.',
87 default=os.path.join(os.getenv('CTDB_BASE',
88 '/usr/local/etc/ctdb'),
89 'etcd'),
90 )
91 args = parser.parse_args()
92
93 return args
94
95
96 def setup_logging(verbose):
97 '''Setup logging based on specified verbosity.
98 '''
99
100 log_levels = [logging.ERROR, logging.WARNING, logging.DEBUG]
101 logging.basicConfig(level=log_levels[min(verbose, len(log_levels)-1)])
102
103
104 def sigterm_handler(signum, frame):
105 """Handler for SIGTERM signals.
106 """
107 sys.exit()
108
109
110 def print_nonl(out):
111 """Dumb shortcut for printing to stdout with no newline.
112 """
113 sys.stdout.write(str(out))
114 sys.stdout.flush()
115
116
117 def int_or_not(s):
118 """Try to convert input to an integer.
119 """
120 try:
121 return int(s)
122 except ValueError:
123 return s
124
125 # Mainline --------------------------------------------------------------------
126 #
127
128
129 def main():
130 args = process_args()
131
132 setup_logging(args.verbose)
133
134 # etcd config defaults
135 etcd_config = {
136 'port': 2379,
137 'locks_dir': '_ctdb',
138 'lock_ttl': 9,
139 'lock_refresh': 2,
140 }
141 # Find and read etcd config file
142 etcd_client_params = (
143 'host',
144 'port',
145 'srv_domain',
146 'version_prefix',
147 'read_timeout',
148 'allow_redirect',
149 'protocol',
150 'cert',
151 'ca_cert',
152 'username',
153 'password',
154 'allow_reconnect',
155 'use_proxies',
156 'expected_cluster_id',
157 'per_host_pool_size',
158 )
159 if os.path.isfile(args.config):
160 f = open(args.config, 'r')
161 for line in f:
162 (key, value) = line.split("=", 1)
163 etcd_config[key.strip()] = int_or_not(value.strip())
164
165 # Minor hack: call out to shell to retrieve CTDB netbios name and PNN.
166 tmp = subprocess.Popen("testparm -s --parameter-name 'netbios name'; \
167 ctdb pnn",
168 shell=True,
169 universal_newlines=True,
170 stdout=subprocess.PIPE
171 ).stdout.read().strip()
172 nb_name, pnn = tmp.split()
173
174 # Try to get and hold the lock
175 try:
176 client = etcd.Client(
177 **{k: etcd_config[k] for k in
178 set(etcd_client_params).intersection(etcd_config)})
179 lock = etcd.Lock(client, etcd_config['locks_dir'] + "/" + nb_name)
180 lock._uuid = lock._uuid + "_" + pnn
181 logging.debug("Updated lock UUID: %s", lock.uuid)
182 ppid = os.getppid()
183 while True:
184 lock.acquire(blocking=False, lock_ttl=etcd_config['lock_ttl'])
185 if lock.is_acquired:
186 print_nonl(0)
187 else:
188 locks = "No locks found."
189 if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
190 keys = client.read(lock.path, recursive=True)
191 if keys is not None:
192 locks = "Existing locks:\n "
193 locks += '\n '.join(
194 (child.key + ": " + child.value for child in
195 keys.children))
196 logging.debug("Lock contention. %s", locks)
197 print_nonl(1)
198 break
199 os.kill(ppid, 0)
200 time.sleep(etcd_config['lock_refresh'])
201 except (OSError, SystemExit):
202 if lock is not None and lock.is_acquired:
203 lock.release()
204 except Exception:
205 print_nonl(3)
206 if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
207 raise
208
209
210 if __name__ == "__main__":
211 signal.signal(signal.SIGTERM, sigterm_handler)
212
213 main()