Take the new doc out of the branch and into trunk
[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
10 import logger
11
12
13 PID_FILE = '/var/run/nm.pid'
14
15 def as_daemon_thread(run):
16     """Call function <run> with no arguments in its own thread."""
17     thr = threading.Thread(target=run)
18     thr.setDaemon(True)
19     thr.start()
20
21 def close_nonstandard_fds():
22     """Close all open file descriptors other than 0, 1, and 2."""
23     _SC_OPEN_MAX = 4
24     for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
25         try: os.close(fd)
26         except OSError: pass  # most likely an fd that isn't open
27
28 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
29 def daemon():
30     """Daemonize the current process."""
31     if os.fork() != 0: os._exit(0)
32     os.setsid()
33     if os.fork() != 0: os._exit(0)
34     os.chdir('/')
35     os.umask(0)
36     devnull = os.open(os.devnull, os.O_RDWR)
37     os.dup2(devnull, 0)
38     crashlog = os.open('/root/nm.stderr', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
39     os.dup2(crashlog, 1)
40     os.dup2(crashlog, 2)
41
42 def fork_as(su, function, *args):
43     """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."""
44     child_pid = os.fork()
45     if child_pid == 0:
46         try:
47             os.chdir('/')
48             close_nonstandard_fds()
49             if su:
50                 pw_ent = pwd.getpwnam(su)
51                 os.setegid(pw_ent[3])
52                 os.seteuid(pw_ent[2])
53             child_pid = os.fork()
54             if child_pid == 0: function(*args)
55         except:
56             os.seteuid(os.getuid())  # undo su so we can write the log file
57             os.setegid(os.getgid())
58             logger.log_exc()
59         os._exit(0)
60     else: os.waitpid(child_pid, 0)
61
62 def pid_file():
63     """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."""
64     other_pid = None
65     if os.access(PID_FILE, os.F_OK):  # check for a pid file
66         handle = open(PID_FILE)  # pid file exists, read it
67         other_pid = int(handle.read())
68         handle.close()
69         # check for a process with that pid by sending signal 0
70         try: os.kill(other_pid, 0)
71         except OSError, e:
72             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
73             else: raise  # who knows
74     if other_pid == None:
75         # write a new pid file
76         write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
77     return other_pid
78
79 def write_file(filename, do_write, **kw_args):
80     """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
81     os.rename(write_temp_file(do_write, **kw_args), filename)
82
83 def write_temp_file(do_write, mode=None, uidgid=None):
84     fd, temporary_filename = tempfile.mkstemp()
85     if mode: os.chmod(temporary_filename, mode)
86     if uidgid: os.chown(temporary_filename, *uidgid)
87     f = os.fdopen(fd, 'w')
88     try: do_write(f)
89     finally: f.close()
90     return temporary_filename