root / lib / utils / io.py @ 437c3e77
History | View | Annotate | Download (20.4 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2010, 2011 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
"""Utility functions for I/O.
|
22 |
|
23 |
"""
|
24 |
|
25 |
import os |
26 |
import logging |
27 |
import shutil |
28 |
import tempfile |
29 |
import errno |
30 |
import time |
31 |
|
32 |
from ganeti import errors |
33 |
from ganeti import constants |
34 |
from ganeti.utils import filelock |
35 |
|
36 |
|
37 |
#: Path generating random UUID
|
38 |
_RANDOM_UUID_FILE = "/proc/sys/kernel/random/uuid"
|
39 |
|
40 |
|
41 |
def ReadFile(file_name, size=-1): |
42 |
"""Reads a file.
|
43 |
|
44 |
@type size: int
|
45 |
@param size: Read at most size bytes (if negative, entire file)
|
46 |
@rtype: str
|
47 |
@return: the (possibly partial) content of the file
|
48 |
|
49 |
"""
|
50 |
f = open(file_name, "r") |
51 |
try:
|
52 |
return f.read(size)
|
53 |
finally:
|
54 |
f.close() |
55 |
|
56 |
|
57 |
def WriteFile(file_name, fn=None, data=None, |
58 |
mode=None, uid=-1, gid=-1, |
59 |
atime=None, mtime=None, close=True, |
60 |
dry_run=False, backup=False, |
61 |
prewrite=None, postwrite=None): |
62 |
"""(Over)write a file atomically.
|
63 |
|
64 |
The file_name and either fn (a function taking one argument, the
|
65 |
file descriptor, and which should write the data to it) or data (the
|
66 |
contents of the file) must be passed. The other arguments are
|
67 |
optional and allow setting the file mode, owner and group, and the
|
68 |
mtime/atime of the file.
|
69 |
|
70 |
If the function doesn't raise an exception, it has succeeded and the
|
71 |
target file has the new contents. If the function has raised an
|
72 |
exception, an existing target file should be unmodified and the
|
73 |
temporary file should be removed.
|
74 |
|
75 |
@type file_name: str
|
76 |
@param file_name: the target filename
|
77 |
@type fn: callable
|
78 |
@param fn: content writing function, called with
|
79 |
file descriptor as parameter
|
80 |
@type data: str
|
81 |
@param data: contents of the file
|
82 |
@type mode: int
|
83 |
@param mode: file mode
|
84 |
@type uid: int
|
85 |
@param uid: the owner of the file
|
86 |
@type gid: int
|
87 |
@param gid: the group of the file
|
88 |
@type atime: int
|
89 |
@param atime: a custom access time to be set on the file
|
90 |
@type mtime: int
|
91 |
@param mtime: a custom modification time to be set on the file
|
92 |
@type close: boolean
|
93 |
@param close: whether to close file after writing it
|
94 |
@type prewrite: callable
|
95 |
@param prewrite: function to be called before writing content
|
96 |
@type postwrite: callable
|
97 |
@param postwrite: function to be called after writing content
|
98 |
|
99 |
@rtype: None or int
|
100 |
@return: None if the 'close' parameter evaluates to True,
|
101 |
otherwise the file descriptor
|
102 |
|
103 |
@raise errors.ProgrammerError: if any of the arguments are not valid
|
104 |
|
105 |
"""
|
106 |
if not os.path.isabs(file_name): |
107 |
raise errors.ProgrammerError("Path passed to WriteFile is not" |
108 |
" absolute: '%s'" % file_name)
|
109 |
|
110 |
if [fn, data].count(None) != 1: |
111 |
raise errors.ProgrammerError("fn or data required") |
112 |
|
113 |
if [atime, mtime].count(None) == 1: |
114 |
raise errors.ProgrammerError("Both atime and mtime must be either" |
115 |
" set or None")
|
116 |
|
117 |
if backup and not dry_run and os.path.isfile(file_name): |
118 |
CreateBackup(file_name) |
119 |
|
120 |
# Whether temporary file needs to be removed (e.g. if any error occurs)
|
121 |
do_remove = True
|
122 |
|
123 |
# Function result
|
124 |
result = None
|
125 |
|
126 |
(dir_name, base_name) = os.path.split(file_name) |
127 |
(fd, new_name) = tempfile.mkstemp(suffix=".new", prefix=base_name,
|
128 |
dir=dir_name) |
129 |
try:
|
130 |
try:
|
131 |
if uid != -1 or gid != -1: |
132 |
os.chown(new_name, uid, gid) |
133 |
if mode:
|
134 |
os.chmod(new_name, mode) |
135 |
if callable(prewrite): |
136 |
prewrite(fd) |
137 |
if data is not None: |
138 |
to_write = len(data)
|
139 |
offset = 0
|
140 |
while offset < to_write:
|
141 |
written = os.write(fd, buffer(data, offset))
|
142 |
assert written >= 0 |
143 |
offset += written |
144 |
assert offset == to_write
|
145 |
else:
|
146 |
fn(fd) |
147 |
if callable(postwrite): |
148 |
postwrite(fd) |
149 |
os.fsync(fd) |
150 |
if atime is not None and mtime is not None: |
151 |
os.utime(new_name, (atime, mtime)) |
152 |
finally:
|
153 |
# Close file unless the file descriptor should be returned
|
154 |
if close:
|
155 |
os.close(fd) |
156 |
else:
|
157 |
result = fd |
158 |
|
159 |
# Rename file to destination name
|
160 |
if not dry_run: |
161 |
os.rename(new_name, file_name) |
162 |
# Successful, no need to remove anymore
|
163 |
do_remove = False
|
164 |
finally:
|
165 |
if do_remove:
|
166 |
RemoveFile(new_name) |
167 |
|
168 |
return result
|
169 |
|
170 |
|
171 |
def GetFileID(path=None, fd=None): |
172 |
"""Returns the file 'id', i.e. the dev/inode and mtime information.
|
173 |
|
174 |
Either the path to the file or the fd must be given.
|
175 |
|
176 |
@param path: the file path
|
177 |
@param fd: a file descriptor
|
178 |
@return: a tuple of (device number, inode number, mtime)
|
179 |
|
180 |
"""
|
181 |
if [path, fd].count(None) != 1: |
182 |
raise errors.ProgrammerError("One and only one of fd/path must be given") |
183 |
|
184 |
if fd is None: |
185 |
st = os.stat(path) |
186 |
else:
|
187 |
st = os.fstat(fd) |
188 |
|
189 |
return (st.st_dev, st.st_ino, st.st_mtime)
|
190 |
|
191 |
|
192 |
def VerifyFileID(fi_disk, fi_ours): |
193 |
"""Verifies that two file IDs are matching.
|
194 |
|
195 |
Differences in the inode/device are not accepted, but and older
|
196 |
timestamp for fi_disk is accepted.
|
197 |
|
198 |
@param fi_disk: tuple (dev, inode, mtime) representing the actual
|
199 |
file data
|
200 |
@param fi_ours: tuple (dev, inode, mtime) representing the last
|
201 |
written file data
|
202 |
@rtype: boolean
|
203 |
|
204 |
"""
|
205 |
(d1, i1, m1) = fi_disk |
206 |
(d2, i2, m2) = fi_ours |
207 |
|
208 |
return (d1, i1) == (d2, i2) and m1 <= m2 |
209 |
|
210 |
|
211 |
def SafeWriteFile(file_name, file_id, **kwargs): |
212 |
"""Wraper over L{WriteFile} that locks the target file.
|
213 |
|
214 |
By keeping the target file locked during WriteFile, we ensure that
|
215 |
cooperating writers will safely serialise access to the file.
|
216 |
|
217 |
@type file_name: str
|
218 |
@param file_name: the target filename
|
219 |
@type file_id: tuple
|
220 |
@param file_id: a result from L{GetFileID}
|
221 |
|
222 |
"""
|
223 |
fd = os.open(file_name, os.O_RDONLY | os.O_CREAT) |
224 |
try:
|
225 |
filelock.LockFile(fd) |
226 |
if file_id is not None: |
227 |
disk_id = GetFileID(fd=fd) |
228 |
if not VerifyFileID(disk_id, file_id): |
229 |
raise errors.LockError("Cannot overwrite file %s, it has been modified" |
230 |
" since last written" % file_name)
|
231 |
return WriteFile(file_name, **kwargs)
|
232 |
finally:
|
233 |
os.close(fd) |
234 |
|
235 |
|
236 |
def ReadOneLineFile(file_name, strict=False): |
237 |
"""Return the first non-empty line from a file.
|
238 |
|
239 |
@type strict: boolean
|
240 |
@param strict: if True, abort if the file has more than one
|
241 |
non-empty line
|
242 |
|
243 |
"""
|
244 |
file_lines = ReadFile(file_name).splitlines() |
245 |
full_lines = filter(bool, file_lines) |
246 |
if not file_lines or not full_lines: |
247 |
raise errors.GenericError("No data in one-liner file %s" % file_name) |
248 |
elif strict and len(full_lines) > 1: |
249 |
raise errors.GenericError("Too many lines in one-liner file %s" % |
250 |
file_name) |
251 |
return full_lines[0] |
252 |
|
253 |
|
254 |
def RemoveFile(filename): |
255 |
"""Remove a file ignoring some errors.
|
256 |
|
257 |
Remove a file, ignoring non-existing ones or directories. Other
|
258 |
errors are passed.
|
259 |
|
260 |
@type filename: str
|
261 |
@param filename: the file to be removed
|
262 |
|
263 |
"""
|
264 |
try:
|
265 |
os.unlink(filename) |
266 |
except OSError, err: |
267 |
if err.errno not in (errno.ENOENT, errno.EISDIR): |
268 |
raise
|
269 |
|
270 |
|
271 |
def RemoveDir(dirname): |
272 |
"""Remove an empty directory.
|
273 |
|
274 |
Remove a directory, ignoring non-existing ones.
|
275 |
Other errors are passed. This includes the case,
|
276 |
where the directory is not empty, so it can't be removed.
|
277 |
|
278 |
@type dirname: str
|
279 |
@param dirname: the empty directory to be removed
|
280 |
|
281 |
"""
|
282 |
try:
|
283 |
os.rmdir(dirname) |
284 |
except OSError, err: |
285 |
if err.errno != errno.ENOENT:
|
286 |
raise
|
287 |
|
288 |
|
289 |
def RenameFile(old, new, mkdir=False, mkdir_mode=0750): |
290 |
"""Renames a file.
|
291 |
|
292 |
@type old: string
|
293 |
@param old: Original path
|
294 |
@type new: string
|
295 |
@param new: New path
|
296 |
@type mkdir: bool
|
297 |
@param mkdir: Whether to create target directory if it doesn't exist
|
298 |
@type mkdir_mode: int
|
299 |
@param mkdir_mode: Mode for newly created directories
|
300 |
|
301 |
"""
|
302 |
try:
|
303 |
return os.rename(old, new)
|
304 |
except OSError, err: |
305 |
# In at least one use case of this function, the job queue, directory
|
306 |
# creation is very rare. Checking for the directory before renaming is not
|
307 |
# as efficient.
|
308 |
if mkdir and err.errno == errno.ENOENT: |
309 |
# Create directory and try again
|
310 |
Makedirs(os.path.dirname(new), mode=mkdir_mode) |
311 |
|
312 |
return os.rename(old, new)
|
313 |
|
314 |
raise
|
315 |
|
316 |
|
317 |
def Makedirs(path, mode=0750): |
318 |
"""Super-mkdir; create a leaf directory and all intermediate ones.
|
319 |
|
320 |
This is a wrapper around C{os.makedirs} adding error handling not implemented
|
321 |
before Python 2.5.
|
322 |
|
323 |
"""
|
324 |
try:
|
325 |
os.makedirs(path, mode) |
326 |
except OSError, err: |
327 |
# Ignore EEXIST. This is only handled in os.makedirs as included in
|
328 |
# Python 2.5 and above.
|
329 |
if err.errno != errno.EEXIST or not os.path.exists(path): |
330 |
raise
|
331 |
|
332 |
|
333 |
def TimestampForFilename(): |
334 |
"""Returns the current time formatted for filenames.
|
335 |
|
336 |
The format doesn't contain colons as some shells and applications treat them
|
337 |
as separators. Uses the local timezone.
|
338 |
|
339 |
"""
|
340 |
return time.strftime("%Y-%m-%d_%H_%M_%S") |
341 |
|
342 |
|
343 |
def CreateBackup(file_name): |
344 |
"""Creates a backup of a file.
|
345 |
|
346 |
@type file_name: str
|
347 |
@param file_name: file to be backed up
|
348 |
@rtype: str
|
349 |
@return: the path to the newly created backup
|
350 |
@raise errors.ProgrammerError: for invalid file names
|
351 |
|
352 |
"""
|
353 |
if not os.path.isfile(file_name): |
354 |
raise errors.ProgrammerError("Can't make a backup of a non-file '%s'" % |
355 |
file_name) |
356 |
|
357 |
prefix = ("%s.backup-%s." %
|
358 |
(os.path.basename(file_name), TimestampForFilename())) |
359 |
dir_name = os.path.dirname(file_name) |
360 |
|
361 |
fsrc = open(file_name, 'rb') |
362 |
try:
|
363 |
(fd, backup_name) = tempfile.mkstemp(prefix=prefix, dir=dir_name) |
364 |
fdst = os.fdopen(fd, 'wb')
|
365 |
try:
|
366 |
logging.debug("Backing up %s at %s", file_name, backup_name)
|
367 |
shutil.copyfileobj(fsrc, fdst) |
368 |
finally:
|
369 |
fdst.close() |
370 |
finally:
|
371 |
fsrc.close() |
372 |
|
373 |
return backup_name
|
374 |
|
375 |
|
376 |
def ListVisibleFiles(path): |
377 |
"""Returns a list of visible files in a directory.
|
378 |
|
379 |
@type path: str
|
380 |
@param path: the directory to enumerate
|
381 |
@rtype: list
|
382 |
@return: the list of all files not starting with a dot
|
383 |
@raise ProgrammerError: if L{path} is not an absolue and normalized path
|
384 |
|
385 |
"""
|
386 |
if not IsNormAbsPath(path): |
387 |
raise errors.ProgrammerError("Path passed to ListVisibleFiles is not" |
388 |
" absolute/normalized: '%s'" % path)
|
389 |
files = [i for i in os.listdir(path) if not i.startswith(".")] |
390 |
return files
|
391 |
|
392 |
|
393 |
def EnsureDirs(dirs): |
394 |
"""Make required directories, if they don't exist.
|
395 |
|
396 |
@param dirs: list of tuples (dir_name, dir_mode)
|
397 |
@type dirs: list of (string, integer)
|
398 |
|
399 |
"""
|
400 |
for dir_name, dir_mode in dirs: |
401 |
try:
|
402 |
os.mkdir(dir_name, dir_mode) |
403 |
except EnvironmentError, err: |
404 |
if err.errno != errno.EEXIST:
|
405 |
raise errors.GenericError("Cannot create needed directory" |
406 |
" '%s': %s" % (dir_name, err))
|
407 |
try:
|
408 |
os.chmod(dir_name, dir_mode) |
409 |
except EnvironmentError, err: |
410 |
raise errors.GenericError("Cannot change directory permissions on" |
411 |
" '%s': %s" % (dir_name, err))
|
412 |
if not os.path.isdir(dir_name): |
413 |
raise errors.GenericError("%s is not a directory" % dir_name) |
414 |
|
415 |
|
416 |
def FindFile(name, search_path, test=os.path.exists): |
417 |
"""Look for a filesystem object in a given path.
|
418 |
|
419 |
This is an abstract method to search for filesystem object (files,
|
420 |
dirs) under a given search path.
|
421 |
|
422 |
@type name: str
|
423 |
@param name: the name to look for
|
424 |
@type search_path: str
|
425 |
@param search_path: location to start at
|
426 |
@type test: callable
|
427 |
@param test: a function taking one argument that should return True
|
428 |
if the a given object is valid; the default value is
|
429 |
os.path.exists, causing only existing files to be returned
|
430 |
@rtype: str or None
|
431 |
@return: full path to the object if found, None otherwise
|
432 |
|
433 |
"""
|
434 |
# validate the filename mask
|
435 |
if constants.EXT_PLUGIN_MASK.match(name) is None: |
436 |
logging.critical("Invalid value passed for external script name: '%s'",
|
437 |
name) |
438 |
return None |
439 |
|
440 |
for dir_name in search_path: |
441 |
# FIXME: investigate switch to PathJoin
|
442 |
item_name = os.path.sep.join([dir_name, name]) |
443 |
# check the user test and that we're indeed resolving to the given
|
444 |
# basename
|
445 |
if test(item_name) and os.path.basename(item_name) == name: |
446 |
return item_name
|
447 |
return None |
448 |
|
449 |
|
450 |
def IsNormAbsPath(path): |
451 |
"""Check whether a path is absolute and also normalized
|
452 |
|
453 |
This avoids things like /dir/../../other/path to be valid.
|
454 |
|
455 |
"""
|
456 |
return os.path.normpath(path) == path and os.path.isabs(path) |
457 |
|
458 |
|
459 |
def PathJoin(*args): |
460 |
"""Safe-join a list of path components.
|
461 |
|
462 |
Requirements:
|
463 |
- the first argument must be an absolute path
|
464 |
- no component in the path must have backtracking (e.g. /../),
|
465 |
since we check for normalization at the end
|
466 |
|
467 |
@param args: the path components to be joined
|
468 |
@raise ValueError: for invalid paths
|
469 |
|
470 |
"""
|
471 |
# ensure we're having at least one path passed in
|
472 |
assert args
|
473 |
# ensure the first component is an absolute and normalized path name
|
474 |
root = args[0]
|
475 |
if not IsNormAbsPath(root): |
476 |
raise ValueError("Invalid parameter to PathJoin: '%s'" % str(args[0])) |
477 |
result = os.path.join(*args) |
478 |
# ensure that the whole path is normalized
|
479 |
if not IsNormAbsPath(result): |
480 |
raise ValueError("Invalid parameters to PathJoin: '%s'" % str(args)) |
481 |
# check that we're still under the original prefix
|
482 |
prefix = os.path.commonprefix([root, result]) |
483 |
if prefix != root:
|
484 |
raise ValueError("Error: path joining resulted in different prefix" |
485 |
" (%s != %s)" % (prefix, root))
|
486 |
return result
|
487 |
|
488 |
|
489 |
def TailFile(fname, lines=20): |
490 |
"""Return the last lines from a file.
|
491 |
|
492 |
@note: this function will only read and parse the last 4KB of
|
493 |
the file; if the lines are very long, it could be that less
|
494 |
than the requested number of lines are returned
|
495 |
|
496 |
@param fname: the file name
|
497 |
@type lines: int
|
498 |
@param lines: the (maximum) number of lines to return
|
499 |
|
500 |
"""
|
501 |
fd = open(fname, "r") |
502 |
try:
|
503 |
fd.seek(0, 2) |
504 |
pos = fd.tell() |
505 |
pos = max(0, pos-4096) |
506 |
fd.seek(pos, 0)
|
507 |
raw_data = fd.read() |
508 |
finally:
|
509 |
fd.close() |
510 |
|
511 |
rows = raw_data.splitlines() |
512 |
return rows[-lines:]
|
513 |
|
514 |
|
515 |
def BytesToMebibyte(value): |
516 |
"""Converts bytes to mebibytes.
|
517 |
|
518 |
@type value: int
|
519 |
@param value: Value in bytes
|
520 |
@rtype: int
|
521 |
@return: Value in mebibytes
|
522 |
|
523 |
"""
|
524 |
return int(round(value / (1024.0 * 1024.0), 0)) |
525 |
|
526 |
|
527 |
def CalculateDirectorySize(path): |
528 |
"""Calculates the size of a directory recursively.
|
529 |
|
530 |
@type path: string
|
531 |
@param path: Path to directory
|
532 |
@rtype: int
|
533 |
@return: Size in mebibytes
|
534 |
|
535 |
"""
|
536 |
size = 0
|
537 |
|
538 |
for (curpath, _, files) in os.walk(path): |
539 |
for filename in files: |
540 |
st = os.lstat(PathJoin(curpath, filename)) |
541 |
size += st.st_size |
542 |
|
543 |
return BytesToMebibyte(size)
|
544 |
|
545 |
|
546 |
def GetFilesystemStats(path): |
547 |
"""Returns the total and free space on a filesystem.
|
548 |
|
549 |
@type path: string
|
550 |
@param path: Path on filesystem to be examined
|
551 |
@rtype: int
|
552 |
@return: tuple of (Total space, Free space) in mebibytes
|
553 |
|
554 |
"""
|
555 |
st = os.statvfs(path) |
556 |
|
557 |
fsize = BytesToMebibyte(st.f_bavail * st.f_frsize) |
558 |
tsize = BytesToMebibyte(st.f_blocks * st.f_frsize) |
559 |
return (tsize, fsize)
|
560 |
|
561 |
|
562 |
def ReadPidFile(pidfile): |
563 |
"""Read a pid from a file.
|
564 |
|
565 |
@type pidfile: string
|
566 |
@param pidfile: path to the file containing the pid
|
567 |
@rtype: int
|
568 |
@return: The process id, if the file exists and contains a valid PID,
|
569 |
otherwise 0
|
570 |
|
571 |
"""
|
572 |
try:
|
573 |
raw_data = ReadOneLineFile(pidfile) |
574 |
except EnvironmentError, err: |
575 |
if err.errno != errno.ENOENT:
|
576 |
logging.exception("Can't read pid file")
|
577 |
return 0 |
578 |
|
579 |
try:
|
580 |
pid = int(raw_data)
|
581 |
except (TypeError, ValueError), err: |
582 |
logging.info("Can't parse pid file contents", exc_info=True) |
583 |
return 0 |
584 |
|
585 |
return pid
|
586 |
|
587 |
|
588 |
def ReadLockedPidFile(path): |
589 |
"""Reads a locked PID file.
|
590 |
|
591 |
This can be used together with L{utils.process.StartDaemon}.
|
592 |
|
593 |
@type path: string
|
594 |
@param path: Path to PID file
|
595 |
@return: PID as integer or, if file was unlocked or couldn't be opened, None
|
596 |
|
597 |
"""
|
598 |
try:
|
599 |
fd = os.open(path, os.O_RDONLY) |
600 |
except EnvironmentError, err: |
601 |
if err.errno == errno.ENOENT:
|
602 |
# PID file doesn't exist
|
603 |
return None |
604 |
raise
|
605 |
|
606 |
try:
|
607 |
try:
|
608 |
# Try to acquire lock
|
609 |
filelock.LockFile(fd) |
610 |
except errors.LockError:
|
611 |
# Couldn't lock, daemon is running
|
612 |
return int(os.read(fd, 100)) |
613 |
finally:
|
614 |
os.close(fd) |
615 |
|
616 |
return None |
617 |
|
618 |
|
619 |
def AddAuthorizedKey(file_obj, key): |
620 |
"""Adds an SSH public key to an authorized_keys file.
|
621 |
|
622 |
@type file_obj: str or file handle
|
623 |
@param file_obj: path to authorized_keys file
|
624 |
@type key: str
|
625 |
@param key: string containing key
|
626 |
|
627 |
"""
|
628 |
key_fields = key.split() |
629 |
|
630 |
if isinstance(file_obj, basestring): |
631 |
f = open(file_obj, 'a+') |
632 |
else:
|
633 |
f = file_obj |
634 |
|
635 |
try:
|
636 |
nl = True
|
637 |
for line in f: |
638 |
# Ignore whitespace changes
|
639 |
if line.split() == key_fields:
|
640 |
break
|
641 |
nl = line.endswith('\n')
|
642 |
else:
|
643 |
if not nl: |
644 |
f.write("\n")
|
645 |
f.write(key.rstrip('\r\n'))
|
646 |
f.write("\n")
|
647 |
f.flush() |
648 |
finally:
|
649 |
f.close() |
650 |
|
651 |
|
652 |
def RemoveAuthorizedKey(file_name, key): |
653 |
"""Removes an SSH public key from an authorized_keys file.
|
654 |
|
655 |
@type file_name: str
|
656 |
@param file_name: path to authorized_keys file
|
657 |
@type key: str
|
658 |
@param key: string containing key
|
659 |
|
660 |
"""
|
661 |
key_fields = key.split() |
662 |
|
663 |
fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name)) |
664 |
try:
|
665 |
out = os.fdopen(fd, 'w')
|
666 |
try:
|
667 |
f = open(file_name, 'r') |
668 |
try:
|
669 |
for line in f: |
670 |
# Ignore whitespace changes while comparing lines
|
671 |
if line.split() != key_fields:
|
672 |
out.write(line) |
673 |
|
674 |
out.flush() |
675 |
os.rename(tmpname, file_name) |
676 |
finally:
|
677 |
f.close() |
678 |
finally:
|
679 |
out.close() |
680 |
except:
|
681 |
RemoveFile(tmpname) |
682 |
raise
|
683 |
|
684 |
|
685 |
def DaemonPidFileName(name): |
686 |
"""Compute a ganeti pid file absolute path
|
687 |
|
688 |
@type name: str
|
689 |
@param name: the daemon name
|
690 |
@rtype: str
|
691 |
@return: the full path to the pidfile corresponding to the given
|
692 |
daemon name
|
693 |
|
694 |
"""
|
695 |
return PathJoin(constants.RUN_GANETI_DIR, "%s.pid" % name) |
696 |
|
697 |
|
698 |
def WritePidFile(pidfile): |
699 |
"""Write the current process pidfile.
|
700 |
|
701 |
@type pidfile: string
|
702 |
@param pidfile: the path to the file to be written
|
703 |
@raise errors.LockError: if the pid file already exists and
|
704 |
points to a live process
|
705 |
@rtype: int
|
706 |
@return: the file descriptor of the lock file; do not close this unless
|
707 |
you want to unlock the pid file
|
708 |
|
709 |
"""
|
710 |
# We don't rename nor truncate the file to not drop locks under
|
711 |
# existing processes
|
712 |
fd_pidfile = os.open(pidfile, os.O_WRONLY | os.O_CREAT, 0600)
|
713 |
|
714 |
# Lock the PID file (and fail if not possible to do so). Any code
|
715 |
# wanting to send a signal to the daemon should try to lock the PID
|
716 |
# file before reading it. If acquiring the lock succeeds, the daemon is
|
717 |
# no longer running and the signal should not be sent.
|
718 |
filelock.LockFile(fd_pidfile) |
719 |
|
720 |
os.write(fd_pidfile, "%d\n" % os.getpid())
|
721 |
|
722 |
return fd_pidfile
|
723 |
|
724 |
|
725 |
def ReadWatcherPauseFile(filename, now=None, remove_after=3600): |
726 |
"""Reads the watcher pause file.
|
727 |
|
728 |
@type filename: string
|
729 |
@param filename: Path to watcher pause file
|
730 |
@type now: None, float or int
|
731 |
@param now: Current time as Unix timestamp
|
732 |
@type remove_after: int
|
733 |
@param remove_after: Remove watcher pause file after specified amount of
|
734 |
seconds past the pause end time
|
735 |
|
736 |
"""
|
737 |
if now is None: |
738 |
now = time.time() |
739 |
|
740 |
try:
|
741 |
value = ReadFile(filename) |
742 |
except IOError, err: |
743 |
if err.errno != errno.ENOENT:
|
744 |
raise
|
745 |
value = None
|
746 |
|
747 |
if value is not None: |
748 |
try:
|
749 |
value = int(value)
|
750 |
except ValueError: |
751 |
logging.warning(("Watcher pause file (%s) contains invalid value,"
|
752 |
" removing it"), filename)
|
753 |
RemoveFile(filename) |
754 |
value = None
|
755 |
|
756 |
if value is not None: |
757 |
# Remove file if it's outdated
|
758 |
if now > (value + remove_after):
|
759 |
RemoveFile(filename) |
760 |
value = None
|
761 |
|
762 |
elif now > value:
|
763 |
value = None
|
764 |
|
765 |
return value
|
766 |
|
767 |
|
768 |
def NewUUID(): |
769 |
"""Returns a random UUID.
|
770 |
|
771 |
@note: This is a Linux-specific method as it uses the /proc
|
772 |
filesystem.
|
773 |
@rtype: str
|
774 |
|
775 |
"""
|
776 |
return ReadFile(_RANDOM_UUID_FILE, size=128).rstrip("\n") |