Added ReCreate. Also added try catch to api eval of rpc method.
[nodemanager.git] / tools.py
1 """A few things that didn't seem to fit anywhere else."""
2
3 import cPickle
4 import errno
5 import os
6 import pwd
7 import tempfile
8 import threading
9 import fcntl
10
11 import logger
12
13
14 PID_FILE = '/var/run/nm.pid'
15
16 def as_daemon_thread(run):
17     """Call function <run> with no arguments in its own thread."""
18     thr = threading.Thread(target=run)
19     thr.setDaemon(True)
20     thr.start()
21
22 def close_nonstandard_fds():
23     """Close all open file descriptors other than 0, 1, and 2."""
24     _SC_OPEN_MAX = 4
25     for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
26         try: os.close(fd)
27         except OSError: pass  # most likely an fd that isn't open
28
29 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
30 def daemon():
31     """Daemonize the current process."""
32     if os.fork() != 0: os._exit(0)
33     os.setsid()
34     if os.fork() != 0: os._exit(0)
35     os.chdir('/')
36     os.umask(0)
37     devnull = os.open(os.devnull, os.O_RDWR)
38     os.dup2(devnull, 0)
39     crashlog = os.open('/root/nm.stderr', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
40     os.dup2(crashlog, 1)
41     os.dup2(crashlog, 2)
42
43 def fork_as(su, function, *args):
44     """fork(), cd / to avoid keeping unused directories open, close all nonstandard file descriptors (to avoid capturing open sockets), fork() again (to avoid zombies) and call <function> with arguments <args> in the grandchild process.  If <su> is not None, set our group and user ids appropriately in the child process."""
45     child_pid = os.fork()
46     if child_pid == 0:
47         try:
48             os.chdir('/')
49             close_nonstandard_fds()
50             if su:
51                 pw_ent = pwd.getpwnam(su)
52                 os.setegid(pw_ent[3])
53                 os.seteuid(pw_ent[2])
54             child_pid = os.fork()
55             if child_pid == 0: function(*args)
56         except:
57             os.seteuid(os.getuid())  # undo su so we can write the log file
58             os.setegid(os.getgid())
59             logger.log_exc()
60         os._exit(0)
61     else: os.waitpid(child_pid, 0)
62
63 def pid_file():
64     """We use a pid file to ensure that only one copy of NM is running at a given time.  If successful, this function will write a pid file containing the pid of the current process.  The return value is the pid of the other running process, or None otherwise."""
65     other_pid = None
66     if os.access(PID_FILE, os.F_OK):  # check for a pid file
67         handle = open(PID_FILE)  # pid file exists, read it
68         other_pid = int(handle.read())
69         handle.close()
70         # check for a process with that pid by sending signal 0
71         try: os.kill(other_pid, 0)
72         except OSError, e:
73             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
74             else: raise  # who knows
75     if other_pid == None:
76         # write a new pid file
77         write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
78     return other_pid
79
80 def write_file(filename, do_write, **kw_args):
81     """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
82     os.rename(write_temp_file(do_write, **kw_args), filename)
83
84 def write_temp_file(do_write, mode=None, uidgid=None):
85     fd, temporary_filename = tempfile.mkstemp()
86     if mode: os.chmod(temporary_filename, mode)
87     if uidgid: os.chown(temporary_filename, *uidgid)
88     f = os.fdopen(fd, 'w')
89     try: do_write(f)
90     finally: f.close()
91     return temporary_filename
92
93
94 class NMLock:
95     def __init__(self, file):
96         self.fd = os.open(file, os.O_RDWR|os.O_CREAT, 0600)
97         flags = fcntl.fcntl(self.fd, fcntl.F_GETFD)
98         flags |= fcntl.FD_CLOEXEC
99         fcntl.fcntl(self.fd, fcntl.F_SETFD, flags)
100     def __del__(self):
101         os.close(self.fd)
102     def acquire(self):
103         fcntl.lockf(self.fd, fcntl.LOCK_EX)
104     def release(self):
105         fcntl.lockf(self.fd, fcntl.LOCK_UN)