root / lib / utils.py @ ac492887
History | View | Annotate | Download (106.3 kB)
1 | 2f31098c | Iustin Pop | #
|
---|---|---|---|
2 | a8083063 | Iustin Pop | #
|
3 | a8083063 | Iustin Pop | |
4 | a8083063 | Iustin Pop | # Copyright (C) 2006, 2007 Google Inc.
|
5 | a8083063 | Iustin Pop | #
|
6 | a8083063 | Iustin Pop | # This program is free software; you can redistribute it and/or modify
|
7 | a8083063 | Iustin Pop | # it under the terms of the GNU General Public License as published by
|
8 | a8083063 | Iustin Pop | # the Free Software Foundation; either version 2 of the License, or
|
9 | a8083063 | Iustin Pop | # (at your option) any later version.
|
10 | a8083063 | Iustin Pop | #
|
11 | a8083063 | Iustin Pop | # This program is distributed in the hope that it will be useful, but
|
12 | a8083063 | Iustin Pop | # WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 | a8083063 | Iustin Pop | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 | a8083063 | Iustin Pop | # General Public License for more details.
|
15 | a8083063 | Iustin Pop | #
|
16 | a8083063 | Iustin Pop | # You should have received a copy of the GNU General Public License
|
17 | a8083063 | Iustin Pop | # along with this program; if not, write to the Free Software
|
18 | a8083063 | Iustin Pop | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 | a8083063 | Iustin Pop | # 02110-1301, USA.
|
20 | a8083063 | Iustin Pop | |
21 | a8083063 | Iustin Pop | |
22 | 58885d79 | Iustin Pop | """Ganeti utility module.
|
23 | 58885d79 | Iustin Pop |
|
24 | 58885d79 | Iustin Pop | This module holds functions that can be used in both daemons (all) and
|
25 | 58885d79 | Iustin Pop | the command line scripts.
|
26 | 899d2a81 | Michael Hanselmann |
|
27 | a8083063 | Iustin Pop | """
|
28 | a8083063 | Iustin Pop | |
29 | a8083063 | Iustin Pop | |
30 | a8083063 | Iustin Pop | import os |
31 | c1dd99d4 | Michael Hanselmann | import sys |
32 | a8083063 | Iustin Pop | import time |
33 | 113b55aa | Iustin Pop | import subprocess |
34 | a8083063 | Iustin Pop | import re |
35 | a8083063 | Iustin Pop | import socket |
36 | a8083063 | Iustin Pop | import tempfile |
37 | a8083063 | Iustin Pop | import shutil |
38 | 4ca1b175 | Alexander Schreiber | import errno |
39 | 2f8b60b3 | Iustin Pop | import pwd |
40 | 78feb6fb | Guido Trotter | import itertools |
41 | 9c233417 | Iustin Pop | import select |
42 | 9c233417 | Iustin Pop | import fcntl |
43 | 8f765069 | Iustin Pop | import resource |
44 | bb698c1f | Iustin Pop | import logging |
45 | 551b6283 | Iustin Pop | import logging.handlers |
46 | de499029 | Michael Hanselmann | import signal |
47 | bdd5e420 | Michael Hanselmann | import OpenSSL |
48 | 27e46076 | Michael Hanselmann | import datetime |
49 | 27e46076 | Michael Hanselmann | import calendar |
50 | 68857643 | Michael Hanselmann | import hmac |
51 | 339be5a8 | Michael Hanselmann | import collections |
52 | f93f2016 | Michael Hanselmann | import struct |
53 | f93f2016 | Michael Hanselmann | import IN |
54 | 9c233417 | Iustin Pop | |
55 | 9c233417 | Iustin Pop | from cStringIO import StringIO |
56 | a8083063 | Iustin Pop | |
57 | 7ffe8fba | Carlos Valiente | try:
|
58 | 23e0ef8c | Guido Trotter | # pylint: disable-msg=F0401
|
59 | 4b6fa0bf | Luca Bigliardi | import ctypes |
60 | 4b6fa0bf | Luca Bigliardi | except ImportError: |
61 | 4b6fa0bf | Luca Bigliardi | ctypes = None
|
62 | 4b6fa0bf | Luca Bigliardi | |
63 | a8083063 | Iustin Pop | from ganeti import errors |
64 | 3aecd2c7 | Iustin Pop | from ganeti import constants |
65 | 716a32cb | Guido Trotter | from ganeti import compat |
66 | a8083063 | Iustin Pop | |
67 | 16abfbc2 | Alexander Schreiber | |
68 | a8083063 | Iustin Pop | _locksheld = [] |
69 | a8083063 | Iustin Pop | _re_shell_unquoted = re.compile('^[-.,=:/_+@A-Za-z0-9]+$')
|
70 | a8083063 | Iustin Pop | |
71 | e67bd559 | Michael Hanselmann | debug_locks = False
|
72 | 58885d79 | Iustin Pop | |
73 | 58885d79 | Iustin Pop | #: when set to True, L{RunCmd} is disabled
|
74 | b74159ee | Iustin Pop | no_fork = False
|
75 | f362096f | Iustin Pop | |
76 | 13998ef2 | Michael Hanselmann | _RANDOM_UUID_FILE = "/proc/sys/kernel/random/uuid"
|
77 | 13998ef2 | Michael Hanselmann | |
78 | 68857643 | Michael Hanselmann | HEX_CHAR_RE = r"[a-zA-Z0-9]"
|
79 | 68857643 | Michael Hanselmann | VALID_X509_SIGNATURE_SALT = re.compile("^%s+$" % HEX_CHAR_RE, re.S)
|
80 | 68857643 | Michael Hanselmann | X509_SIGNATURE = re.compile(r"^%s:\s*(?P<salt>%s+)/(?P<sign>%s+)$" %
|
81 | 68857643 | Michael Hanselmann | (re.escape(constants.X509_CERT_SIGNATURE_HEADER), |
82 | 68857643 | Michael Hanselmann | HEX_CHAR_RE, HEX_CHAR_RE), |
83 | 68857643 | Michael Hanselmann | re.S | re.I) |
84 | 68857643 | Michael Hanselmann | |
85 | 28f34048 | Michael Hanselmann | _VALID_SERVICE_NAME_RE = re.compile("^[-_.a-zA-Z0-9]{1,128}$")
|
86 | 28f34048 | Michael Hanselmann | |
87 | f93f2016 | Michael Hanselmann | # Structure definition for getsockopt(SOL_SOCKET, SO_PEERCRED, ...):
|
88 | f93f2016 | Michael Hanselmann | # struct ucred { pid_t pid; uid_t uid; gid_t gid; };
|
89 | f93f2016 | Michael Hanselmann | #
|
90 | f93f2016 | Michael Hanselmann | # The GNU C Library defines gid_t and uid_t to be "unsigned int" and
|
91 | f93f2016 | Michael Hanselmann | # pid_t to "int".
|
92 | f93f2016 | Michael Hanselmann | #
|
93 | f93f2016 | Michael Hanselmann | # IEEE Std 1003.1-2008:
|
94 | f93f2016 | Michael Hanselmann | # "nlink_t, uid_t, gid_t, and id_t shall be integer types"
|
95 | f93f2016 | Michael Hanselmann | # "blksize_t, pid_t, and ssize_t shall be signed integer types"
|
96 | f93f2016 | Michael Hanselmann | _STRUCT_UCRED = "iII"
|
97 | f93f2016 | Michael Hanselmann | _STRUCT_UCRED_SIZE = struct.calcsize(_STRUCT_UCRED) |
98 | f93f2016 | Michael Hanselmann | |
99 | 24d70417 | Michael Hanselmann | # Certificate verification results
|
100 | 24d70417 | Michael Hanselmann | (CERT_WARNING, |
101 | 24d70417 | Michael Hanselmann | CERT_ERROR) = range(1, 3) |
102 | 24d70417 | Michael Hanselmann | |
103 | 4b6fa0bf | Luca Bigliardi | # Flags for mlockall() (from bits/mman.h)
|
104 | 4b6fa0bf | Luca Bigliardi | _MCL_CURRENT = 1
|
105 | 4b6fa0bf | Luca Bigliardi | _MCL_FUTURE = 2
|
106 | 4b6fa0bf | Luca Bigliardi | |
107 | 7c0d6283 | Michael Hanselmann | |
108 | a8083063 | Iustin Pop | class RunResult(object): |
109 | 58885d79 | Iustin Pop | """Holds the result of running external programs.
|
110 | 58885d79 | Iustin Pop |
|
111 | 58885d79 | Iustin Pop | @type exit_code: int
|
112 | 58885d79 | Iustin Pop | @ivar exit_code: the exit code of the program, or None (if the program
|
113 | 58885d79 | Iustin Pop | didn't exit())
|
114 | 58885d79 | Iustin Pop | @type signal: int or None
|
115 | 58885d79 | Iustin Pop | @ivar signal: the signal that caused the program to finish, or None
|
116 | 58885d79 | Iustin Pop | (if the program wasn't terminated by a signal)
|
117 | 58885d79 | Iustin Pop | @type stdout: str
|
118 | 58885d79 | Iustin Pop | @ivar stdout: the standard output of the program
|
119 | 58885d79 | Iustin Pop | @type stderr: str
|
120 | 58885d79 | Iustin Pop | @ivar stderr: the standard error of the program
|
121 | 58885d79 | Iustin Pop | @type failed: boolean
|
122 | 58885d79 | Iustin Pop | @ivar failed: True in case the program was
|
123 | 58885d79 | Iustin Pop | terminated by a signal or exited with a non-zero exit code
|
124 | 58885d79 | Iustin Pop | @ivar fail_reason: a string detailing the termination reason
|
125 | a8083063 | Iustin Pop |
|
126 | a8083063 | Iustin Pop | """
|
127 | a8083063 | Iustin Pop | __slots__ = ["exit_code", "signal", "stdout", "stderr", |
128 | a8083063 | Iustin Pop | "failed", "fail_reason", "cmd"] |
129 | a8083063 | Iustin Pop | |
130 | a8083063 | Iustin Pop | |
131 | 38206f3c | Iustin Pop | def __init__(self, exit_code, signal_, stdout, stderr, cmd): |
132 | a8083063 | Iustin Pop | self.cmd = cmd
|
133 | a8083063 | Iustin Pop | self.exit_code = exit_code
|
134 | 38206f3c | Iustin Pop | self.signal = signal_
|
135 | a8083063 | Iustin Pop | self.stdout = stdout
|
136 | a8083063 | Iustin Pop | self.stderr = stderr
|
137 | 38206f3c | Iustin Pop | self.failed = (signal_ is not None or exit_code != 0) |
138 | a8083063 | Iustin Pop | |
139 | a8083063 | Iustin Pop | if self.signal is not None: |
140 | a8083063 | Iustin Pop | self.fail_reason = "terminated by signal %s" % self.signal |
141 | a8083063 | Iustin Pop | elif self.exit_code is not None: |
142 | a8083063 | Iustin Pop | self.fail_reason = "exited with exit code %s" % self.exit_code |
143 | a8083063 | Iustin Pop | else:
|
144 | a8083063 | Iustin Pop | self.fail_reason = "unable to determine termination reason" |
145 | a8083063 | Iustin Pop | |
146 | bb698c1f | Iustin Pop | if self.failed: |
147 | bb698c1f | Iustin Pop | logging.debug("Command '%s' failed (%s); output: %s",
|
148 | bb698c1f | Iustin Pop | self.cmd, self.fail_reason, self.output) |
149 | f362096f | Iustin Pop | |
150 | a8083063 | Iustin Pop | def _GetOutput(self): |
151 | a8083063 | Iustin Pop | """Returns the combined stdout and stderr for easier usage.
|
152 | a8083063 | Iustin Pop |
|
153 | a8083063 | Iustin Pop | """
|
154 | a8083063 | Iustin Pop | return self.stdout + self.stderr |
155 | a8083063 | Iustin Pop | |
156 | a8083063 | Iustin Pop | output = property(_GetOutput, None, None, "Return full output") |
157 | a8083063 | Iustin Pop | |
158 | a8083063 | Iustin Pop | |
159 | bb3776b4 | Michael Hanselmann | def _BuildCmdEnvironment(env, reset): |
160 | c1dd99d4 | Michael Hanselmann | """Builds the environment for an external program.
|
161 | c1dd99d4 | Michael Hanselmann |
|
162 | c1dd99d4 | Michael Hanselmann | """
|
163 | bb3776b4 | Michael Hanselmann | if reset:
|
164 | bb3776b4 | Michael Hanselmann | cmd_env = {} |
165 | bb3776b4 | Michael Hanselmann | else:
|
166 | bb3776b4 | Michael Hanselmann | cmd_env = os.environ.copy() |
167 | bb3776b4 | Michael Hanselmann | cmd_env["LC_ALL"] = "C" |
168 | bb3776b4 | Michael Hanselmann | |
169 | c1dd99d4 | Michael Hanselmann | if env is not None: |
170 | c1dd99d4 | Michael Hanselmann | cmd_env.update(env) |
171 | bb3776b4 | Michael Hanselmann | |
172 | c1dd99d4 | Michael Hanselmann | return cmd_env
|
173 | c1dd99d4 | Michael Hanselmann | |
174 | c1dd99d4 | Michael Hanselmann | |
175 | bb3776b4 | Michael Hanselmann | def RunCmd(cmd, env=None, output=None, cwd="/", reset_env=False): |
176 | a8083063 | Iustin Pop | """Execute a (shell) command.
|
177 | a8083063 | Iustin Pop |
|
178 | a8083063 | Iustin Pop | The command should not read from its standard input, as it will be
|
179 | a8083063 | Iustin Pop | closed.
|
180 | a8083063 | Iustin Pop |
|
181 | c1dd99d4 | Michael Hanselmann | @type cmd: string or list
|
182 | 36117c2b | Iustin Pop | @param cmd: Command to run
|
183 | 2557ff82 | Guido Trotter | @type env: dict
|
184 | c1dd99d4 | Michael Hanselmann | @param env: Additional environment variables
|
185 | 36117c2b | Iustin Pop | @type output: str
|
186 | 58885d79 | Iustin Pop | @param output: if desired, the output of the command can be
|
187 | 36117c2b | Iustin Pop | saved in a file instead of the RunResult instance; this
|
188 | 36117c2b | Iustin Pop | parameter denotes the file name (if not None)
|
189 | 8797df43 | Iustin Pop | @type cwd: string
|
190 | 8797df43 | Iustin Pop | @param cwd: if specified, will be used as the working
|
191 | 8797df43 | Iustin Pop | directory for the command; the default will be /
|
192 | bf4daac9 | Guido Trotter | @type reset_env: boolean
|
193 | bf4daac9 | Guido Trotter | @param reset_env: whether to reset or keep the default os environment
|
194 | 36117c2b | Iustin Pop | @rtype: L{RunResult}
|
195 | 58885d79 | Iustin Pop | @return: RunResult instance
|
196 | 5bbd3f7f | Michael Hanselmann | @raise errors.ProgrammerError: if we call this when forks are disabled
|
197 | a8083063 | Iustin Pop |
|
198 | a8083063 | Iustin Pop | """
|
199 | b74159ee | Iustin Pop | if no_fork:
|
200 | b74159ee | Iustin Pop | raise errors.ProgrammerError("utils.RunCmd() called with fork() disabled") |
201 | b74159ee | Iustin Pop | |
202 | c1dd99d4 | Michael Hanselmann | if isinstance(cmd, basestring): |
203 | c1dd99d4 | Michael Hanselmann | strcmd = cmd |
204 | c1dd99d4 | Michael Hanselmann | shell = True
|
205 | c1dd99d4 | Michael Hanselmann | else:
|
206 | a8083063 | Iustin Pop | cmd = [str(val) for val in cmd] |
207 | c1dd99d4 | Michael Hanselmann | strcmd = ShellQuoteArgs(cmd) |
208 | 113b55aa | Iustin Pop | shell = False
|
209 | c1dd99d4 | Michael Hanselmann | |
210 | c1dd99d4 | Michael Hanselmann | if output:
|
211 | c1dd99d4 | Michael Hanselmann | logging.debug("RunCmd %s, output file '%s'", strcmd, output)
|
212 | 113b55aa | Iustin Pop | else:
|
213 | c1dd99d4 | Michael Hanselmann | logging.debug("RunCmd %s", strcmd)
|
214 | 2557ff82 | Guido Trotter | |
215 | bb3776b4 | Michael Hanselmann | cmd_env = _BuildCmdEnvironment(env, reset_env) |
216 | 2557ff82 | Guido Trotter | |
217 | c803b052 | Iustin Pop | try:
|
218 | c803b052 | Iustin Pop | if output is None: |
219 | c803b052 | Iustin Pop | out, err, status = _RunCmdPipe(cmd, cmd_env, shell, cwd) |
220 | c803b052 | Iustin Pop | else:
|
221 | c803b052 | Iustin Pop | status = _RunCmdFile(cmd, cmd_env, shell, output, cwd) |
222 | c803b052 | Iustin Pop | out = err = ""
|
223 | c803b052 | Iustin Pop | except OSError, err: |
224 | c803b052 | Iustin Pop | if err.errno == errno.ENOENT:
|
225 | c803b052 | Iustin Pop | raise errors.OpExecError("Can't execute '%s': not found (%s)" % |
226 | c803b052 | Iustin Pop | (strcmd, err)) |
227 | c803b052 | Iustin Pop | else:
|
228 | c803b052 | Iustin Pop | raise
|
229 | 36117c2b | Iustin Pop | |
230 | 36117c2b | Iustin Pop | if status >= 0: |
231 | 36117c2b | Iustin Pop | exitcode = status |
232 | 36117c2b | Iustin Pop | signal_ = None
|
233 | 36117c2b | Iustin Pop | else:
|
234 | 36117c2b | Iustin Pop | exitcode = None
|
235 | 36117c2b | Iustin Pop | signal_ = -status |
236 | 36117c2b | Iustin Pop | |
237 | 36117c2b | Iustin Pop | return RunResult(exitcode, signal_, out, err, strcmd)
|
238 | 36117c2b | Iustin Pop | |
239 | ae59efea | Michael Hanselmann | |
240 | c1dd99d4 | Michael Hanselmann | def StartDaemon(cmd, env=None, cwd="/", output=None, output_fd=None, |
241 | c1dd99d4 | Michael Hanselmann | pidfile=None):
|
242 | c1dd99d4 | Michael Hanselmann | """Start a daemon process after forking twice.
|
243 | c1dd99d4 | Michael Hanselmann |
|
244 | c1dd99d4 | Michael Hanselmann | @type cmd: string or list
|
245 | c1dd99d4 | Michael Hanselmann | @param cmd: Command to run
|
246 | c1dd99d4 | Michael Hanselmann | @type env: dict
|
247 | c1dd99d4 | Michael Hanselmann | @param env: Additional environment variables
|
248 | c1dd99d4 | Michael Hanselmann | @type cwd: string
|
249 | c1dd99d4 | Michael Hanselmann | @param cwd: Working directory for the program
|
250 | c1dd99d4 | Michael Hanselmann | @type output: string
|
251 | c1dd99d4 | Michael Hanselmann | @param output: Path to file in which to save the output
|
252 | c1dd99d4 | Michael Hanselmann | @type output_fd: int
|
253 | c1dd99d4 | Michael Hanselmann | @param output_fd: File descriptor for output
|
254 | c1dd99d4 | Michael Hanselmann | @type pidfile: string
|
255 | c1dd99d4 | Michael Hanselmann | @param pidfile: Process ID file
|
256 | c1dd99d4 | Michael Hanselmann | @rtype: int
|
257 | c1dd99d4 | Michael Hanselmann | @return: Daemon process ID
|
258 | c1dd99d4 | Michael Hanselmann | @raise errors.ProgrammerError: if we call this when forks are disabled
|
259 | c1dd99d4 | Michael Hanselmann |
|
260 | c1dd99d4 | Michael Hanselmann | """
|
261 | c1dd99d4 | Michael Hanselmann | if no_fork:
|
262 | c1dd99d4 | Michael Hanselmann | raise errors.ProgrammerError("utils.StartDaemon() called with fork()" |
263 | c1dd99d4 | Michael Hanselmann | " disabled")
|
264 | c1dd99d4 | Michael Hanselmann | |
265 | c1dd99d4 | Michael Hanselmann | if output and not (bool(output) ^ (output_fd is not None)): |
266 | c1dd99d4 | Michael Hanselmann | raise errors.ProgrammerError("Only one of 'output' and 'output_fd' can be" |
267 | c1dd99d4 | Michael Hanselmann | " specified")
|
268 | c1dd99d4 | Michael Hanselmann | |
269 | c1dd99d4 | Michael Hanselmann | if isinstance(cmd, basestring): |
270 | c1dd99d4 | Michael Hanselmann | cmd = ["/bin/sh", "-c", cmd] |
271 | c1dd99d4 | Michael Hanselmann | |
272 | c1dd99d4 | Michael Hanselmann | strcmd = ShellQuoteArgs(cmd) |
273 | c1dd99d4 | Michael Hanselmann | |
274 | c1dd99d4 | Michael Hanselmann | if output:
|
275 | c1dd99d4 | Michael Hanselmann | logging.debug("StartDaemon %s, output file '%s'", strcmd, output)
|
276 | c1dd99d4 | Michael Hanselmann | else:
|
277 | c1dd99d4 | Michael Hanselmann | logging.debug("StartDaemon %s", strcmd)
|
278 | c1dd99d4 | Michael Hanselmann | |
279 | bb3776b4 | Michael Hanselmann | cmd_env = _BuildCmdEnvironment(env, False)
|
280 | c1dd99d4 | Michael Hanselmann | |
281 | c1dd99d4 | Michael Hanselmann | # Create pipe for sending PID back
|
282 | c1dd99d4 | Michael Hanselmann | (pidpipe_read, pidpipe_write) = os.pipe() |
283 | c1dd99d4 | Michael Hanselmann | try:
|
284 | c1dd99d4 | Michael Hanselmann | try:
|
285 | c1dd99d4 | Michael Hanselmann | # Create pipe for sending error messages
|
286 | c1dd99d4 | Michael Hanselmann | (errpipe_read, errpipe_write) = os.pipe() |
287 | c1dd99d4 | Michael Hanselmann | try:
|
288 | c1dd99d4 | Michael Hanselmann | try:
|
289 | c1dd99d4 | Michael Hanselmann | # First fork
|
290 | c1dd99d4 | Michael Hanselmann | pid = os.fork() |
291 | c1dd99d4 | Michael Hanselmann | if pid == 0: |
292 | c1dd99d4 | Michael Hanselmann | try:
|
293 | c1dd99d4 | Michael Hanselmann | # Child process, won't return
|
294 | e0bb431e | Michael Hanselmann | _StartDaemonChild(errpipe_read, errpipe_write, |
295 | e0bb431e | Michael Hanselmann | pidpipe_read, pidpipe_write, |
296 | e0bb431e | Michael Hanselmann | cmd, cmd_env, cwd, |
297 | e0bb431e | Michael Hanselmann | output, output_fd, pidfile) |
298 | c1dd99d4 | Michael Hanselmann | finally:
|
299 | c1dd99d4 | Michael Hanselmann | # Well, maybe child process failed
|
300 | e0bb431e | Michael Hanselmann | os._exit(1) # pylint: disable-msg=W0212 |
301 | c1dd99d4 | Michael Hanselmann | finally:
|
302 | c1dd99d4 | Michael Hanselmann | _CloseFDNoErr(errpipe_write) |
303 | c1dd99d4 | Michael Hanselmann | |
304 | c1dd99d4 | Michael Hanselmann | # Wait for daemon to be started (or an error message to arrive) and read
|
305 | c1dd99d4 | Michael Hanselmann | # up to 100 KB as an error message
|
306 | c1dd99d4 | Michael Hanselmann | errormsg = RetryOnSignal(os.read, errpipe_read, 100 * 1024) |
307 | c1dd99d4 | Michael Hanselmann | finally:
|
308 | c1dd99d4 | Michael Hanselmann | _CloseFDNoErr(errpipe_read) |
309 | c1dd99d4 | Michael Hanselmann | finally:
|
310 | c1dd99d4 | Michael Hanselmann | _CloseFDNoErr(pidpipe_write) |
311 | c1dd99d4 | Michael Hanselmann | |
312 | c1dd99d4 | Michael Hanselmann | # Read up to 128 bytes for PID
|
313 | c1dd99d4 | Michael Hanselmann | pidtext = RetryOnSignal(os.read, pidpipe_read, 128)
|
314 | c1dd99d4 | Michael Hanselmann | finally:
|
315 | c1dd99d4 | Michael Hanselmann | _CloseFDNoErr(pidpipe_read) |
316 | c1dd99d4 | Michael Hanselmann | |
317 | c1dd99d4 | Michael Hanselmann | # Try to avoid zombies by waiting for child process
|
318 | c1dd99d4 | Michael Hanselmann | try:
|
319 | c1dd99d4 | Michael Hanselmann | os.waitpid(pid, 0)
|
320 | c1dd99d4 | Michael Hanselmann | except OSError: |
321 | c1dd99d4 | Michael Hanselmann | pass
|
322 | c1dd99d4 | Michael Hanselmann | |
323 | c1dd99d4 | Michael Hanselmann | if errormsg:
|
324 | c1dd99d4 | Michael Hanselmann | raise errors.OpExecError("Error when starting daemon process: %r" % |
325 | c1dd99d4 | Michael Hanselmann | errormsg) |
326 | c1dd99d4 | Michael Hanselmann | |
327 | c1dd99d4 | Michael Hanselmann | try:
|
328 | c1dd99d4 | Michael Hanselmann | return int(pidtext) |
329 | c1dd99d4 | Michael Hanselmann | except (ValueError, TypeError), err: |
330 | c1dd99d4 | Michael Hanselmann | raise errors.OpExecError("Error while trying to parse PID %r: %s" % |
331 | c1dd99d4 | Michael Hanselmann | (pidtext, err)) |
332 | c1dd99d4 | Michael Hanselmann | |
333 | c1dd99d4 | Michael Hanselmann | |
334 | e0bb431e | Michael Hanselmann | def _StartDaemonChild(errpipe_read, errpipe_write, |
335 | e0bb431e | Michael Hanselmann | pidpipe_read, pidpipe_write, |
336 | e0bb431e | Michael Hanselmann | args, env, cwd, |
337 | e0bb431e | Michael Hanselmann | output, fd_output, pidfile): |
338 | c1dd99d4 | Michael Hanselmann | """Child process for starting daemon.
|
339 | c1dd99d4 | Michael Hanselmann |
|
340 | c1dd99d4 | Michael Hanselmann | """
|
341 | c1dd99d4 | Michael Hanselmann | try:
|
342 | c1dd99d4 | Michael Hanselmann | # Close parent's side
|
343 | c1dd99d4 | Michael Hanselmann | _CloseFDNoErr(errpipe_read) |
344 | c1dd99d4 | Michael Hanselmann | _CloseFDNoErr(pidpipe_read) |
345 | c1dd99d4 | Michael Hanselmann | |
346 | c1dd99d4 | Michael Hanselmann | # First child process
|
347 | c1dd99d4 | Michael Hanselmann | os.chdir("/")
|
348 | c1dd99d4 | Michael Hanselmann | os.umask(077)
|
349 | c1dd99d4 | Michael Hanselmann | os.setsid() |
350 | c1dd99d4 | Michael Hanselmann | |
351 | c1dd99d4 | Michael Hanselmann | # And fork for the second time
|
352 | c1dd99d4 | Michael Hanselmann | pid = os.fork() |
353 | c1dd99d4 | Michael Hanselmann | if pid != 0: |
354 | c1dd99d4 | Michael Hanselmann | # Exit first child process
|
355 | c1dd99d4 | Michael Hanselmann | os._exit(0) # pylint: disable-msg=W0212 |
356 | c1dd99d4 | Michael Hanselmann | |
357 | c1dd99d4 | Michael Hanselmann | # Make sure pipe is closed on execv* (and thereby notifies original process)
|
358 | c1dd99d4 | Michael Hanselmann | SetCloseOnExecFlag(errpipe_write, True)
|
359 | c1dd99d4 | Michael Hanselmann | |
360 | c1dd99d4 | Michael Hanselmann | # List of file descriptors to be left open
|
361 | c1dd99d4 | Michael Hanselmann | noclose_fds = [errpipe_write] |
362 | c1dd99d4 | Michael Hanselmann | |
363 | c1dd99d4 | Michael Hanselmann | # Open PID file
|
364 | c1dd99d4 | Michael Hanselmann | if pidfile:
|
365 | c1dd99d4 | Michael Hanselmann | try:
|
366 | c1dd99d4 | Michael Hanselmann | # TODO: Atomic replace with another locked file instead of writing into
|
367 | c1dd99d4 | Michael Hanselmann | # it after creating
|
368 | c1dd99d4 | Michael Hanselmann | fd_pidfile = os.open(pidfile, os.O_WRONLY | os.O_CREAT, 0600)
|
369 | c1dd99d4 | Michael Hanselmann | |
370 | c1dd99d4 | Michael Hanselmann | # Lock the PID file (and fail if not possible to do so). Any code
|
371 | c1dd99d4 | Michael Hanselmann | # wanting to send a signal to the daemon should try to lock the PID
|
372 | c1dd99d4 | Michael Hanselmann | # file before reading it. If acquiring the lock succeeds, the daemon is
|
373 | c1dd99d4 | Michael Hanselmann | # no longer running and the signal should not be sent.
|
374 | c1dd99d4 | Michael Hanselmann | LockFile(fd_pidfile) |
375 | c1dd99d4 | Michael Hanselmann | |
376 | c1dd99d4 | Michael Hanselmann | os.write(fd_pidfile, "%d\n" % os.getpid())
|
377 | c1dd99d4 | Michael Hanselmann | except Exception, err: |
378 | c1dd99d4 | Michael Hanselmann | raise Exception("Creating and locking PID file failed: %s" % err) |
379 | c1dd99d4 | Michael Hanselmann | |
380 | c1dd99d4 | Michael Hanselmann | # Keeping the file open to hold the lock
|
381 | c1dd99d4 | Michael Hanselmann | noclose_fds.append(fd_pidfile) |
382 | c1dd99d4 | Michael Hanselmann | |
383 | c1dd99d4 | Michael Hanselmann | SetCloseOnExecFlag(fd_pidfile, False)
|
384 | c1dd99d4 | Michael Hanselmann | else:
|
385 | c1dd99d4 | Michael Hanselmann | fd_pidfile = None
|
386 | c1dd99d4 | Michael Hanselmann | |
387 | c1dd99d4 | Michael Hanselmann | # Open /dev/null
|
388 | c1dd99d4 | Michael Hanselmann | fd_devnull = os.open(os.devnull, os.O_RDWR) |
389 | c1dd99d4 | Michael Hanselmann | |
390 | c1dd99d4 | Michael Hanselmann | assert not output or (bool(output) ^ (fd_output is not None)) |
391 | c1dd99d4 | Michael Hanselmann | |
392 | c1dd99d4 | Michael Hanselmann | if fd_output is not None: |
393 | c1dd99d4 | Michael Hanselmann | pass
|
394 | c1dd99d4 | Michael Hanselmann | elif output:
|
395 | c1dd99d4 | Michael Hanselmann | # Open output file
|
396 | c1dd99d4 | Michael Hanselmann | try:
|
397 | c1dd99d4 | Michael Hanselmann | # TODO: Implement flag to set append=yes/no
|
398 | c1dd99d4 | Michael Hanselmann | fd_output = os.open(output, os.O_WRONLY | os.O_CREAT, 0600)
|
399 | c1dd99d4 | Michael Hanselmann | except EnvironmentError, err: |
400 | c1dd99d4 | Michael Hanselmann | raise Exception("Opening output file failed: %s" % err) |
401 | c1dd99d4 | Michael Hanselmann | else:
|
402 | c1dd99d4 | Michael Hanselmann | fd_output = fd_devnull |
403 | c1dd99d4 | Michael Hanselmann | |
404 | c1dd99d4 | Michael Hanselmann | # Redirect standard I/O
|
405 | c1dd99d4 | Michael Hanselmann | os.dup2(fd_devnull, 0)
|
406 | c1dd99d4 | Michael Hanselmann | os.dup2(fd_output, 1)
|
407 | c1dd99d4 | Michael Hanselmann | os.dup2(fd_output, 2)
|
408 | c1dd99d4 | Michael Hanselmann | |
409 | c1dd99d4 | Michael Hanselmann | # Send daemon PID to parent
|
410 | c1dd99d4 | Michael Hanselmann | RetryOnSignal(os.write, pidpipe_write, str(os.getpid()))
|
411 | c1dd99d4 | Michael Hanselmann | |
412 | c1dd99d4 | Michael Hanselmann | # Close all file descriptors except stdio and error message pipe
|
413 | c1dd99d4 | Michael Hanselmann | CloseFDs(noclose_fds=noclose_fds) |
414 | c1dd99d4 | Michael Hanselmann | |
415 | c1dd99d4 | Michael Hanselmann | # Change working directory
|
416 | c1dd99d4 | Michael Hanselmann | os.chdir(cwd) |
417 | c1dd99d4 | Michael Hanselmann | |
418 | c1dd99d4 | Michael Hanselmann | if env is None: |
419 | c1dd99d4 | Michael Hanselmann | os.execvp(args[0], args)
|
420 | c1dd99d4 | Michael Hanselmann | else:
|
421 | c1dd99d4 | Michael Hanselmann | os.execvpe(args[0], args, env)
|
422 | c1dd99d4 | Michael Hanselmann | except: # pylint: disable-msg=W0702 |
423 | c1dd99d4 | Michael Hanselmann | try:
|
424 | c1dd99d4 | Michael Hanselmann | # Report errors to original process
|
425 | c1dd99d4 | Michael Hanselmann | buf = str(sys.exc_info()[1]) |
426 | c1dd99d4 | Michael Hanselmann | |
427 | c1dd99d4 | Michael Hanselmann | RetryOnSignal(os.write, errpipe_write, buf) |
428 | c1dd99d4 | Michael Hanselmann | except: # pylint: disable-msg=W0702 |
429 | c1dd99d4 | Michael Hanselmann | # Ignore errors in error handling
|
430 | c1dd99d4 | Michael Hanselmann | pass
|
431 | c1dd99d4 | Michael Hanselmann | |
432 | c1dd99d4 | Michael Hanselmann | os._exit(1) # pylint: disable-msg=W0212 |
433 | c1dd99d4 | Michael Hanselmann | |
434 | c1dd99d4 | Michael Hanselmann | |
435 | 8797df43 | Iustin Pop | def _RunCmdPipe(cmd, env, via_shell, cwd): |
436 | 36117c2b | Iustin Pop | """Run a command and return its output.
|
437 | 36117c2b | Iustin Pop |
|
438 | 36117c2b | Iustin Pop | @type cmd: string or list
|
439 | 36117c2b | Iustin Pop | @param cmd: Command to run
|
440 | 36117c2b | Iustin Pop | @type env: dict
|
441 | 36117c2b | Iustin Pop | @param env: The environment to use
|
442 | 36117c2b | Iustin Pop | @type via_shell: bool
|
443 | 36117c2b | Iustin Pop | @param via_shell: if we should run via the shell
|
444 | 8797df43 | Iustin Pop | @type cwd: string
|
445 | 8797df43 | Iustin Pop | @param cwd: the working directory for the program
|
446 | 36117c2b | Iustin Pop | @rtype: tuple
|
447 | 36117c2b | Iustin Pop | @return: (out, err, status)
|
448 | 36117c2b | Iustin Pop |
|
449 | 36117c2b | Iustin Pop | """
|
450 | 9c233417 | Iustin Pop | poller = select.poll() |
451 | 36117c2b | Iustin Pop | child = subprocess.Popen(cmd, shell=via_shell, |
452 | 113b55aa | Iustin Pop | stderr=subprocess.PIPE, |
453 | 113b55aa | Iustin Pop | stdout=subprocess.PIPE, |
454 | 113b55aa | Iustin Pop | stdin=subprocess.PIPE, |
455 | 8797df43 | Iustin Pop | close_fds=True, env=env,
|
456 | 8797df43 | Iustin Pop | cwd=cwd) |
457 | 113b55aa | Iustin Pop | |
458 | 113b55aa | Iustin Pop | child.stdin.close() |
459 | 9c233417 | Iustin Pop | poller.register(child.stdout, select.POLLIN) |
460 | 9c233417 | Iustin Pop | poller.register(child.stderr, select.POLLIN) |
461 | 9c233417 | Iustin Pop | out = StringIO() |
462 | 9c233417 | Iustin Pop | err = StringIO() |
463 | 9c233417 | Iustin Pop | fdmap = { |
464 | 9c233417 | Iustin Pop | child.stdout.fileno(): (out, child.stdout), |
465 | 9c233417 | Iustin Pop | child.stderr.fileno(): (err, child.stderr), |
466 | 9c233417 | Iustin Pop | } |
467 | 9c233417 | Iustin Pop | for fd in fdmap: |
468 | 287a1740 | Michael Hanselmann | SetNonblockFlag(fd, True)
|
469 | 9c233417 | Iustin Pop | |
470 | 9c233417 | Iustin Pop | while fdmap:
|
471 | edcb5d9e | Michael Hanselmann | pollresult = RetryOnSignal(poller.poll) |
472 | bf988c29 | Guido Trotter | |
473 | bf988c29 | Guido Trotter | for fd, event in pollresult: |
474 | 9c233417 | Iustin Pop | if event & select.POLLIN or event & select.POLLPRI: |
475 | 9c233417 | Iustin Pop | data = fdmap[fd][1].read()
|
476 | 9c233417 | Iustin Pop | # no data from read signifies EOF (the same as POLLHUP)
|
477 | 9c233417 | Iustin Pop | if not data: |
478 | 9c233417 | Iustin Pop | poller.unregister(fd) |
479 | 9c233417 | Iustin Pop | del fdmap[fd]
|
480 | 9c233417 | Iustin Pop | continue
|
481 | 9c233417 | Iustin Pop | fdmap[fd][0].write(data)
|
482 | 9c233417 | Iustin Pop | if (event & select.POLLNVAL or event & select.POLLHUP or |
483 | 9c233417 | Iustin Pop | event & select.POLLERR): |
484 | 9c233417 | Iustin Pop | poller.unregister(fd) |
485 | 9c233417 | Iustin Pop | del fdmap[fd]
|
486 | 9c233417 | Iustin Pop | |
487 | 9c233417 | Iustin Pop | out = out.getvalue() |
488 | 9c233417 | Iustin Pop | err = err.getvalue() |
489 | a8083063 | Iustin Pop | |
490 | a8083063 | Iustin Pop | status = child.wait() |
491 | 36117c2b | Iustin Pop | return out, err, status
|
492 | a8083063 | Iustin Pop | |
493 | 36117c2b | Iustin Pop | |
494 | 8797df43 | Iustin Pop | def _RunCmdFile(cmd, env, via_shell, output, cwd): |
495 | 36117c2b | Iustin Pop | """Run a command and save its output to a file.
|
496 | 36117c2b | Iustin Pop |
|
497 | 36117c2b | Iustin Pop | @type cmd: string or list
|
498 | 36117c2b | Iustin Pop | @param cmd: Command to run
|
499 | 36117c2b | Iustin Pop | @type env: dict
|
500 | 36117c2b | Iustin Pop | @param env: The environment to use
|
501 | 36117c2b | Iustin Pop | @type via_shell: bool
|
502 | 36117c2b | Iustin Pop | @param via_shell: if we should run via the shell
|
503 | 36117c2b | Iustin Pop | @type output: str
|
504 | 36117c2b | Iustin Pop | @param output: the filename in which to save the output
|
505 | 8797df43 | Iustin Pop | @type cwd: string
|
506 | 8797df43 | Iustin Pop | @param cwd: the working directory for the program
|
507 | 36117c2b | Iustin Pop | @rtype: int
|
508 | 36117c2b | Iustin Pop | @return: the exit status
|
509 | 36117c2b | Iustin Pop |
|
510 | 36117c2b | Iustin Pop | """
|
511 | 36117c2b | Iustin Pop | fh = open(output, "a") |
512 | 36117c2b | Iustin Pop | try:
|
513 | 36117c2b | Iustin Pop | child = subprocess.Popen(cmd, shell=via_shell, |
514 | 36117c2b | Iustin Pop | stderr=subprocess.STDOUT, |
515 | 36117c2b | Iustin Pop | stdout=fh, |
516 | 36117c2b | Iustin Pop | stdin=subprocess.PIPE, |
517 | 8797df43 | Iustin Pop | close_fds=True, env=env,
|
518 | 8797df43 | Iustin Pop | cwd=cwd) |
519 | 36117c2b | Iustin Pop | |
520 | 36117c2b | Iustin Pop | child.stdin.close() |
521 | 36117c2b | Iustin Pop | status = child.wait() |
522 | 36117c2b | Iustin Pop | finally:
|
523 | 36117c2b | Iustin Pop | fh.close() |
524 | 36117c2b | Iustin Pop | return status
|
525 | a8083063 | Iustin Pop | |
526 | a8083063 | Iustin Pop | |
527 | 73027ed2 | Michael Hanselmann | def SetCloseOnExecFlag(fd, enable): |
528 | 73027ed2 | Michael Hanselmann | """Sets or unsets the close-on-exec flag on a file descriptor.
|
529 | 73027ed2 | Michael Hanselmann |
|
530 | 73027ed2 | Michael Hanselmann | @type fd: int
|
531 | 73027ed2 | Michael Hanselmann | @param fd: File descriptor
|
532 | 73027ed2 | Michael Hanselmann | @type enable: bool
|
533 | 73027ed2 | Michael Hanselmann | @param enable: Whether to set or unset it.
|
534 | 73027ed2 | Michael Hanselmann |
|
535 | 73027ed2 | Michael Hanselmann | """
|
536 | 73027ed2 | Michael Hanselmann | flags = fcntl.fcntl(fd, fcntl.F_GETFD) |
537 | 73027ed2 | Michael Hanselmann | |
538 | 73027ed2 | Michael Hanselmann | if enable:
|
539 | 73027ed2 | Michael Hanselmann | flags |= fcntl.FD_CLOEXEC |
540 | 73027ed2 | Michael Hanselmann | else:
|
541 | 73027ed2 | Michael Hanselmann | flags &= ~fcntl.FD_CLOEXEC |
542 | 73027ed2 | Michael Hanselmann | |
543 | 73027ed2 | Michael Hanselmann | fcntl.fcntl(fd, fcntl.F_SETFD, flags) |
544 | 73027ed2 | Michael Hanselmann | |
545 | 73027ed2 | Michael Hanselmann | |
546 | 287a1740 | Michael Hanselmann | def SetNonblockFlag(fd, enable): |
547 | 287a1740 | Michael Hanselmann | """Sets or unsets the O_NONBLOCK flag on on a file descriptor.
|
548 | 287a1740 | Michael Hanselmann |
|
549 | 287a1740 | Michael Hanselmann | @type fd: int
|
550 | 287a1740 | Michael Hanselmann | @param fd: File descriptor
|
551 | 287a1740 | Michael Hanselmann | @type enable: bool
|
552 | 287a1740 | Michael Hanselmann | @param enable: Whether to set or unset it
|
553 | 287a1740 | Michael Hanselmann |
|
554 | 287a1740 | Michael Hanselmann | """
|
555 | 287a1740 | Michael Hanselmann | flags = fcntl.fcntl(fd, fcntl.F_GETFL) |
556 | 287a1740 | Michael Hanselmann | |
557 | 287a1740 | Michael Hanselmann | if enable:
|
558 | 287a1740 | Michael Hanselmann | flags |= os.O_NONBLOCK |
559 | 287a1740 | Michael Hanselmann | else:
|
560 | 287a1740 | Michael Hanselmann | flags &= ~os.O_NONBLOCK |
561 | 287a1740 | Michael Hanselmann | |
562 | 287a1740 | Michael Hanselmann | fcntl.fcntl(fd, fcntl.F_SETFL, flags) |
563 | 287a1740 | Michael Hanselmann | |
564 | 287a1740 | Michael Hanselmann | |
565 | edcb5d9e | Michael Hanselmann | def RetryOnSignal(fn, *args, **kwargs): |
566 | edcb5d9e | Michael Hanselmann | """Calls a function again if it failed due to EINTR.
|
567 | edcb5d9e | Michael Hanselmann |
|
568 | edcb5d9e | Michael Hanselmann | """
|
569 | edcb5d9e | Michael Hanselmann | while True: |
570 | edcb5d9e | Michael Hanselmann | try:
|
571 | edcb5d9e | Michael Hanselmann | return fn(*args, **kwargs)
|
572 | 965d0e5b | Guido Trotter | except EnvironmentError, err: |
573 | edcb5d9e | Michael Hanselmann | if err.errno != errno.EINTR:
|
574 | edcb5d9e | Michael Hanselmann | raise
|
575 | 965d0e5b | Guido Trotter | except (socket.error, select.error), err:
|
576 | 965d0e5b | Guido Trotter | # In python 2.6 and above select.error is an IOError, so it's handled
|
577 | 965d0e5b | Guido Trotter | # above, in 2.5 and below it's not, and it's handled here.
|
578 | edcb5d9e | Michael Hanselmann | if not (err.args and err.args[0] == errno.EINTR): |
579 | edcb5d9e | Michael Hanselmann | raise
|
580 | edcb5d9e | Michael Hanselmann | |
581 | edcb5d9e | Michael Hanselmann | |
582 | 6bb65e3a | Guido Trotter | def RunParts(dir_name, env=None, reset_env=False): |
583 | 6bb65e3a | Guido Trotter | """Run Scripts or programs in a directory
|
584 | 6bb65e3a | Guido Trotter |
|
585 | 6bb65e3a | Guido Trotter | @type dir_name: string
|
586 | 6bb65e3a | Guido Trotter | @param dir_name: absolute path to a directory
|
587 | 6bb65e3a | Guido Trotter | @type env: dict
|
588 | 6bb65e3a | Guido Trotter | @param env: The environment to use
|
589 | 6bb65e3a | Guido Trotter | @type reset_env: boolean
|
590 | 6bb65e3a | Guido Trotter | @param reset_env: whether to reset or keep the default os environment
|
591 | 6bb65e3a | Guido Trotter | @rtype: list of tuples
|
592 | 6bb65e3a | Guido Trotter | @return: list of (name, (one of RUNDIR_STATUS), RunResult)
|
593 | 6bb65e3a | Guido Trotter |
|
594 | 6bb65e3a | Guido Trotter | """
|
595 | 6bb65e3a | Guido Trotter | rr = [] |
596 | 6bb65e3a | Guido Trotter | |
597 | 6bb65e3a | Guido Trotter | try:
|
598 | 6bb65e3a | Guido Trotter | dir_contents = ListVisibleFiles(dir_name) |
599 | 6bb65e3a | Guido Trotter | except OSError, err: |
600 | 6bb65e3a | Guido Trotter | logging.warning("RunParts: skipping %s (cannot list: %s)", dir_name, err)
|
601 | 6bb65e3a | Guido Trotter | return rr
|
602 | 6bb65e3a | Guido Trotter | |
603 | 6bb65e3a | Guido Trotter | for relname in sorted(dir_contents): |
604 | c4feafe8 | Iustin Pop | fname = PathJoin(dir_name, relname) |
605 | 6bb65e3a | Guido Trotter | if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and |
606 | 6bb65e3a | Guido Trotter | constants.EXT_PLUGIN_MASK.match(relname) is not None): |
607 | 6bb65e3a | Guido Trotter | rr.append((relname, constants.RUNPARTS_SKIP, None))
|
608 | 6bb65e3a | Guido Trotter | else:
|
609 | 6bb65e3a | Guido Trotter | try:
|
610 | 6bb65e3a | Guido Trotter | result = RunCmd([fname], env=env, reset_env=reset_env) |
611 | 6bb65e3a | Guido Trotter | except Exception, err: # pylint: disable-msg=W0703 |
612 | 6bb65e3a | Guido Trotter | rr.append((relname, constants.RUNPARTS_ERR, str(err)))
|
613 | 6bb65e3a | Guido Trotter | else:
|
614 | 6bb65e3a | Guido Trotter | rr.append((relname, constants.RUNPARTS_RUN, result)) |
615 | 6bb65e3a | Guido Trotter | |
616 | 6bb65e3a | Guido Trotter | return rr
|
617 | 6bb65e3a | Guido Trotter | |
618 | 6bb65e3a | Guido Trotter | |
619 | f93f2016 | Michael Hanselmann | def GetSocketCredentials(sock): |
620 | f93f2016 | Michael Hanselmann | """Returns the credentials of the foreign process connected to a socket.
|
621 | f93f2016 | Michael Hanselmann |
|
622 | f93f2016 | Michael Hanselmann | @param sock: Unix socket
|
623 | f93f2016 | Michael Hanselmann | @rtype: tuple; (number, number, number)
|
624 | f93f2016 | Michael Hanselmann | @return: The PID, UID and GID of the connected foreign process.
|
625 | f93f2016 | Michael Hanselmann |
|
626 | f93f2016 | Michael Hanselmann | """
|
627 | f93f2016 | Michael Hanselmann | peercred = sock.getsockopt(socket.SOL_SOCKET, IN.SO_PEERCRED, |
628 | f93f2016 | Michael Hanselmann | _STRUCT_UCRED_SIZE) |
629 | f93f2016 | Michael Hanselmann | return struct.unpack(_STRUCT_UCRED, peercred)
|
630 | f93f2016 | Michael Hanselmann | |
631 | f93f2016 | Michael Hanselmann | |
632 | a8083063 | Iustin Pop | def RemoveFile(filename): |
633 | a8083063 | Iustin Pop | """Remove a file ignoring some errors.
|
634 | a8083063 | Iustin Pop |
|
635 | a8083063 | Iustin Pop | Remove a file, ignoring non-existing ones or directories. Other
|
636 | a8083063 | Iustin Pop | errors are passed.
|
637 | a8083063 | Iustin Pop |
|
638 | 58885d79 | Iustin Pop | @type filename: str
|
639 | 58885d79 | Iustin Pop | @param filename: the file to be removed
|
640 | 58885d79 | Iustin Pop |
|
641 | a8083063 | Iustin Pop | """
|
642 | a8083063 | Iustin Pop | try:
|
643 | a8083063 | Iustin Pop | os.unlink(filename) |
644 | a8083063 | Iustin Pop | except OSError, err: |
645 | 4ca1b175 | Alexander Schreiber | if err.errno not in (errno.ENOENT, errno.EISDIR): |
646 | a8083063 | Iustin Pop | raise
|
647 | a8083063 | Iustin Pop | |
648 | 72087dcd | Balazs Lecz | |
649 | 72087dcd | Balazs Lecz | def RemoveDir(dirname): |
650 | 72087dcd | Balazs Lecz | """Remove an empty directory.
|
651 | 72087dcd | Balazs Lecz |
|
652 | 72087dcd | Balazs Lecz | Remove a directory, ignoring non-existing ones.
|
653 | 72087dcd | Balazs Lecz | Other errors are passed. This includes the case,
|
654 | 72087dcd | Balazs Lecz | where the directory is not empty, so it can't be removed.
|
655 | 72087dcd | Balazs Lecz |
|
656 | 72087dcd | Balazs Lecz | @type dirname: str
|
657 | 72087dcd | Balazs Lecz | @param dirname: the empty directory to be removed
|
658 | 72087dcd | Balazs Lecz |
|
659 | 72087dcd | Balazs Lecz | """
|
660 | 72087dcd | Balazs Lecz | try:
|
661 | 72087dcd | Balazs Lecz | os.rmdir(dirname) |
662 | 72087dcd | Balazs Lecz | except OSError, err: |
663 | 72087dcd | Balazs Lecz | if err.errno != errno.ENOENT:
|
664 | 72087dcd | Balazs Lecz | raise
|
665 | 72087dcd | Balazs Lecz | |
666 | a8083063 | Iustin Pop | |
667 | 6e797216 | Michael Hanselmann | def RenameFile(old, new, mkdir=False, mkdir_mode=0750): |
668 | 6e797216 | Michael Hanselmann | """Renames a file.
|
669 | 6e797216 | Michael Hanselmann |
|
670 | 6e797216 | Michael Hanselmann | @type old: string
|
671 | 6e797216 | Michael Hanselmann | @param old: Original path
|
672 | 6e797216 | Michael Hanselmann | @type new: string
|
673 | 6e797216 | Michael Hanselmann | @param new: New path
|
674 | 6e797216 | Michael Hanselmann | @type mkdir: bool
|
675 | 6e797216 | Michael Hanselmann | @param mkdir: Whether to create target directory if it doesn't exist
|
676 | 6e797216 | Michael Hanselmann | @type mkdir_mode: int
|
677 | 6e797216 | Michael Hanselmann | @param mkdir_mode: Mode for newly created directories
|
678 | 6e797216 | Michael Hanselmann |
|
679 | 6e797216 | Michael Hanselmann | """
|
680 | 6e797216 | Michael Hanselmann | try:
|
681 | 6e797216 | Michael Hanselmann | return os.rename(old, new)
|
682 | 6e797216 | Michael Hanselmann | except OSError, err: |
683 | 6e797216 | Michael Hanselmann | # In at least one use case of this function, the job queue, directory
|
684 | 6e797216 | Michael Hanselmann | # creation is very rare. Checking for the directory before renaming is not
|
685 | 6e797216 | Michael Hanselmann | # as efficient.
|
686 | 6e797216 | Michael Hanselmann | if mkdir and err.errno == errno.ENOENT: |
687 | 6e797216 | Michael Hanselmann | # Create directory and try again
|
688 | cc2f004d | Michael Hanselmann | Makedirs(os.path.dirname(new), mode=mkdir_mode) |
689 | a426508d | Michael Hanselmann | |
690 | 6e797216 | Michael Hanselmann | return os.rename(old, new)
|
691 | a426508d | Michael Hanselmann | |
692 | 6e797216 | Michael Hanselmann | raise
|
693 | 6e797216 | Michael Hanselmann | |
694 | 6e797216 | Michael Hanselmann | |
695 | 76e5f8b5 | Michael Hanselmann | def Makedirs(path, mode=0750): |
696 | 76e5f8b5 | Michael Hanselmann | """Super-mkdir; create a leaf directory and all intermediate ones.
|
697 | 76e5f8b5 | Michael Hanselmann |
|
698 | 76e5f8b5 | Michael Hanselmann | This is a wrapper around C{os.makedirs} adding error handling not implemented
|
699 | 76e5f8b5 | Michael Hanselmann | before Python 2.5.
|
700 | 76e5f8b5 | Michael Hanselmann |
|
701 | 76e5f8b5 | Michael Hanselmann | """
|
702 | 76e5f8b5 | Michael Hanselmann | try:
|
703 | 76e5f8b5 | Michael Hanselmann | os.makedirs(path, mode) |
704 | 76e5f8b5 | Michael Hanselmann | except OSError, err: |
705 | 76e5f8b5 | Michael Hanselmann | # Ignore EEXIST. This is only handled in os.makedirs as included in
|
706 | 76e5f8b5 | Michael Hanselmann | # Python 2.5 and above.
|
707 | 76e5f8b5 | Michael Hanselmann | if err.errno != errno.EEXIST or not os.path.exists(path): |
708 | 76e5f8b5 | Michael Hanselmann | raise
|
709 | 76e5f8b5 | Michael Hanselmann | |
710 | 76e5f8b5 | Michael Hanselmann | |
711 | 055f822b | Michael Hanselmann | def ResetTempfileModule(): |
712 | 055f822b | Michael Hanselmann | """Resets the random name generator of the tempfile module.
|
713 | 055f822b | Michael Hanselmann |
|
714 | 055f822b | Michael Hanselmann | This function should be called after C{os.fork} in the child process to
|
715 | 055f822b | Michael Hanselmann | ensure it creates a newly seeded random generator. Otherwise it would
|
716 | 055f822b | Michael Hanselmann | generate the same random parts as the parent process. If several processes
|
717 | 055f822b | Michael Hanselmann | race for the creation of a temporary file, this could lead to one not getting
|
718 | 055f822b | Michael Hanselmann | a temporary name.
|
719 | 055f822b | Michael Hanselmann |
|
720 | 055f822b | Michael Hanselmann | """
|
721 | 055f822b | Michael Hanselmann | # pylint: disable-msg=W0212
|
722 | 055f822b | Michael Hanselmann | if hasattr(tempfile, "_once_lock") and hasattr(tempfile, "_name_sequence"): |
723 | 055f822b | Michael Hanselmann | tempfile._once_lock.acquire() |
724 | 055f822b | Michael Hanselmann | try:
|
725 | 055f822b | Michael Hanselmann | # Reset random name generator
|
726 | 055f822b | Michael Hanselmann | tempfile._name_sequence = None
|
727 | 055f822b | Michael Hanselmann | finally:
|
728 | 055f822b | Michael Hanselmann | tempfile._once_lock.release() |
729 | 055f822b | Michael Hanselmann | else:
|
730 | 055f822b | Michael Hanselmann | logging.critical("The tempfile module misses at least one of the"
|
731 | 055f822b | Michael Hanselmann | " '_once_lock' and '_name_sequence' attributes")
|
732 | 055f822b | Michael Hanselmann | |
733 | 055f822b | Michael Hanselmann | |
734 | a8083063 | Iustin Pop | def _FingerprintFile(filename): |
735 | a8083063 | Iustin Pop | """Compute the fingerprint of a file.
|
736 | a8083063 | Iustin Pop |
|
737 | a8083063 | Iustin Pop | If the file does not exist, a None will be returned
|
738 | a8083063 | Iustin Pop | instead.
|
739 | a8083063 | Iustin Pop |
|
740 | 58885d79 | Iustin Pop | @type filename: str
|
741 | 58885d79 | Iustin Pop | @param filename: the filename to checksum
|
742 | 58885d79 | Iustin Pop | @rtype: str
|
743 | 58885d79 | Iustin Pop | @return: the hex digest of the sha checksum of the contents
|
744 | 58885d79 | Iustin Pop | of the file
|
745 | a8083063 | Iustin Pop |
|
746 | a8083063 | Iustin Pop | """
|
747 | a8083063 | Iustin Pop | if not (os.path.exists(filename) and os.path.isfile(filename)): |
748 | a8083063 | Iustin Pop | return None |
749 | a8083063 | Iustin Pop | |
750 | a8083063 | Iustin Pop | f = open(filename)
|
751 | a8083063 | Iustin Pop | |
752 | 716a32cb | Guido Trotter | fp = compat.sha1_hash() |
753 | a8083063 | Iustin Pop | while True: |
754 | a8083063 | Iustin Pop | data = f.read(4096)
|
755 | a8083063 | Iustin Pop | if not data: |
756 | a8083063 | Iustin Pop | break
|
757 | a8083063 | Iustin Pop | |
758 | a8083063 | Iustin Pop | fp.update(data) |
759 | a8083063 | Iustin Pop | |
760 | a8083063 | Iustin Pop | return fp.hexdigest()
|
761 | a8083063 | Iustin Pop | |
762 | a8083063 | Iustin Pop | |
763 | a8083063 | Iustin Pop | def FingerprintFiles(files): |
764 | a8083063 | Iustin Pop | """Compute fingerprints for a list of files.
|
765 | a8083063 | Iustin Pop |
|
766 | 58885d79 | Iustin Pop | @type files: list
|
767 | 58885d79 | Iustin Pop | @param files: the list of filename to fingerprint
|
768 | 58885d79 | Iustin Pop | @rtype: dict
|
769 | 58885d79 | Iustin Pop | @return: a dictionary filename: fingerprint, holding only
|
770 | 58885d79 | Iustin Pop | existing files
|
771 | a8083063 | Iustin Pop |
|
772 | a8083063 | Iustin Pop | """
|
773 | a8083063 | Iustin Pop | ret = {} |
774 | a8083063 | Iustin Pop | |
775 | a8083063 | Iustin Pop | for filename in files: |
776 | a8083063 | Iustin Pop | cksum = _FingerprintFile(filename) |
777 | a8083063 | Iustin Pop | if cksum:
|
778 | a8083063 | Iustin Pop | ret[filename] = cksum |
779 | a8083063 | Iustin Pop | |
780 | a8083063 | Iustin Pop | return ret
|
781 | a8083063 | Iustin Pop | |
782 | a8083063 | Iustin Pop | |
783 | a5728081 | Guido Trotter | def ForceDictType(target, key_types, allowed_values=None): |
784 | a5728081 | Guido Trotter | """Force the values of a dict to have certain types.
|
785 | a5728081 | Guido Trotter |
|
786 | a5728081 | Guido Trotter | @type target: dict
|
787 | a5728081 | Guido Trotter | @param target: the dict to update
|
788 | a5728081 | Guido Trotter | @type key_types: dict
|
789 | a5728081 | Guido Trotter | @param key_types: dict mapping target dict keys to types
|
790 | a5728081 | Guido Trotter | in constants.ENFORCEABLE_TYPES
|
791 | a5728081 | Guido Trotter | @type allowed_values: list
|
792 | a5728081 | Guido Trotter | @keyword allowed_values: list of specially allowed values
|
793 | a5728081 | Guido Trotter |
|
794 | a5728081 | Guido Trotter | """
|
795 | a5728081 | Guido Trotter | if allowed_values is None: |
796 | a5728081 | Guido Trotter | allowed_values = [] |
797 | a5728081 | Guido Trotter | |
798 | 8b46606c | Guido Trotter | if not isinstance(target, dict): |
799 | 8b46606c | Guido Trotter | msg = "Expected dictionary, got '%s'" % target
|
800 | 8b46606c | Guido Trotter | raise errors.TypeEnforcementError(msg)
|
801 | 8b46606c | Guido Trotter | |
802 | a5728081 | Guido Trotter | for key in target: |
803 | a5728081 | Guido Trotter | if key not in key_types: |
804 | a5728081 | Guido Trotter | msg = "Unknown key '%s'" % key
|
805 | a5728081 | Guido Trotter | raise errors.TypeEnforcementError(msg)
|
806 | a5728081 | Guido Trotter | |
807 | a5728081 | Guido Trotter | if target[key] in allowed_values: |
808 | a5728081 | Guido Trotter | continue
|
809 | a5728081 | Guido Trotter | |
810 | 29921401 | Iustin Pop | ktype = key_types[key] |
811 | 29921401 | Iustin Pop | if ktype not in constants.ENFORCEABLE_TYPES: |
812 | 29921401 | Iustin Pop | msg = "'%s' has non-enforceable type %s" % (key, ktype)
|
813 | a5728081 | Guido Trotter | raise errors.ProgrammerError(msg)
|
814 | a5728081 | Guido Trotter | |
815 | 29921401 | Iustin Pop | if ktype == constants.VTYPE_STRING:
|
816 | a5728081 | Guido Trotter | if not isinstance(target[key], basestring): |
817 | a5728081 | Guido Trotter | if isinstance(target[key], bool) and not target[key]: |
818 | a5728081 | Guido Trotter | target[key] = ''
|
819 | a5728081 | Guido Trotter | else:
|
820 | a5728081 | Guido Trotter | msg = "'%s' (value %s) is not a valid string" % (key, target[key])
|
821 | a5728081 | Guido Trotter | raise errors.TypeEnforcementError(msg)
|
822 | 29921401 | Iustin Pop | elif ktype == constants.VTYPE_BOOL:
|
823 | a5728081 | Guido Trotter | if isinstance(target[key], basestring) and target[key]: |
824 | a5728081 | Guido Trotter | if target[key].lower() == constants.VALUE_FALSE:
|
825 | a5728081 | Guido Trotter | target[key] = False
|
826 | a5728081 | Guido Trotter | elif target[key].lower() == constants.VALUE_TRUE:
|
827 | a5728081 | Guido Trotter | target[key] = True
|
828 | a5728081 | Guido Trotter | else:
|
829 | a5728081 | Guido Trotter | msg = "'%s' (value %s) is not a valid boolean" % (key, target[key])
|
830 | a5728081 | Guido Trotter | raise errors.TypeEnforcementError(msg)
|
831 | a5728081 | Guido Trotter | elif target[key]:
|
832 | a5728081 | Guido Trotter | target[key] = True
|
833 | a5728081 | Guido Trotter | else:
|
834 | a5728081 | Guido Trotter | target[key] = False
|
835 | 29921401 | Iustin Pop | elif ktype == constants.VTYPE_SIZE:
|
836 | a5728081 | Guido Trotter | try:
|
837 | a5728081 | Guido Trotter | target[key] = ParseUnit(target[key]) |
838 | a5728081 | Guido Trotter | except errors.UnitParseError, err:
|
839 | a5728081 | Guido Trotter | msg = "'%s' (value %s) is not a valid size. error: %s" % \
|
840 | a5728081 | Guido Trotter | (key, target[key], err) |
841 | a5728081 | Guido Trotter | raise errors.TypeEnforcementError(msg)
|
842 | 29921401 | Iustin Pop | elif ktype == constants.VTYPE_INT:
|
843 | a5728081 | Guido Trotter | try:
|
844 | a5728081 | Guido Trotter | target[key] = int(target[key])
|
845 | a5728081 | Guido Trotter | except (ValueError, TypeError): |
846 | a5728081 | Guido Trotter | msg = "'%s' (value %s) is not a valid integer" % (key, target[key])
|
847 | a5728081 | Guido Trotter | raise errors.TypeEnforcementError(msg)
|
848 | a5728081 | Guido Trotter | |
849 | a5728081 | Guido Trotter | |
850 | a01b500b | Michael Hanselmann | def _GetProcStatusPath(pid): |
851 | a01b500b | Michael Hanselmann | """Returns the path for a PID's proc status file.
|
852 | a01b500b | Michael Hanselmann |
|
853 | a01b500b | Michael Hanselmann | @type pid: int
|
854 | a01b500b | Michael Hanselmann | @param pid: Process ID
|
855 | a01b500b | Michael Hanselmann | @rtype: string
|
856 | a01b500b | Michael Hanselmann |
|
857 | a01b500b | Michael Hanselmann | """
|
858 | a01b500b | Michael Hanselmann | return "/proc/%d/status" % pid |
859 | a01b500b | Michael Hanselmann | |
860 | a01b500b | Michael Hanselmann | |
861 | a8083063 | Iustin Pop | def IsProcessAlive(pid): |
862 | a8083063 | Iustin Pop | """Check if a given pid exists on the system.
|
863 | a8083063 | Iustin Pop |
|
864 | 44bf25ff | Iustin Pop | @note: zombie status is not handled, so zombie processes
|
865 | 44bf25ff | Iustin Pop | will be returned as alive
|
866 | 58885d79 | Iustin Pop | @type pid: int
|
867 | 58885d79 | Iustin Pop | @param pid: the process ID to check
|
868 | 58885d79 | Iustin Pop | @rtype: boolean
|
869 | 58885d79 | Iustin Pop | @return: True if the process exists
|
870 | a8083063 | Iustin Pop |
|
871 | a8083063 | Iustin Pop | """
|
872 | 5ef5ea45 | Guido Trotter | def _TryStat(name): |
873 | 5ef5ea45 | Guido Trotter | try:
|
874 | 5ef5ea45 | Guido Trotter | os.stat(name) |
875 | 5ef5ea45 | Guido Trotter | return True |
876 | 5ef5ea45 | Guido Trotter | except EnvironmentError, err: |
877 | 5ef5ea45 | Guido Trotter | if err.errno in (errno.ENOENT, errno.ENOTDIR): |
878 | 5ef5ea45 | Guido Trotter | return False |
879 | 5ef5ea45 | Guido Trotter | elif err.errno == errno.EINVAL:
|
880 | 5ef5ea45 | Guido Trotter | raise RetryAgain(err)
|
881 | 5ef5ea45 | Guido Trotter | raise
|
882 | 5ef5ea45 | Guido Trotter | |
883 | 5ef5ea45 | Guido Trotter | assert isinstance(pid, int), "pid must be an integer" |
884 | d9f311d7 | Iustin Pop | if pid <= 0: |
885 | d9f311d7 | Iustin Pop | return False |
886 | d9f311d7 | Iustin Pop | |
887 | 5ef5ea45 | Guido Trotter | # /proc in a multiprocessor environment can have strange behaviors.
|
888 | 5ef5ea45 | Guido Trotter | # Retry the os.stat a few times until we get a good result.
|
889 | a8083063 | Iustin Pop | try:
|
890 | a01b500b | Michael Hanselmann | return Retry(_TryStat, (0.01, 1.5, 0.1), 0.5, |
891 | a01b500b | Michael Hanselmann | args=[_GetProcStatusPath(pid)]) |
892 | 5ef5ea45 | Guido Trotter | except RetryTimeout, err:
|
893 | 5ef5ea45 | Guido Trotter | err.RaiseInner() |
894 | a8083063 | Iustin Pop | |
895 | a8083063 | Iustin Pop | |
896 | a01b500b | Michael Hanselmann | def _ParseSigsetT(sigset): |
897 | a01b500b | Michael Hanselmann | """Parse a rendered sigset_t value.
|
898 | a01b500b | Michael Hanselmann |
|
899 | a01b500b | Michael Hanselmann | This is the opposite of the Linux kernel's fs/proc/array.c:render_sigset_t
|
900 | a01b500b | Michael Hanselmann | function.
|
901 | a01b500b | Michael Hanselmann |
|
902 | a01b500b | Michael Hanselmann | @type sigset: string
|
903 | a01b500b | Michael Hanselmann | @param sigset: Rendered signal set from /proc/$pid/status
|
904 | a01b500b | Michael Hanselmann | @rtype: set
|
905 | a01b500b | Michael Hanselmann | @return: Set of all enabled signal numbers
|
906 | a01b500b | Michael Hanselmann |
|
907 | a01b500b | Michael Hanselmann | """
|
908 | a01b500b | Michael Hanselmann | result = set()
|
909 | a01b500b | Michael Hanselmann | |
910 | a01b500b | Michael Hanselmann | signum = 0
|
911 | a01b500b | Michael Hanselmann | for ch in reversed(sigset): |
912 | a01b500b | Michael Hanselmann | chv = int(ch, 16) |
913 | a01b500b | Michael Hanselmann | |
914 | a01b500b | Michael Hanselmann | # The following could be done in a loop, but it's easier to read and
|
915 | a01b500b | Michael Hanselmann | # understand in the unrolled form
|
916 | a01b500b | Michael Hanselmann | if chv & 1: |
917 | a01b500b | Michael Hanselmann | result.add(signum + 1)
|
918 | a01b500b | Michael Hanselmann | if chv & 2: |
919 | a01b500b | Michael Hanselmann | result.add(signum + 2)
|
920 | a01b500b | Michael Hanselmann | if chv & 4: |
921 | a01b500b | Michael Hanselmann | result.add(signum + 3)
|
922 | a01b500b | Michael Hanselmann | if chv & 8: |
923 | a01b500b | Michael Hanselmann | result.add(signum + 4)
|
924 | a01b500b | Michael Hanselmann | |
925 | a01b500b | Michael Hanselmann | signum += 4
|
926 | a01b500b | Michael Hanselmann | |
927 | a01b500b | Michael Hanselmann | return result
|
928 | a01b500b | Michael Hanselmann | |
929 | a01b500b | Michael Hanselmann | |
930 | a01b500b | Michael Hanselmann | def _GetProcStatusField(pstatus, field): |
931 | a01b500b | Michael Hanselmann | """Retrieves a field from the contents of a proc status file.
|
932 | a01b500b | Michael Hanselmann |
|
933 | a01b500b | Michael Hanselmann | @type pstatus: string
|
934 | a01b500b | Michael Hanselmann | @param pstatus: Contents of /proc/$pid/status
|
935 | a01b500b | Michael Hanselmann | @type field: string
|
936 | a01b500b | Michael Hanselmann | @param field: Name of field whose value should be returned
|
937 | a01b500b | Michael Hanselmann | @rtype: string
|
938 | a01b500b | Michael Hanselmann |
|
939 | a01b500b | Michael Hanselmann | """
|
940 | a01b500b | Michael Hanselmann | for line in pstatus.splitlines(): |
941 | a01b500b | Michael Hanselmann | parts = line.split(":", 1) |
942 | a01b500b | Michael Hanselmann | |
943 | a01b500b | Michael Hanselmann | if len(parts) < 2 or parts[0] != field: |
944 | a01b500b | Michael Hanselmann | continue
|
945 | a01b500b | Michael Hanselmann | |
946 | a01b500b | Michael Hanselmann | return parts[1].strip() |
947 | a01b500b | Michael Hanselmann | |
948 | a01b500b | Michael Hanselmann | return None |
949 | a01b500b | Michael Hanselmann | |
950 | a01b500b | Michael Hanselmann | |
951 | a01b500b | Michael Hanselmann | def IsProcessHandlingSignal(pid, signum, status_path=None): |
952 | a01b500b | Michael Hanselmann | """Checks whether a process is handling a signal.
|
953 | a01b500b | Michael Hanselmann |
|
954 | a01b500b | Michael Hanselmann | @type pid: int
|
955 | a01b500b | Michael Hanselmann | @param pid: Process ID
|
956 | a01b500b | Michael Hanselmann | @type signum: int
|
957 | a01b500b | Michael Hanselmann | @param signum: Signal number
|
958 | a01b500b | Michael Hanselmann | @rtype: bool
|
959 | a01b500b | Michael Hanselmann |
|
960 | a01b500b | Michael Hanselmann | """
|
961 | a01b500b | Michael Hanselmann | if status_path is None: |
962 | a01b500b | Michael Hanselmann | status_path = _GetProcStatusPath(pid) |
963 | a01b500b | Michael Hanselmann | |
964 | a01b500b | Michael Hanselmann | try:
|
965 | a01b500b | Michael Hanselmann | proc_status = ReadFile(status_path) |
966 | a01b500b | Michael Hanselmann | except EnvironmentError, err: |
967 | a01b500b | Michael Hanselmann | # In at least one case, reading /proc/$pid/status failed with ESRCH.
|
968 | a01b500b | Michael Hanselmann | if err.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL, errno.ESRCH): |
969 | a01b500b | Michael Hanselmann | return False |
970 | a01b500b | Michael Hanselmann | raise
|
971 | a01b500b | Michael Hanselmann | |
972 | a01b500b | Michael Hanselmann | sigcgt = _GetProcStatusField(proc_status, "SigCgt")
|
973 | a01b500b | Michael Hanselmann | if sigcgt is None: |
974 | a01b500b | Michael Hanselmann | raise RuntimeError("%s is missing 'SigCgt' field" % status_path) |
975 | a01b500b | Michael Hanselmann | |
976 | a01b500b | Michael Hanselmann | # Now check whether signal is handled
|
977 | a01b500b | Michael Hanselmann | return signum in _ParseSigsetT(sigcgt) |
978 | a01b500b | Michael Hanselmann | |
979 | a01b500b | Michael Hanselmann | |
980 | d9f311d7 | Iustin Pop | def ReadPidFile(pidfile): |
981 | 58885d79 | Iustin Pop | """Read a pid from a file.
|
982 | fee80e90 | Guido Trotter |
|
983 | 58885d79 | Iustin Pop | @type pidfile: string
|
984 | 58885d79 | Iustin Pop | @param pidfile: path to the file containing the pid
|
985 | 58885d79 | Iustin Pop | @rtype: int
|
986 | 1de62f37 | Guido Trotter | @return: The process id, if the file exists and contains a valid PID,
|
987 | d9f311d7 | Iustin Pop | otherwise 0
|
988 | fee80e90 | Guido Trotter |
|
989 | fee80e90 | Guido Trotter | """
|
990 | fee80e90 | Guido Trotter | try:
|
991 | 682f7601 | Guido Trotter | raw_data = ReadOneLineFile(pidfile) |
992 | d9f311d7 | Iustin Pop | except EnvironmentError, err: |
993 | d9f311d7 | Iustin Pop | if err.errno != errno.ENOENT:
|
994 | 13998ef2 | Michael Hanselmann | logging.exception("Can't read pid file")
|
995 | d9f311d7 | Iustin Pop | return 0 |
996 | fee80e90 | Guido Trotter | |
997 | fee80e90 | Guido Trotter | try:
|
998 | 13998ef2 | Michael Hanselmann | pid = int(raw_data)
|
999 | 691744c4 | Iustin Pop | except (TypeError, ValueError), err: |
1000 | 8161a646 | Iustin Pop | logging.info("Can't parse pid file contents", exc_info=True) |
1001 | d9f311d7 | Iustin Pop | return 0 |
1002 | fee80e90 | Guido Trotter | |
1003 | d9f311d7 | Iustin Pop | return pid
|
1004 | fee80e90 | Guido Trotter | |
1005 | fee80e90 | Guido Trotter | |
1006 | debed9ae | Michael Hanselmann | def ReadLockedPidFile(path): |
1007 | debed9ae | Michael Hanselmann | """Reads a locked PID file.
|
1008 | debed9ae | Michael Hanselmann |
|
1009 | debed9ae | Michael Hanselmann | This can be used together with L{StartDaemon}.
|
1010 | debed9ae | Michael Hanselmann |
|
1011 | debed9ae | Michael Hanselmann | @type path: string
|
1012 | debed9ae | Michael Hanselmann | @param path: Path to PID file
|
1013 | debed9ae | Michael Hanselmann | @return: PID as integer or, if file was unlocked or couldn't be opened, None
|
1014 | debed9ae | Michael Hanselmann |
|
1015 | debed9ae | Michael Hanselmann | """
|
1016 | debed9ae | Michael Hanselmann | try:
|
1017 | debed9ae | Michael Hanselmann | fd = os.open(path, os.O_RDONLY) |
1018 | debed9ae | Michael Hanselmann | except EnvironmentError, err: |
1019 | debed9ae | Michael Hanselmann | if err.errno == errno.ENOENT:
|
1020 | debed9ae | Michael Hanselmann | # PID file doesn't exist
|
1021 | debed9ae | Michael Hanselmann | return None |
1022 | debed9ae | Michael Hanselmann | raise
|
1023 | debed9ae | Michael Hanselmann | |
1024 | debed9ae | Michael Hanselmann | try:
|
1025 | debed9ae | Michael Hanselmann | try:
|
1026 | debed9ae | Michael Hanselmann | # Try to acquire lock
|
1027 | debed9ae | Michael Hanselmann | LockFile(fd) |
1028 | debed9ae | Michael Hanselmann | except errors.LockError:
|
1029 | debed9ae | Michael Hanselmann | # Couldn't lock, daemon is running
|
1030 | debed9ae | Michael Hanselmann | return int(os.read(fd, 100)) |
1031 | debed9ae | Michael Hanselmann | finally:
|
1032 | debed9ae | Michael Hanselmann | os.close(fd) |
1033 | debed9ae | Michael Hanselmann | |
1034 | debed9ae | Michael Hanselmann | return None |
1035 | debed9ae | Michael Hanselmann | |
1036 | debed9ae | Michael Hanselmann | |
1037 | 256eb94b | Guido Trotter | def MatchNameComponent(key, name_list, case_sensitive=True): |
1038 | a8083063 | Iustin Pop | """Try to match a name against a list.
|
1039 | a8083063 | Iustin Pop |
|
1040 | a8083063 | Iustin Pop | This function will try to match a name like test1 against a list
|
1041 | 58885d79 | Iustin Pop | like C{['test1.example.com', 'test2.example.com', ...]}. Against
|
1042 | 58885d79 | Iustin Pop | this list, I{'test1'} as well as I{'test1.example'} will match, but
|
1043 | 58885d79 | Iustin Pop | not I{'test1.ex'}. A multiple match will be considered as no match
|
1044 | 58885d79 | Iustin Pop | at all (e.g. I{'test1'} against C{['test1.example.com',
|
1045 | 3a541d90 | Iustin Pop | 'test1.example.org']}), except when the key fully matches an entry
|
1046 | 3a541d90 | Iustin Pop | (e.g. I{'test1'} against C{['test1', 'test1.example.com']}).
|
1047 | a8083063 | Iustin Pop |
|
1048 | 58885d79 | Iustin Pop | @type key: str
|
1049 | 58885d79 | Iustin Pop | @param key: the name to be searched
|
1050 | 58885d79 | Iustin Pop | @type name_list: list
|
1051 | 58885d79 | Iustin Pop | @param name_list: the list of strings against which to search the key
|
1052 | 256eb94b | Guido Trotter | @type case_sensitive: boolean
|
1053 | 256eb94b | Guido Trotter | @param case_sensitive: whether to provide a case-sensitive match
|
1054 | a8083063 | Iustin Pop |
|
1055 | 58885d79 | Iustin Pop | @rtype: None or str
|
1056 | 58885d79 | Iustin Pop | @return: None if there is no match I{or} if there are multiple matches,
|
1057 | 58885d79 | Iustin Pop | otherwise the element from the list which matches
|
1058 | a8083063 | Iustin Pop |
|
1059 | a8083063 | Iustin Pop | """
|
1060 | 3a541d90 | Iustin Pop | if key in name_list: |
1061 | 3a541d90 | Iustin Pop | return key
|
1062 | 256eb94b | Guido Trotter | |
1063 | 256eb94b | Guido Trotter | re_flags = 0
|
1064 | 256eb94b | Guido Trotter | if not case_sensitive: |
1065 | 256eb94b | Guido Trotter | re_flags |= re.IGNORECASE |
1066 | 099c52ad | Iustin Pop | key = key.upper() |
1067 | 256eb94b | Guido Trotter | mo = re.compile("^%s(\..*)?$" % re.escape(key), re_flags)
|
1068 | 256eb94b | Guido Trotter | names_filtered = [] |
1069 | 256eb94b | Guido Trotter | string_matches = [] |
1070 | 256eb94b | Guido Trotter | for name in name_list: |
1071 | 256eb94b | Guido Trotter | if mo.match(name) is not None: |
1072 | 256eb94b | Guido Trotter | names_filtered.append(name) |
1073 | 099c52ad | Iustin Pop | if not case_sensitive and key == name.upper(): |
1074 | 256eb94b | Guido Trotter | string_matches.append(name) |
1075 | 256eb94b | Guido Trotter | |
1076 | 256eb94b | Guido Trotter | if len(string_matches) == 1: |
1077 | 256eb94b | Guido Trotter | return string_matches[0] |
1078 | 256eb94b | Guido Trotter | if len(names_filtered) == 1: |
1079 | 256eb94b | Guido Trotter | return names_filtered[0] |
1080 | 256eb94b | Guido Trotter | return None |
1081 | a8083063 | Iustin Pop | |
1082 | a8083063 | Iustin Pop | |
1083 | bcf043c9 | Iustin Pop | class HostInfo: |
1084 | 89e1fc26 | Iustin Pop | """Class implementing resolver and hostname functionality
|
1085 | bcf043c9 | Iustin Pop |
|
1086 | bcf043c9 | Iustin Pop | """
|
1087 | 26288e68 | Iustin Pop | _VALID_NAME_RE = re.compile("^[a-z0-9._-]{1,255}$")
|
1088 | 26288e68 | Iustin Pop | |
1089 | 89e1fc26 | Iustin Pop | def __init__(self, name=None): |
1090 | bcf043c9 | Iustin Pop | """Initialize the host name object.
|
1091 | bcf043c9 | Iustin Pop |
|
1092 | 89e1fc26 | Iustin Pop | If the name argument is not passed, it will use this system's
|
1093 | 89e1fc26 | Iustin Pop | name.
|
1094 | bcf043c9 | Iustin Pop |
|
1095 | bcf043c9 | Iustin Pop | """
|
1096 | 89e1fc26 | Iustin Pop | if name is None: |
1097 | 89e1fc26 | Iustin Pop | name = self.SysName()
|
1098 | 89e1fc26 | Iustin Pop | |
1099 | 89e1fc26 | Iustin Pop | self.query = name
|
1100 | 89e1fc26 | Iustin Pop | self.name, self.aliases, self.ipaddrs = self.LookupHostname(name) |
1101 | bcf043c9 | Iustin Pop | self.ip = self.ipaddrs[0] |
1102 | bcf043c9 | Iustin Pop | |
1103 | c8a0948f | Michael Hanselmann | def ShortName(self): |
1104 | c8a0948f | Michael Hanselmann | """Returns the hostname without domain.
|
1105 | c8a0948f | Michael Hanselmann |
|
1106 | c8a0948f | Michael Hanselmann | """
|
1107 | c8a0948f | Michael Hanselmann | return self.name.split('.')[0] |
1108 | c8a0948f | Michael Hanselmann | |
1109 | 89e1fc26 | Iustin Pop | @staticmethod
|
1110 | 89e1fc26 | Iustin Pop | def SysName(): |
1111 | 89e1fc26 | Iustin Pop | """Return the current system's name.
|
1112 | bcf043c9 | Iustin Pop |
|
1113 | 58885d79 | Iustin Pop | This is simply a wrapper over C{socket.gethostname()}.
|
1114 | a8083063 | Iustin Pop |
|
1115 | 89e1fc26 | Iustin Pop | """
|
1116 | 89e1fc26 | Iustin Pop | return socket.gethostname()
|
1117 | a8083063 | Iustin Pop | |
1118 | 89e1fc26 | Iustin Pop | @staticmethod
|
1119 | 89e1fc26 | Iustin Pop | def LookupHostname(hostname): |
1120 | 89e1fc26 | Iustin Pop | """Look up hostname
|
1121 | a8083063 | Iustin Pop |
|
1122 | 58885d79 | Iustin Pop | @type hostname: str
|
1123 | 58885d79 | Iustin Pop | @param hostname: hostname to look up
|
1124 | 89e1fc26 | Iustin Pop |
|
1125 | 58885d79 | Iustin Pop | @rtype: tuple
|
1126 | 58885d79 | Iustin Pop | @return: a tuple (name, aliases, ipaddrs) as returned by
|
1127 | 58885d79 | Iustin Pop | C{socket.gethostbyname_ex}
|
1128 | 58885d79 | Iustin Pop | @raise errors.ResolverError: in case of errors in resolving
|
1129 | 89e1fc26 | Iustin Pop |
|
1130 | 89e1fc26 | Iustin Pop | """
|
1131 | 89e1fc26 | Iustin Pop | try:
|
1132 | 89e1fc26 | Iustin Pop | result = socket.gethostbyname_ex(hostname) |
1133 | 98fa19b0 | Iustin Pop | except (socket.gaierror, socket.herror, socket.error), err:
|
1134 | 98fa19b0 | Iustin Pop | # hostname not found in DNS, or other socket exception in the
|
1135 | 98fa19b0 | Iustin Pop | # (code, description format)
|
1136 | 89e1fc26 | Iustin Pop | raise errors.ResolverError(hostname, err.args[0], err.args[1]) |
1137 | a8083063 | Iustin Pop | |
1138 | 89e1fc26 | Iustin Pop | return result
|
1139 | a8083063 | Iustin Pop | |
1140 | 26288e68 | Iustin Pop | @classmethod
|
1141 | 26288e68 | Iustin Pop | def NormalizeName(cls, hostname): |
1142 | 26288e68 | Iustin Pop | """Validate and normalize the given hostname.
|
1143 | 26288e68 | Iustin Pop |
|
1144 | 26288e68 | Iustin Pop | @attention: the validation is a bit more relaxed than the standards
|
1145 | 26288e68 | Iustin Pop | require; most importantly, we allow underscores in names
|
1146 | 26288e68 | Iustin Pop | @raise errors.OpPrereqError: when the name is not valid
|
1147 | 26288e68 | Iustin Pop |
|
1148 | 26288e68 | Iustin Pop | """
|
1149 | 26288e68 | Iustin Pop | hostname = hostname.lower() |
1150 | 26288e68 | Iustin Pop | if (not cls._VALID_NAME_RE.match(hostname) or |
1151 | 26288e68 | Iustin Pop | # double-dots, meaning empty label
|
1152 | 26288e68 | Iustin Pop | ".." in hostname or |
1153 | 26288e68 | Iustin Pop | # empty initial label
|
1154 | 26288e68 | Iustin Pop | hostname.startswith(".")):
|
1155 | 26288e68 | Iustin Pop | raise errors.OpPrereqError("Invalid hostname '%s'" % hostname, |
1156 | 26288e68 | Iustin Pop | errors.ECODE_INVAL) |
1157 | 26288e68 | Iustin Pop | if hostname.endswith("."): |
1158 | 26288e68 | Iustin Pop | hostname = hostname.rstrip(".")
|
1159 | 26288e68 | Iustin Pop | return hostname
|
1160 | 26288e68 | Iustin Pop | |
1161 | a8083063 | Iustin Pop | |
1162 | 28f34048 | Michael Hanselmann | def ValidateServiceName(name): |
1163 | 28f34048 | Michael Hanselmann | """Validate the given service name.
|
1164 | 28f34048 | Michael Hanselmann |
|
1165 | 28f34048 | Michael Hanselmann | @type name: number or string
|
1166 | 28f34048 | Michael Hanselmann | @param name: Service name or port specification
|
1167 | 28f34048 | Michael Hanselmann |
|
1168 | 28f34048 | Michael Hanselmann | """
|
1169 | 28f34048 | Michael Hanselmann | try:
|
1170 | 28f34048 | Michael Hanselmann | numport = int(name)
|
1171 | 28f34048 | Michael Hanselmann | except (ValueError, TypeError): |
1172 | 28f34048 | Michael Hanselmann | # Non-numeric service name
|
1173 | 28f34048 | Michael Hanselmann | valid = _VALID_SERVICE_NAME_RE.match(name) |
1174 | 28f34048 | Michael Hanselmann | else:
|
1175 | 28f34048 | Michael Hanselmann | # Numeric port (protocols other than TCP or UDP might need adjustments
|
1176 | 28f34048 | Michael Hanselmann | # here)
|
1177 | 28f34048 | Michael Hanselmann | valid = (numport >= 0 and numport < (1 << 16)) |
1178 | 28f34048 | Michael Hanselmann | |
1179 | 28f34048 | Michael Hanselmann | if not valid: |
1180 | 28f34048 | Michael Hanselmann | raise errors.OpPrereqError("Invalid service name '%s'" % name, |
1181 | 28f34048 | Michael Hanselmann | errors.ECODE_INVAL) |
1182 | 28f34048 | Michael Hanselmann | |
1183 | 28f34048 | Michael Hanselmann | return name
|
1184 | 28f34048 | Michael Hanselmann | |
1185 | 28f34048 | Michael Hanselmann | |
1186 | 104f4ca1 | Iustin Pop | def GetHostInfo(name=None): |
1187 | 104f4ca1 | Iustin Pop | """Lookup host name and raise an OpPrereqError for failures"""
|
1188 | 104f4ca1 | Iustin Pop | |
1189 | 104f4ca1 | Iustin Pop | try:
|
1190 | 104f4ca1 | Iustin Pop | return HostInfo(name)
|
1191 | 104f4ca1 | Iustin Pop | except errors.ResolverError, err:
|
1192 | 104f4ca1 | Iustin Pop | raise errors.OpPrereqError("The given name (%s) does not resolve: %s" % |
1193 | 104f4ca1 | Iustin Pop | (err[0], err[2]), errors.ECODE_RESOLVER) |
1194 | 104f4ca1 | Iustin Pop | |
1195 | 104f4ca1 | Iustin Pop | |
1196 | a8083063 | Iustin Pop | def ListVolumeGroups(): |
1197 | a8083063 | Iustin Pop | """List volume groups and their size
|
1198 | a8083063 | Iustin Pop |
|
1199 | 58885d79 | Iustin Pop | @rtype: dict
|
1200 | 58885d79 | Iustin Pop | @return:
|
1201 | 58885d79 | Iustin Pop | Dictionary with keys volume name and values
|
1202 | 58885d79 | Iustin Pop | the size of the volume
|
1203 | a8083063 | Iustin Pop |
|
1204 | a8083063 | Iustin Pop | """
|
1205 | a8083063 | Iustin Pop | command = "vgs --noheadings --units m --nosuffix -o name,size"
|
1206 | a8083063 | Iustin Pop | result = RunCmd(command) |
1207 | a8083063 | Iustin Pop | retval = {} |
1208 | a8083063 | Iustin Pop | if result.failed:
|
1209 | a8083063 | Iustin Pop | return retval
|
1210 | a8083063 | Iustin Pop | |
1211 | a8083063 | Iustin Pop | for line in result.stdout.splitlines(): |
1212 | a8083063 | Iustin Pop | try:
|
1213 | a8083063 | Iustin Pop | name, size = line.split() |
1214 | a8083063 | Iustin Pop | size = int(float(size)) |
1215 | a8083063 | Iustin Pop | except (IndexError, ValueError), err: |
1216 | bb698c1f | Iustin Pop | logging.error("Invalid output from vgs (%s): %s", err, line)
|
1217 | a8083063 | Iustin Pop | continue
|
1218 | a8083063 | Iustin Pop | |
1219 | a8083063 | Iustin Pop | retval[name] = size |
1220 | a8083063 | Iustin Pop | |
1221 | a8083063 | Iustin Pop | return retval
|
1222 | a8083063 | Iustin Pop | |
1223 | a8083063 | Iustin Pop | |
1224 | a8083063 | Iustin Pop | def BridgeExists(bridge): |
1225 | a8083063 | Iustin Pop | """Check whether the given bridge exists in the system
|
1226 | a8083063 | Iustin Pop |
|
1227 | 58885d79 | Iustin Pop | @type bridge: str
|
1228 | 58885d79 | Iustin Pop | @param bridge: the bridge name to check
|
1229 | 58885d79 | Iustin Pop | @rtype: boolean
|
1230 | 58885d79 | Iustin Pop | @return: True if it does
|
1231 | a8083063 | Iustin Pop |
|
1232 | a8083063 | Iustin Pop | """
|
1233 | a8083063 | Iustin Pop | return os.path.isdir("/sys/class/net/%s/bridge" % bridge) |
1234 | a8083063 | Iustin Pop | |
1235 | a8083063 | Iustin Pop | |
1236 | a8083063 | Iustin Pop | def NiceSort(name_list): |
1237 | a8083063 | Iustin Pop | """Sort a list of strings based on digit and non-digit groupings.
|
1238 | a8083063 | Iustin Pop |
|
1239 | 58885d79 | Iustin Pop | Given a list of names C{['a1', 'a10', 'a11', 'a2']} this function
|
1240 | 58885d79 | Iustin Pop | will sort the list in the logical order C{['a1', 'a2', 'a10',
|
1241 | 58885d79 | Iustin Pop | 'a11']}.
|
1242 | a8083063 | Iustin Pop |
|
1243 | a8083063 | Iustin Pop | The sort algorithm breaks each name in groups of either only-digits
|
1244 | a8083063 | Iustin Pop | or no-digits. Only the first eight such groups are considered, and
|
1245 | a8083063 | Iustin Pop | after that we just use what's left of the string.
|
1246 | a8083063 | Iustin Pop |
|
1247 | 58885d79 | Iustin Pop | @type name_list: list
|
1248 | 58885d79 | Iustin Pop | @param name_list: the names to be sorted
|
1249 | 58885d79 | Iustin Pop | @rtype: list
|
1250 | 58885d79 | Iustin Pop | @return: a copy of the name list sorted with our algorithm
|
1251 | a8083063 | Iustin Pop |
|
1252 | a8083063 | Iustin Pop | """
|
1253 | a8083063 | Iustin Pop | _SORTER_BASE = "(\D+|\d+)"
|
1254 | a8083063 | Iustin Pop | _SORTER_FULL = "^%s%s?%s?%s?%s?%s?%s?%s?.*$" % (_SORTER_BASE, _SORTER_BASE,
|
1255 | a8083063 | Iustin Pop | _SORTER_BASE, _SORTER_BASE, |
1256 | a8083063 | Iustin Pop | _SORTER_BASE, _SORTER_BASE, |
1257 | a8083063 | Iustin Pop | _SORTER_BASE, _SORTER_BASE) |
1258 | a8083063 | Iustin Pop | _SORTER_RE = re.compile(_SORTER_FULL) |
1259 | a8083063 | Iustin Pop | _SORTER_NODIGIT = re.compile("^\D*$")
|
1260 | a8083063 | Iustin Pop | def _TryInt(val): |
1261 | a8083063 | Iustin Pop | """Attempts to convert a variable to integer."""
|
1262 | a8083063 | Iustin Pop | if val is None or _SORTER_NODIGIT.match(val): |
1263 | a8083063 | Iustin Pop | return val
|
1264 | a8083063 | Iustin Pop | rval = int(val)
|
1265 | a8083063 | Iustin Pop | return rval
|
1266 | a8083063 | Iustin Pop | |
1267 | a8083063 | Iustin Pop | to_sort = [([_TryInt(grp) for grp in _SORTER_RE.match(name).groups()], name) |
1268 | a8083063 | Iustin Pop | for name in name_list] |
1269 | a8083063 | Iustin Pop | to_sort.sort() |
1270 | a8083063 | Iustin Pop | return [tup[1] for tup in to_sort] |
1271 | a8083063 | Iustin Pop | |
1272 | a8083063 | Iustin Pop | |
1273 | a8083063 | Iustin Pop | def TryConvert(fn, val): |
1274 | a8083063 | Iustin Pop | """Try to convert a value ignoring errors.
|
1275 | a8083063 | Iustin Pop |
|
1276 | 58885d79 | Iustin Pop | This function tries to apply function I{fn} to I{val}. If no
|
1277 | 58885d79 | Iustin Pop | C{ValueError} or C{TypeError} exceptions are raised, it will return
|
1278 | 58885d79 | Iustin Pop | the result, else it will return the original value. Any other
|
1279 | 58885d79 | Iustin Pop | exceptions are propagated to the caller.
|
1280 | 58885d79 | Iustin Pop |
|
1281 | 58885d79 | Iustin Pop | @type fn: callable
|
1282 | 58885d79 | Iustin Pop | @param fn: function to apply to the value
|
1283 | 58885d79 | Iustin Pop | @param val: the value to be converted
|
1284 | 58885d79 | Iustin Pop | @return: The converted value if the conversion was successful,
|
1285 | 58885d79 | Iustin Pop | otherwise the original value.
|
1286 | a8083063 | Iustin Pop |
|
1287 | a8083063 | Iustin Pop | """
|
1288 | a8083063 | Iustin Pop | try:
|
1289 | a8083063 | Iustin Pop | nv = fn(val) |
1290 | 7c4d6c7b | Michael Hanselmann | except (ValueError, TypeError): |
1291 | a8083063 | Iustin Pop | nv = val |
1292 | a8083063 | Iustin Pop | return nv
|
1293 | a8083063 | Iustin Pop | |
1294 | a8083063 | Iustin Pop | |
1295 | c0c3fa27 | Manuel Franceschini | def _GenericIsValidIP(family, ip): |
1296 | c0c3fa27 | Manuel Franceschini | """Generic internal version of ip validation.
|
1297 | c0c3fa27 | Manuel Franceschini |
|
1298 | c0c3fa27 | Manuel Franceschini | @type family: int
|
1299 | c0c3fa27 | Manuel Franceschini | @param family: socket.AF_INET | socket.AF_INET6
|
1300 | c0c3fa27 | Manuel Franceschini | @type ip: str
|
1301 | c0c3fa27 | Manuel Franceschini | @param ip: the address to be checked
|
1302 | c0c3fa27 | Manuel Franceschini | @rtype: boolean
|
1303 | c0c3fa27 | Manuel Franceschini | @return: True if ip is valid, False otherwise
|
1304 | c0c3fa27 | Manuel Franceschini |
|
1305 | c0c3fa27 | Manuel Franceschini | """
|
1306 | c0c3fa27 | Manuel Franceschini | try:
|
1307 | c0c3fa27 | Manuel Franceschini | socket.inet_pton(family, ip) |
1308 | c0c3fa27 | Manuel Franceschini | return True |
1309 | c0c3fa27 | Manuel Franceschini | except socket.error:
|
1310 | c0c3fa27 | Manuel Franceschini | return False |
1311 | c0c3fa27 | Manuel Franceschini | |
1312 | c0c3fa27 | Manuel Franceschini | |
1313 | c0c3fa27 | Manuel Franceschini | def IsValidIP4(ip): |
1314 | c0c3fa27 | Manuel Franceschini | """Verifies an IPv4 address.
|
1315 | c0c3fa27 | Manuel Franceschini |
|
1316 | c0c3fa27 | Manuel Franceschini | This function checks if the given address is a valid IPv4 address.
|
1317 | c0c3fa27 | Manuel Franceschini |
|
1318 | c0c3fa27 | Manuel Franceschini | @type ip: str
|
1319 | c0c3fa27 | Manuel Franceschini | @param ip: the address to be checked
|
1320 | c0c3fa27 | Manuel Franceschini | @rtype: boolean
|
1321 | c0c3fa27 | Manuel Franceschini | @return: True if ip is valid, False otherwise
|
1322 | c0c3fa27 | Manuel Franceschini |
|
1323 | c0c3fa27 | Manuel Franceschini | """
|
1324 | c0c3fa27 | Manuel Franceschini | return _GenericIsValidIP(socket.AF_INET, ip)
|
1325 | c0c3fa27 | Manuel Franceschini | |
1326 | c0c3fa27 | Manuel Franceschini | |
1327 | c0c3fa27 | Manuel Franceschini | def IsValidIP6(ip): |
1328 | c0c3fa27 | Manuel Franceschini | """Verifies an IPv6 address.
|
1329 | c0c3fa27 | Manuel Franceschini |
|
1330 | c0c3fa27 | Manuel Franceschini | This function checks if the given address is a valid IPv6 address.
|
1331 | c0c3fa27 | Manuel Franceschini |
|
1332 | c0c3fa27 | Manuel Franceschini | @type ip: str
|
1333 | c0c3fa27 | Manuel Franceschini | @param ip: the address to be checked
|
1334 | c0c3fa27 | Manuel Franceschini | @rtype: boolean
|
1335 | c0c3fa27 | Manuel Franceschini | @return: True if ip is valid, False otherwise
|
1336 | c0c3fa27 | Manuel Franceschini |
|
1337 | c0c3fa27 | Manuel Franceschini | """
|
1338 | c0c3fa27 | Manuel Franceschini | return _GenericIsValidIP(socket.AF_INET6, ip)
|
1339 | c0c3fa27 | Manuel Franceschini | |
1340 | c0c3fa27 | Manuel Franceschini | |
1341 | a8083063 | Iustin Pop | def IsValidIP(ip): |
1342 | c0c3fa27 | Manuel Franceschini | """Verifies an IP address.
|
1343 | a8083063 | Iustin Pop |
|
1344 | c0c3fa27 | Manuel Franceschini | This function checks if the given IP address (both IPv4 and IPv6) is valid.
|
1345 | 58885d79 | Iustin Pop |
|
1346 | 58885d79 | Iustin Pop | @type ip: str
|
1347 | 58885d79 | Iustin Pop | @param ip: the address to be checked
|
1348 | c0c3fa27 | Manuel Franceschini | @rtype: boolean
|
1349 | c0c3fa27 | Manuel Franceschini | @return: True if ip is valid, False otherwise
|
1350 | a8083063 | Iustin Pop |
|
1351 | a8083063 | Iustin Pop | """
|
1352 | c0c3fa27 | Manuel Franceschini | return IsValidIP4(ip) or IsValidIP6(ip) |
1353 | a8083063 | Iustin Pop | |
1354 | a8083063 | Iustin Pop | |
1355 | 2632795d | Manuel Franceschini | def GetAddressFamily(ip): |
1356 | 2632795d | Manuel Franceschini | """Get the address family of the given address.
|
1357 | 2632795d | Manuel Franceschini |
|
1358 | 2632795d | Manuel Franceschini | @type ip: str
|
1359 | 2632795d | Manuel Franceschini | @param ip: ip address whose family will be returned
|
1360 | 2632795d | Manuel Franceschini | @rtype: int
|
1361 | 2632795d | Manuel Franceschini | @return: socket.AF_INET or socket.AF_INET6
|
1362 | 2632795d | Manuel Franceschini | @raise errors.GenericError: for invalid addresses
|
1363 | 2632795d | Manuel Franceschini |
|
1364 | 2632795d | Manuel Franceschini | """
|
1365 | 2632795d | Manuel Franceschini | if IsValidIP6(ip):
|
1366 | 2632795d | Manuel Franceschini | return socket.AF_INET6
|
1367 | 2632795d | Manuel Franceschini | elif IsValidIP4(ip):
|
1368 | 2632795d | Manuel Franceschini | return socket.AF_INET
|
1369 | 2632795d | Manuel Franceschini | else:
|
1370 | 2632795d | Manuel Franceschini | raise errors.GenericError("Address %s not valid" % ip) |
1371 | 2632795d | Manuel Franceschini | |
1372 | 2632795d | Manuel Franceschini | |
1373 | a8083063 | Iustin Pop | def IsValidShellParam(word): |
1374 | a8083063 | Iustin Pop | """Verifies is the given word is safe from the shell's p.o.v.
|
1375 | a8083063 | Iustin Pop |
|
1376 | a8083063 | Iustin Pop | This means that we can pass this to a command via the shell and be
|
1377 | a8083063 | Iustin Pop | sure that it doesn't alter the command line and is passed as such to
|
1378 | a8083063 | Iustin Pop | the actual command.
|
1379 | a8083063 | Iustin Pop |
|
1380 | a8083063 | Iustin Pop | Note that we are overly restrictive here, in order to be on the safe
|
1381 | a8083063 | Iustin Pop | side.
|
1382 | a8083063 | Iustin Pop |
|
1383 | 58885d79 | Iustin Pop | @type word: str
|
1384 | 58885d79 | Iustin Pop | @param word: the word to check
|
1385 | 58885d79 | Iustin Pop | @rtype: boolean
|
1386 | 58885d79 | Iustin Pop | @return: True if the word is 'safe'
|
1387 | 58885d79 | Iustin Pop |
|
1388 | a8083063 | Iustin Pop | """
|
1389 | a8083063 | Iustin Pop | return bool(re.match("^[-a-zA-Z0-9._+/:%@]+$", word)) |
1390 | a8083063 | Iustin Pop | |
1391 | a8083063 | Iustin Pop | |
1392 | a8083063 | Iustin Pop | def BuildShellCmd(template, *args): |
1393 | a8083063 | Iustin Pop | """Build a safe shell command line from the given arguments.
|
1394 | a8083063 | Iustin Pop |
|
1395 | a8083063 | Iustin Pop | This function will check all arguments in the args list so that they
|
1396 | a8083063 | Iustin Pop | are valid shell parameters (i.e. they don't contain shell
|
1397 | 5bbd3f7f | Michael Hanselmann | metacharacters). If everything is ok, it will return the result of
|
1398 | a8083063 | Iustin Pop | template % args.
|
1399 | a8083063 | Iustin Pop |
|
1400 | 58885d79 | Iustin Pop | @type template: str
|
1401 | 58885d79 | Iustin Pop | @param template: the string holding the template for the
|
1402 | 58885d79 | Iustin Pop | string formatting
|
1403 | 58885d79 | Iustin Pop | @rtype: str
|
1404 | 58885d79 | Iustin Pop | @return: the expanded command line
|
1405 | 58885d79 | Iustin Pop |
|
1406 | a8083063 | Iustin Pop | """
|
1407 | a8083063 | Iustin Pop | for word in args: |
1408 | a8083063 | Iustin Pop | if not IsValidShellParam(word): |
1409 | 3ecf6786 | Iustin Pop | raise errors.ProgrammerError("Shell argument '%s' contains" |
1410 | 3ecf6786 | Iustin Pop | " invalid characters" % word)
|
1411 | a8083063 | Iustin Pop | return template % args
|
1412 | a8083063 | Iustin Pop | |
1413 | a8083063 | Iustin Pop | |
1414 | 9fbfbb7b | Iustin Pop | def FormatUnit(value, units): |
1415 | a8083063 | Iustin Pop | """Formats an incoming number of MiB with the appropriate unit.
|
1416 | a8083063 | Iustin Pop |
|
1417 | 58885d79 | Iustin Pop | @type value: int
|
1418 | 58885d79 | Iustin Pop | @param value: integer representing the value in MiB (1048576)
|
1419 | 9fbfbb7b | Iustin Pop | @type units: char
|
1420 | 9fbfbb7b | Iustin Pop | @param units: the type of formatting we should do:
|
1421 | 9fbfbb7b | Iustin Pop | - 'h' for automatic scaling
|
1422 | 9fbfbb7b | Iustin Pop | - 'm' for MiBs
|
1423 | 9fbfbb7b | Iustin Pop | - 'g' for GiBs
|
1424 | 9fbfbb7b | Iustin Pop | - 't' for TiBs
|
1425 | 58885d79 | Iustin Pop | @rtype: str
|
1426 | 58885d79 | Iustin Pop | @return: the formatted value (with suffix)
|
1427 | a8083063 | Iustin Pop |
|
1428 | a8083063 | Iustin Pop | """
|
1429 | 9fbfbb7b | Iustin Pop | if units not in ('m', 'g', 't', 'h'): |
1430 | 9fbfbb7b | Iustin Pop | raise errors.ProgrammerError("Invalid unit specified '%s'" % str(units)) |
1431 | a8083063 | Iustin Pop | |
1432 | 9fbfbb7b | Iustin Pop | suffix = ''
|
1433 | 9fbfbb7b | Iustin Pop | |
1434 | 9fbfbb7b | Iustin Pop | if units == 'm' or (units == 'h' and value < 1024): |
1435 | 9fbfbb7b | Iustin Pop | if units == 'h': |
1436 | 9fbfbb7b | Iustin Pop | suffix = 'M'
|
1437 | 9fbfbb7b | Iustin Pop | return "%d%s" % (round(value, 0), suffix) |
1438 | 9fbfbb7b | Iustin Pop | |
1439 | 9fbfbb7b | Iustin Pop | elif units == 'g' or (units == 'h' and value < (1024 * 1024)): |
1440 | 9fbfbb7b | Iustin Pop | if units == 'h': |
1441 | 9fbfbb7b | Iustin Pop | suffix = 'G'
|
1442 | 9fbfbb7b | Iustin Pop | return "%0.1f%s" % (round(float(value) / 1024, 1), suffix) |
1443 | a8083063 | Iustin Pop | |
1444 | a8083063 | Iustin Pop | else:
|
1445 | 9fbfbb7b | Iustin Pop | if units == 'h': |
1446 | 9fbfbb7b | Iustin Pop | suffix = 'T'
|
1447 | 9fbfbb7b | Iustin Pop | return "%0.1f%s" % (round(float(value) / 1024 / 1024, 1), suffix) |
1448 | a8083063 | Iustin Pop | |
1449 | a8083063 | Iustin Pop | |
1450 | a8083063 | Iustin Pop | def ParseUnit(input_string): |
1451 | a8083063 | Iustin Pop | """Tries to extract number and scale from the given string.
|
1452 | a8083063 | Iustin Pop |
|
1453 | 58885d79 | Iustin Pop | Input must be in the format C{NUMBER+ [DOT NUMBER+] SPACE*
|
1454 | 58885d79 | Iustin Pop | [UNIT]}. If no unit is specified, it defaults to MiB. Return value
|
1455 | 58885d79 | Iustin Pop | is always an int in MiB.
|
1456 | a8083063 | Iustin Pop |
|
1457 | a8083063 | Iustin Pop | """
|
1458 | 9939547b | Iustin Pop | m = re.match('^([.\d]+)\s*([a-zA-Z]+)?$', str(input_string)) |
1459 | a8083063 | Iustin Pop | if not m: |
1460 | 3ecf6786 | Iustin Pop | raise errors.UnitParseError("Invalid format") |
1461 | a8083063 | Iustin Pop | |
1462 | a8083063 | Iustin Pop | value = float(m.groups()[0]) |
1463 | a8083063 | Iustin Pop | |
1464 | a8083063 | Iustin Pop | unit = m.groups()[1]
|
1465 | a8083063 | Iustin Pop | if unit:
|
1466 | a8083063 | Iustin Pop | lcunit = unit.lower() |
1467 | a8083063 | Iustin Pop | else:
|
1468 | a8083063 | Iustin Pop | lcunit = 'm'
|
1469 | a8083063 | Iustin Pop | |
1470 | a8083063 | Iustin Pop | if lcunit in ('m', 'mb', 'mib'): |
1471 | a8083063 | Iustin Pop | # Value already in MiB
|
1472 | a8083063 | Iustin Pop | pass
|
1473 | a8083063 | Iustin Pop | |
1474 | a8083063 | Iustin Pop | elif lcunit in ('g', 'gb', 'gib'): |
1475 | a8083063 | Iustin Pop | value *= 1024
|
1476 | a8083063 | Iustin Pop | |
1477 | a8083063 | Iustin Pop | elif lcunit in ('t', 'tb', 'tib'): |
1478 | a8083063 | Iustin Pop | value *= 1024 * 1024 |
1479 | a8083063 | Iustin Pop | |
1480 | a8083063 | Iustin Pop | else:
|
1481 | 3ecf6786 | Iustin Pop | raise errors.UnitParseError("Unknown unit: %s" % unit) |
1482 | a8083063 | Iustin Pop | |
1483 | a8083063 | Iustin Pop | # Make sure we round up
|
1484 | a8083063 | Iustin Pop | if int(value) < value: |
1485 | a8083063 | Iustin Pop | value += 1
|
1486 | a8083063 | Iustin Pop | |
1487 | a8083063 | Iustin Pop | # Round up to the next multiple of 4
|
1488 | a8083063 | Iustin Pop | value = int(value)
|
1489 | a8083063 | Iustin Pop | if value % 4: |
1490 | a8083063 | Iustin Pop | value += 4 - value % 4 |
1491 | a8083063 | Iustin Pop | |
1492 | a8083063 | Iustin Pop | return value
|
1493 | a8083063 | Iustin Pop | |
1494 | a8083063 | Iustin Pop | |
1495 | a8083063 | Iustin Pop | def AddAuthorizedKey(file_name, key): |
1496 | a8083063 | Iustin Pop | """Adds an SSH public key to an authorized_keys file.
|
1497 | a8083063 | Iustin Pop |
|
1498 | 58885d79 | Iustin Pop | @type file_name: str
|
1499 | 58885d79 | Iustin Pop | @param file_name: path to authorized_keys file
|
1500 | 58885d79 | Iustin Pop | @type key: str
|
1501 | 58885d79 | Iustin Pop | @param key: string containing key
|
1502 | 58885d79 | Iustin Pop |
|
1503 | a8083063 | Iustin Pop | """
|
1504 | a8083063 | Iustin Pop | key_fields = key.split() |
1505 | a8083063 | Iustin Pop | |
1506 | a8083063 | Iustin Pop | f = open(file_name, 'a+') |
1507 | a8083063 | Iustin Pop | try:
|
1508 | a8083063 | Iustin Pop | nl = True
|
1509 | a8083063 | Iustin Pop | for line in f: |
1510 | a8083063 | Iustin Pop | # Ignore whitespace changes
|
1511 | a8083063 | Iustin Pop | if line.split() == key_fields:
|
1512 | a8083063 | Iustin Pop | break
|
1513 | a8083063 | Iustin Pop | nl = line.endswith('\n')
|
1514 | a8083063 | Iustin Pop | else:
|
1515 | a8083063 | Iustin Pop | if not nl: |
1516 | a8083063 | Iustin Pop | f.write("\n")
|
1517 | a8083063 | Iustin Pop | f.write(key.rstrip('\r\n'))
|
1518 | a8083063 | Iustin Pop | f.write("\n")
|
1519 | a8083063 | Iustin Pop | f.flush() |
1520 | a8083063 | Iustin Pop | finally:
|
1521 | a8083063 | Iustin Pop | f.close() |
1522 | a8083063 | Iustin Pop | |
1523 | a8083063 | Iustin Pop | |
1524 | a8083063 | Iustin Pop | def RemoveAuthorizedKey(file_name, key): |
1525 | a8083063 | Iustin Pop | """Removes an SSH public key from an authorized_keys file.
|
1526 | a8083063 | Iustin Pop |
|
1527 | 58885d79 | Iustin Pop | @type file_name: str
|
1528 | 58885d79 | Iustin Pop | @param file_name: path to authorized_keys file
|
1529 | 58885d79 | Iustin Pop | @type key: str
|
1530 | 58885d79 | Iustin Pop | @param key: string containing key
|
1531 | 58885d79 | Iustin Pop |
|
1532 | a8083063 | Iustin Pop | """
|
1533 | a8083063 | Iustin Pop | key_fields = key.split() |
1534 | a8083063 | Iustin Pop | |
1535 | a8083063 | Iustin Pop | fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name)) |
1536 | a8083063 | Iustin Pop | try:
|
1537 | 59f82e3f | Michael Hanselmann | out = os.fdopen(fd, 'w')
|
1538 | a8083063 | Iustin Pop | try:
|
1539 | 59f82e3f | Michael Hanselmann | f = open(file_name, 'r') |
1540 | 59f82e3f | Michael Hanselmann | try:
|
1541 | 59f82e3f | Michael Hanselmann | for line in f: |
1542 | 59f82e3f | Michael Hanselmann | # Ignore whitespace changes while comparing lines
|
1543 | 59f82e3f | Michael Hanselmann | if line.split() != key_fields:
|
1544 | 59f82e3f | Michael Hanselmann | out.write(line) |
1545 | 899d2a81 | Michael Hanselmann | |
1546 | 899d2a81 | Michael Hanselmann | out.flush() |
1547 | 899d2a81 | Michael Hanselmann | os.rename(tmpname, file_name) |
1548 | 899d2a81 | Michael Hanselmann | finally:
|
1549 | 899d2a81 | Michael Hanselmann | f.close() |
1550 | 899d2a81 | Michael Hanselmann | finally:
|
1551 | 899d2a81 | Michael Hanselmann | out.close() |
1552 | 899d2a81 | Michael Hanselmann | except:
|
1553 | 899d2a81 | Michael Hanselmann | RemoveFile(tmpname) |
1554 | 899d2a81 | Michael Hanselmann | raise
|
1555 | 899d2a81 | Michael Hanselmann | |
1556 | 899d2a81 | Michael Hanselmann | |
1557 | 9440aeab | Michael Hanselmann | def SetEtcHostsEntry(file_name, ip, hostname, aliases): |
1558 | 9440aeab | Michael Hanselmann | """Sets the name of an IP address and hostname in /etc/hosts.
|
1559 | 899d2a81 | Michael Hanselmann |
|
1560 | 58885d79 | Iustin Pop | @type file_name: str
|
1561 | 58885d79 | Iustin Pop | @param file_name: path to the file to modify (usually C{/etc/hosts})
|
1562 | 58885d79 | Iustin Pop | @type ip: str
|
1563 | 58885d79 | Iustin Pop | @param ip: the IP address
|
1564 | 58885d79 | Iustin Pop | @type hostname: str
|
1565 | 58885d79 | Iustin Pop | @param hostname: the hostname to be added
|
1566 | 58885d79 | Iustin Pop | @type aliases: list
|
1567 | 58885d79 | Iustin Pop | @param aliases: the list of aliases to add for the hostname
|
1568 | 58885d79 | Iustin Pop |
|
1569 | 899d2a81 | Michael Hanselmann | """
|
1570 | 9b977740 | Guido Trotter | # FIXME: use WriteFile + fn rather than duplicating its efforts
|
1571 | 7fbb1f65 | Michael Hanselmann | # Ensure aliases are unique
|
1572 | 7fbb1f65 | Michael Hanselmann | aliases = UniqueSequence([hostname] + aliases)[1:]
|
1573 | 7fbb1f65 | Michael Hanselmann | |
1574 | 9440aeab | Michael Hanselmann | fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name)) |
1575 | 899d2a81 | Michael Hanselmann | try:
|
1576 | 9440aeab | Michael Hanselmann | out = os.fdopen(fd, 'w')
|
1577 | 9440aeab | Michael Hanselmann | try:
|
1578 | 9440aeab | Michael Hanselmann | f = open(file_name, 'r') |
1579 | 9440aeab | Michael Hanselmann | try:
|
1580 | 9440aeab | Michael Hanselmann | for line in f: |
1581 | 9440aeab | Michael Hanselmann | fields = line.split() |
1582 | 7e3dbb94 | Iustin Pop | if fields and not fields[0].startswith('#') and ip == fields[0]: |
1583 | 9440aeab | Michael Hanselmann | continue
|
1584 | 9440aeab | Michael Hanselmann | out.write(line) |
1585 | 9440aeab | Michael Hanselmann | |
1586 | 7e3dbb94 | Iustin Pop | out.write("%s\t%s" % (ip, hostname))
|
1587 | 9440aeab | Michael Hanselmann | if aliases:
|
1588 | 9440aeab | Michael Hanselmann | out.write(" %s" % ' '.join(aliases)) |
1589 | 9440aeab | Michael Hanselmann | out.write('\n')
|
1590 | 9440aeab | Michael Hanselmann | |
1591 | 9440aeab | Michael Hanselmann | out.flush() |
1592 | 2e3e75b7 | Michael Hanselmann | os.fsync(out) |
1593 | 9b977740 | Guido Trotter | os.chmod(tmpname, 0644)
|
1594 | 9440aeab | Michael Hanselmann | os.rename(tmpname, file_name) |
1595 | 9440aeab | Michael Hanselmann | finally:
|
1596 | 9440aeab | Michael Hanselmann | f.close() |
1597 | 9440aeab | Michael Hanselmann | finally:
|
1598 | 9440aeab | Michael Hanselmann | out.close() |
1599 | 9440aeab | Michael Hanselmann | except:
|
1600 | 9440aeab | Michael Hanselmann | RemoveFile(tmpname) |
1601 | 9440aeab | Michael Hanselmann | raise
|
1602 | 899d2a81 | Michael Hanselmann | |
1603 | 899d2a81 | Michael Hanselmann | |
1604 | d9c02ca6 | Michael Hanselmann | def AddHostToEtcHosts(hostname): |
1605 | d9c02ca6 | Michael Hanselmann | """Wrapper around SetEtcHostsEntry.
|
1606 | d9c02ca6 | Michael Hanselmann |
|
1607 | 58885d79 | Iustin Pop | @type hostname: str
|
1608 | 58885d79 | Iustin Pop | @param hostname: a hostname that will be resolved and added to
|
1609 | 58885d79 | Iustin Pop | L{constants.ETC_HOSTS}
|
1610 | 58885d79 | Iustin Pop |
|
1611 | d9c02ca6 | Michael Hanselmann | """
|
1612 | d9c02ca6 | Michael Hanselmann | hi = HostInfo(name=hostname) |
1613 | d9c02ca6 | Michael Hanselmann | SetEtcHostsEntry(constants.ETC_HOSTS, hi.ip, hi.name, [hi.ShortName()]) |
1614 | d9c02ca6 | Michael Hanselmann | |
1615 | d9c02ca6 | Michael Hanselmann | |
1616 | 899d2a81 | Michael Hanselmann | def RemoveEtcHostsEntry(file_name, hostname): |
1617 | 3e1cdf9f | Michael Hanselmann | """Removes a hostname from /etc/hosts.
|
1618 | 899d2a81 | Michael Hanselmann |
|
1619 | 9440aeab | Michael Hanselmann | IP addresses without names are removed from the file.
|
1620 | 58885d79 | Iustin Pop |
|
1621 | 58885d79 | Iustin Pop | @type file_name: str
|
1622 | 58885d79 | Iustin Pop | @param file_name: path to the file to modify (usually C{/etc/hosts})
|
1623 | 58885d79 | Iustin Pop | @type hostname: str
|
1624 | 58885d79 | Iustin Pop | @param hostname: the hostname to be removed
|
1625 | 58885d79 | Iustin Pop |
|
1626 | 899d2a81 | Michael Hanselmann | """
|
1627 | 9b977740 | Guido Trotter | # FIXME: use WriteFile + fn rather than duplicating its efforts
|
1628 | 899d2a81 | Michael Hanselmann | fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name)) |
1629 | 899d2a81 | Michael Hanselmann | try:
|
1630 | 899d2a81 | Michael Hanselmann | out = os.fdopen(fd, 'w')
|
1631 | 899d2a81 | Michael Hanselmann | try:
|
1632 | 899d2a81 | Michael Hanselmann | f = open(file_name, 'r') |
1633 | 899d2a81 | Michael Hanselmann | try:
|
1634 | 899d2a81 | Michael Hanselmann | for line in f: |
1635 | 899d2a81 | Michael Hanselmann | fields = line.split() |
1636 | 899d2a81 | Michael Hanselmann | if len(fields) > 1 and not fields[0].startswith('#'): |
1637 | 899d2a81 | Michael Hanselmann | names = fields[1:]
|
1638 | 899d2a81 | Michael Hanselmann | if hostname in names: |
1639 | 899d2a81 | Michael Hanselmann | while hostname in names: |
1640 | 899d2a81 | Michael Hanselmann | names.remove(hostname) |
1641 | 899d2a81 | Michael Hanselmann | if names:
|
1642 | 9440aeab | Michael Hanselmann | out.write("%s %s\n" % (fields[0], ' '.join(names))) |
1643 | 899d2a81 | Michael Hanselmann | continue
|
1644 | 899d2a81 | Michael Hanselmann | |
1645 | 899d2a81 | Michael Hanselmann | out.write(line) |
1646 | 59f82e3f | Michael Hanselmann | |
1647 | 59f82e3f | Michael Hanselmann | out.flush() |
1648 | 2e3e75b7 | Michael Hanselmann | os.fsync(out) |
1649 | 9b977740 | Guido Trotter | os.chmod(tmpname, 0644)
|
1650 | 59f82e3f | Michael Hanselmann | os.rename(tmpname, file_name) |
1651 | 59f82e3f | Michael Hanselmann | finally:
|
1652 | 59f82e3f | Michael Hanselmann | f.close() |
1653 | a8083063 | Iustin Pop | finally:
|
1654 | 59f82e3f | Michael Hanselmann | out.close() |
1655 | 59f82e3f | Michael Hanselmann | except:
|
1656 | 59f82e3f | Michael Hanselmann | RemoveFile(tmpname) |
1657 | 59f82e3f | Michael Hanselmann | raise
|
1658 | a8083063 | Iustin Pop | |
1659 | a8083063 | Iustin Pop | |
1660 | d9c02ca6 | Michael Hanselmann | def RemoveHostFromEtcHosts(hostname): |
1661 | d9c02ca6 | Michael Hanselmann | """Wrapper around RemoveEtcHostsEntry.
|
1662 | d9c02ca6 | Michael Hanselmann |
|
1663 | 58885d79 | Iustin Pop | @type hostname: str
|
1664 | 58885d79 | Iustin Pop | @param hostname: hostname that will be resolved and its
|
1665 | 58885d79 | Iustin Pop | full and shot name will be removed from
|
1666 | 58885d79 | Iustin Pop | L{constants.ETC_HOSTS}
|
1667 | 58885d79 | Iustin Pop |
|
1668 | d9c02ca6 | Michael Hanselmann | """
|
1669 | d9c02ca6 | Michael Hanselmann | hi = HostInfo(name=hostname) |
1670 | d9c02ca6 | Michael Hanselmann | RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.name) |
1671 | d9c02ca6 | Michael Hanselmann | RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.ShortName()) |
1672 | d9c02ca6 | Michael Hanselmann | |
1673 | d9c02ca6 | Michael Hanselmann | |
1674 | 1d466a4f | Michael Hanselmann | def TimestampForFilename(): |
1675 | 1d466a4f | Michael Hanselmann | """Returns the current time formatted for filenames.
|
1676 | 1d466a4f | Michael Hanselmann |
|
1677 | 1d466a4f | Michael Hanselmann | The format doesn't contain colons as some shells and applications them as
|
1678 | 1d466a4f | Michael Hanselmann | separators.
|
1679 | 1d466a4f | Michael Hanselmann |
|
1680 | 1d466a4f | Michael Hanselmann | """
|
1681 | 1d466a4f | Michael Hanselmann | return time.strftime("%Y-%m-%d_%H_%M_%S") |
1682 | 1d466a4f | Michael Hanselmann | |
1683 | 1d466a4f | Michael Hanselmann | |
1684 | a8083063 | Iustin Pop | def CreateBackup(file_name): |
1685 | a8083063 | Iustin Pop | """Creates a backup of a file.
|
1686 | a8083063 | Iustin Pop |
|
1687 | 58885d79 | Iustin Pop | @type file_name: str
|
1688 | 58885d79 | Iustin Pop | @param file_name: file to be backed up
|
1689 | 58885d79 | Iustin Pop | @rtype: str
|
1690 | 58885d79 | Iustin Pop | @return: the path to the newly created backup
|
1691 | 58885d79 | Iustin Pop | @raise errors.ProgrammerError: for invalid file names
|
1692 | a8083063 | Iustin Pop |
|
1693 | a8083063 | Iustin Pop | """
|
1694 | a8083063 | Iustin Pop | if not os.path.isfile(file_name): |
1695 | 3ecf6786 | Iustin Pop | raise errors.ProgrammerError("Can't make a backup of a non-file '%s'" % |
1696 | 3ecf6786 | Iustin Pop | file_name) |
1697 | a8083063 | Iustin Pop | |
1698 | 1d466a4f | Michael Hanselmann | prefix = ("%s.backup-%s." %
|
1699 | 1d466a4f | Michael Hanselmann | (os.path.basename(file_name), TimestampForFilename())) |
1700 | 65fe4693 | Iustin Pop | dir_name = os.path.dirname(file_name) |
1701 | 081b1e69 | Michael Hanselmann | |
1702 | 081b1e69 | Michael Hanselmann | fsrc = open(file_name, 'rb') |
1703 | 081b1e69 | Michael Hanselmann | try:
|
1704 | 65fe4693 | Iustin Pop | (fd, backup_name) = tempfile.mkstemp(prefix=prefix, dir=dir_name) |
1705 | 081b1e69 | Michael Hanselmann | fdst = os.fdopen(fd, 'wb')
|
1706 | 081b1e69 | Michael Hanselmann | try:
|
1707 | 1d466a4f | Michael Hanselmann | logging.debug("Backing up %s at %s", file_name, backup_name)
|
1708 | 081b1e69 | Michael Hanselmann | shutil.copyfileobj(fsrc, fdst) |
1709 | 081b1e69 | Michael Hanselmann | finally:
|
1710 | 081b1e69 | Michael Hanselmann | fdst.close() |
1711 | 081b1e69 | Michael Hanselmann | finally:
|
1712 | 081b1e69 | Michael Hanselmann | fsrc.close() |
1713 | 081b1e69 | Michael Hanselmann | |
1714 | a8083063 | Iustin Pop | return backup_name
|
1715 | a8083063 | Iustin Pop | |
1716 | a8083063 | Iustin Pop | |
1717 | a8083063 | Iustin Pop | def ShellQuote(value): |
1718 | a8083063 | Iustin Pop | """Quotes shell argument according to POSIX.
|
1719 | 3ecf6786 | Iustin Pop |
|
1720 | 58885d79 | Iustin Pop | @type value: str
|
1721 | 58885d79 | Iustin Pop | @param value: the argument to be quoted
|
1722 | 58885d79 | Iustin Pop | @rtype: str
|
1723 | 58885d79 | Iustin Pop | @return: the quoted value
|
1724 | 58885d79 | Iustin Pop |
|
1725 | a8083063 | Iustin Pop | """
|
1726 | a8083063 | Iustin Pop | if _re_shell_unquoted.match(value):
|
1727 | a8083063 | Iustin Pop | return value
|
1728 | a8083063 | Iustin Pop | else:
|
1729 | a8083063 | Iustin Pop | return "'%s'" % value.replace("'", "'\\''") |
1730 | a8083063 | Iustin Pop | |
1731 | a8083063 | Iustin Pop | |
1732 | a8083063 | Iustin Pop | def ShellQuoteArgs(args): |
1733 | 58885d79 | Iustin Pop | """Quotes a list of shell arguments.
|
1734 | 58885d79 | Iustin Pop |
|
1735 | 58885d79 | Iustin Pop | @type args: list
|
1736 | 58885d79 | Iustin Pop | @param args: list of arguments to be quoted
|
1737 | 58885d79 | Iustin Pop | @rtype: str
|
1738 | 5bbd3f7f | Michael Hanselmann | @return: the quoted arguments concatenated with spaces
|
1739 | a8083063 | Iustin Pop |
|
1740 | a8083063 | Iustin Pop | """
|
1741 | a8083063 | Iustin Pop | return ' '.join([ShellQuote(i) for i in args]) |
1742 | 88d14415 | Michael Hanselmann | |
1743 | 88d14415 | Michael Hanselmann | |
1744 | b15d625f | Iustin Pop | def TcpPing(target, port, timeout=10, live_port_needed=False, source=None): |
1745 | 2c30e9d7 | Alexander Schreiber | """Simple ping implementation using TCP connect(2).
|
1746 | 2c30e9d7 | Alexander Schreiber |
|
1747 | 58885d79 | Iustin Pop | Check if the given IP is reachable by doing attempting a TCP connect
|
1748 | 58885d79 | Iustin Pop | to it.
|
1749 | 58885d79 | Iustin Pop |
|
1750 | 58885d79 | Iustin Pop | @type target: str
|
1751 | 58885d79 | Iustin Pop | @param target: the IP or hostname to ping
|
1752 | 58885d79 | Iustin Pop | @type port: int
|
1753 | 58885d79 | Iustin Pop | @param port: the port to connect to
|
1754 | 58885d79 | Iustin Pop | @type timeout: int
|
1755 | 5bbd3f7f | Michael Hanselmann | @param timeout: the timeout on the connection attempt
|
1756 | 58885d79 | Iustin Pop | @type live_port_needed: boolean
|
1757 | 58885d79 | Iustin Pop | @param live_port_needed: whether a closed port will cause the
|
1758 | 58885d79 | Iustin Pop | function to return failure, as if there was a timeout
|
1759 | 58885d79 | Iustin Pop | @type source: str or None
|
1760 | 58885d79 | Iustin Pop | @param source: if specified, will cause the connect to be made
|
1761 | 58885d79 | Iustin Pop | from this specific source address; failures to bind other
|
1762 | 58885d79 | Iustin Pop | than C{EADDRNOTAVAIL} will be ignored
|
1763 | 2c30e9d7 | Alexander Schreiber |
|
1764 | 2c30e9d7 | Alexander Schreiber | """
|
1765 | cf0e6df7 | Manuel Franceschini | try:
|
1766 | cf0e6df7 | Manuel Franceschini | family = GetAddressFamily(target) |
1767 | cf0e6df7 | Manuel Franceschini | except errors.GenericError:
|
1768 | cf0e6df7 | Manuel Franceschini | return False |
1769 | 2c30e9d7 | Alexander Schreiber | |
1770 | cf0e6df7 | Manuel Franceschini | sock = socket.socket(family, socket.SOCK_STREAM) |
1771 | 0b5ad33e | Iustin Pop | success = False
|
1772 | 2c30e9d7 | Alexander Schreiber | |
1773 | b15d625f | Iustin Pop | if source is not None: |
1774 | b15d625f | Iustin Pop | try:
|
1775 | b15d625f | Iustin Pop | sock.bind((source, 0))
|
1776 | 7c4d6c7b | Michael Hanselmann | except socket.error, (errcode, _):
|
1777 | b15d625f | Iustin Pop | if errcode == errno.EADDRNOTAVAIL:
|
1778 | b15d625f | Iustin Pop | success = False
|
1779 | 2c30e9d7 | Alexander Schreiber | |
1780 | 2c30e9d7 | Alexander Schreiber | sock.settimeout(timeout) |
1781 | 2c30e9d7 | Alexander Schreiber | |
1782 | 2c30e9d7 | Alexander Schreiber | try:
|
1783 | 2c30e9d7 | Alexander Schreiber | sock.connect((target, port)) |
1784 | 2c30e9d7 | Alexander Schreiber | sock.close() |
1785 | 2c30e9d7 | Alexander Schreiber | success = True
|
1786 | 2c30e9d7 | Alexander Schreiber | except socket.timeout:
|
1787 | 2c30e9d7 | Alexander Schreiber | success = False
|
1788 | 099c52ad | Iustin Pop | except socket.error, (errcode, _):
|
1789 | 4ca1b175 | Alexander Schreiber | success = (not live_port_needed) and (errcode == errno.ECONNREFUSED) |
1790 | 2c30e9d7 | Alexander Schreiber | |
1791 | 2c30e9d7 | Alexander Schreiber | return success
|
1792 | eedbda4b | Michael Hanselmann | |
1793 | eedbda4b | Michael Hanselmann | |
1794 | caad16e2 | Iustin Pop | def OwnIpAddress(address): |
1795 | caad16e2 | Iustin Pop | """Check if the current host has the the given IP address.
|
1796 | caad16e2 | Iustin Pop |
|
1797 | 56e4c4a0 | Manuel Franceschini | This is done by trying to bind the given address. We return True if we
|
1798 | 56e4c4a0 | Manuel Franceschini | succeed or false if a socket.error is raised.
|
1799 | caad16e2 | Iustin Pop |
|
1800 | caad16e2 | Iustin Pop | @type address: string
|
1801 | 5bbd3f7f | Michael Hanselmann | @param address: the address to check
|
1802 | caad16e2 | Iustin Pop | @rtype: bool
|
1803 | 58885d79 | Iustin Pop | @return: True if we own the address
|
1804 | caad16e2 | Iustin Pop |
|
1805 | caad16e2 | Iustin Pop | """
|
1806 | 56e4c4a0 | Manuel Franceschini | family = GetAddressFamily(address) |
1807 | 56e4c4a0 | Manuel Franceschini | s = socket.socket(family, socket.SOCK_DGRAM) |
1808 | 56e4c4a0 | Manuel Franceschini | success = False
|
1809 | 56e4c4a0 | Manuel Franceschini | try:
|
1810 | ac492887 | Michael Hanselmann | try:
|
1811 | ac492887 | Michael Hanselmann | s.bind((address, 0))
|
1812 | ac492887 | Michael Hanselmann | success = True
|
1813 | ac492887 | Michael Hanselmann | except socket.error:
|
1814 | ac492887 | Michael Hanselmann | success = False
|
1815 | 56e4c4a0 | Manuel Franceschini | finally:
|
1816 | 56e4c4a0 | Manuel Franceschini | s.close() |
1817 | 56e4c4a0 | Manuel Franceschini | return success
|
1818 | caad16e2 | Iustin Pop | |
1819 | caad16e2 | Iustin Pop | |
1820 | b5b8309d | Guido Trotter | def ListVisibleFiles(path): |
1821 | 58885d79 | Iustin Pop | """Returns a list of visible files in a directory.
|
1822 | 58885d79 | Iustin Pop |
|
1823 | 58885d79 | Iustin Pop | @type path: str
|
1824 | 58885d79 | Iustin Pop | @param path: the directory to enumerate
|
1825 | 58885d79 | Iustin Pop | @rtype: list
|
1826 | 58885d79 | Iustin Pop | @return: the list of all files not starting with a dot
|
1827 | 04a69a18 | Iustin Pop | @raise ProgrammerError: if L{path} is not an absolue and normalized path
|
1828 | eedbda4b | Michael Hanselmann |
|
1829 | eedbda4b | Michael Hanselmann | """
|
1830 | 04a69a18 | Iustin Pop | if not IsNormAbsPath(path): |
1831 | 04a69a18 | Iustin Pop | raise errors.ProgrammerError("Path passed to ListVisibleFiles is not" |
1832 | 04a69a18 | Iustin Pop | " absolute/normalized: '%s'" % path)
|
1833 | f3299a07 | Michael Hanselmann | files = [i for i in os.listdir(path) if not i.startswith(".")] |
1834 | f3299a07 | Michael Hanselmann | return files
|
1835 | 2f8b60b3 | Iustin Pop | |
1836 | 2f8b60b3 | Iustin Pop | |
1837 | 257f4c0a | Iustin Pop | def GetHomeDir(user, default=None): |
1838 | 257f4c0a | Iustin Pop | """Try to get the homedir of the given user.
|
1839 | 257f4c0a | Iustin Pop |
|
1840 | 257f4c0a | Iustin Pop | The user can be passed either as a string (denoting the name) or as
|
1841 | 257f4c0a | Iustin Pop | an integer (denoting the user id). If the user is not found, the
|
1842 | 257f4c0a | Iustin Pop | 'default' argument is returned, which defaults to None.
|
1843 | 2f8b60b3 | Iustin Pop |
|
1844 | 2f8b60b3 | Iustin Pop | """
|
1845 | 2f8b60b3 | Iustin Pop | try:
|
1846 | 257f4c0a | Iustin Pop | if isinstance(user, basestring): |
1847 | 257f4c0a | Iustin Pop | result = pwd.getpwnam(user) |
1848 | 257f4c0a | Iustin Pop | elif isinstance(user, (int, long)): |
1849 | 257f4c0a | Iustin Pop | result = pwd.getpwuid(user) |
1850 | 257f4c0a | Iustin Pop | else:
|
1851 | 257f4c0a | Iustin Pop | raise errors.ProgrammerError("Invalid type passed to GetHomeDir (%s)" % |
1852 | 257f4c0a | Iustin Pop | type(user))
|
1853 | 2f8b60b3 | Iustin Pop | except KeyError: |
1854 | 2f8b60b3 | Iustin Pop | return default
|
1855 | 2f8b60b3 | Iustin Pop | return result.pw_dir
|
1856 | 59072e7e | Michael Hanselmann | |
1857 | 59072e7e | Michael Hanselmann | |
1858 | 24818e8f | Michael Hanselmann | def NewUUID(): |
1859 | 59072e7e | Michael Hanselmann | """Returns a random UUID.
|
1860 | 59072e7e | Michael Hanselmann |
|
1861 | 58885d79 | Iustin Pop | @note: This is a Linux-specific method as it uses the /proc
|
1862 | 58885d79 | Iustin Pop | filesystem.
|
1863 | 58885d79 | Iustin Pop | @rtype: str
|
1864 | 58885d79 | Iustin Pop |
|
1865 | 59072e7e | Michael Hanselmann | """
|
1866 | 13998ef2 | Michael Hanselmann | return ReadFile(_RANDOM_UUID_FILE, size=128).rstrip("\n") |
1867 | 087b34fe | Iustin Pop | |
1868 | 087b34fe | Iustin Pop | |
1869 | ec2c2bc4 | Luca Bigliardi | def GenerateSecret(numbytes=20): |
1870 | 33081d90 | Iustin Pop | """Generates a random secret.
|
1871 | 33081d90 | Iustin Pop |
|
1872 | ec2c2bc4 | Luca Bigliardi | This will generate a pseudo-random secret returning an hex string
|
1873 | 33081d90 | Iustin Pop | (so that it can be used where an ASCII string is needed).
|
1874 | 33081d90 | Iustin Pop |
|
1875 | ec2c2bc4 | Luca Bigliardi | @param numbytes: the number of bytes which will be represented by the returned
|
1876 | ec2c2bc4 | Luca Bigliardi | string (defaulting to 20, the length of a SHA1 hash)
|
1877 | 58885d79 | Iustin Pop | @rtype: str
|
1878 | ec2c2bc4 | Luca Bigliardi | @return: an hex representation of the pseudo-random sequence
|
1879 | 58885d79 | Iustin Pop |
|
1880 | 33081d90 | Iustin Pop | """
|
1881 | ec2c2bc4 | Luca Bigliardi | return os.urandom(numbytes).encode('hex') |
1882 | 33081d90 | Iustin Pop | |
1883 | 33081d90 | Iustin Pop | |
1884 | 9dae41ad | Guido Trotter | def EnsureDirs(dirs): |
1885 | 9dae41ad | Guido Trotter | """Make required directories, if they don't exist.
|
1886 | 9dae41ad | Guido Trotter |
|
1887 | 9dae41ad | Guido Trotter | @param dirs: list of tuples (dir_name, dir_mode)
|
1888 | 9dae41ad | Guido Trotter | @type dirs: list of (string, integer)
|
1889 | 9dae41ad | Guido Trotter |
|
1890 | 9dae41ad | Guido Trotter | """
|
1891 | 9dae41ad | Guido Trotter | for dir_name, dir_mode in dirs: |
1892 | 9dae41ad | Guido Trotter | try:
|
1893 | 1b2c8f85 | Iustin Pop | os.mkdir(dir_name, dir_mode) |
1894 | 9dae41ad | Guido Trotter | except EnvironmentError, err: |
1895 | 9dae41ad | Guido Trotter | if err.errno != errno.EEXIST:
|
1896 | 9dae41ad | Guido Trotter | raise errors.GenericError("Cannot create needed directory" |
1897 | 1b2c8f85 | Iustin Pop | " '%s': %s" % (dir_name, err))
|
1898 | b73360e3 | Balazs Lecz | try:
|
1899 | b73360e3 | Balazs Lecz | os.chmod(dir_name, dir_mode) |
1900 | b73360e3 | Balazs Lecz | except EnvironmentError, err: |
1901 | b73360e3 | Balazs Lecz | raise errors.GenericError("Cannot change directory permissions on" |
1902 | b73360e3 | Balazs Lecz | " '%s': %s" % (dir_name, err))
|
1903 | 9dae41ad | Guido Trotter | if not os.path.isdir(dir_name): |
1904 | 9dae41ad | Guido Trotter | raise errors.GenericError("%s is not a directory" % dir_name) |
1905 | 9dae41ad | Guido Trotter | |
1906 | 9dae41ad | Guido Trotter | |
1907 | 582ed043 | Guido Trotter | def ReadFile(file_name, size=-1): |
1908 | ca0aa6d0 | Michael Hanselmann | """Reads a file.
|
1909 | ca0aa6d0 | Michael Hanselmann |
|
1910 | 016308cb | Iustin Pop | @type size: int
|
1911 | 016308cb | Iustin Pop | @param size: Read at most size bytes (if negative, entire file)
|
1912 | 58885d79 | Iustin Pop | @rtype: str
|
1913 | 5bbd3f7f | Michael Hanselmann | @return: the (possibly partial) content of the file
|
1914 | ca0aa6d0 | Michael Hanselmann |
|
1915 | ca0aa6d0 | Michael Hanselmann | """
|
1916 | ca0aa6d0 | Michael Hanselmann | f = open(file_name, "r") |
1917 | ca0aa6d0 | Michael Hanselmann | try:
|
1918 | 582ed043 | Guido Trotter | return f.read(size)
|
1919 | ca0aa6d0 | Michael Hanselmann | finally:
|
1920 | ca0aa6d0 | Michael Hanselmann | f.close() |
1921 | ca0aa6d0 | Michael Hanselmann | |
1922 | ca0aa6d0 | Michael Hanselmann | |
1923 | 087b34fe | Iustin Pop | def WriteFile(file_name, fn=None, data=None, |
1924 | 087b34fe | Iustin Pop | mode=None, uid=-1, gid=-1, |
1925 | 71714516 | Michael Hanselmann | atime=None, mtime=None, close=True, |
1926 | 04a8d789 | Michael Hanselmann | dry_run=False, backup=False, |
1927 | 71714516 | Michael Hanselmann | prewrite=None, postwrite=None): |
1928 | 087b34fe | Iustin Pop | """(Over)write a file atomically.
|
1929 | 087b34fe | Iustin Pop |
|
1930 | 087b34fe | Iustin Pop | The file_name and either fn (a function taking one argument, the
|
1931 | 087b34fe | Iustin Pop | file descriptor, and which should write the data to it) or data (the
|
1932 | 087b34fe | Iustin Pop | contents of the file) must be passed. The other arguments are
|
1933 | 087b34fe | Iustin Pop | optional and allow setting the file mode, owner and group, and the
|
1934 | 087b34fe | Iustin Pop | mtime/atime of the file.
|
1935 | 087b34fe | Iustin Pop |
|
1936 | 087b34fe | Iustin Pop | If the function doesn't raise an exception, it has succeeded and the
|
1937 | 69efe319 | Michael Hanselmann | target file has the new contents. If the function has raised an
|
1938 | 087b34fe | Iustin Pop | exception, an existing target file should be unmodified and the
|
1939 | 087b34fe | Iustin Pop | temporary file should be removed.
|
1940 | 087b34fe | Iustin Pop |
|
1941 | 58885d79 | Iustin Pop | @type file_name: str
|
1942 | 58885d79 | Iustin Pop | @param file_name: the target filename
|
1943 | 58885d79 | Iustin Pop | @type fn: callable
|
1944 | 58885d79 | Iustin Pop | @param fn: content writing function, called with
|
1945 | 58885d79 | Iustin Pop | file descriptor as parameter
|
1946 | 69efe319 | Michael Hanselmann | @type data: str
|
1947 | 58885d79 | Iustin Pop | @param data: contents of the file
|
1948 | 58885d79 | Iustin Pop | @type mode: int
|
1949 | 58885d79 | Iustin Pop | @param mode: file mode
|
1950 | 58885d79 | Iustin Pop | @type uid: int
|
1951 | 58885d79 | Iustin Pop | @param uid: the owner of the file
|
1952 | 58885d79 | Iustin Pop | @type gid: int
|
1953 | 58885d79 | Iustin Pop | @param gid: the group of the file
|
1954 | 58885d79 | Iustin Pop | @type atime: int
|
1955 | 58885d79 | Iustin Pop | @param atime: a custom access time to be set on the file
|
1956 | 58885d79 | Iustin Pop | @type mtime: int
|
1957 | 58885d79 | Iustin Pop | @param mtime: a custom modification time to be set on the file
|
1958 | 58885d79 | Iustin Pop | @type close: boolean
|
1959 | 58885d79 | Iustin Pop | @param close: whether to close file after writing it
|
1960 | 58885d79 | Iustin Pop | @type prewrite: callable
|
1961 | 58885d79 | Iustin Pop | @param prewrite: function to be called before writing content
|
1962 | 58885d79 | Iustin Pop | @type postwrite: callable
|
1963 | 58885d79 | Iustin Pop | @param postwrite: function to be called after writing content
|
1964 | 58885d79 | Iustin Pop |
|
1965 | 58885d79 | Iustin Pop | @rtype: None or int
|
1966 | 58885d79 | Iustin Pop | @return: None if the 'close' parameter evaluates to True,
|
1967 | 58885d79 | Iustin Pop | otherwise the file descriptor
|
1968 | 58885d79 | Iustin Pop |
|
1969 | 69efe319 | Michael Hanselmann | @raise errors.ProgrammerError: if any of the arguments are not valid
|
1970 | 71714516 | Michael Hanselmann |
|
1971 | 087b34fe | Iustin Pop | """
|
1972 | 04a8d789 | Michael Hanselmann | if not os.path.isabs(file_name): |
1973 | 087b34fe | Iustin Pop | raise errors.ProgrammerError("Path passed to WriteFile is not" |
1974 | 087b34fe | Iustin Pop | " absolute: '%s'" % file_name)
|
1975 | 087b34fe | Iustin Pop | |
1976 | 087b34fe | Iustin Pop | if [fn, data].count(None) != 1: |
1977 | 087b34fe | Iustin Pop | raise errors.ProgrammerError("fn or data required") |
1978 | 087b34fe | Iustin Pop | |
1979 | 087b34fe | Iustin Pop | if [atime, mtime].count(None) == 1: |
1980 | 087b34fe | Iustin Pop | raise errors.ProgrammerError("Both atime and mtime must be either" |
1981 | 087b34fe | Iustin Pop | " set or None")
|
1982 | 087b34fe | Iustin Pop | |
1983 | 70f4497c | Michael Hanselmann | if backup and not dry_run and os.path.isfile(file_name): |
1984 | 70f4497c | Michael Hanselmann | CreateBackup(file_name) |
1985 | 087b34fe | Iustin Pop | |
1986 | 087b34fe | Iustin Pop | dir_name, base_name = os.path.split(file_name) |
1987 | 087b34fe | Iustin Pop | fd, new_name = tempfile.mkstemp('.new', base_name, dir_name)
|
1988 | 81b7354c | Iustin Pop | do_remove = True
|
1989 | 087b34fe | Iustin Pop | # here we need to make sure we remove the temp file, if any error
|
1990 | 087b34fe | Iustin Pop | # leaves it in place
|
1991 | 087b34fe | Iustin Pop | try:
|
1992 | 087b34fe | Iustin Pop | if uid != -1 or gid != -1: |
1993 | 087b34fe | Iustin Pop | os.chown(new_name, uid, gid) |
1994 | 087b34fe | Iustin Pop | if mode:
|
1995 | 087b34fe | Iustin Pop | os.chmod(new_name, mode) |
1996 | 71714516 | Michael Hanselmann | if callable(prewrite): |
1997 | 71714516 | Michael Hanselmann | prewrite(fd) |
1998 | 087b34fe | Iustin Pop | if data is not None: |
1999 | 087b34fe | Iustin Pop | os.write(fd, data) |
2000 | 087b34fe | Iustin Pop | else:
|
2001 | 087b34fe | Iustin Pop | fn(fd) |
2002 | 71714516 | Michael Hanselmann | if callable(postwrite): |
2003 | 71714516 | Michael Hanselmann | postwrite(fd) |
2004 | 087b34fe | Iustin Pop | os.fsync(fd) |
2005 | 087b34fe | Iustin Pop | if atime is not None and mtime is not None: |
2006 | 087b34fe | Iustin Pop | os.utime(new_name, (atime, mtime)) |
2007 | 70f4497c | Michael Hanselmann | if not dry_run: |
2008 | 70f4497c | Michael Hanselmann | os.rename(new_name, file_name) |
2009 | 81b7354c | Iustin Pop | do_remove = False
|
2010 | 087b34fe | Iustin Pop | finally:
|
2011 | 71714516 | Michael Hanselmann | if close:
|
2012 | 71714516 | Michael Hanselmann | os.close(fd) |
2013 | 71714516 | Michael Hanselmann | result = None
|
2014 | 71714516 | Michael Hanselmann | else:
|
2015 | 71714516 | Michael Hanselmann | result = fd |
2016 | 81b7354c | Iustin Pop | if do_remove:
|
2017 | 81b7354c | Iustin Pop | RemoveFile(new_name) |
2018 | 78feb6fb | Guido Trotter | |
2019 | 71714516 | Michael Hanselmann | return result
|
2020 | 71714516 | Michael Hanselmann | |
2021 | 78feb6fb | Guido Trotter | |
2022 | e587b46a | Guido Trotter | def ReadOneLineFile(file_name, strict=False): |
2023 | e587b46a | Guido Trotter | """Return the first non-empty line from a file.
|
2024 | e587b46a | Guido Trotter |
|
2025 | e587b46a | Guido Trotter | @type strict: boolean
|
2026 | e587b46a | Guido Trotter | @param strict: if True, abort if the file has more than one
|
2027 | e587b46a | Guido Trotter | non-empty line
|
2028 | e587b46a | Guido Trotter |
|
2029 | e587b46a | Guido Trotter | """
|
2030 | e587b46a | Guido Trotter | file_lines = ReadFile(file_name).splitlines() |
2031 | e587b46a | Guido Trotter | full_lines = filter(bool, file_lines) |
2032 | e587b46a | Guido Trotter | if not file_lines or not full_lines: |
2033 | e587b46a | Guido Trotter | raise errors.GenericError("No data in one-liner file %s" % file_name) |
2034 | e587b46a | Guido Trotter | elif strict and len(full_lines) > 1: |
2035 | e587b46a | Guido Trotter | raise errors.GenericError("Too many lines in one-liner file %s" % |
2036 | e587b46a | Guido Trotter | file_name) |
2037 | e587b46a | Guido Trotter | return full_lines[0] |
2038 | e587b46a | Guido Trotter | |
2039 | e587b46a | Guido Trotter | |
2040 | 7b4126b7 | Iustin Pop | def FirstFree(seq, base=0): |
2041 | 7b4126b7 | Iustin Pop | """Returns the first non-existing integer from seq.
|
2042 | 7b4126b7 | Iustin Pop |
|
2043 | 7b4126b7 | Iustin Pop | The seq argument should be a sorted list of positive integers. The
|
2044 | 7b4126b7 | Iustin Pop | first time the index of an element is smaller than the element
|
2045 | 7b4126b7 | Iustin Pop | value, the index will be returned.
|
2046 | 7b4126b7 | Iustin Pop |
|
2047 | 7b4126b7 | Iustin Pop | The base argument is used to start at a different offset,
|
2048 | 58885d79 | Iustin Pop | i.e. C{[3, 4, 6]} with I{offset=3} will return 5.
|
2049 | 58885d79 | Iustin Pop |
|
2050 | 58885d79 | Iustin Pop | Example: C{[0, 1, 3]} will return I{2}.
|
2051 | 7b4126b7 | Iustin Pop |
|
2052 | 58885d79 | Iustin Pop | @type seq: sequence
|
2053 | 58885d79 | Iustin Pop | @param seq: the sequence to be analyzed.
|
2054 | 58885d79 | Iustin Pop | @type base: int
|
2055 | 58885d79 | Iustin Pop | @param base: use this value as the base index of the sequence
|
2056 | 58885d79 | Iustin Pop | @rtype: int
|
2057 | 58885d79 | Iustin Pop | @return: the first non-used index in the sequence
|
2058 | 7b4126b7 | Iustin Pop |
|
2059 | 7b4126b7 | Iustin Pop | """
|
2060 | 7b4126b7 | Iustin Pop | for idx, elem in enumerate(seq): |
2061 | 7b4126b7 | Iustin Pop | assert elem >= base, "Passed element is higher than base offset" |
2062 | 7b4126b7 | Iustin Pop | if elem > idx + base:
|
2063 | 7b4126b7 | Iustin Pop | # idx is not used
|
2064 | 7b4126b7 | Iustin Pop | return idx + base
|
2065 | 7b4126b7 | Iustin Pop | return None |
2066 | 7b4126b7 | Iustin Pop | |
2067 | 7b4126b7 | Iustin Pop | |
2068 | dfdc4060 | Guido Trotter | def SingleWaitForFdCondition(fdobj, event, timeout): |
2069 | dcd511c8 | Guido Trotter | """Waits for a condition to occur on the socket.
|
2070 | dcd511c8 | Guido Trotter |
|
2071 | dfdc4060 | Guido Trotter | Immediately returns at the first interruption.
|
2072 | dfdc4060 | Guido Trotter |
|
2073 | dfdc4060 | Guido Trotter | @type fdobj: integer or object supporting a fileno() method
|
2074 | dfdc4060 | Guido Trotter | @param fdobj: entity to wait for events on
|
2075 | dfdc4060 | Guido Trotter | @type event: integer
|
2076 | dcd511c8 | Guido Trotter | @param event: ORed condition (see select module)
|
2077 | dcd511c8 | Guido Trotter | @type timeout: float or None
|
2078 | dcd511c8 | Guido Trotter | @param timeout: Timeout in seconds
|
2079 | dcd511c8 | Guido Trotter | @rtype: int or None
|
2080 | dcd511c8 | Guido Trotter | @return: None for timeout, otherwise occured conditions
|
2081 | dcd511c8 | Guido Trotter |
|
2082 | dcd511c8 | Guido Trotter | """
|
2083 | dcd511c8 | Guido Trotter | check = (event | select.POLLPRI | |
2084 | dcd511c8 | Guido Trotter | select.POLLNVAL | select.POLLHUP | select.POLLERR) |
2085 | dcd511c8 | Guido Trotter | |
2086 | dcd511c8 | Guido Trotter | if timeout is not None: |
2087 | dcd511c8 | Guido Trotter | # Poller object expects milliseconds
|
2088 | dcd511c8 | Guido Trotter | timeout *= 1000
|
2089 | dcd511c8 | Guido Trotter | |
2090 | dcd511c8 | Guido Trotter | poller = select.poll() |
2091 | dfdc4060 | Guido Trotter | poller.register(fdobj, event) |
2092 | dcd511c8 | Guido Trotter | try:
|
2093 | dfdc4060 | Guido Trotter | # TODO: If the main thread receives a signal and we have no timeout, we
|
2094 | dfdc4060 | Guido Trotter | # could wait forever. This should check a global "quit" flag or something
|
2095 | dfdc4060 | Guido Trotter | # every so often.
|
2096 | dfdc4060 | Guido Trotter | io_events = poller.poll(timeout) |
2097 | dfdc4060 | Guido Trotter | except select.error, err:
|
2098 | dfdc4060 | Guido Trotter | if err[0] != errno.EINTR: |
2099 | dfdc4060 | Guido Trotter | raise
|
2100 | dfdc4060 | Guido Trotter | io_events = [] |
2101 | dfdc4060 | Guido Trotter | if io_events and io_events[0][1] & check: |
2102 | dfdc4060 | Guido Trotter | return io_events[0][1] |
2103 | dfdc4060 | Guido Trotter | else:
|
2104 | dfdc4060 | Guido Trotter | return None |
2105 | dfdc4060 | Guido Trotter | |
2106 | dfdc4060 | Guido Trotter | |
2107 | dfdc4060 | Guido Trotter | class FdConditionWaiterHelper(object): |
2108 | dfdc4060 | Guido Trotter | """Retry helper for WaitForFdCondition.
|
2109 | dfdc4060 | Guido Trotter |
|
2110 | dfdc4060 | Guido Trotter | This class contains the retried and wait functions that make sure
|
2111 | dfdc4060 | Guido Trotter | WaitForFdCondition can continue waiting until the timeout is actually
|
2112 | dfdc4060 | Guido Trotter | expired.
|
2113 | dfdc4060 | Guido Trotter |
|
2114 | dfdc4060 | Guido Trotter | """
|
2115 | dfdc4060 | Guido Trotter | |
2116 | dfdc4060 | Guido Trotter | def __init__(self, timeout): |
2117 | dfdc4060 | Guido Trotter | self.timeout = timeout
|
2118 | dfdc4060 | Guido Trotter | |
2119 | dfdc4060 | Guido Trotter | def Poll(self, fdobj, event): |
2120 | dfdc4060 | Guido Trotter | result = SingleWaitForFdCondition(fdobj, event, self.timeout)
|
2121 | dfdc4060 | Guido Trotter | if result is None: |
2122 | dfdc4060 | Guido Trotter | raise RetryAgain()
|
2123 | dfdc4060 | Guido Trotter | else:
|
2124 | dfdc4060 | Guido Trotter | return result
|
2125 | dfdc4060 | Guido Trotter | |
2126 | dfdc4060 | Guido Trotter | def UpdateTimeout(self, timeout): |
2127 | dfdc4060 | Guido Trotter | self.timeout = timeout
|
2128 | dfdc4060 | Guido Trotter | |
2129 | dfdc4060 | Guido Trotter | |
2130 | dfdc4060 | Guido Trotter | def WaitForFdCondition(fdobj, event, timeout): |
2131 | dfdc4060 | Guido Trotter | """Waits for a condition to occur on the socket.
|
2132 | dfdc4060 | Guido Trotter |
|
2133 | dfdc4060 | Guido Trotter | Retries until the timeout is expired, even if interrupted.
|
2134 | dfdc4060 | Guido Trotter |
|
2135 | dfdc4060 | Guido Trotter | @type fdobj: integer or object supporting a fileno() method
|
2136 | dfdc4060 | Guido Trotter | @param fdobj: entity to wait for events on
|
2137 | dfdc4060 | Guido Trotter | @type event: integer
|
2138 | dfdc4060 | Guido Trotter | @param event: ORed condition (see select module)
|
2139 | dfdc4060 | Guido Trotter | @type timeout: float or None
|
2140 | dfdc4060 | Guido Trotter | @param timeout: Timeout in seconds
|
2141 | dfdc4060 | Guido Trotter | @rtype: int or None
|
2142 | dfdc4060 | Guido Trotter | @return: None for timeout, otherwise occured conditions
|
2143 | dfdc4060 | Guido Trotter |
|
2144 | dfdc4060 | Guido Trotter | """
|
2145 | dfdc4060 | Guido Trotter | if timeout is not None: |
2146 | dfdc4060 | Guido Trotter | retrywaiter = FdConditionWaiterHelper(timeout) |
2147 | 1b429e2a | Iustin Pop | try:
|
2148 | 1b429e2a | Iustin Pop | result = Retry(retrywaiter.Poll, RETRY_REMAINING_TIME, timeout, |
2149 | 1b429e2a | Iustin Pop | args=(fdobj, event), wait_fn=retrywaiter.UpdateTimeout) |
2150 | 1b429e2a | Iustin Pop | except RetryTimeout:
|
2151 | 1b429e2a | Iustin Pop | result = None
|
2152 | dfdc4060 | Guido Trotter | else:
|
2153 | dfdc4060 | Guido Trotter | result = None
|
2154 | dfdc4060 | Guido Trotter | while result is None: |
2155 | dfdc4060 | Guido Trotter | result = SingleWaitForFdCondition(fdobj, event, timeout) |
2156 | dfdc4060 | Guido Trotter | return result
|
2157 | 2de64672 | Iustin Pop | |
2158 | 2de64672 | Iustin Pop | |
2159 | f7414041 | Michael Hanselmann | def UniqueSequence(seq): |
2160 | f7414041 | Michael Hanselmann | """Returns a list with unique elements.
|
2161 | f7414041 | Michael Hanselmann |
|
2162 | f7414041 | Michael Hanselmann | Element order is preserved.
|
2163 | 58885d79 | Iustin Pop |
|
2164 | 58885d79 | Iustin Pop | @type seq: sequence
|
2165 | 5bbd3f7f | Michael Hanselmann | @param seq: the sequence with the source elements
|
2166 | 58885d79 | Iustin Pop | @rtype: list
|
2167 | 58885d79 | Iustin Pop | @return: list of unique elements from seq
|
2168 | 58885d79 | Iustin Pop |
|
2169 | f7414041 | Michael Hanselmann | """
|
2170 | f7414041 | Michael Hanselmann | seen = set()
|
2171 | f7414041 | Michael Hanselmann | return [i for i in seq if i not in seen and not seen.add(i)] |
2172 | 1862d460 | Alexander Schreiber | |
2173 | 1862d460 | Alexander Schreiber | |
2174 | 82187135 | Renรฉ Nussbaumer | def NormalizeAndValidateMac(mac): |
2175 | 82187135 | Renรฉ Nussbaumer | """Normalizes and check if a MAC address is valid.
|
2176 | 1862d460 | Alexander Schreiber |
|
2177 | 5bbd3f7f | Michael Hanselmann | Checks whether the supplied MAC address is formally correct, only
|
2178 | 82187135 | Renรฉ Nussbaumer | accepts colon separated format. Normalize it to all lower.
|
2179 | 58885d79 | Iustin Pop |
|
2180 | 58885d79 | Iustin Pop | @type mac: str
|
2181 | 58885d79 | Iustin Pop | @param mac: the MAC to be validated
|
2182 | 82187135 | Renรฉ Nussbaumer | @rtype: str
|
2183 | 82187135 | Renรฉ Nussbaumer | @return: returns the normalized and validated MAC.
|
2184 | 82187135 | Renรฉ Nussbaumer |
|
2185 | 82187135 | Renรฉ Nussbaumer | @raise errors.OpPrereqError: If the MAC isn't valid
|
2186 | 58885d79 | Iustin Pop |
|
2187 | 1862d460 | Alexander Schreiber | """
|
2188 | 82187135 | Renรฉ Nussbaumer | mac_check = re.compile("^([0-9a-f]{2}(:|$)){6}$", re.I)
|
2189 | 82187135 | Renรฉ Nussbaumer | if not mac_check.match(mac): |
2190 | 82187135 | Renรฉ Nussbaumer | raise errors.OpPrereqError("Invalid MAC address specified: %s" % |
2191 | 82187135 | Renรฉ Nussbaumer | mac, errors.ECODE_INVAL) |
2192 | 82187135 | Renรฉ Nussbaumer | |
2193 | 82187135 | Renรฉ Nussbaumer | return mac.lower()
|
2194 | 06009e27 | Iustin Pop | |
2195 | 06009e27 | Iustin Pop | |
2196 | 06009e27 | Iustin Pop | def TestDelay(duration): |
2197 | 06009e27 | Iustin Pop | """Sleep for a fixed amount of time.
|
2198 | 06009e27 | Iustin Pop |
|
2199 | 58885d79 | Iustin Pop | @type duration: float
|
2200 | 58885d79 | Iustin Pop | @param duration: the sleep duration
|
2201 | 58885d79 | Iustin Pop | @rtype: boolean
|
2202 | 58885d79 | Iustin Pop | @return: False for negative value, True otherwise
|
2203 | 58885d79 | Iustin Pop |
|
2204 | 06009e27 | Iustin Pop | """
|
2205 | 06009e27 | Iustin Pop | if duration < 0: |
2206 | 38ea42a1 | Iustin Pop | return False, "Invalid sleep duration" |
2207 | 06009e27 | Iustin Pop | time.sleep(duration) |
2208 | 38ea42a1 | Iustin Pop | return True, None |
2209 | 8f765069 | Iustin Pop | |
2210 | 8f765069 | Iustin Pop | |
2211 | 7d88772a | Iustin Pop | def _CloseFDNoErr(fd, retries=5): |
2212 | 7d88772a | Iustin Pop | """Close a file descriptor ignoring errors.
|
2213 | 8f765069 | Iustin Pop |
|
2214 | 7d88772a | Iustin Pop | @type fd: int
|
2215 | 7d88772a | Iustin Pop | @param fd: the file descriptor
|
2216 | 7d88772a | Iustin Pop | @type retries: int
|
2217 | 7d88772a | Iustin Pop | @param retries: how many retries to make, in case we get any
|
2218 | 7d88772a | Iustin Pop | other error than EBADF
|
2219 | 7d88772a | Iustin Pop |
|
2220 | 7d88772a | Iustin Pop | """
|
2221 | 7d88772a | Iustin Pop | try:
|
2222 | 7d88772a | Iustin Pop | os.close(fd) |
2223 | 7d88772a | Iustin Pop | except OSError, err: |
2224 | 7d88772a | Iustin Pop | if err.errno != errno.EBADF:
|
2225 | 7d88772a | Iustin Pop | if retries > 0: |
2226 | 7d88772a | Iustin Pop | _CloseFDNoErr(fd, retries - 1)
|
2227 | 7d88772a | Iustin Pop | # else either it's closed already or we're out of retries, so we
|
2228 | 7d88772a | Iustin Pop | # ignore this and go on
|
2229 | 7d88772a | Iustin Pop | |
2230 | 7d88772a | Iustin Pop | |
2231 | 7d88772a | Iustin Pop | def CloseFDs(noclose_fds=None): |
2232 | 7d88772a | Iustin Pop | """Close file descriptors.
|
2233 | 7d88772a | Iustin Pop |
|
2234 | 7d88772a | Iustin Pop | This closes all file descriptors above 2 (i.e. except
|
2235 | 7d88772a | Iustin Pop | stdin/out/err).
|
2236 | 8f765069 | Iustin Pop |
|
2237 | 58885d79 | Iustin Pop | @type noclose_fds: list or None
|
2238 | 58885d79 | Iustin Pop | @param noclose_fds: if given, it denotes a list of file descriptor
|
2239 | 58885d79 | Iustin Pop | that should not be closed
|
2240 | 58885d79 | Iustin Pop |
|
2241 | 8f765069 | Iustin Pop | """
|
2242 | 8f765069 | Iustin Pop | # Default maximum for the number of available file descriptors.
|
2243 | 8f765069 | Iustin Pop | if 'SC_OPEN_MAX' in os.sysconf_names: |
2244 | 8f765069 | Iustin Pop | try:
|
2245 | 8f765069 | Iustin Pop | MAXFD = os.sysconf('SC_OPEN_MAX')
|
2246 | 8f765069 | Iustin Pop | if MAXFD < 0: |
2247 | 8f765069 | Iustin Pop | MAXFD = 1024
|
2248 | 8f765069 | Iustin Pop | except OSError: |
2249 | 8f765069 | Iustin Pop | MAXFD = 1024
|
2250 | 8f765069 | Iustin Pop | else:
|
2251 | 8f765069 | Iustin Pop | MAXFD = 1024
|
2252 | 7d88772a | Iustin Pop | maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
|
2253 | 7d88772a | Iustin Pop | if (maxfd == resource.RLIM_INFINITY):
|
2254 | 7d88772a | Iustin Pop | maxfd = MAXFD |
2255 | 7d88772a | Iustin Pop | |
2256 | 7d88772a | Iustin Pop | # Iterate through and close all file descriptors (except the standard ones)
|
2257 | 7d88772a | Iustin Pop | for fd in range(3, maxfd): |
2258 | 7d88772a | Iustin Pop | if noclose_fds and fd in noclose_fds: |
2259 | 7d88772a | Iustin Pop | continue
|
2260 | 7d88772a | Iustin Pop | _CloseFDNoErr(fd) |
2261 | 7d88772a | Iustin Pop | |
2262 | 7d88772a | Iustin Pop | |
2263 | 4b6fa0bf | Luca Bigliardi | def Mlockall(): |
2264 | 4b6fa0bf | Luca Bigliardi | """Lock current process' virtual address space into RAM.
|
2265 | 4b6fa0bf | Luca Bigliardi |
|
2266 | 4b6fa0bf | Luca Bigliardi | This is equivalent to the C call mlockall(MCL_CURRENT|MCL_FUTURE),
|
2267 | 4b6fa0bf | Luca Bigliardi | see mlock(2) for more details. This function requires ctypes module.
|
2268 | 4b6fa0bf | Luca Bigliardi |
|
2269 | 4b6fa0bf | Luca Bigliardi | """
|
2270 | 4b6fa0bf | Luca Bigliardi | if ctypes is None: |
2271 | 4b6fa0bf | Luca Bigliardi | logging.warning("Cannot set memory lock, ctypes module not found")
|
2272 | 4b6fa0bf | Luca Bigliardi | return
|
2273 | 4b6fa0bf | Luca Bigliardi | |
2274 | 4b6fa0bf | Luca Bigliardi | libc = ctypes.cdll.LoadLibrary("libc.so.6")
|
2275 | 4b6fa0bf | Luca Bigliardi | if libc is None: |
2276 | 4b6fa0bf | Luca Bigliardi | logging.error("Cannot set memory lock, ctypes cannot load libc")
|
2277 | 4b6fa0bf | Luca Bigliardi | return
|
2278 | 4b6fa0bf | Luca Bigliardi | |
2279 | 4b6fa0bf | Luca Bigliardi | # Some older version of the ctypes module don't have built-in functionality
|
2280 | 4b6fa0bf | Luca Bigliardi | # to access the errno global variable, where function error codes are stored.
|
2281 | 4b6fa0bf | Luca Bigliardi | # By declaring this variable as a pointer to an integer we can then access
|
2282 | 4b6fa0bf | Luca Bigliardi | # its value correctly, should the mlockall call fail, in order to see what
|
2283 | 4b6fa0bf | Luca Bigliardi | # the actual error code was.
|
2284 | 20601361 | Luca Bigliardi | # pylint: disable-msg=W0212
|
2285 | 4b6fa0bf | Luca Bigliardi | libc.__errno_location.restype = ctypes.POINTER(ctypes.c_int) |
2286 | 4b6fa0bf | Luca Bigliardi | |
2287 | 4b6fa0bf | Luca Bigliardi | if libc.mlockall(_MCL_CURRENT | _MCL_FUTURE):
|
2288 | 20601361 | Luca Bigliardi | # pylint: disable-msg=W0212
|
2289 | 6ed0bbce | Luca Bigliardi | logging.error("Cannot set memory lock: %s",
|
2290 | 4b6fa0bf | Luca Bigliardi | os.strerror(libc.__errno_location().contents.value)) |
2291 | 4b6fa0bf | Luca Bigliardi | return
|
2292 | 4b6fa0bf | Luca Bigliardi | |
2293 | 4b6fa0bf | Luca Bigliardi | logging.debug("Memory lock set")
|
2294 | 4b6fa0bf | Luca Bigliardi | |
2295 | 4b6fa0bf | Luca Bigliardi | |
2296 | 743b53d4 | Renรฉ Nussbaumer | def Daemonize(logfile, run_uid, run_gid): |
2297 | 7d88772a | Iustin Pop | """Daemonize the current process.
|
2298 | 7d88772a | Iustin Pop |
|
2299 | 7d88772a | Iustin Pop | This detaches the current process from the controlling terminal and
|
2300 | 7d88772a | Iustin Pop | runs it in the background as a daemon.
|
2301 | 7d88772a | Iustin Pop |
|
2302 | 7d88772a | Iustin Pop | @type logfile: str
|
2303 | 7d88772a | Iustin Pop | @param logfile: the logfile to which we should redirect stdout/stderr
|
2304 | 743b53d4 | Renรฉ Nussbaumer | @type run_uid: int
|
2305 | 743b53d4 | Renรฉ Nussbaumer | @param run_uid: Run the child under this uid
|
2306 | 743b53d4 | Renรฉ Nussbaumer | @type run_gid: int
|
2307 | 743b53d4 | Renรฉ Nussbaumer | @param run_gid: Run the child under this gid
|
2308 | 7d88772a | Iustin Pop | @rtype: int
|
2309 | 5fcc718f | Iustin Pop | @return: the value zero
|
2310 | 7d88772a | Iustin Pop |
|
2311 | 7d88772a | Iustin Pop | """
|
2312 | 7260cfbe | Iustin Pop | # pylint: disable-msg=W0212
|
2313 | 7260cfbe | Iustin Pop | # yes, we really want os._exit
|
2314 | 7d88772a | Iustin Pop | UMASK = 077
|
2315 | 7d88772a | Iustin Pop | WORKDIR = "/"
|
2316 | 8f765069 | Iustin Pop | |
2317 | 8f765069 | Iustin Pop | # this might fail
|
2318 | 8f765069 | Iustin Pop | pid = os.fork() |
2319 | 8f765069 | Iustin Pop | if (pid == 0): # The first child. |
2320 | 8f765069 | Iustin Pop | os.setsid() |
2321 | 743b53d4 | Renรฉ Nussbaumer | # FIXME: When removing again and moving to start-stop-daemon privilege drop
|
2322 | 743b53d4 | Renรฉ Nussbaumer | # make sure to check for config permission and bail out when invoked
|
2323 | 743b53d4 | Renรฉ Nussbaumer | # with wrong user.
|
2324 | 743b53d4 | Renรฉ Nussbaumer | os.setgid(run_gid) |
2325 | 743b53d4 | Renรฉ Nussbaumer | os.setuid(run_uid) |
2326 | 8f765069 | Iustin Pop | # this might fail
|
2327 | 8f765069 | Iustin Pop | pid = os.fork() # Fork a second child.
|
2328 | 8f765069 | Iustin Pop | if (pid == 0): # The second child. |
2329 | 8f765069 | Iustin Pop | os.chdir(WORKDIR) |
2330 | 8f765069 | Iustin Pop | os.umask(UMASK) |
2331 | 8f765069 | Iustin Pop | else:
|
2332 | 8f765069 | Iustin Pop | # exit() or _exit()? See below.
|
2333 | 8f765069 | Iustin Pop | os._exit(0) # Exit parent (the first child) of the second child. |
2334 | 8f765069 | Iustin Pop | else:
|
2335 | 8f765069 | Iustin Pop | os._exit(0) # Exit parent of the first child. |
2336 | 8f765069 | Iustin Pop | |
2337 | 7d88772a | Iustin Pop | for fd in range(3): |
2338 | 7d88772a | Iustin Pop | _CloseFDNoErr(fd) |
2339 | 7d88772a | Iustin Pop | i = os.open("/dev/null", os.O_RDONLY) # stdin |
2340 | 7d88772a | Iustin Pop | assert i == 0, "Can't close/reopen stdin" |
2341 | 7d88772a | Iustin Pop | i = os.open(logfile, os.O_WRONLY|os.O_CREAT|os.O_APPEND, 0600) # stdout |
2342 | 7d88772a | Iustin Pop | assert i == 1, "Can't close/reopen stdout" |
2343 | 7d88772a | Iustin Pop | # Duplicate standard output to standard error.
|
2344 | 7d88772a | Iustin Pop | os.dup2(1, 2) |
2345 | 8f765069 | Iustin Pop | return 0 |
2346 | 57c177af | Iustin Pop | |
2347 | 57c177af | Iustin Pop | |
2348 | 53beffbb | Iustin Pop | def DaemonPidFileName(name): |
2349 | 58885d79 | Iustin Pop | """Compute a ganeti pid file absolute path
|
2350 | 58885d79 | Iustin Pop |
|
2351 | 58885d79 | Iustin Pop | @type name: str
|
2352 | 58885d79 | Iustin Pop | @param name: the daemon name
|
2353 | 58885d79 | Iustin Pop | @rtype: str
|
2354 | 58885d79 | Iustin Pop | @return: the full path to the pidfile corresponding to the given
|
2355 | 58885d79 | Iustin Pop | daemon name
|
2356 | b330ac0b | Guido Trotter |
|
2357 | b330ac0b | Guido Trotter | """
|
2358 | c4feafe8 | Iustin Pop | return PathJoin(constants.RUN_GANETI_DIR, "%s.pid" % name) |
2359 | b330ac0b | Guido Trotter | |
2360 | b330ac0b | Guido Trotter | |
2361 | 2826b361 | Guido Trotter | def EnsureDaemon(name): |
2362 | 2826b361 | Guido Trotter | """Check for and start daemon if not alive.
|
2363 | 2826b361 | Guido Trotter |
|
2364 | 2826b361 | Guido Trotter | """
|
2365 | 2826b361 | Guido Trotter | result = RunCmd([constants.DAEMON_UTIL, "check-and-start", name])
|
2366 | 2826b361 | Guido Trotter | if result.failed:
|
2367 | 2826b361 | Guido Trotter | logging.error("Can't start daemon '%s', failure %s, output: %s",
|
2368 | 2826b361 | Guido Trotter | name, result.fail_reason, result.output) |
2369 | 2826b361 | Guido Trotter | return False |
2370 | 2826b361 | Guido Trotter | |
2371 | 2826b361 | Guido Trotter | return True |
2372 | b330ac0b | Guido Trotter | |
2373 | b330ac0b | Guido Trotter | |
2374 | db147305 | Tom Limoncelli | def StopDaemon(name): |
2375 | db147305 | Tom Limoncelli | """Stop daemon
|
2376 | db147305 | Tom Limoncelli |
|
2377 | db147305 | Tom Limoncelli | """
|
2378 | db147305 | Tom Limoncelli | result = RunCmd([constants.DAEMON_UTIL, "stop", name])
|
2379 | db147305 | Tom Limoncelli | if result.failed:
|
2380 | db147305 | Tom Limoncelli | logging.error("Can't stop daemon '%s', failure %s, output: %s",
|
2381 | db147305 | Tom Limoncelli | name, result.fail_reason, result.output) |
2382 | db147305 | Tom Limoncelli | return False |
2383 | db147305 | Tom Limoncelli | |
2384 | db147305 | Tom Limoncelli | return True |
2385 | db147305 | Tom Limoncelli | |
2386 | db147305 | Tom Limoncelli | |
2387 | b330ac0b | Guido Trotter | def WritePidFile(name): |
2388 | b330ac0b | Guido Trotter | """Write the current process pidfile.
|
2389 | b330ac0b | Guido Trotter |
|
2390 | 58885d79 | Iustin Pop | The file will be written to L{constants.RUN_GANETI_DIR}I{/name.pid}
|
2391 | 58885d79 | Iustin Pop |
|
2392 | 58885d79 | Iustin Pop | @type name: str
|
2393 | 58885d79 | Iustin Pop | @param name: the daemon name to use
|
2394 | 58885d79 | Iustin Pop | @raise errors.GenericError: if the pid file already exists and
|
2395 | 58885d79 | Iustin Pop | points to a live process
|
2396 | b330ac0b | Guido Trotter |
|
2397 | b330ac0b | Guido Trotter | """
|
2398 | b330ac0b | Guido Trotter | pid = os.getpid() |
2399 | 53beffbb | Iustin Pop | pidfilename = DaemonPidFileName(name) |
2400 | d9f311d7 | Iustin Pop | if IsProcessAlive(ReadPidFile(pidfilename)):
|
2401 | 533bb4b1 | Michael Hanselmann | raise errors.GenericError("%s contains a live process" % pidfilename) |
2402 | b330ac0b | Guido Trotter | |
2403 | b330ac0b | Guido Trotter | WriteFile(pidfilename, data="%d\n" % pid)
|
2404 | b330ac0b | Guido Trotter | |
2405 | b330ac0b | Guido Trotter | |
2406 | b330ac0b | Guido Trotter | def RemovePidFile(name): |
2407 | b330ac0b | Guido Trotter | """Remove the current process pidfile.
|
2408 | b330ac0b | Guido Trotter |
|
2409 | b330ac0b | Guido Trotter | Any errors are ignored.
|
2410 | b330ac0b | Guido Trotter |
|
2411 | 58885d79 | Iustin Pop | @type name: str
|
2412 | 58885d79 | Iustin Pop | @param name: the daemon name used to derive the pidfile name
|
2413 | 58885d79 | Iustin Pop |
|
2414 | b330ac0b | Guido Trotter | """
|
2415 | 53beffbb | Iustin Pop | pidfilename = DaemonPidFileName(name) |
2416 | b330ac0b | Guido Trotter | # TODO: we could check here that the file contains our pid
|
2417 | b330ac0b | Guido Trotter | try:
|
2418 | b330ac0b | Guido Trotter | RemoveFile(pidfilename) |
2419 | 7260cfbe | Iustin Pop | except: # pylint: disable-msg=W0702 |
2420 | b330ac0b | Guido Trotter | pass
|
2421 | b330ac0b | Guido Trotter | |
2422 | b330ac0b | Guido Trotter | |
2423 | ff5251bc | Iustin Pop | def KillProcess(pid, signal_=signal.SIGTERM, timeout=30, |
2424 | ff5251bc | Iustin Pop | waitpid=False):
|
2425 | b2a1f511 | Iustin Pop | """Kill a process given by its pid.
|
2426 | b2a1f511 | Iustin Pop |
|
2427 | b2a1f511 | Iustin Pop | @type pid: int
|
2428 | b2a1f511 | Iustin Pop | @param pid: The PID to terminate.
|
2429 | 38206f3c | Iustin Pop | @type signal_: int
|
2430 | 38206f3c | Iustin Pop | @param signal_: The signal to send, by default SIGTERM
|
2431 | b2a1f511 | Iustin Pop | @type timeout: int
|
2432 | b2a1f511 | Iustin Pop | @param timeout: The timeout after which, if the process is still alive,
|
2433 | b2a1f511 | Iustin Pop | a SIGKILL will be sent. If not positive, no such checking
|
2434 | b2a1f511 | Iustin Pop | will be done
|
2435 | ff5251bc | Iustin Pop | @type waitpid: boolean
|
2436 | ff5251bc | Iustin Pop | @param waitpid: If true, we should waitpid on this process after
|
2437 | ff5251bc | Iustin Pop | sending signals, since it's our own child and otherwise it
|
2438 | ff5251bc | Iustin Pop | would remain as zombie
|
2439 | b2a1f511 | Iustin Pop |
|
2440 | b2a1f511 | Iustin Pop | """
|
2441 | ff5251bc | Iustin Pop | def _helper(pid, signal_, wait): |
2442 | ff5251bc | Iustin Pop | """Simple helper to encapsulate the kill/waitpid sequence"""
|
2443 | 560cbec1 | Michael Hanselmann | if IgnoreProcessNotFound(os.kill, pid, signal_) and wait: |
2444 | ff5251bc | Iustin Pop | try:
|
2445 | ff5251bc | Iustin Pop | os.waitpid(pid, os.WNOHANG) |
2446 | ff5251bc | Iustin Pop | except OSError: |
2447 | ff5251bc | Iustin Pop | pass
|
2448 | ff5251bc | Iustin Pop | |
2449 | b2a1f511 | Iustin Pop | if pid <= 0: |
2450 | b2a1f511 | Iustin Pop | # kill with pid=0 == suicide
|
2451 | b2a1f511 | Iustin Pop | raise errors.ProgrammerError("Invalid pid given '%s'" % pid) |
2452 | b2a1f511 | Iustin Pop | |
2453 | b2a1f511 | Iustin Pop | if not IsProcessAlive(pid): |
2454 | b2a1f511 | Iustin Pop | return
|
2455 | 31892b4c | Michael Hanselmann | |
2456 | ff5251bc | Iustin Pop | _helper(pid, signal_, waitpid) |
2457 | 31892b4c | Michael Hanselmann | |
2458 | b2a1f511 | Iustin Pop | if timeout <= 0: |
2459 | b2a1f511 | Iustin Pop | return
|
2460 | 7167159a | Michael Hanselmann | |
2461 | 31892b4c | Michael Hanselmann | def _CheckProcess(): |
2462 | 31892b4c | Michael Hanselmann | if not IsProcessAlive(pid): |
2463 | 31892b4c | Michael Hanselmann | return
|
2464 | 31892b4c | Michael Hanselmann | |
2465 | 7167159a | Michael Hanselmann | try:
|
2466 | 7167159a | Michael Hanselmann | (result_pid, _) = os.waitpid(pid, os.WNOHANG) |
2467 | 7167159a | Michael Hanselmann | except OSError: |
2468 | 31892b4c | Michael Hanselmann | raise RetryAgain()
|
2469 | 31892b4c | Michael Hanselmann | |
2470 | 31892b4c | Michael Hanselmann | if result_pid > 0: |
2471 | 31892b4c | Michael Hanselmann | return
|
2472 | 31892b4c | Michael Hanselmann | |
2473 | 31892b4c | Michael Hanselmann | raise RetryAgain()
|
2474 | 31892b4c | Michael Hanselmann | |
2475 | 31892b4c | Michael Hanselmann | try:
|
2476 | 31892b4c | Michael Hanselmann | # Wait up to $timeout seconds
|
2477 | 31892b4c | Michael Hanselmann | Retry(_CheckProcess, (0.01, 1.5, 0.1), timeout) |
2478 | 31892b4c | Michael Hanselmann | except RetryTimeout:
|
2479 | 31892b4c | Michael Hanselmann | pass
|
2480 | 7167159a | Michael Hanselmann | |
2481 | b2a1f511 | Iustin Pop | if IsProcessAlive(pid):
|
2482 | 7167159a | Michael Hanselmann | # Kill process if it's still alive
|
2483 | e1bd0072 | Iustin Pop | _helper(pid, signal.SIGKILL, waitpid) |
2484 | b2a1f511 | Iustin Pop | |
2485 | b2a1f511 | Iustin Pop | |
2486 | 57c177af | Iustin Pop | def FindFile(name, search_path, test=os.path.exists): |
2487 | 57c177af | Iustin Pop | """Look for a filesystem object in a given path.
|
2488 | 57c177af | Iustin Pop |
|
2489 | 57c177af | Iustin Pop | This is an abstract method to search for filesystem object (files,
|
2490 | 57c177af | Iustin Pop | dirs) under a given search path.
|
2491 | 57c177af | Iustin Pop |
|
2492 | 58885d79 | Iustin Pop | @type name: str
|
2493 | 58885d79 | Iustin Pop | @param name: the name to look for
|
2494 | 58885d79 | Iustin Pop | @type search_path: str
|
2495 | 58885d79 | Iustin Pop | @param search_path: location to start at
|
2496 | 58885d79 | Iustin Pop | @type test: callable
|
2497 | 58885d79 | Iustin Pop | @param test: a function taking one argument that should return True
|
2498 | 58885d79 | Iustin Pop | if the a given object is valid; the default value is
|
2499 | 58885d79 | Iustin Pop | os.path.exists, causing only existing files to be returned
|
2500 | 58885d79 | Iustin Pop | @rtype: str or None
|
2501 | 58885d79 | Iustin Pop | @return: full path to the object if found, None otherwise
|
2502 | 57c177af | Iustin Pop |
|
2503 | 57c177af | Iustin Pop | """
|
2504 | f95c81bf | Iustin Pop | # validate the filename mask
|
2505 | f95c81bf | Iustin Pop | if constants.EXT_PLUGIN_MASK.match(name) is None: |
2506 | f95c81bf | Iustin Pop | logging.critical("Invalid value passed for external script name: '%s'",
|
2507 | f95c81bf | Iustin Pop | name) |
2508 | f95c81bf | Iustin Pop | return None |
2509 | f95c81bf | Iustin Pop | |
2510 | 57c177af | Iustin Pop | for dir_name in search_path: |
2511 | e02b9114 | Iustin Pop | # FIXME: investigate switch to PathJoin
|
2512 | 57c177af | Iustin Pop | item_name = os.path.sep.join([dir_name, name]) |
2513 | f95c81bf | Iustin Pop | # check the user test and that we're indeed resolving to the given
|
2514 | f95c81bf | Iustin Pop | # basename
|
2515 | f95c81bf | Iustin Pop | if test(item_name) and os.path.basename(item_name) == name: |
2516 | 57c177af | Iustin Pop | return item_name
|
2517 | 57c177af | Iustin Pop | return None |
2518 | 8d1a2a64 | Michael Hanselmann | |
2519 | 8d1a2a64 | Michael Hanselmann | |
2520 | 8d1a2a64 | Michael Hanselmann | def CheckVolumeGroupSize(vglist, vgname, minsize): |
2521 | 8d1a2a64 | Michael Hanselmann | """Checks if the volume group list is valid.
|
2522 | 8d1a2a64 | Michael Hanselmann |
|
2523 | 58885d79 | Iustin Pop | The function will check if a given volume group is in the list of
|
2524 | 58885d79 | Iustin Pop | volume groups and has a minimum size.
|
2525 | 58885d79 | Iustin Pop |
|
2526 | 58885d79 | Iustin Pop | @type vglist: dict
|
2527 | 58885d79 | Iustin Pop | @param vglist: dictionary of volume group names and their size
|
2528 | 58885d79 | Iustin Pop | @type vgname: str
|
2529 | 58885d79 | Iustin Pop | @param vgname: the volume group we should check
|
2530 | 58885d79 | Iustin Pop | @type minsize: int
|
2531 | 58885d79 | Iustin Pop | @param minsize: the minimum size we accept
|
2532 | 58885d79 | Iustin Pop | @rtype: None or str
|
2533 | 58885d79 | Iustin Pop | @return: None for success, otherwise the error message
|
2534 | 8d1a2a64 | Michael Hanselmann |
|
2535 | 8d1a2a64 | Michael Hanselmann | """
|
2536 | 8d1a2a64 | Michael Hanselmann | vgsize = vglist.get(vgname, None)
|
2537 | 8d1a2a64 | Michael Hanselmann | if vgsize is None: |
2538 | 8d1a2a64 | Michael Hanselmann | return "volume group '%s' missing" % vgname |
2539 | 8d1a2a64 | Michael Hanselmann | elif vgsize < minsize:
|
2540 | 8d1a2a64 | Michael Hanselmann | return ("volume group '%s' too small (%s MiB required, %d MiB found)" % |
2541 | 8d1a2a64 | Michael Hanselmann | (vgname, minsize, vgsize)) |
2542 | 8d1a2a64 | Michael Hanselmann | return None |
2543 | 7996a135 | Iustin Pop | |
2544 | 7996a135 | Iustin Pop | |
2545 | 45bc5e4a | Michael Hanselmann | def SplitTime(value): |
2546 | 739be818 | Michael Hanselmann | """Splits time as floating point number into a tuple.
|
2547 | 739be818 | Michael Hanselmann |
|
2548 | 45bc5e4a | Michael Hanselmann | @param value: Time in seconds
|
2549 | 45bc5e4a | Michael Hanselmann | @type value: int or float
|
2550 | 45bc5e4a | Michael Hanselmann | @return: Tuple containing (seconds, microseconds)
|
2551 | 739be818 | Michael Hanselmann |
|
2552 | 739be818 | Michael Hanselmann | """
|
2553 | 45bc5e4a | Michael Hanselmann | (seconds, microseconds) = divmod(int(value * 1000000), 1000000) |
2554 | 45bc5e4a | Michael Hanselmann | |
2555 | 45bc5e4a | Michael Hanselmann | assert 0 <= seconds, \ |
2556 | 45bc5e4a | Michael Hanselmann | "Seconds must be larger than or equal to 0, but are %s" % seconds
|
2557 | 45bc5e4a | Michael Hanselmann | assert 0 <= microseconds <= 999999, \ |
2558 | 45bc5e4a | Michael Hanselmann | "Microseconds must be 0-999999, but are %s" % microseconds
|
2559 | 45bc5e4a | Michael Hanselmann | |
2560 | 45bc5e4a | Michael Hanselmann | return (int(seconds), int(microseconds)) |
2561 | 739be818 | Michael Hanselmann | |
2562 | 739be818 | Michael Hanselmann | |
2563 | 739be818 | Michael Hanselmann | def MergeTime(timetuple): |
2564 | 739be818 | Michael Hanselmann | """Merges a tuple into time as a floating point number.
|
2565 | 739be818 | Michael Hanselmann |
|
2566 | 45bc5e4a | Michael Hanselmann | @param timetuple: Time as tuple, (seconds, microseconds)
|
2567 | 739be818 | Michael Hanselmann | @type timetuple: tuple
|
2568 | 739be818 | Michael Hanselmann | @return: Time as a floating point number expressed in seconds
|
2569 | 739be818 | Michael Hanselmann |
|
2570 | 739be818 | Michael Hanselmann | """
|
2571 | 45bc5e4a | Michael Hanselmann | (seconds, microseconds) = timetuple |
2572 | 739be818 | Michael Hanselmann | |
2573 | 45bc5e4a | Michael Hanselmann | assert 0 <= seconds, \ |
2574 | 45bc5e4a | Michael Hanselmann | "Seconds must be larger than or equal to 0, but are %s" % seconds
|
2575 | 45bc5e4a | Michael Hanselmann | assert 0 <= microseconds <= 999999, \ |
2576 | 45bc5e4a | Michael Hanselmann | "Microseconds must be 0-999999, but are %s" % microseconds
|
2577 | 739be818 | Michael Hanselmann | |
2578 | 45bc5e4a | Michael Hanselmann | return float(seconds) + (float(microseconds) * 0.000001) |
2579 | 739be818 | Michael Hanselmann | |
2580 | 739be818 | Michael Hanselmann | |
2581 | cd50653c | Guido Trotter | def GetDaemonPort(daemon_name): |
2582 | cd50653c | Guido Trotter | """Get the daemon port for this cluster.
|
2583 | 4a8b186a | Michael Hanselmann |
|
2584 | 4a8b186a | Michael Hanselmann | Note that this routine does not read a ganeti-specific file, but
|
2585 | 58885d79 | Iustin Pop | instead uses C{socket.getservbyname} to allow pre-customization of
|
2586 | 4a8b186a | Michael Hanselmann | this parameter outside of Ganeti.
|
2587 | 4a8b186a | Michael Hanselmann |
|
2588 | cd50653c | Guido Trotter | @type daemon_name: string
|
2589 | cd50653c | Guido Trotter | @param daemon_name: daemon name (in constants.DAEMONS_PORTS)
|
2590 | 58885d79 | Iustin Pop | @rtype: int
|
2591 | 58885d79 | Iustin Pop |
|
2592 | 4a8b186a | Michael Hanselmann | """
|
2593 | cd50653c | Guido Trotter | if daemon_name not in constants.DAEMONS_PORTS: |
2594 | cd50653c | Guido Trotter | raise errors.ProgrammerError("Unknown daemon: %s" % daemon_name) |
2595 | cd50653c | Guido Trotter | |
2596 | cd50653c | Guido Trotter | (proto, default_port) = constants.DAEMONS_PORTS[daemon_name] |
2597 | 4a8b186a | Michael Hanselmann | try:
|
2598 | cd50653c | Guido Trotter | port = socket.getservbyname(daemon_name, proto) |
2599 | 4a8b186a | Michael Hanselmann | except socket.error:
|
2600 | cd50653c | Guido Trotter | port = default_port |
2601 | 4a8b186a | Michael Hanselmann | |
2602 | 4a8b186a | Michael Hanselmann | return port
|
2603 | 4a8b186a | Michael Hanselmann | |
2604 | 4a8b186a | Michael Hanselmann | |
2605 | de3b8e39 | Luca Bigliardi | class LogFileHandler(logging.FileHandler): |
2606 | de3b8e39 | Luca Bigliardi | """Log handler that doesn't fallback to stderr.
|
2607 | de3b8e39 | Luca Bigliardi |
|
2608 | de3b8e39 | Luca Bigliardi | When an error occurs while writing on the logfile, logging.FileHandler tries
|
2609 | de3b8e39 | Luca Bigliardi | to log on stderr. This doesn't work in ganeti since stderr is redirected to
|
2610 | de3b8e39 | Luca Bigliardi | the logfile. This class avoids failures reporting errors to /dev/console.
|
2611 | de3b8e39 | Luca Bigliardi |
|
2612 | de3b8e39 | Luca Bigliardi | """
|
2613 | de3b8e39 | Luca Bigliardi | def __init__(self, filename, mode="a", encoding=None): |
2614 | de3b8e39 | Luca Bigliardi | """Open the specified file and use it as the stream for logging.
|
2615 | de3b8e39 | Luca Bigliardi |
|
2616 | de3b8e39 | Luca Bigliardi | Also open /dev/console to report errors while logging.
|
2617 | de3b8e39 | Luca Bigliardi |
|
2618 | de3b8e39 | Luca Bigliardi | """
|
2619 | de3b8e39 | Luca Bigliardi | logging.FileHandler.__init__(self, filename, mode, encoding)
|
2620 | de3b8e39 | Luca Bigliardi | self.console = open(constants.DEV_CONSOLE, "a") |
2621 | de3b8e39 | Luca Bigliardi | |
2622 | 20601361 | Luca Bigliardi | def handleError(self, record): # pylint: disable-msg=C0103 |
2623 | de3b8e39 | Luca Bigliardi | """Handle errors which occur during an emit() call.
|
2624 | de3b8e39 | Luca Bigliardi |
|
2625 | de3b8e39 | Luca Bigliardi | Try to handle errors with FileHandler method, if it fails write to
|
2626 | de3b8e39 | Luca Bigliardi | /dev/console.
|
2627 | de3b8e39 | Luca Bigliardi |
|
2628 | de3b8e39 | Luca Bigliardi | """
|
2629 | de3b8e39 | Luca Bigliardi | try:
|
2630 | 05b35f15 | Luca Bigliardi | logging.FileHandler.handleError(self, record)
|
2631 | 20601361 | Luca Bigliardi | except Exception: # pylint: disable-msg=W0703 |
2632 | de3b8e39 | Luca Bigliardi | try:
|
2633 | de3b8e39 | Luca Bigliardi | self.console.write("Cannot log message:\n%s\n" % self.format(record)) |
2634 | 20601361 | Luca Bigliardi | except Exception: # pylint: disable-msg=W0703 |
2635 | de3b8e39 | Luca Bigliardi | # Log handler tried everything it could, now just give up
|
2636 | de3b8e39 | Luca Bigliardi | pass
|
2637 | de3b8e39 | Luca Bigliardi | |
2638 | de3b8e39 | Luca Bigliardi | |
2639 | ea34193f | Iustin Pop | def SetupLogging(logfile, debug=0, stderr_logging=False, program="", |
2640 | 49e60a28 | Luca Bigliardi | multithreaded=False, syslog=constants.SYSLOG_USAGE,
|
2641 | 49e60a28 | Luca Bigliardi | console_logging=False):
|
2642 | 82d9caef | Iustin Pop | """Configures the logging module.
|
2643 | 82d9caef | Iustin Pop |
|
2644 | 58885d79 | Iustin Pop | @type logfile: str
|
2645 | 58885d79 | Iustin Pop | @param logfile: the filename to which we should log
|
2646 | ea34193f | Iustin Pop | @type debug: integer
|
2647 | ea34193f | Iustin Pop | @param debug: if greater than zero, enable debug messages, otherwise
|
2648 | 58885d79 | Iustin Pop | only those at C{INFO} and above level
|
2649 | 58885d79 | Iustin Pop | @type stderr_logging: boolean
|
2650 | 58885d79 | Iustin Pop | @param stderr_logging: whether we should also log to the standard error
|
2651 | 58885d79 | Iustin Pop | @type program: str
|
2652 | 58885d79 | Iustin Pop | @param program: the name under which we should log messages
|
2653 | d21d09d6 | Iustin Pop | @type multithreaded: boolean
|
2654 | d21d09d6 | Iustin Pop | @param multithreaded: if True, will add the thread name to the log file
|
2655 | 551b6283 | Iustin Pop | @type syslog: string
|
2656 | 551b6283 | Iustin Pop | @param syslog: one of 'no', 'yes', 'only':
|
2657 | 551b6283 | Iustin Pop | - if no, syslog is not used
|
2658 | 551b6283 | Iustin Pop | - if yes, syslog is used (in addition to file-logging)
|
2659 | 551b6283 | Iustin Pop | - if only, only syslog is used
|
2660 | 49e60a28 | Luca Bigliardi | @type console_logging: boolean
|
2661 | 49e60a28 | Luca Bigliardi | @param console_logging: if True, will use a FileHandler which falls back to
|
2662 | 49e60a28 | Luca Bigliardi | the system console if logging fails
|
2663 | 58885d79 | Iustin Pop | @raise EnvironmentError: if we can't open the log file and
|
2664 | 551b6283 | Iustin Pop | syslog/stderr logging is disabled
|
2665 | 58885d79 | Iustin Pop |
|
2666 | 82d9caef | Iustin Pop | """
|
2667 | d21d09d6 | Iustin Pop | fmt = "%(asctime)s: " + program + " pid=%(process)d" |
2668 | 551b6283 | Iustin Pop | sft = program + "[%(process)d]:"
|
2669 | d21d09d6 | Iustin Pop | if multithreaded:
|
2670 | d21d09d6 | Iustin Pop | fmt += "/%(threadName)s"
|
2671 | 551b6283 | Iustin Pop | sft += " (%(threadName)s)"
|
2672 | 82d9caef | Iustin Pop | if debug:
|
2673 | d21d09d6 | Iustin Pop | fmt += " %(module)s:%(lineno)s"
|
2674 | 551b6283 | Iustin Pop | # no debug info for syslog loggers
|
2675 | d21d09d6 | Iustin Pop | fmt += " %(levelname)s %(message)s"
|
2676 | 551b6283 | Iustin Pop | # yes, we do want the textual level, as remote syslog will probably
|
2677 | 551b6283 | Iustin Pop | # lose the error level, and it's easier to grep for it
|
2678 | 551b6283 | Iustin Pop | sft += " %(levelname)s %(message)s"
|
2679 | 82d9caef | Iustin Pop | formatter = logging.Formatter(fmt) |
2680 | 551b6283 | Iustin Pop | sys_fmt = logging.Formatter(sft) |
2681 | 82d9caef | Iustin Pop | |
2682 | 82d9caef | Iustin Pop | root_logger = logging.getLogger("")
|
2683 | 82d9caef | Iustin Pop | root_logger.setLevel(logging.NOTSET) |
2684 | 82d9caef | Iustin Pop | |
2685 | 6346a9e5 | Michael Hanselmann | # Remove all previously setup handlers
|
2686 | 6346a9e5 | Michael Hanselmann | for handler in root_logger.handlers: |
2687 | 7d88772a | Iustin Pop | handler.close() |
2688 | 6346a9e5 | Michael Hanselmann | root_logger.removeHandler(handler) |
2689 | 6346a9e5 | Michael Hanselmann | |
2690 | 82d9caef | Iustin Pop | if stderr_logging:
|
2691 | 82d9caef | Iustin Pop | stderr_handler = logging.StreamHandler() |
2692 | 82d9caef | Iustin Pop | stderr_handler.setFormatter(formatter) |
2693 | 82d9caef | Iustin Pop | if debug:
|
2694 | 82d9caef | Iustin Pop | stderr_handler.setLevel(logging.NOTSET) |
2695 | 82d9caef | Iustin Pop | else:
|
2696 | 82d9caef | Iustin Pop | stderr_handler.setLevel(logging.CRITICAL) |
2697 | 82d9caef | Iustin Pop | root_logger.addHandler(stderr_handler) |
2698 | 82d9caef | Iustin Pop | |
2699 | 551b6283 | Iustin Pop | if syslog in (constants.SYSLOG_YES, constants.SYSLOG_ONLY): |
2700 | 551b6283 | Iustin Pop | facility = logging.handlers.SysLogHandler.LOG_DAEMON |
2701 | 551b6283 | Iustin Pop | syslog_handler = logging.handlers.SysLogHandler(constants.SYSLOG_SOCKET, |
2702 | 551b6283 | Iustin Pop | facility) |
2703 | 551b6283 | Iustin Pop | syslog_handler.setFormatter(sys_fmt) |
2704 | 551b6283 | Iustin Pop | # Never enable debug over syslog
|
2705 | 551b6283 | Iustin Pop | syslog_handler.setLevel(logging.INFO) |
2706 | 551b6283 | Iustin Pop | root_logger.addHandler(syslog_handler) |
2707 | 551b6283 | Iustin Pop | |
2708 | 551b6283 | Iustin Pop | if syslog != constants.SYSLOG_ONLY:
|
2709 | 551b6283 | Iustin Pop | # this can fail, if the logging directories are not setup or we have
|
2710 | 551b6283 | Iustin Pop | # a permisssion problem; in this case, it's best to log but ignore
|
2711 | 551b6283 | Iustin Pop | # the error if stderr_logging is True, and if false we re-raise the
|
2712 | 551b6283 | Iustin Pop | # exception since otherwise we could run but without any logs at all
|
2713 | 551b6283 | Iustin Pop | try:
|
2714 | 49e60a28 | Luca Bigliardi | if console_logging:
|
2715 | 49e60a28 | Luca Bigliardi | logfile_handler = LogFileHandler(logfile) |
2716 | 49e60a28 | Luca Bigliardi | else:
|
2717 | 49e60a28 | Luca Bigliardi | logfile_handler = logging.FileHandler(logfile) |
2718 | 551b6283 | Iustin Pop | logfile_handler.setFormatter(formatter) |
2719 | 551b6283 | Iustin Pop | if debug:
|
2720 | 551b6283 | Iustin Pop | logfile_handler.setLevel(logging.DEBUG) |
2721 | 551b6283 | Iustin Pop | else:
|
2722 | 551b6283 | Iustin Pop | logfile_handler.setLevel(logging.INFO) |
2723 | 551b6283 | Iustin Pop | root_logger.addHandler(logfile_handler) |
2724 | 551b6283 | Iustin Pop | except EnvironmentError: |
2725 | 551b6283 | Iustin Pop | if stderr_logging or syslog == constants.SYSLOG_YES: |
2726 | 551b6283 | Iustin Pop | logging.exception("Failed to enable logging to file '%s'", logfile)
|
2727 | 551b6283 | Iustin Pop | else:
|
2728 | 551b6283 | Iustin Pop | # we need to re-raise the exception
|
2729 | 551b6283 | Iustin Pop | raise
|
2730 | 82d9caef | Iustin Pop | |
2731 | 016d04b3 | Michael Hanselmann | |
2732 | da961187 | Guido Trotter | def IsNormAbsPath(path): |
2733 | 17c61836 | Guido Trotter | """Check whether a path is absolute and also normalized
|
2734 | da961187 | Guido Trotter |
|
2735 | da961187 | Guido Trotter | This avoids things like /dir/../../other/path to be valid.
|
2736 | da961187 | Guido Trotter |
|
2737 | da961187 | Guido Trotter | """
|
2738 | da961187 | Guido Trotter | return os.path.normpath(path) == path and os.path.isabs(path) |
2739 | 82d9caef | Iustin Pop | |
2740 | 016d04b3 | Michael Hanselmann | |
2741 | 4bb678e9 | Iustin Pop | def PathJoin(*args): |
2742 | 4bb678e9 | Iustin Pop | """Safe-join a list of path components.
|
2743 | 4bb678e9 | Iustin Pop |
|
2744 | 4bb678e9 | Iustin Pop | Requirements:
|
2745 | 4bb678e9 | Iustin Pop | - the first argument must be an absolute path
|
2746 | 4bb678e9 | Iustin Pop | - no component in the path must have backtracking (e.g. /../),
|
2747 | 4bb678e9 | Iustin Pop | since we check for normalization at the end
|
2748 | 4bb678e9 | Iustin Pop |
|
2749 | 4bb678e9 | Iustin Pop | @param args: the path components to be joined
|
2750 | 4bb678e9 | Iustin Pop | @raise ValueError: for invalid paths
|
2751 | 4bb678e9 | Iustin Pop |
|
2752 | 4bb678e9 | Iustin Pop | """
|
2753 | 4bb678e9 | Iustin Pop | # ensure we're having at least one path passed in
|
2754 | 4bb678e9 | Iustin Pop | assert args
|
2755 | 4bb678e9 | Iustin Pop | # ensure the first component is an absolute and normalized path name
|
2756 | 4bb678e9 | Iustin Pop | root = args[0]
|
2757 | 4bb678e9 | Iustin Pop | if not IsNormAbsPath(root): |
2758 | 4bb678e9 | Iustin Pop | raise ValueError("Invalid parameter to PathJoin: '%s'" % str(args[0])) |
2759 | 4bb678e9 | Iustin Pop | result = os.path.join(*args) |
2760 | 4bb678e9 | Iustin Pop | # ensure that the whole path is normalized
|
2761 | 4bb678e9 | Iustin Pop | if not IsNormAbsPath(result): |
2762 | 4bb678e9 | Iustin Pop | raise ValueError("Invalid parameters to PathJoin: '%s'" % str(args)) |
2763 | 4bb678e9 | Iustin Pop | # check that we're still under the original prefix
|
2764 | 4bb678e9 | Iustin Pop | prefix = os.path.commonprefix([root, result]) |
2765 | 4bb678e9 | Iustin Pop | if prefix != root:
|
2766 | 4bb678e9 | Iustin Pop | raise ValueError("Error: path joining resulted in different prefix" |
2767 | 4bb678e9 | Iustin Pop | " (%s != %s)" % (prefix, root))
|
2768 | 4bb678e9 | Iustin Pop | return result
|
2769 | 4bb678e9 | Iustin Pop | |
2770 | 4bb678e9 | Iustin Pop | |
2771 | f65f63ef | Iustin Pop | def TailFile(fname, lines=20): |
2772 | f65f63ef | Iustin Pop | """Return the last lines from a file.
|
2773 | f65f63ef | Iustin Pop |
|
2774 | f65f63ef | Iustin Pop | @note: this function will only read and parse the last 4KB of
|
2775 | f65f63ef | Iustin Pop | the file; if the lines are very long, it could be that less
|
2776 | f65f63ef | Iustin Pop | than the requested number of lines are returned
|
2777 | f65f63ef | Iustin Pop |
|
2778 | f65f63ef | Iustin Pop | @param fname: the file name
|
2779 | f65f63ef | Iustin Pop | @type lines: int
|
2780 | f65f63ef | Iustin Pop | @param lines: the (maximum) number of lines to return
|
2781 | f65f63ef | Iustin Pop |
|
2782 | f65f63ef | Iustin Pop | """
|
2783 | f65f63ef | Iustin Pop | fd = open(fname, "r") |
2784 | f65f63ef | Iustin Pop | try:
|
2785 | f65f63ef | Iustin Pop | fd.seek(0, 2) |
2786 | f65f63ef | Iustin Pop | pos = fd.tell() |
2787 | f65f63ef | Iustin Pop | pos = max(0, pos-4096) |
2788 | f65f63ef | Iustin Pop | fd.seek(pos, 0)
|
2789 | f65f63ef | Iustin Pop | raw_data = fd.read() |
2790 | f65f63ef | Iustin Pop | finally:
|
2791 | f65f63ef | Iustin Pop | fd.close() |
2792 | f65f63ef | Iustin Pop | |
2793 | f65f63ef | Iustin Pop | rows = raw_data.splitlines() |
2794 | f65f63ef | Iustin Pop | return rows[-lines:]
|
2795 | f65f63ef | Iustin Pop | |
2796 | f65f63ef | Iustin Pop | |
2797 | 24d70417 | Michael Hanselmann | def FormatTimestampWithTZ(secs): |
2798 | 24d70417 | Michael Hanselmann | """Formats a Unix timestamp with the local timezone.
|
2799 | 24d70417 | Michael Hanselmann |
|
2800 | 24d70417 | Michael Hanselmann | """
|
2801 | 24d70417 | Michael Hanselmann | return time.strftime("%F %T %Z", time.gmtime(secs)) |
2802 | 24d70417 | Michael Hanselmann | |
2803 | 24d70417 | Michael Hanselmann | |
2804 | 27e46076 | Michael Hanselmann | def _ParseAsn1Generalizedtime(value): |
2805 | 27e46076 | Michael Hanselmann | """Parses an ASN1 GENERALIZEDTIME timestamp as used by pyOpenSSL.
|
2806 | 27e46076 | Michael Hanselmann |
|
2807 | 27e46076 | Michael Hanselmann | @type value: string
|
2808 | 27e46076 | Michael Hanselmann | @param value: ASN1 GENERALIZEDTIME timestamp
|
2809 | 27e46076 | Michael Hanselmann |
|
2810 | 27e46076 | Michael Hanselmann | """
|
2811 | 27e46076 | Michael Hanselmann | m = re.match(r"^(\d+)([-+]\d\d)(\d\d)$", value)
|
2812 | 27e46076 | Michael Hanselmann | if m:
|
2813 | 27e46076 | Michael Hanselmann | # We have an offset
|
2814 | 27e46076 | Michael Hanselmann | asn1time = m.group(1)
|
2815 | 27e46076 | Michael Hanselmann | hours = int(m.group(2)) |
2816 | 27e46076 | Michael Hanselmann | minutes = int(m.group(3)) |
2817 | 27e46076 | Michael Hanselmann | utcoffset = (60 * hours) + minutes
|
2818 | 27e46076 | Michael Hanselmann | else:
|
2819 | 27e46076 | Michael Hanselmann | if not value.endswith("Z"): |
2820 | 27e46076 | Michael Hanselmann | raise ValueError("Missing timezone") |
2821 | 27e46076 | Michael Hanselmann | asn1time = value[:-1]
|
2822 | 27e46076 | Michael Hanselmann | utcoffset = 0
|
2823 | 27e46076 | Michael Hanselmann | |
2824 | 27e46076 | Michael Hanselmann | parsed = time.strptime(asn1time, "%Y%m%d%H%M%S")
|
2825 | 27e46076 | Michael Hanselmann | |
2826 | 27e46076 | Michael Hanselmann | tt = datetime.datetime(*(parsed[:7])) - datetime.timedelta(minutes=utcoffset)
|
2827 | 27e46076 | Michael Hanselmann | |
2828 | 27e46076 | Michael Hanselmann | return calendar.timegm(tt.utctimetuple())
|
2829 | 27e46076 | Michael Hanselmann | |
2830 | 27e46076 | Michael Hanselmann | |
2831 | 27e46076 | Michael Hanselmann | def GetX509CertValidity(cert): |
2832 | 27e46076 | Michael Hanselmann | """Returns the validity period of the certificate.
|
2833 | 27e46076 | Michael Hanselmann |
|
2834 | 27e46076 | Michael Hanselmann | @type cert: OpenSSL.crypto.X509
|
2835 | 27e46076 | Michael Hanselmann | @param cert: X509 certificate object
|
2836 | 27e46076 | Michael Hanselmann |
|
2837 | 27e46076 | Michael Hanselmann | """
|
2838 | 27e46076 | Michael Hanselmann | # The get_notBefore and get_notAfter functions are only supported in
|
2839 | 27e46076 | Michael Hanselmann | # pyOpenSSL 0.7 and above.
|
2840 | 27e46076 | Michael Hanselmann | try:
|
2841 | 27e46076 | Michael Hanselmann | get_notbefore_fn = cert.get_notBefore |
2842 | 27e46076 | Michael Hanselmann | except AttributeError: |
2843 | 27e46076 | Michael Hanselmann | not_before = None
|
2844 | 27e46076 | Michael Hanselmann | else:
|
2845 | 27e46076 | Michael Hanselmann | not_before_asn1 = get_notbefore_fn() |
2846 | 27e46076 | Michael Hanselmann | |
2847 | 27e46076 | Michael Hanselmann | if not_before_asn1 is None: |
2848 | 27e46076 | Michael Hanselmann | not_before = None
|
2849 | 27e46076 | Michael Hanselmann | else:
|
2850 | 27e46076 | Michael Hanselmann | not_before = _ParseAsn1Generalizedtime(not_before_asn1) |
2851 | 27e46076 | Michael Hanselmann | |
2852 | 27e46076 | Michael Hanselmann | try:
|
2853 | 27e46076 | Michael Hanselmann | get_notafter_fn = cert.get_notAfter |
2854 | 27e46076 | Michael Hanselmann | except AttributeError: |
2855 | 27e46076 | Michael Hanselmann | not_after = None
|
2856 | 27e46076 | Michael Hanselmann | else:
|
2857 | 27e46076 | Michael Hanselmann | not_after_asn1 = get_notafter_fn() |
2858 | 27e46076 | Michael Hanselmann | |
2859 | 27e46076 | Michael Hanselmann | if not_after_asn1 is None: |
2860 | 27e46076 | Michael Hanselmann | not_after = None
|
2861 | 27e46076 | Michael Hanselmann | else:
|
2862 | 27e46076 | Michael Hanselmann | not_after = _ParseAsn1Generalizedtime(not_after_asn1) |
2863 | 27e46076 | Michael Hanselmann | |
2864 | 27e46076 | Michael Hanselmann | return (not_before, not_after)
|
2865 | 27e46076 | Michael Hanselmann | |
2866 | 27e46076 | Michael Hanselmann | |
2867 | 24d70417 | Michael Hanselmann | def _VerifyCertificateInner(expired, not_before, not_after, now, |
2868 | 24d70417 | Michael Hanselmann | warn_days, error_days): |
2869 | 24d70417 | Michael Hanselmann | """Verifies certificate validity.
|
2870 | 24d70417 | Michael Hanselmann |
|
2871 | 24d70417 | Michael Hanselmann | @type expired: bool
|
2872 | 24d70417 | Michael Hanselmann | @param expired: Whether pyOpenSSL considers the certificate as expired
|
2873 | 24d70417 | Michael Hanselmann | @type not_before: number or None
|
2874 | 24d70417 | Michael Hanselmann | @param not_before: Unix timestamp before which certificate is not valid
|
2875 | 24d70417 | Michael Hanselmann | @type not_after: number or None
|
2876 | 24d70417 | Michael Hanselmann | @param not_after: Unix timestamp after which certificate is invalid
|
2877 | 24d70417 | Michael Hanselmann | @type now: number
|
2878 | 24d70417 | Michael Hanselmann | @param now: Current time as Unix timestamp
|
2879 | 24d70417 | Michael Hanselmann | @type warn_days: number or None
|
2880 | 24d70417 | Michael Hanselmann | @param warn_days: How many days before expiration a warning should be reported
|
2881 | 24d70417 | Michael Hanselmann | @type error_days: number or None
|
2882 | 24d70417 | Michael Hanselmann | @param error_days: How many days before expiration an error should be reported
|
2883 | 24d70417 | Michael Hanselmann |
|
2884 | 24d70417 | Michael Hanselmann | """
|
2885 | 24d70417 | Michael Hanselmann | if expired:
|
2886 | 24d70417 | Michael Hanselmann | msg = "Certificate is expired"
|
2887 | 24d70417 | Michael Hanselmann | |
2888 | 24d70417 | Michael Hanselmann | if not_before is not None and not_after is not None: |
2889 | 24d70417 | Michael Hanselmann | msg += (" (valid from %s to %s)" %
|
2890 | 24d70417 | Michael Hanselmann | (FormatTimestampWithTZ(not_before), |
2891 | 24d70417 | Michael Hanselmann | FormatTimestampWithTZ(not_after))) |
2892 | 24d70417 | Michael Hanselmann | elif not_before is not None: |
2893 | 24d70417 | Michael Hanselmann | msg += " (valid from %s)" % FormatTimestampWithTZ(not_before)
|
2894 | 24d70417 | Michael Hanselmann | elif not_after is not None: |
2895 | 24d70417 | Michael Hanselmann | msg += " (valid until %s)" % FormatTimestampWithTZ(not_after)
|
2896 | 24d70417 | Michael Hanselmann | |
2897 | 24d70417 | Michael Hanselmann | return (CERT_ERROR, msg)
|
2898 | 24d70417 | Michael Hanselmann | |
2899 | 24d70417 | Michael Hanselmann | elif not_before is not None and not_before > now: |
2900 | 24d70417 | Michael Hanselmann | return (CERT_WARNING,
|
2901 | 24d70417 | Michael Hanselmann | "Certificate not yet valid (valid from %s)" %
|
2902 | 24d70417 | Michael Hanselmann | FormatTimestampWithTZ(not_before)) |
2903 | 24d70417 | Michael Hanselmann | |
2904 | 24d70417 | Michael Hanselmann | elif not_after is not None: |
2905 | 24d70417 | Michael Hanselmann | remaining_days = int((not_after - now) / (24 * 3600)) |
2906 | 24d70417 | Michael Hanselmann | |
2907 | 24d70417 | Michael Hanselmann | msg = "Certificate expires in about %d days" % remaining_days
|
2908 | 24d70417 | Michael Hanselmann | |
2909 | 24d70417 | Michael Hanselmann | if error_days is not None and remaining_days <= error_days: |
2910 | 24d70417 | Michael Hanselmann | return (CERT_ERROR, msg)
|
2911 | 24d70417 | Michael Hanselmann | |
2912 | 24d70417 | Michael Hanselmann | if warn_days is not None and remaining_days <= warn_days: |
2913 | 24d70417 | Michael Hanselmann | return (CERT_WARNING, msg)
|
2914 | 24d70417 | Michael Hanselmann | |
2915 | 24d70417 | Michael Hanselmann | return (None, None) |
2916 | 24d70417 | Michael Hanselmann | |
2917 | 24d70417 | Michael Hanselmann | |
2918 | 24d70417 | Michael Hanselmann | def VerifyX509Certificate(cert, warn_days, error_days): |
2919 | 24d70417 | Michael Hanselmann | """Verifies a certificate for LUVerifyCluster.
|
2920 | 24d70417 | Michael Hanselmann |
|
2921 | 24d70417 | Michael Hanselmann | @type cert: OpenSSL.crypto.X509
|
2922 | 24d70417 | Michael Hanselmann | @param cert: X509 certificate object
|
2923 | 24d70417 | Michael Hanselmann | @type warn_days: number or None
|
2924 | 24d70417 | Michael Hanselmann | @param warn_days: How many days before expiration a warning should be reported
|
2925 | 24d70417 | Michael Hanselmann | @type error_days: number or None
|
2926 | 24d70417 | Michael Hanselmann | @param error_days: How many days before expiration an error should be reported
|
2927 | 24d70417 | Michael Hanselmann |
|
2928 | 24d70417 | Michael Hanselmann | """
|
2929 | 24d70417 | Michael Hanselmann | # Depending on the pyOpenSSL version, this can just return (None, None)
|
2930 | 24d70417 | Michael Hanselmann | (not_before, not_after) = GetX509CertValidity(cert) |
2931 | 24d70417 | Michael Hanselmann | |
2932 | 24d70417 | Michael Hanselmann | return _VerifyCertificateInner(cert.has_expired(), not_before, not_after,
|
2933 | 24d70417 | Michael Hanselmann | time.time(), warn_days, error_days) |
2934 | 24d70417 | Michael Hanselmann | |
2935 | 24d70417 | Michael Hanselmann | |
2936 | 68857643 | Michael Hanselmann | def SignX509Certificate(cert, key, salt): |
2937 | 68857643 | Michael Hanselmann | """Sign a X509 certificate.
|
2938 | 68857643 | Michael Hanselmann |
|
2939 | 68857643 | Michael Hanselmann | An RFC822-like signature header is added in front of the certificate.
|
2940 | 68857643 | Michael Hanselmann |
|
2941 | 68857643 | Michael Hanselmann | @type cert: OpenSSL.crypto.X509
|
2942 | 68857643 | Michael Hanselmann | @param cert: X509 certificate object
|
2943 | 68857643 | Michael Hanselmann | @type key: string
|
2944 | 68857643 | Michael Hanselmann | @param key: Key for HMAC
|
2945 | 68857643 | Michael Hanselmann | @type salt: string
|
2946 | 68857643 | Michael Hanselmann | @param salt: Salt for HMAC
|
2947 | 68857643 | Michael Hanselmann | @rtype: string
|
2948 | 68857643 | Michael Hanselmann | @return: Serialized and signed certificate in PEM format
|
2949 | 68857643 | Michael Hanselmann |
|
2950 | 68857643 | Michael Hanselmann | """
|
2951 | 68857643 | Michael Hanselmann | if not VALID_X509_SIGNATURE_SALT.match(salt): |
2952 | 68857643 | Michael Hanselmann | raise errors.GenericError("Invalid salt: %r" % salt) |
2953 | 68857643 | Michael Hanselmann | |
2954 | 68857643 | Michael Hanselmann | # Dumping as PEM here ensures the certificate is in a sane format
|
2955 | 68857643 | Michael Hanselmann | cert_pem = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) |
2956 | 68857643 | Michael Hanselmann | |
2957 | 68857643 | Michael Hanselmann | return ("%s: %s/%s\n\n%s" % |
2958 | 68857643 | Michael Hanselmann | (constants.X509_CERT_SIGNATURE_HEADER, salt, |
2959 | 3718bf6d | Michael Hanselmann | Sha1Hmac(key, cert_pem, salt=salt), |
2960 | 68857643 | Michael Hanselmann | cert_pem)) |
2961 | 68857643 | Michael Hanselmann | |
2962 | 68857643 | Michael Hanselmann | |
2963 | 68857643 | Michael Hanselmann | def _ExtractX509CertificateSignature(cert_pem): |
2964 | 68857643 | Michael Hanselmann | """Helper function to extract signature from X509 certificate.
|
2965 | 68857643 | Michael Hanselmann |
|
2966 | 68857643 | Michael Hanselmann | """
|
2967 | 68857643 | Michael Hanselmann | # Extract signature from original PEM data
|
2968 | 68857643 | Michael Hanselmann | for line in cert_pem.splitlines(): |
2969 | 68857643 | Michael Hanselmann | if line.startswith("---"): |
2970 | 68857643 | Michael Hanselmann | break
|
2971 | 68857643 | Michael Hanselmann | |
2972 | 68857643 | Michael Hanselmann | m = X509_SIGNATURE.match(line.strip()) |
2973 | 68857643 | Michael Hanselmann | if m:
|
2974 | 68857643 | Michael Hanselmann | return (m.group("salt"), m.group("sign")) |
2975 | 68857643 | Michael Hanselmann | |
2976 | 68857643 | Michael Hanselmann | raise errors.GenericError("X509 certificate signature is missing") |
2977 | 68857643 | Michael Hanselmann | |
2978 | 68857643 | Michael Hanselmann | |
2979 | 68857643 | Michael Hanselmann | def LoadSignedX509Certificate(cert_pem, key): |
2980 | 68857643 | Michael Hanselmann | """Verifies a signed X509 certificate.
|
2981 | 68857643 | Michael Hanselmann |
|
2982 | 68857643 | Michael Hanselmann | @type cert_pem: string
|
2983 | 68857643 | Michael Hanselmann | @param cert_pem: Certificate in PEM format and with signature header
|
2984 | 68857643 | Michael Hanselmann | @type key: string
|
2985 | 68857643 | Michael Hanselmann | @param key: Key for HMAC
|
2986 | 68857643 | Michael Hanselmann | @rtype: tuple; (OpenSSL.crypto.X509, string)
|
2987 | 68857643 | Michael Hanselmann | @return: X509 certificate object and salt
|
2988 | 68857643 | Michael Hanselmann |
|
2989 | 68857643 | Michael Hanselmann | """
|
2990 | 68857643 | Michael Hanselmann | (salt, signature) = _ExtractX509CertificateSignature(cert_pem) |
2991 | 68857643 | Michael Hanselmann | |
2992 | 68857643 | Michael Hanselmann | # Load certificate
|
2993 | 68857643 | Michael Hanselmann | cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_pem) |
2994 | 68857643 | Michael Hanselmann | |
2995 | 68857643 | Michael Hanselmann | # Dump again to ensure it's in a sane format
|
2996 | 68857643 | Michael Hanselmann | sane_pem = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) |
2997 | 68857643 | Michael Hanselmann | |
2998 | 3718bf6d | Michael Hanselmann | if not VerifySha1Hmac(key, sane_pem, signature, salt=salt): |
2999 | 68857643 | Michael Hanselmann | raise errors.GenericError("X509 certificate signature is invalid") |
3000 | 68857643 | Michael Hanselmann | |
3001 | 68857643 | Michael Hanselmann | return (cert, salt)
|
3002 | 68857643 | Michael Hanselmann | |
3003 | 68857643 | Michael Hanselmann | |
3004 | 3718bf6d | Michael Hanselmann | def Sha1Hmac(key, text, salt=None): |
3005 | 615aaaba | Michael Hanselmann | """Calculates the HMAC-SHA1 digest of a text.
|
3006 | 615aaaba | Michael Hanselmann |
|
3007 | 615aaaba | Michael Hanselmann | HMAC is defined in RFC2104.
|
3008 | 615aaaba | Michael Hanselmann |
|
3009 | 615aaaba | Michael Hanselmann | @type key: string
|
3010 | 615aaaba | Michael Hanselmann | @param key: Secret key
|
3011 | 615aaaba | Michael Hanselmann | @type text: string
|
3012 | 615aaaba | Michael Hanselmann |
|
3013 | 615aaaba | Michael Hanselmann | """
|
3014 | 3718bf6d | Michael Hanselmann | if salt:
|
3015 | 3718bf6d | Michael Hanselmann | salted_text = salt + text |
3016 | 3718bf6d | Michael Hanselmann | else:
|
3017 | 3718bf6d | Michael Hanselmann | salted_text = text |
3018 | 3718bf6d | Michael Hanselmann | |
3019 | 716a32cb | Guido Trotter | return hmac.new(key, salted_text, compat.sha1).hexdigest()
|
3020 | 615aaaba | Michael Hanselmann | |
3021 | 615aaaba | Michael Hanselmann | |
3022 | 3718bf6d | Michael Hanselmann | def VerifySha1Hmac(key, text, digest, salt=None): |
3023 | 615aaaba | Michael Hanselmann | """Verifies the HMAC-SHA1 digest of a text.
|
3024 | 615aaaba | Michael Hanselmann |
|
3025 | 615aaaba | Michael Hanselmann | HMAC is defined in RFC2104.
|
3026 | 615aaaba | Michael Hanselmann |
|
3027 | 615aaaba | Michael Hanselmann | @type key: string
|
3028 | 615aaaba | Michael Hanselmann | @param key: Secret key
|
3029 | 615aaaba | Michael Hanselmann | @type text: string
|
3030 | 615aaaba | Michael Hanselmann | @type digest: string
|
3031 | 615aaaba | Michael Hanselmann | @param digest: Expected digest
|
3032 | 615aaaba | Michael Hanselmann | @rtype: bool
|
3033 | 615aaaba | Michael Hanselmann | @return: Whether HMAC-SHA1 digest matches
|
3034 | 615aaaba | Michael Hanselmann |
|
3035 | 615aaaba | Michael Hanselmann | """
|
3036 | 3718bf6d | Michael Hanselmann | return digest.lower() == Sha1Hmac(key, text, salt=salt).lower()
|
3037 | 615aaaba | Michael Hanselmann | |
3038 | 615aaaba | Michael Hanselmann | |
3039 | 26f15862 | Iustin Pop | def SafeEncode(text): |
3040 | 26f15862 | Iustin Pop | """Return a 'safe' version of a source string.
|
3041 | 26f15862 | Iustin Pop |
|
3042 | 26f15862 | Iustin Pop | This function mangles the input string and returns a version that
|
3043 | d392fa34 | Iustin Pop | should be safe to display/encode as ASCII. To this end, we first
|
3044 | 26f15862 | Iustin Pop | convert it to ASCII using the 'backslashreplace' encoding which
|
3045 | d392fa34 | Iustin Pop | should get rid of any non-ASCII chars, and then we process it
|
3046 | d392fa34 | Iustin Pop | through a loop copied from the string repr sources in the python; we
|
3047 | d392fa34 | Iustin Pop | don't use string_escape anymore since that escape single quotes and
|
3048 | d392fa34 | Iustin Pop | backslashes too, and that is too much; and that escaping is not
|
3049 | d392fa34 | Iustin Pop | stable, i.e. string_escape(string_escape(x)) != string_escape(x).
|
3050 | 26f15862 | Iustin Pop |
|
3051 | 26f15862 | Iustin Pop | @type text: str or unicode
|
3052 | 26f15862 | Iustin Pop | @param text: input data
|
3053 | 26f15862 | Iustin Pop | @rtype: str
|
3054 | 26f15862 | Iustin Pop | @return: a safe version of text
|
3055 | 26f15862 | Iustin Pop |
|
3056 | 26f15862 | Iustin Pop | """
|
3057 | d392fa34 | Iustin Pop | if isinstance(text, unicode): |
3058 | 5bbd3f7f | Michael Hanselmann | # only if unicode; if str already, we handle it below
|
3059 | d392fa34 | Iustin Pop | text = text.encode('ascii', 'backslashreplace') |
3060 | d392fa34 | Iustin Pop | resu = ""
|
3061 | d392fa34 | Iustin Pop | for char in text: |
3062 | d392fa34 | Iustin Pop | c = ord(char)
|
3063 | d392fa34 | Iustin Pop | if char == '\t': |
3064 | d392fa34 | Iustin Pop | resu += r'\t'
|
3065 | d392fa34 | Iustin Pop | elif char == '\n': |
3066 | d392fa34 | Iustin Pop | resu += r'\n'
|
3067 | d392fa34 | Iustin Pop | elif char == '\r': |
3068 | d392fa34 | Iustin Pop | resu += r'\'r'
|
3069 | d392fa34 | Iustin Pop | elif c < 32 or c >= 127: # non-printable |
3070 | d392fa34 | Iustin Pop | resu += "\\x%02x" % (c & 0xff) |
3071 | d392fa34 | Iustin Pop | else:
|
3072 | d392fa34 | Iustin Pop | resu += char |
3073 | d392fa34 | Iustin Pop | return resu
|
3074 | 26f15862 | Iustin Pop | |
3075 | 26f15862 | Iustin Pop | |
3076 | 5b69bc7c | Iustin Pop | def UnescapeAndSplit(text, sep=","): |
3077 | 5b69bc7c | Iustin Pop | """Split and unescape a string based on a given separator.
|
3078 | 5b69bc7c | Iustin Pop |
|
3079 | 5b69bc7c | Iustin Pop | This function splits a string based on a separator where the
|
3080 | 5b69bc7c | Iustin Pop | separator itself can be escape in order to be an element of the
|
3081 | 5b69bc7c | Iustin Pop | elements. The escaping rules are (assuming coma being the
|
3082 | 5b69bc7c | Iustin Pop | separator):
|
3083 | 5b69bc7c | Iustin Pop | - a plain , separates the elements
|
3084 | 5b69bc7c | Iustin Pop | - a sequence \\\\, (double backslash plus comma) is handled as a
|
3085 | 5b69bc7c | Iustin Pop | backslash plus a separator comma
|
3086 | 5b69bc7c | Iustin Pop | - a sequence \, (backslash plus comma) is handled as a
|
3087 | 5b69bc7c | Iustin Pop | non-separator comma
|
3088 | 5b69bc7c | Iustin Pop |
|
3089 | 5b69bc7c | Iustin Pop | @type text: string
|
3090 | 5b69bc7c | Iustin Pop | @param text: the string to split
|
3091 | 5b69bc7c | Iustin Pop | @type sep: string
|
3092 | 5b69bc7c | Iustin Pop | @param text: the separator
|
3093 | 5b69bc7c | Iustin Pop | @rtype: string
|
3094 | 5b69bc7c | Iustin Pop | @return: a list of strings
|
3095 | 5b69bc7c | Iustin Pop |
|
3096 | 5b69bc7c | Iustin Pop | """
|
3097 | 5b69bc7c | Iustin Pop | # we split the list by sep (with no escaping at this stage)
|
3098 | 5b69bc7c | Iustin Pop | slist = text.split(sep) |
3099 | 5b69bc7c | Iustin Pop | # next, we revisit the elements and if any of them ended with an odd
|
3100 | 5b69bc7c | Iustin Pop | # number of backslashes, then we join it with the next
|
3101 | 5b69bc7c | Iustin Pop | rlist = [] |
3102 | 5b69bc7c | Iustin Pop | while slist:
|
3103 | 5b69bc7c | Iustin Pop | e1 = slist.pop(0)
|
3104 | 5b69bc7c | Iustin Pop | if e1.endswith("\\"): |
3105 | 5b69bc7c | Iustin Pop | num_b = len(e1) - len(e1.rstrip("\\")) |
3106 | 5b69bc7c | Iustin Pop | if num_b % 2 == 1: |
3107 | 5b69bc7c | Iustin Pop | e2 = slist.pop(0)
|
3108 | 5b69bc7c | Iustin Pop | # here the backslashes remain (all), and will be reduced in
|
3109 | 5b69bc7c | Iustin Pop | # the next step
|
3110 | 5b69bc7c | Iustin Pop | rlist.append(e1 + sep + e2) |
3111 | 5b69bc7c | Iustin Pop | continue
|
3112 | 5b69bc7c | Iustin Pop | rlist.append(e1) |
3113 | 5b69bc7c | Iustin Pop | # finally, replace backslash-something with something
|
3114 | 5b69bc7c | Iustin Pop | rlist = [re.sub(r"\\(.)", r"\1", v) for v in rlist] |
3115 | 5b69bc7c | Iustin Pop | return rlist
|
3116 | 5b69bc7c | Iustin Pop | |
3117 | 5b69bc7c | Iustin Pop | |
3118 | ab3e6da8 | Iustin Pop | def CommaJoin(names): |
3119 | ab3e6da8 | Iustin Pop | """Nicely join a set of identifiers.
|
3120 | ab3e6da8 | Iustin Pop |
|
3121 | ab3e6da8 | Iustin Pop | @param names: set, list or tuple
|
3122 | ab3e6da8 | Iustin Pop | @return: a string with the formatted results
|
3123 | ab3e6da8 | Iustin Pop |
|
3124 | ab3e6da8 | Iustin Pop | """
|
3125 | 1f864b60 | Iustin Pop | return ", ".join([str(val) for val in names]) |
3126 | ab3e6da8 | Iustin Pop | |
3127 | ab3e6da8 | Iustin Pop | |
3128 | 3f6a47a8 | Michael Hanselmann | def BytesToMebibyte(value): |
3129 | 3f6a47a8 | Michael Hanselmann | """Converts bytes to mebibytes.
|
3130 | 3f6a47a8 | Michael Hanselmann |
|
3131 | 3f6a47a8 | Michael Hanselmann | @type value: int
|
3132 | 3f6a47a8 | Michael Hanselmann | @param value: Value in bytes
|
3133 | 3f6a47a8 | Michael Hanselmann | @rtype: int
|
3134 | 3f6a47a8 | Michael Hanselmann | @return: Value in mebibytes
|
3135 | 3f6a47a8 | Michael Hanselmann |
|
3136 | 3f6a47a8 | Michael Hanselmann | """
|
3137 | 3f6a47a8 | Michael Hanselmann | return int(round(value / (1024.0 * 1024.0), 0)) |
3138 | 3f6a47a8 | Michael Hanselmann | |
3139 | 3f6a47a8 | Michael Hanselmann | |
3140 | 3f6a47a8 | Michael Hanselmann | def CalculateDirectorySize(path): |
3141 | 3f6a47a8 | Michael Hanselmann | """Calculates the size of a directory recursively.
|
3142 | 3f6a47a8 | Michael Hanselmann |
|
3143 | 3f6a47a8 | Michael Hanselmann | @type path: string
|
3144 | 3f6a47a8 | Michael Hanselmann | @param path: Path to directory
|
3145 | 3f6a47a8 | Michael Hanselmann | @rtype: int
|
3146 | 3f6a47a8 | Michael Hanselmann | @return: Size in mebibytes
|
3147 | 3f6a47a8 | Michael Hanselmann |
|
3148 | 3f6a47a8 | Michael Hanselmann | """
|
3149 | 3f6a47a8 | Michael Hanselmann | size = 0
|
3150 | 3f6a47a8 | Michael Hanselmann | |
3151 | 3f6a47a8 | Michael Hanselmann | for (curpath, _, files) in os.walk(path): |
3152 | 2a887df9 | Michael Hanselmann | for filename in files: |
3153 | c4feafe8 | Iustin Pop | st = os.lstat(PathJoin(curpath, filename)) |
3154 | 3f6a47a8 | Michael Hanselmann | size += st.st_size |
3155 | 3f6a47a8 | Michael Hanselmann | |
3156 | 3f6a47a8 | Michael Hanselmann | return BytesToMebibyte(size)
|
3157 | 3f6a47a8 | Michael Hanselmann | |
3158 | 3f6a47a8 | Michael Hanselmann | |
3159 | 620a85fd | Iustin Pop | def GetFilesystemStats(path): |
3160 | 620a85fd | Iustin Pop | """Returns the total and free space on a filesystem.
|
3161 | 3f6a47a8 | Michael Hanselmann |
|
3162 | 3f6a47a8 | Michael Hanselmann | @type path: string
|
3163 | 3f6a47a8 | Michael Hanselmann | @param path: Path on filesystem to be examined
|
3164 | 3f6a47a8 | Michael Hanselmann | @rtype: int
|
3165 | 620a85fd | Iustin Pop | @return: tuple of (Total space, Free space) in mebibytes
|
3166 | 3f6a47a8 | Michael Hanselmann |
|
3167 | 3f6a47a8 | Michael Hanselmann | """
|
3168 | 3f6a47a8 | Michael Hanselmann | st = os.statvfs(path) |
3169 | 3f6a47a8 | Michael Hanselmann | |
3170 | 620a85fd | Iustin Pop | fsize = BytesToMebibyte(st.f_bavail * st.f_frsize) |
3171 | 620a85fd | Iustin Pop | tsize = BytesToMebibyte(st.f_blocks * st.f_frsize) |
3172 | 620a85fd | Iustin Pop | return (tsize, fsize)
|
3173 | 3f6a47a8 | Michael Hanselmann | |
3174 | 3f6a47a8 | Michael Hanselmann | |
3175 | bdefe5dd | Michael Hanselmann | def RunInSeparateProcess(fn, *args): |
3176 | eb58f7bd | Michael Hanselmann | """Runs a function in a separate process.
|
3177 | eb58f7bd | Michael Hanselmann |
|
3178 | eb58f7bd | Michael Hanselmann | Note: Only boolean return values are supported.
|
3179 | eb58f7bd | Michael Hanselmann |
|
3180 | eb58f7bd | Michael Hanselmann | @type fn: callable
|
3181 | eb58f7bd | Michael Hanselmann | @param fn: Function to be called
|
3182 | bdefe5dd | Michael Hanselmann | @rtype: bool
|
3183 | bdefe5dd | Michael Hanselmann | @return: Function's result
|
3184 | eb58f7bd | Michael Hanselmann |
|
3185 | eb58f7bd | Michael Hanselmann | """
|
3186 | eb58f7bd | Michael Hanselmann | pid = os.fork() |
3187 | eb58f7bd | Michael Hanselmann | if pid == 0: |
3188 | eb58f7bd | Michael Hanselmann | # Child process
|
3189 | eb58f7bd | Michael Hanselmann | try:
|
3190 | 82869978 | Michael Hanselmann | # In case the function uses temporary files
|
3191 | 82869978 | Michael Hanselmann | ResetTempfileModule() |
3192 | 82869978 | Michael Hanselmann | |
3193 | eb58f7bd | Michael Hanselmann | # Call function
|
3194 | bdefe5dd | Michael Hanselmann | result = int(bool(fn(*args))) |
3195 | eb58f7bd | Michael Hanselmann | assert result in (0, 1) |
3196 | eb58f7bd | Michael Hanselmann | except: # pylint: disable-msg=W0702 |
3197 | eb58f7bd | Michael Hanselmann | logging.exception("Error while calling function in separate process")
|
3198 | eb58f7bd | Michael Hanselmann | # 0 and 1 are reserved for the return value
|
3199 | eb58f7bd | Michael Hanselmann | result = 33
|
3200 | eb58f7bd | Michael Hanselmann | |
3201 | eb58f7bd | Michael Hanselmann | os._exit(result) # pylint: disable-msg=W0212
|
3202 | eb58f7bd | Michael Hanselmann | |
3203 | eb58f7bd | Michael Hanselmann | # Parent process
|
3204 | eb58f7bd | Michael Hanselmann | |
3205 | eb58f7bd | Michael Hanselmann | # Avoid zombies and check exit code
|
3206 | eb58f7bd | Michael Hanselmann | (_, status) = os.waitpid(pid, 0)
|
3207 | eb58f7bd | Michael Hanselmann | |
3208 | eb58f7bd | Michael Hanselmann | if os.WIFSIGNALED(status):
|
3209 | eb58f7bd | Michael Hanselmann | exitcode = None
|
3210 | eb58f7bd | Michael Hanselmann | signum = os.WTERMSIG(status) |
3211 | eb58f7bd | Michael Hanselmann | else:
|
3212 | eb58f7bd | Michael Hanselmann | exitcode = os.WEXITSTATUS(status) |
3213 | eb58f7bd | Michael Hanselmann | signum = None
|
3214 | eb58f7bd | Michael Hanselmann | |
3215 | eb58f7bd | Michael Hanselmann | if not (exitcode in (0, 1) and signum is None): |
3216 | eb58f7bd | Michael Hanselmann | raise errors.GenericError("Child program failed (code=%s, signal=%s)" % |
3217 | eb58f7bd | Michael Hanselmann | (exitcode, signum)) |
3218 | eb58f7bd | Michael Hanselmann | |
3219 | eb58f7bd | Michael Hanselmann | return bool(exitcode) |
3220 | eb58f7bd | Michael Hanselmann | |
3221 | eb58f7bd | Michael Hanselmann | |
3222 | 560cbec1 | Michael Hanselmann | def IgnoreProcessNotFound(fn, *args, **kwargs): |
3223 | 560cbec1 | Michael Hanselmann | """Ignores ESRCH when calling a process-related function.
|
3224 | 560cbec1 | Michael Hanselmann |
|
3225 | 560cbec1 | Michael Hanselmann | ESRCH is raised when a process is not found.
|
3226 | 560cbec1 | Michael Hanselmann |
|
3227 | 560cbec1 | Michael Hanselmann | @rtype: bool
|
3228 | 560cbec1 | Michael Hanselmann | @return: Whether process was found
|
3229 | 560cbec1 | Michael Hanselmann |
|
3230 | 560cbec1 | Michael Hanselmann | """
|
3231 | 560cbec1 | Michael Hanselmann | try:
|
3232 | 560cbec1 | Michael Hanselmann | fn(*args, **kwargs) |
3233 | 560cbec1 | Michael Hanselmann | except EnvironmentError, err: |
3234 | 560cbec1 | Michael Hanselmann | # Ignore ESRCH
|
3235 | 560cbec1 | Michael Hanselmann | if err.errno == errno.ESRCH:
|
3236 | 560cbec1 | Michael Hanselmann | return False |
3237 | 560cbec1 | Michael Hanselmann | raise
|
3238 | 560cbec1 | Michael Hanselmann | |
3239 | 560cbec1 | Michael Hanselmann | return True |
3240 | 560cbec1 | Michael Hanselmann | |
3241 | 560cbec1 | Michael Hanselmann | |
3242 | 232144d0 | Guido Trotter | def IgnoreSignals(fn, *args, **kwargs): |
3243 | 232144d0 | Guido Trotter | """Tries to call a function ignoring failures due to EINTR.
|
3244 | 232144d0 | Guido Trotter |
|
3245 | 232144d0 | Guido Trotter | """
|
3246 | 232144d0 | Guido Trotter | try:
|
3247 | 232144d0 | Guido Trotter | return fn(*args, **kwargs)
|
3248 | 965d0e5b | Guido Trotter | except EnvironmentError, err: |
3249 | 2fd7f564 | Guido Trotter | if err.errno == errno.EINTR:
|
3250 | 2fd7f564 | Guido Trotter | return None |
3251 | 2fd7f564 | Guido Trotter | else:
|
3252 | 232144d0 | Guido Trotter | raise
|
3253 | 965d0e5b | Guido Trotter | except (select.error, socket.error), err:
|
3254 | 965d0e5b | Guido Trotter | # In python 2.6 and above select.error is an IOError, so it's handled
|
3255 | 965d0e5b | Guido Trotter | # above, in 2.5 and below it's not, and it's handled here.
|
3256 | 2fd7f564 | Guido Trotter | if err.args and err.args[0] == errno.EINTR: |
3257 | 2fd7f564 | Guido Trotter | return None |
3258 | 2fd7f564 | Guido Trotter | else:
|
3259 | 232144d0 | Guido Trotter | raise
|
3260 | 232144d0 | Guido Trotter | |
3261 | 232144d0 | Guido Trotter | |
3262 | eb0f0ce0 | Michael Hanselmann | def LockFile(fd): |
3263 | eb0f0ce0 | Michael Hanselmann | """Locks a file using POSIX locks.
|
3264 | eb0f0ce0 | Michael Hanselmann |
|
3265 | 58885d79 | Iustin Pop | @type fd: int
|
3266 | 58885d79 | Iustin Pop | @param fd: the file descriptor we need to lock
|
3267 | 58885d79 | Iustin Pop |
|
3268 | eb0f0ce0 | Michael Hanselmann | """
|
3269 | eb0f0ce0 | Michael Hanselmann | try:
|
3270 | eb0f0ce0 | Michael Hanselmann | fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) |
3271 | eb0f0ce0 | Michael Hanselmann | except IOError, err: |
3272 | eb0f0ce0 | Michael Hanselmann | if err.errno == errno.EAGAIN:
|
3273 | eb0f0ce0 | Michael Hanselmann | raise errors.LockError("File already locked") |
3274 | eb0f0ce0 | Michael Hanselmann | raise
|
3275 | de499029 | Michael Hanselmann | |
3276 | de499029 | Michael Hanselmann | |
3277 | 3b813dd2 | Iustin Pop | def FormatTime(val): |
3278 | 3b813dd2 | Iustin Pop | """Formats a time value.
|
3279 | 3b813dd2 | Iustin Pop |
|
3280 | 3b813dd2 | Iustin Pop | @type val: float or None
|
3281 | 3b813dd2 | Iustin Pop | @param val: the timestamp as returned by time.time()
|
3282 | 3b813dd2 | Iustin Pop | @return: a string value or N/A if we don't have a valid timestamp
|
3283 | 3b813dd2 | Iustin Pop |
|
3284 | 3b813dd2 | Iustin Pop | """
|
3285 | 3b813dd2 | Iustin Pop | if val is None or not isinstance(val, (int, float)): |
3286 | 3b813dd2 | Iustin Pop | return "N/A" |
3287 | 3b813dd2 | Iustin Pop | # these two codes works on Linux, but they are not guaranteed on all
|
3288 | 3b813dd2 | Iustin Pop | # platforms
|
3289 | 3b813dd2 | Iustin Pop | return time.strftime("%F %T", time.localtime(val)) |
3290 | 3b813dd2 | Iustin Pop | |
3291 | 3b813dd2 | Iustin Pop | |
3292 | f8ea4ada | Michael Hanselmann | def FormatSeconds(secs): |
3293 | f8ea4ada | Michael Hanselmann | """Formats seconds for easier reading.
|
3294 | f8ea4ada | Michael Hanselmann |
|
3295 | f8ea4ada | Michael Hanselmann | @type secs: number
|
3296 | f8ea4ada | Michael Hanselmann | @param secs: Number of seconds
|
3297 | f8ea4ada | Michael Hanselmann | @rtype: string
|
3298 | f8ea4ada | Michael Hanselmann | @return: Formatted seconds (e.g. "2d 9h 19m 49s")
|
3299 | f8ea4ada | Michael Hanselmann |
|
3300 | f8ea4ada | Michael Hanselmann | """
|
3301 | f8ea4ada | Michael Hanselmann | parts = [] |
3302 | f8ea4ada | Michael Hanselmann | |
3303 | f8ea4ada | Michael Hanselmann | secs = round(secs, 0) |
3304 | f8ea4ada | Michael Hanselmann | |
3305 | f8ea4ada | Michael Hanselmann | if secs > 0: |
3306 | f8ea4ada | Michael Hanselmann | # Negative values would be a bit tricky
|
3307 | f8ea4ada | Michael Hanselmann | for unit, one in [("d", 24 * 60 * 60), ("h", 60 * 60), ("m", 60)]: |
3308 | f8ea4ada | Michael Hanselmann | (complete, secs) = divmod(secs, one)
|
3309 | f8ea4ada | Michael Hanselmann | if complete or parts: |
3310 | f8ea4ada | Michael Hanselmann | parts.append("%d%s" % (complete, unit))
|
3311 | f8ea4ada | Michael Hanselmann | |
3312 | f8ea4ada | Michael Hanselmann | parts.append("%ds" % secs)
|
3313 | f8ea4ada | Michael Hanselmann | |
3314 | f8ea4ada | Michael Hanselmann | return " ".join(parts) |
3315 | f8ea4ada | Michael Hanselmann | |
3316 | f8ea4ada | Michael Hanselmann | |
3317 | 5cbe43a5 | Michael Hanselmann | def ReadWatcherPauseFile(filename, now=None, remove_after=3600): |
3318 | 05e50653 | Michael Hanselmann | """Reads the watcher pause file.
|
3319 | 05e50653 | Michael Hanselmann |
|
3320 | 5cbe43a5 | Michael Hanselmann | @type filename: string
|
3321 | 5cbe43a5 | Michael Hanselmann | @param filename: Path to watcher pause file
|
3322 | 5cbe43a5 | Michael Hanselmann | @type now: None, float or int
|
3323 | 5cbe43a5 | Michael Hanselmann | @param now: Current time as Unix timestamp
|
3324 | 5cbe43a5 | Michael Hanselmann | @type remove_after: int
|
3325 | 5cbe43a5 | Michael Hanselmann | @param remove_after: Remove watcher pause file after specified amount of
|
3326 | 5cbe43a5 | Michael Hanselmann | seconds past the pause end time
|
3327 | 5cbe43a5 | Michael Hanselmann |
|
3328 | 05e50653 | Michael Hanselmann | """
|
3329 | 05e50653 | Michael Hanselmann | if now is None: |
3330 | 05e50653 | Michael Hanselmann | now = time.time() |
3331 | 05e50653 | Michael Hanselmann | |
3332 | 05e50653 | Michael Hanselmann | try:
|
3333 | 05e50653 | Michael Hanselmann | value = ReadFile(filename) |
3334 | 05e50653 | Michael Hanselmann | except IOError, err: |
3335 | 05e50653 | Michael Hanselmann | if err.errno != errno.ENOENT:
|
3336 | 05e50653 | Michael Hanselmann | raise
|
3337 | 05e50653 | Michael Hanselmann | value = None
|
3338 | 05e50653 | Michael Hanselmann | |
3339 | 05e50653 | Michael Hanselmann | if value is not None: |
3340 | 05e50653 | Michael Hanselmann | try:
|
3341 | 05e50653 | Michael Hanselmann | value = int(value)
|
3342 | 05e50653 | Michael Hanselmann | except ValueError: |
3343 | 5cbe43a5 | Michael Hanselmann | logging.warning(("Watcher pause file (%s) contains invalid value,"
|
3344 | 5cbe43a5 | Michael Hanselmann | " removing it"), filename)
|
3345 | 5cbe43a5 | Michael Hanselmann | RemoveFile(filename) |
3346 | 05e50653 | Michael Hanselmann | value = None
|
3347 | 05e50653 | Michael Hanselmann | |
3348 | 05e50653 | Michael Hanselmann | if value is not None: |
3349 | 5cbe43a5 | Michael Hanselmann | # Remove file if it's outdated
|
3350 | 5cbe43a5 | Michael Hanselmann | if now > (value + remove_after):
|
3351 | 5cbe43a5 | Michael Hanselmann | RemoveFile(filename) |
3352 | 5cbe43a5 | Michael Hanselmann | value = None
|
3353 | 5cbe43a5 | Michael Hanselmann | |
3354 | 5cbe43a5 | Michael Hanselmann | elif now > value:
|
3355 | 05e50653 | Michael Hanselmann | value = None
|
3356 | 05e50653 | Michael Hanselmann | |
3357 | 05e50653 | Michael Hanselmann | return value
|
3358 | 05e50653 | Michael Hanselmann | |
3359 | 05e50653 | Michael Hanselmann | |
3360 | de0ea66b | Michael Hanselmann | class RetryTimeout(Exception): |
3361 | de0ea66b | Michael Hanselmann | """Retry loop timed out.
|
3362 | de0ea66b | Michael Hanselmann |
|
3363 | 40bc67e1 | Guido Trotter | Any arguments which was passed by the retried function to RetryAgain will be
|
3364 | 40bc67e1 | Guido Trotter | preserved in RetryTimeout, if it is raised. If such argument was an exception
|
3365 | 40bc67e1 | Guido Trotter | the RaiseInner helper method will reraise it.
|
3366 | 40bc67e1 | Guido Trotter |
|
3367 | de0ea66b | Michael Hanselmann | """
|
3368 | 506be7c5 | Guido Trotter | def RaiseInner(self): |
3369 | 506be7c5 | Guido Trotter | if self.args and isinstance(self.args[0], Exception): |
3370 | 506be7c5 | Guido Trotter | raise self.args[0] |
3371 | 506be7c5 | Guido Trotter | else:
|
3372 | 506be7c5 | Guido Trotter | raise RetryTimeout(*self.args) |
3373 | de0ea66b | Michael Hanselmann | |
3374 | de0ea66b | Michael Hanselmann | |
3375 | de0ea66b | Michael Hanselmann | class RetryAgain(Exception): |
3376 | de0ea66b | Michael Hanselmann | """Retry again.
|
3377 | de0ea66b | Michael Hanselmann |
|
3378 | 40bc67e1 | Guido Trotter | Any arguments passed to RetryAgain will be preserved, if a timeout occurs, as
|
3379 | 40bc67e1 | Guido Trotter | arguments to RetryTimeout. If an exception is passed, the RaiseInner() method
|
3380 | 40bc67e1 | Guido Trotter | of the RetryTimeout() method can be used to reraise it.
|
3381 | 40bc67e1 | Guido Trotter |
|
3382 | de0ea66b | Michael Hanselmann | """
|
3383 | de0ea66b | Michael Hanselmann | |
3384 | de0ea66b | Michael Hanselmann | |
3385 | de0ea66b | Michael Hanselmann | class _RetryDelayCalculator(object): |
3386 | de0ea66b | Michael Hanselmann | """Calculator for increasing delays.
|
3387 | de0ea66b | Michael Hanselmann |
|
3388 | de0ea66b | Michael Hanselmann | """
|
3389 | de0ea66b | Michael Hanselmann | __slots__ = [ |
3390 | de0ea66b | Michael Hanselmann | "_factor",
|
3391 | de0ea66b | Michael Hanselmann | "_limit",
|
3392 | de0ea66b | Michael Hanselmann | "_next",
|
3393 | de0ea66b | Michael Hanselmann | "_start",
|
3394 | de0ea66b | Michael Hanselmann | ] |
3395 | de0ea66b | Michael Hanselmann | |
3396 | de0ea66b | Michael Hanselmann | def __init__(self, start, factor, limit): |
3397 | de0ea66b | Michael Hanselmann | """Initializes this class.
|
3398 | de0ea66b | Michael Hanselmann |
|
3399 | de0ea66b | Michael Hanselmann | @type start: float
|
3400 | de0ea66b | Michael Hanselmann | @param start: Initial delay
|
3401 | de0ea66b | Michael Hanselmann | @type factor: float
|
3402 | de0ea66b | Michael Hanselmann | @param factor: Factor for delay increase
|
3403 | de0ea66b | Michael Hanselmann | @type limit: float or None
|
3404 | de0ea66b | Michael Hanselmann | @param limit: Upper limit for delay or None for no limit
|
3405 | de0ea66b | Michael Hanselmann |
|
3406 | de0ea66b | Michael Hanselmann | """
|
3407 | de0ea66b | Michael Hanselmann | assert start > 0.0 |
3408 | de0ea66b | Michael Hanselmann | assert factor >= 1.0 |
3409 | de0ea66b | Michael Hanselmann | assert limit is None or limit >= 0.0 |
3410 | de0ea66b | Michael Hanselmann | |
3411 | de0ea66b | Michael Hanselmann | self._start = start
|
3412 | de0ea66b | Michael Hanselmann | self._factor = factor
|
3413 | de0ea66b | Michael Hanselmann | self._limit = limit
|
3414 | de0ea66b | Michael Hanselmann | |
3415 | de0ea66b | Michael Hanselmann | self._next = start
|
3416 | de0ea66b | Michael Hanselmann | |
3417 | de0ea66b | Michael Hanselmann | def __call__(self): |
3418 | de0ea66b | Michael Hanselmann | """Returns current delay and calculates the next one.
|
3419 | de0ea66b | Michael Hanselmann |
|
3420 | de0ea66b | Michael Hanselmann | """
|
3421 | de0ea66b | Michael Hanselmann | current = self._next
|
3422 | de0ea66b | Michael Hanselmann | |
3423 | de0ea66b | Michael Hanselmann | # Update for next run
|
3424 | de0ea66b | Michael Hanselmann | if self._limit is None or self._next < self._limit: |
3425 | 26751075 | Michael Hanselmann | self._next = min(self._limit, self._next * self._factor) |
3426 | de0ea66b | Michael Hanselmann | |
3427 | de0ea66b | Michael Hanselmann | return current
|
3428 | de0ea66b | Michael Hanselmann | |
3429 | de0ea66b | Michael Hanselmann | |
3430 | de0ea66b | Michael Hanselmann | #: Special delay to specify whole remaining timeout
|
3431 | de0ea66b | Michael Hanselmann | RETRY_REMAINING_TIME = object()
|
3432 | de0ea66b | Michael Hanselmann | |
3433 | de0ea66b | Michael Hanselmann | |
3434 | de0ea66b | Michael Hanselmann | def Retry(fn, delay, timeout, args=None, wait_fn=time.sleep, |
3435 | de0ea66b | Michael Hanselmann | _time_fn=time.time): |
3436 | de0ea66b | Michael Hanselmann | """Call a function repeatedly until it succeeds.
|
3437 | de0ea66b | Michael Hanselmann |
|
3438 | de0ea66b | Michael Hanselmann | The function C{fn} is called repeatedly until it doesn't throw L{RetryAgain}
|
3439 | de0ea66b | Michael Hanselmann | anymore. Between calls a delay, specified by C{delay}, is inserted. After a
|
3440 | de0ea66b | Michael Hanselmann | total of C{timeout} seconds, this function throws L{RetryTimeout}.
|
3441 | de0ea66b | Michael Hanselmann |
|
3442 | de0ea66b | Michael Hanselmann | C{delay} can be one of the following:
|
3443 | de0ea66b | Michael Hanselmann | - callable returning the delay length as a float
|
3444 | de0ea66b | Michael Hanselmann | - Tuple of (start, factor, limit)
|
3445 | de0ea66b | Michael Hanselmann | - L{RETRY_REMAINING_TIME} to sleep until the timeout expires (this is
|
3446 | de0ea66b | Michael Hanselmann | useful when overriding L{wait_fn} to wait for an external event)
|
3447 | de0ea66b | Michael Hanselmann | - A static delay as a number (int or float)
|
3448 | de0ea66b | Michael Hanselmann |
|
3449 | de0ea66b | Michael Hanselmann | @type fn: callable
|
3450 | de0ea66b | Michael Hanselmann | @param fn: Function to be called
|
3451 | de0ea66b | Michael Hanselmann | @param delay: Either a callable (returning the delay), a tuple of (start,
|
3452 | de0ea66b | Michael Hanselmann | factor, limit) (see L{_RetryDelayCalculator}),
|
3453 | de0ea66b | Michael Hanselmann | L{RETRY_REMAINING_TIME} or a number (int or float)
|
3454 | de0ea66b | Michael Hanselmann | @type timeout: float
|
3455 | de0ea66b | Michael Hanselmann | @param timeout: Total timeout
|
3456 | de0ea66b | Michael Hanselmann | @type wait_fn: callable
|
3457 | de0ea66b | Michael Hanselmann | @param wait_fn: Waiting function
|
3458 | de0ea66b | Michael Hanselmann | @return: Return value of function
|
3459 | de0ea66b | Michael Hanselmann |
|
3460 | de0ea66b | Michael Hanselmann | """
|
3461 | de0ea66b | Michael Hanselmann | assert callable(fn) |
3462 | de0ea66b | Michael Hanselmann | assert callable(wait_fn) |
3463 | de0ea66b | Michael Hanselmann | assert callable(_time_fn) |
3464 | de0ea66b | Michael Hanselmann | |
3465 | de0ea66b | Michael Hanselmann | if args is None: |
3466 | de0ea66b | Michael Hanselmann | args = [] |
3467 | de0ea66b | Michael Hanselmann | |
3468 | de0ea66b | Michael Hanselmann | end_time = _time_fn() + timeout |
3469 | de0ea66b | Michael Hanselmann | |
3470 | de0ea66b | Michael Hanselmann | if callable(delay): |
3471 | de0ea66b | Michael Hanselmann | # External function to calculate delay
|
3472 | de0ea66b | Michael Hanselmann | calc_delay = delay |
3473 | de0ea66b | Michael Hanselmann | |
3474 | de0ea66b | Michael Hanselmann | elif isinstance(delay, (tuple, list)): |
3475 | de0ea66b | Michael Hanselmann | # Increasing delay with optional upper boundary
|
3476 | de0ea66b | Michael Hanselmann | (start, factor, limit) = delay |
3477 | de0ea66b | Michael Hanselmann | calc_delay = _RetryDelayCalculator(start, factor, limit) |
3478 | de0ea66b | Michael Hanselmann | |
3479 | de0ea66b | Michael Hanselmann | elif delay is RETRY_REMAINING_TIME: |
3480 | de0ea66b | Michael Hanselmann | # Always use the remaining time
|
3481 | de0ea66b | Michael Hanselmann | calc_delay = None
|
3482 | de0ea66b | Michael Hanselmann | |
3483 | de0ea66b | Michael Hanselmann | else:
|
3484 | de0ea66b | Michael Hanselmann | # Static delay
|
3485 | de0ea66b | Michael Hanselmann | calc_delay = lambda: delay
|
3486 | de0ea66b | Michael Hanselmann | |
3487 | de0ea66b | Michael Hanselmann | assert calc_delay is None or callable(calc_delay) |
3488 | de0ea66b | Michael Hanselmann | |
3489 | de0ea66b | Michael Hanselmann | while True: |
3490 | 506be7c5 | Guido Trotter | retry_args = [] |
3491 | de0ea66b | Michael Hanselmann | try:
|
3492 | 7260cfbe | Iustin Pop | # pylint: disable-msg=W0142
|
3493 | de0ea66b | Michael Hanselmann | return fn(*args)
|
3494 | 506be7c5 | Guido Trotter | except RetryAgain, err:
|
3495 | 506be7c5 | Guido Trotter | retry_args = err.args |
3496 | 1b429e2a | Iustin Pop | except RetryTimeout:
|
3497 | 1b429e2a | Iustin Pop | raise errors.ProgrammerError("Nested retry loop detected that didn't" |
3498 | 1b429e2a | Iustin Pop | " handle RetryTimeout")
|
3499 | de0ea66b | Michael Hanselmann | |
3500 | de0ea66b | Michael Hanselmann | remaining_time = end_time - _time_fn() |
3501 | de0ea66b | Michael Hanselmann | |
3502 | de0ea66b | Michael Hanselmann | if remaining_time < 0.0: |
3503 | 506be7c5 | Guido Trotter | # pylint: disable-msg=W0142
|
3504 | 506be7c5 | Guido Trotter | raise RetryTimeout(*retry_args)
|
3505 | de0ea66b | Michael Hanselmann | |
3506 | de0ea66b | Michael Hanselmann | assert remaining_time >= 0.0 |
3507 | de0ea66b | Michael Hanselmann | |
3508 | de0ea66b | Michael Hanselmann | if calc_delay is None: |
3509 | de0ea66b | Michael Hanselmann | wait_fn(remaining_time) |
3510 | de0ea66b | Michael Hanselmann | else:
|
3511 | de0ea66b | Michael Hanselmann | current_delay = calc_delay() |
3512 | de0ea66b | Michael Hanselmann | if current_delay > 0.0: |
3513 | de0ea66b | Michael Hanselmann | wait_fn(current_delay) |
3514 | de0ea66b | Michael Hanselmann | |
3515 | de0ea66b | Michael Hanselmann | |
3516 | bdd5e420 | Michael Hanselmann | def GetClosedTempfile(*args, **kwargs): |
3517 | bdd5e420 | Michael Hanselmann | """Creates a temporary file and returns its path.
|
3518 | a55474c7 | Michael Hanselmann |
|
3519 | bdd5e420 | Michael Hanselmann | """
|
3520 | bdd5e420 | Michael Hanselmann | (fd, path) = tempfile.mkstemp(*args, **kwargs) |
3521 | bdd5e420 | Michael Hanselmann | _CloseFDNoErr(fd) |
3522 | bdd5e420 | Michael Hanselmann | return path
|
3523 | bdd5e420 | Michael Hanselmann | |
3524 | bdd5e420 | Michael Hanselmann | |
3525 | bdd5e420 | Michael Hanselmann | def GenerateSelfSignedX509Cert(common_name, validity): |
3526 | bdd5e420 | Michael Hanselmann | """Generates a self-signed X509 certificate.
|
3527 | bdd5e420 | Michael Hanselmann |
|
3528 | bdd5e420 | Michael Hanselmann | @type common_name: string
|
3529 | bdd5e420 | Michael Hanselmann | @param common_name: commonName value
|
3530 | a55474c7 | Michael Hanselmann | @type validity: int
|
3531 | bdd5e420 | Michael Hanselmann | @param validity: Validity for certificate in seconds
|
3532 | a55474c7 | Michael Hanselmann |
|
3533 | a55474c7 | Michael Hanselmann | """
|
3534 | bdd5e420 | Michael Hanselmann | # Create private and public key
|
3535 | bdd5e420 | Michael Hanselmann | key = OpenSSL.crypto.PKey() |
3536 | bdd5e420 | Michael Hanselmann | key.generate_key(OpenSSL.crypto.TYPE_RSA, constants.RSA_KEY_BITS) |
3537 | bdd5e420 | Michael Hanselmann | |
3538 | bdd5e420 | Michael Hanselmann | # Create self-signed certificate
|
3539 | bdd5e420 | Michael Hanselmann | cert = OpenSSL.crypto.X509() |
3540 | bdd5e420 | Michael Hanselmann | if common_name:
|
3541 | bdd5e420 | Michael Hanselmann | cert.get_subject().CN = common_name |
3542 | bdd5e420 | Michael Hanselmann | cert.set_serial_number(1)
|
3543 | bdd5e420 | Michael Hanselmann | cert.gmtime_adj_notBefore(0)
|
3544 | bdd5e420 | Michael Hanselmann | cert.gmtime_adj_notAfter(validity) |
3545 | bdd5e420 | Michael Hanselmann | cert.set_issuer(cert.get_subject()) |
3546 | bdd5e420 | Michael Hanselmann | cert.set_pubkey(key) |
3547 | bdd5e420 | Michael Hanselmann | cert.sign(key, constants.X509_CERT_SIGN_DIGEST) |
3548 | bdd5e420 | Michael Hanselmann | |
3549 | bdd5e420 | Michael Hanselmann | key_pem = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) |
3550 | bdd5e420 | Michael Hanselmann | cert_pem = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) |
3551 | bdd5e420 | Michael Hanselmann | |
3552 | bdd5e420 | Michael Hanselmann | return (key_pem, cert_pem)
|
3553 | bdd5e420 | Michael Hanselmann | |
3554 | bdd5e420 | Michael Hanselmann | |
3555 | bdd5e420 | Michael Hanselmann | def GenerateSelfSignedSslCert(filename, validity=(5 * 365)): |
3556 | bdd5e420 | Michael Hanselmann | """Legacy function to generate self-signed X509 certificate.
|
3557 | bdd5e420 | Michael Hanselmann |
|
3558 | bdd5e420 | Michael Hanselmann | """
|
3559 | bdd5e420 | Michael Hanselmann | (key_pem, cert_pem) = GenerateSelfSignedX509Cert(None,
|
3560 | bdd5e420 | Michael Hanselmann | validity * 24 * 60 * 60) |
3561 | bdd5e420 | Michael Hanselmann | |
3562 | bdd5e420 | Michael Hanselmann | WriteFile(filename, mode=0400, data=key_pem + cert_pem)
|
3563 | a55474c7 | Michael Hanselmann | |
3564 | a55474c7 | Michael Hanselmann | |
3565 | a87b4824 | Michael Hanselmann | class FileLock(object): |
3566 | a87b4824 | Michael Hanselmann | """Utility class for file locks.
|
3567 | a87b4824 | Michael Hanselmann |
|
3568 | a87b4824 | Michael Hanselmann | """
|
3569 | b4478d34 | Michael Hanselmann | def __init__(self, fd, filename): |
3570 | 58885d79 | Iustin Pop | """Constructor for FileLock.
|
3571 | 58885d79 | Iustin Pop |
|
3572 | b4478d34 | Michael Hanselmann | @type fd: file
|
3573 | b4478d34 | Michael Hanselmann | @param fd: File object
|
3574 | 58885d79 | Iustin Pop | @type filename: str
|
3575 | b4478d34 | Michael Hanselmann | @param filename: Path of the file opened at I{fd}
|
3576 | 58885d79 | Iustin Pop |
|
3577 | 58885d79 | Iustin Pop | """
|
3578 | b4478d34 | Michael Hanselmann | self.fd = fd
|
3579 | a87b4824 | Michael Hanselmann | self.filename = filename
|
3580 | b4478d34 | Michael Hanselmann | |
3581 | b4478d34 | Michael Hanselmann | @classmethod
|
3582 | b4478d34 | Michael Hanselmann | def Open(cls, filename): |
3583 | b4478d34 | Michael Hanselmann | """Creates and opens a file to be used as a file-based lock.
|
3584 | b4478d34 | Michael Hanselmann |
|
3585 | b4478d34 | Michael Hanselmann | @type filename: string
|
3586 | b4478d34 | Michael Hanselmann | @param filename: path to the file to be locked
|
3587 | b4478d34 | Michael Hanselmann |
|
3588 | b4478d34 | Michael Hanselmann | """
|
3589 | b4478d34 | Michael Hanselmann | # Using "os.open" is necessary to allow both opening existing file
|
3590 | b4478d34 | Michael Hanselmann | # read/write and creating if not existing. Vanilla "open" will truncate an
|
3591 | b4478d34 | Michael Hanselmann | # existing file -or- allow creating if not existing.
|
3592 | b4478d34 | Michael Hanselmann | return cls(os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT), "w+"), |
3593 | b4478d34 | Michael Hanselmann | filename) |
3594 | a87b4824 | Michael Hanselmann | |
3595 | a87b4824 | Michael Hanselmann | def __del__(self): |
3596 | a87b4824 | Michael Hanselmann | self.Close()
|
3597 | a87b4824 | Michael Hanselmann | |
3598 | a87b4824 | Michael Hanselmann | def Close(self): |
3599 | 58885d79 | Iustin Pop | """Close the file and release the lock.
|
3600 | 58885d79 | Iustin Pop |
|
3601 | 58885d79 | Iustin Pop | """
|
3602 | aac3fbf0 | Iustin Pop | if hasattr(self, "fd") and self.fd: |
3603 | a87b4824 | Michael Hanselmann | self.fd.close()
|
3604 | a87b4824 | Michael Hanselmann | self.fd = None |
3605 | a87b4824 | Michael Hanselmann | |
3606 | aa74b828 | Michael Hanselmann | def _flock(self, flag, blocking, timeout, errmsg): |
3607 | aa74b828 | Michael Hanselmann | """Wrapper for fcntl.flock.
|
3608 | aa74b828 | Michael Hanselmann |
|
3609 | aa74b828 | Michael Hanselmann | @type flag: int
|
3610 | 58885d79 | Iustin Pop | @param flag: operation flag
|
3611 | aa74b828 | Michael Hanselmann | @type blocking: bool
|
3612 | 58885d79 | Iustin Pop | @param blocking: whether the operation should be done in blocking mode.
|
3613 | aa74b828 | Michael Hanselmann | @type timeout: None or float
|
3614 | 58885d79 | Iustin Pop | @param timeout: for how long the operation should be retried (implies
|
3615 | aa74b828 | Michael Hanselmann | non-blocking mode).
|
3616 | aa74b828 | Michael Hanselmann | @type errmsg: string
|
3617 | 58885d79 | Iustin Pop | @param errmsg: error message in case operation fails.
|
3618 | aa74b828 | Michael Hanselmann |
|
3619 | aa74b828 | Michael Hanselmann | """
|
3620 | a87b4824 | Michael Hanselmann | assert self.fd, "Lock was closed" |
3621 | aa74b828 | Michael Hanselmann | assert timeout is None or timeout >= 0, \ |
3622 | aa74b828 | Michael Hanselmann | "If specified, timeout must be positive"
|
3623 | cc4c9b91 | Michael Hanselmann | assert not (flag & fcntl.LOCK_NB), "LOCK_NB must not be set" |
3624 | a87b4824 | Michael Hanselmann | |
3625 | cc4c9b91 | Michael Hanselmann | # When a timeout is used, LOCK_NB must always be set
|
3626 | cc4c9b91 | Michael Hanselmann | if not (timeout is None and blocking): |
3627 | a87b4824 | Michael Hanselmann | flag |= fcntl.LOCK_NB |
3628 | a87b4824 | Michael Hanselmann | |
3629 | cc4c9b91 | Michael Hanselmann | if timeout is None: |
3630 | cc4c9b91 | Michael Hanselmann | self._Lock(self.fd, flag, timeout) |
3631 | cc4c9b91 | Michael Hanselmann | else:
|
3632 | cc4c9b91 | Michael Hanselmann | try:
|
3633 | cc4c9b91 | Michael Hanselmann | Retry(self._Lock, (0.1, 1.2, 1.0), timeout, |
3634 | cc4c9b91 | Michael Hanselmann | args=(self.fd, flag, timeout))
|
3635 | cc4c9b91 | Michael Hanselmann | except RetryTimeout:
|
3636 | cc4c9b91 | Michael Hanselmann | raise errors.LockError(errmsg)
|
3637 | aa74b828 | Michael Hanselmann | |
3638 | cc4c9b91 | Michael Hanselmann | @staticmethod
|
3639 | cc4c9b91 | Michael Hanselmann | def _Lock(fd, flag, timeout): |
3640 | cc4c9b91 | Michael Hanselmann | try:
|
3641 | cc4c9b91 | Michael Hanselmann | fcntl.flock(fd, flag) |
3642 | cc4c9b91 | Michael Hanselmann | except IOError, err: |
3643 | cc4c9b91 | Michael Hanselmann | if timeout is not None and err.errno == errno.EAGAIN: |
3644 | cc4c9b91 | Michael Hanselmann | raise RetryAgain()
|
3645 | 31892b4c | Michael Hanselmann | |
3646 | cc4c9b91 | Michael Hanselmann | logging.exception("fcntl.flock failed")
|
3647 | cc4c9b91 | Michael Hanselmann | raise
|
3648 | aa74b828 | Michael Hanselmann | |
3649 | aa74b828 | Michael Hanselmann | def Exclusive(self, blocking=False, timeout=None): |
3650 | a87b4824 | Michael Hanselmann | """Locks the file in exclusive mode.
|
3651 | a87b4824 | Michael Hanselmann |
|
3652 | 58885d79 | Iustin Pop | @type blocking: boolean
|
3653 | 58885d79 | Iustin Pop | @param blocking: whether to block and wait until we
|
3654 | 58885d79 | Iustin Pop | can lock the file or return immediately
|
3655 | 58885d79 | Iustin Pop | @type timeout: int or None
|
3656 | 58885d79 | Iustin Pop | @param timeout: if not None, the duration to wait for the lock
|
3657 | 58885d79 | Iustin Pop | (in blocking mode)
|
3658 | 58885d79 | Iustin Pop |
|
3659 | a87b4824 | Michael Hanselmann | """
|
3660 | aa74b828 | Michael Hanselmann | self._flock(fcntl.LOCK_EX, blocking, timeout,
|
3661 | a87b4824 | Michael Hanselmann | "Failed to lock %s in exclusive mode" % self.filename) |
3662 | a87b4824 | Michael Hanselmann | |
3663 | aa74b828 | Michael Hanselmann | def Shared(self, blocking=False, timeout=None): |
3664 | a87b4824 | Michael Hanselmann | """Locks the file in shared mode.
|
3665 | a87b4824 | Michael Hanselmann |
|
3666 | 58885d79 | Iustin Pop | @type blocking: boolean
|
3667 | 58885d79 | Iustin Pop | @param blocking: whether to block and wait until we
|
3668 | 58885d79 | Iustin Pop | can lock the file or return immediately
|
3669 | 58885d79 | Iustin Pop | @type timeout: int or None
|
3670 | 58885d79 | Iustin Pop | @param timeout: if not None, the duration to wait for the lock
|
3671 | 58885d79 | Iustin Pop | (in blocking mode)
|
3672 | 58885d79 | Iustin Pop |
|
3673 | a87b4824 | Michael Hanselmann | """
|
3674 | aa74b828 | Michael Hanselmann | self._flock(fcntl.LOCK_SH, blocking, timeout,
|
3675 | a87b4824 | Michael Hanselmann | "Failed to lock %s in shared mode" % self.filename) |
3676 | a87b4824 | Michael Hanselmann | |
3677 | aa74b828 | Michael Hanselmann | def Unlock(self, blocking=True, timeout=None): |
3678 | a87b4824 | Michael Hanselmann | """Unlocks the file.
|
3679 | a87b4824 | Michael Hanselmann |
|
3680 | 58885d79 | Iustin Pop | According to C{flock(2)}, unlocking can also be a nonblocking
|
3681 | 58885d79 | Iustin Pop | operation::
|
3682 | 58885d79 | Iustin Pop |
|
3683 | 58885d79 | Iustin Pop | To make a non-blocking request, include LOCK_NB with any of the above
|
3684 | 58885d79 | Iustin Pop | operations.
|
3685 | 58885d79 | Iustin Pop |
|
3686 | 58885d79 | Iustin Pop | @type blocking: boolean
|
3687 | 58885d79 | Iustin Pop | @param blocking: whether to block and wait until we
|
3688 | 58885d79 | Iustin Pop | can lock the file or return immediately
|
3689 | 58885d79 | Iustin Pop | @type timeout: int or None
|
3690 | 58885d79 | Iustin Pop | @param timeout: if not None, the duration to wait for the lock
|
3691 | 58885d79 | Iustin Pop | (in blocking mode)
|
3692 | a87b4824 | Michael Hanselmann |
|
3693 | a87b4824 | Michael Hanselmann | """
|
3694 | aa74b828 | Michael Hanselmann | self._flock(fcntl.LOCK_UN, blocking, timeout,
|
3695 | a87b4824 | Michael Hanselmann | "Failed to unlock %s" % self.filename) |
3696 | a87b4824 | Michael Hanselmann | |
3697 | a87b4824 | Michael Hanselmann | |
3698 | 339be5a8 | Michael Hanselmann | class LineSplitter: |
3699 | 339be5a8 | Michael Hanselmann | """Splits data chunks into lines separated by newline.
|
3700 | 339be5a8 | Michael Hanselmann |
|
3701 | 339be5a8 | Michael Hanselmann | Instances provide a file-like interface.
|
3702 | 339be5a8 | Michael Hanselmann |
|
3703 | 339be5a8 | Michael Hanselmann | """
|
3704 | 339be5a8 | Michael Hanselmann | def __init__(self, line_fn, *args): |
3705 | 339be5a8 | Michael Hanselmann | """Initializes this class.
|
3706 | 339be5a8 | Michael Hanselmann |
|
3707 | 339be5a8 | Michael Hanselmann | @type line_fn: callable
|
3708 | 339be5a8 | Michael Hanselmann | @param line_fn: Function called for each line, first parameter is line
|
3709 | 339be5a8 | Michael Hanselmann | @param args: Extra arguments for L{line_fn}
|
3710 | 339be5a8 | Michael Hanselmann |
|
3711 | 339be5a8 | Michael Hanselmann | """
|
3712 | 339be5a8 | Michael Hanselmann | assert callable(line_fn) |
3713 | 339be5a8 | Michael Hanselmann | |
3714 | 339be5a8 | Michael Hanselmann | if args:
|
3715 | 339be5a8 | Michael Hanselmann | # Python 2.4 doesn't have functools.partial yet
|
3716 | 339be5a8 | Michael Hanselmann | self._line_fn = \
|
3717 | 339be5a8 | Michael Hanselmann | lambda line: line_fn(line, *args) # pylint: disable-msg=W0142 |
3718 | 339be5a8 | Michael Hanselmann | else:
|
3719 | 339be5a8 | Michael Hanselmann | self._line_fn = line_fn
|
3720 | 339be5a8 | Michael Hanselmann | |
3721 | 339be5a8 | Michael Hanselmann | self._lines = collections.deque()
|
3722 | 339be5a8 | Michael Hanselmann | self._buffer = "" |
3723 | 339be5a8 | Michael Hanselmann | |
3724 | 339be5a8 | Michael Hanselmann | def write(self, data): |
3725 | 339be5a8 | Michael Hanselmann | parts = (self._buffer + data).split("\n") |
3726 | 339be5a8 | Michael Hanselmann | self._buffer = parts.pop()
|
3727 | 339be5a8 | Michael Hanselmann | self._lines.extend(parts)
|
3728 | 339be5a8 | Michael Hanselmann | |
3729 | 339be5a8 | Michael Hanselmann | def flush(self): |
3730 | 339be5a8 | Michael Hanselmann | while self._lines: |
3731 | 339be5a8 | Michael Hanselmann | self._line_fn(self._lines.popleft().rstrip("\r\n")) |
3732 | 339be5a8 | Michael Hanselmann | |
3733 | 339be5a8 | Michael Hanselmann | def close(self): |
3734 | 339be5a8 | Michael Hanselmann | self.flush()
|
3735 | 339be5a8 | Michael Hanselmann | if self._buffer: |
3736 | 339be5a8 | Michael Hanselmann | self._line_fn(self._buffer) |
3737 | 339be5a8 | Michael Hanselmann | |
3738 | 339be5a8 | Michael Hanselmann | |
3739 | 451575de | Guido Trotter | def SignalHandled(signums): |
3740 | 451575de | Guido Trotter | """Signal Handled decoration.
|
3741 | 451575de | Guido Trotter |
|
3742 | 451575de | Guido Trotter | This special decorator installs a signal handler and then calls the target
|
3743 | 451575de | Guido Trotter | function. The function must accept a 'signal_handlers' keyword argument,
|
3744 | 451575de | Guido Trotter | which will contain a dict indexed by signal number, with SignalHandler
|
3745 | 451575de | Guido Trotter | objects as values.
|
3746 | 451575de | Guido Trotter |
|
3747 | 451575de | Guido Trotter | The decorator can be safely stacked with iself, to handle multiple signals
|
3748 | 451575de | Guido Trotter | with different handlers.
|
3749 | 451575de | Guido Trotter |
|
3750 | 451575de | Guido Trotter | @type signums: list
|
3751 | 451575de | Guido Trotter | @param signums: signals to intercept
|
3752 | 451575de | Guido Trotter |
|
3753 | 451575de | Guido Trotter | """
|
3754 | 451575de | Guido Trotter | def wrap(fn): |
3755 | 451575de | Guido Trotter | def sig_function(*args, **kwargs): |
3756 | 451575de | Guido Trotter | assert 'signal_handlers' not in kwargs or \ |
3757 | 451575de | Guido Trotter | kwargs['signal_handlers'] is None or \ |
3758 | 451575de | Guido Trotter | isinstance(kwargs['signal_handlers'], dict), \ |
3759 | 451575de | Guido Trotter | "Wrong signal_handlers parameter in original function call"
|
3760 | 451575de | Guido Trotter | if 'signal_handlers' in kwargs and kwargs['signal_handlers'] is not None: |
3761 | 451575de | Guido Trotter | signal_handlers = kwargs['signal_handlers']
|
3762 | 451575de | Guido Trotter | else:
|
3763 | 451575de | Guido Trotter | signal_handlers = {} |
3764 | 451575de | Guido Trotter | kwargs['signal_handlers'] = signal_handlers
|
3765 | 451575de | Guido Trotter | sighandler = SignalHandler(signums) |
3766 | 451575de | Guido Trotter | try:
|
3767 | 451575de | Guido Trotter | for sig in signums: |
3768 | 451575de | Guido Trotter | signal_handlers[sig] = sighandler |
3769 | 451575de | Guido Trotter | return fn(*args, **kwargs)
|
3770 | 451575de | Guido Trotter | finally:
|
3771 | 451575de | Guido Trotter | sighandler.Reset() |
3772 | 451575de | Guido Trotter | return sig_function
|
3773 | 451575de | Guido Trotter | return wrap
|
3774 | 451575de | Guido Trotter | |
3775 | 451575de | Guido Trotter | |
3776 | b9768937 | Michael Hanselmann | class SignalWakeupFd(object): |
3777 | b9768937 | Michael Hanselmann | try:
|
3778 | b9768937 | Michael Hanselmann | # This is only supported in Python 2.5 and above (some distributions
|
3779 | b9768937 | Michael Hanselmann | # backported it to Python 2.4)
|
3780 | b9768937 | Michael Hanselmann | _set_wakeup_fd_fn = signal.set_wakeup_fd |
3781 | b9768937 | Michael Hanselmann | except AttributeError: |
3782 | b9768937 | Michael Hanselmann | # Not supported
|
3783 | b9768937 | Michael Hanselmann | def _SetWakeupFd(self, _): # pylint: disable-msg=R0201 |
3784 | b9768937 | Michael Hanselmann | return -1 |
3785 | b9768937 | Michael Hanselmann | else:
|
3786 | b9768937 | Michael Hanselmann | def _SetWakeupFd(self, fd): |
3787 | b9768937 | Michael Hanselmann | return self._set_wakeup_fd_fn(fd) |
3788 | b9768937 | Michael Hanselmann | |
3789 | b9768937 | Michael Hanselmann | def __init__(self): |
3790 | b9768937 | Michael Hanselmann | """Initializes this class.
|
3791 | b9768937 | Michael Hanselmann |
|
3792 | b9768937 | Michael Hanselmann | """
|
3793 | b9768937 | Michael Hanselmann | (read_fd, write_fd) = os.pipe() |
3794 | b9768937 | Michael Hanselmann | |
3795 | b9768937 | Michael Hanselmann | # Once these succeeded, the file descriptors will be closed automatically.
|
3796 | b9768937 | Michael Hanselmann | # Buffer size 0 is important, otherwise .read() with a specified length
|
3797 | b9768937 | Michael Hanselmann | # might buffer data and the file descriptors won't be marked readable.
|
3798 | b9768937 | Michael Hanselmann | self._read_fh = os.fdopen(read_fd, "r", 0) |
3799 | b9768937 | Michael Hanselmann | self._write_fh = os.fdopen(write_fd, "w", 0) |
3800 | b9768937 | Michael Hanselmann | |
3801 | b9768937 | Michael Hanselmann | self._previous = self._SetWakeupFd(self._write_fh.fileno()) |
3802 | b9768937 | Michael Hanselmann | |
3803 | b9768937 | Michael Hanselmann | # Utility functions
|
3804 | b9768937 | Michael Hanselmann | self.fileno = self._read_fh.fileno |
3805 | b9768937 | Michael Hanselmann | self.read = self._read_fh.read |
3806 | b9768937 | Michael Hanselmann | |
3807 | b9768937 | Michael Hanselmann | def Reset(self): |
3808 | b9768937 | Michael Hanselmann | """Restores the previous wakeup file descriptor.
|
3809 | b9768937 | Michael Hanselmann |
|
3810 | b9768937 | Michael Hanselmann | """
|
3811 | b9768937 | Michael Hanselmann | if hasattr(self, "_previous") and self._previous is not None: |
3812 | b9768937 | Michael Hanselmann | self._SetWakeupFd(self._previous) |
3813 | b9768937 | Michael Hanselmann | self._previous = None |
3814 | b9768937 | Michael Hanselmann | |
3815 | b9768937 | Michael Hanselmann | def Notify(self): |
3816 | b9768937 | Michael Hanselmann | """Notifies the wakeup file descriptor.
|
3817 | b9768937 | Michael Hanselmann |
|
3818 | b9768937 | Michael Hanselmann | """
|
3819 | b9768937 | Michael Hanselmann | self._write_fh.write("\0") |
3820 | b9768937 | Michael Hanselmann | |
3821 | b9768937 | Michael Hanselmann | def __del__(self): |
3822 | b9768937 | Michael Hanselmann | """Called before object deletion.
|
3823 | b9768937 | Michael Hanselmann |
|
3824 | b9768937 | Michael Hanselmann | """
|
3825 | b9768937 | Michael Hanselmann | self.Reset()
|
3826 | b9768937 | Michael Hanselmann | |
3827 | b9768937 | Michael Hanselmann | |
3828 | de499029 | Michael Hanselmann | class SignalHandler(object): |
3829 | de499029 | Michael Hanselmann | """Generic signal handler class.
|
3830 | de499029 | Michael Hanselmann |
|
3831 | 58885d79 | Iustin Pop | It automatically restores the original handler when deconstructed or
|
3832 | 58885d79 | Iustin Pop | when L{Reset} is called. You can either pass your own handler
|
3833 | 58885d79 | Iustin Pop | function in or query the L{called} attribute to detect whether the
|
3834 | 58885d79 | Iustin Pop | signal was sent.
|
3835 | 58885d79 | Iustin Pop |
|
3836 | 58885d79 | Iustin Pop | @type signum: list
|
3837 | 58885d79 | Iustin Pop | @ivar signum: the signals we handle
|
3838 | 58885d79 | Iustin Pop | @type called: boolean
|
3839 | 58885d79 | Iustin Pop | @ivar called: tracks whether any of the signals have been raised
|
3840 | de499029 | Michael Hanselmann |
|
3841 | de499029 | Michael Hanselmann | """
|
3842 | b9768937 | Michael Hanselmann | def __init__(self, signum, handler_fn=None, wakeup=None): |
3843 | de499029 | Michael Hanselmann | """Constructs a new SignalHandler instance.
|
3844 | de499029 | Michael Hanselmann |
|
3845 | 58885d79 | Iustin Pop | @type signum: int or list of ints
|
3846 | de499029 | Michael Hanselmann | @param signum: Single signal number or set of signal numbers
|
3847 | 92b61ec7 | Michael Hanselmann | @type handler_fn: callable
|
3848 | 92b61ec7 | Michael Hanselmann | @param handler_fn: Signal handling function
|
3849 | de499029 | Michael Hanselmann |
|
3850 | de499029 | Michael Hanselmann | """
|
3851 | 92b61ec7 | Michael Hanselmann | assert handler_fn is None or callable(handler_fn) |
3852 | 92b61ec7 | Michael Hanselmann | |
3853 | 6c52849e | Guido Trotter | self.signum = set(signum) |
3854 | de499029 | Michael Hanselmann | self.called = False |
3855 | de499029 | Michael Hanselmann | |
3856 | 92b61ec7 | Michael Hanselmann | self._handler_fn = handler_fn
|
3857 | b9768937 | Michael Hanselmann | self._wakeup = wakeup
|
3858 | 92b61ec7 | Michael Hanselmann | |
3859 | de499029 | Michael Hanselmann | self._previous = {}
|
3860 | de499029 | Michael Hanselmann | try:
|
3861 | de499029 | Michael Hanselmann | for signum in self.signum: |
3862 | de499029 | Michael Hanselmann | # Setup handler
|
3863 | de499029 | Michael Hanselmann | prev_handler = signal.signal(signum, self._HandleSignal)
|
3864 | de499029 | Michael Hanselmann | try:
|
3865 | de499029 | Michael Hanselmann | self._previous[signum] = prev_handler
|
3866 | de499029 | Michael Hanselmann | except:
|
3867 | de499029 | Michael Hanselmann | # Restore previous handler
|
3868 | de499029 | Michael Hanselmann | signal.signal(signum, prev_handler) |
3869 | de499029 | Michael Hanselmann | raise
|
3870 | de499029 | Michael Hanselmann | except:
|
3871 | de499029 | Michael Hanselmann | # Reset all handlers
|
3872 | de499029 | Michael Hanselmann | self.Reset()
|
3873 | de499029 | Michael Hanselmann | # Here we have a race condition: a handler may have already been called,
|
3874 | de499029 | Michael Hanselmann | # but there's not much we can do about it at this point.
|
3875 | de499029 | Michael Hanselmann | raise
|
3876 | de499029 | Michael Hanselmann | |
3877 | de499029 | Michael Hanselmann | def __del__(self): |
3878 | de499029 | Michael Hanselmann | self.Reset()
|
3879 | de499029 | Michael Hanselmann | |
3880 | de499029 | Michael Hanselmann | def Reset(self): |
3881 | de499029 | Michael Hanselmann | """Restore previous handler.
|
3882 | de499029 | Michael Hanselmann |
|
3883 | 58885d79 | Iustin Pop | This will reset all the signals to their previous handlers.
|
3884 | 58885d79 | Iustin Pop |
|
3885 | de499029 | Michael Hanselmann | """
|
3886 | de499029 | Michael Hanselmann | for signum, prev_handler in self._previous.items(): |
3887 | de499029 | Michael Hanselmann | signal.signal(signum, prev_handler) |
3888 | de499029 | Michael Hanselmann | # If successful, remove from dict
|
3889 | de499029 | Michael Hanselmann | del self._previous[signum] |
3890 | de499029 | Michael Hanselmann | |
3891 | de499029 | Michael Hanselmann | def Clear(self): |
3892 | 58885d79 | Iustin Pop | """Unsets the L{called} flag.
|
3893 | de499029 | Michael Hanselmann |
|
3894 | de499029 | Michael Hanselmann | This function can be used in case a signal may arrive several times.
|
3895 | de499029 | Michael Hanselmann |
|
3896 | de499029 | Michael Hanselmann | """
|
3897 | de499029 | Michael Hanselmann | self.called = False |
3898 | de499029 | Michael Hanselmann | |
3899 | 92b61ec7 | Michael Hanselmann | def _HandleSignal(self, signum, frame): |
3900 | de499029 | Michael Hanselmann | """Actual signal handling function.
|
3901 | de499029 | Michael Hanselmann |
|
3902 | de499029 | Michael Hanselmann | """
|
3903 | de499029 | Michael Hanselmann | # This is not nice and not absolutely atomic, but it appears to be the only
|
3904 | de499029 | Michael Hanselmann | # solution in Python -- there are no atomic types.
|
3905 | de499029 | Michael Hanselmann | self.called = True |
3906 | a2d2e1a7 | Iustin Pop | |
3907 | b9768937 | Michael Hanselmann | if self._wakeup: |
3908 | b9768937 | Michael Hanselmann | # Notify whoever is interested in signals
|
3909 | b9768937 | Michael Hanselmann | self._wakeup.Notify()
|
3910 | b9768937 | Michael Hanselmann | |
3911 | 92b61ec7 | Michael Hanselmann | if self._handler_fn: |
3912 | 92b61ec7 | Michael Hanselmann | self._handler_fn(signum, frame)
|
3913 | 92b61ec7 | Michael Hanselmann | |
3914 | a2d2e1a7 | Iustin Pop | |
3915 | a2d2e1a7 | Iustin Pop | class FieldSet(object): |
3916 | a2d2e1a7 | Iustin Pop | """A simple field set.
|
3917 | a2d2e1a7 | Iustin Pop |
|
3918 | a2d2e1a7 | Iustin Pop | Among the features are:
|
3919 | a2d2e1a7 | Iustin Pop | - checking if a string is among a list of static string or regex objects
|
3920 | a2d2e1a7 | Iustin Pop | - checking if a whole list of string matches
|
3921 | a2d2e1a7 | Iustin Pop | - returning the matching groups from a regex match
|
3922 | a2d2e1a7 | Iustin Pop |
|
3923 | a2d2e1a7 | Iustin Pop | Internally, all fields are held as regular expression objects.
|
3924 | a2d2e1a7 | Iustin Pop |
|
3925 | a2d2e1a7 | Iustin Pop | """
|
3926 | a2d2e1a7 | Iustin Pop | def __init__(self, *items): |
3927 | a2d2e1a7 | Iustin Pop | self.items = [re.compile("^%s$" % value) for value in items] |
3928 | a2d2e1a7 | Iustin Pop | |
3929 | a2d2e1a7 | Iustin Pop | def Extend(self, other_set): |
3930 | a2d2e1a7 | Iustin Pop | """Extend the field set with the items from another one"""
|
3931 | a2d2e1a7 | Iustin Pop | self.items.extend(other_set.items)
|
3932 | a2d2e1a7 | Iustin Pop | |
3933 | a2d2e1a7 | Iustin Pop | def Matches(self, field): |
3934 | a2d2e1a7 | Iustin Pop | """Checks if a field matches the current set
|
3935 | a2d2e1a7 | Iustin Pop |
|
3936 | a2d2e1a7 | Iustin Pop | @type field: str
|
3937 | a2d2e1a7 | Iustin Pop | @param field: the string to match
|
3938 | 6c881c52 | Iustin Pop | @return: either None or a regular expression match object
|
3939 | a2d2e1a7 | Iustin Pop |
|
3940 | a2d2e1a7 | Iustin Pop | """
|
3941 | a2d2e1a7 | Iustin Pop | for m in itertools.ifilter(None, (val.match(field) for val in self.items)): |
3942 | a2d2e1a7 | Iustin Pop | return m
|
3943 | 6c881c52 | Iustin Pop | return None |
3944 | a2d2e1a7 | Iustin Pop | |
3945 | a2d2e1a7 | Iustin Pop | def NonMatching(self, items): |
3946 | a2d2e1a7 | Iustin Pop | """Returns the list of fields not matching the current set
|
3947 | a2d2e1a7 | Iustin Pop |
|
3948 | a2d2e1a7 | Iustin Pop | @type items: list
|
3949 | a2d2e1a7 | Iustin Pop | @param items: the list of fields to check
|
3950 | a2d2e1a7 | Iustin Pop | @rtype: list
|
3951 | a2d2e1a7 | Iustin Pop | @return: list of non-matching fields
|
3952 | a2d2e1a7 | Iustin Pop |
|
3953 | a2d2e1a7 | Iustin Pop | """
|
3954 | a2d2e1a7 | Iustin Pop | return [val for val in items if not self.Matches(val)] |