More documentation.
[nodemanager.git] / tools.py
1 import cPickle
2 import errno
3 import os
4 import pwd
5 import tempfile
6 import threading
7
8 from config import PID_FILE
9 import logger
10
11
12 def as_daemon_thread(run):
13     """Call function <run> with no arguments in its own thread."""
14     thr = threading.Thread(target=run)
15     thr.setDaemon(True)
16     thr.start()
17
18
19 def close_nonstandard_fds():
20     """Close all open file descriptors other than 0, 1, and 2."""
21     _SC_OPEN_MAX = 4
22     for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
23         try: os.close(fd)
24         except OSError: pass  # most likely an fd that isn't open
25
26
27 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
28 def daemon():
29     """Daemonize the current process."""
30     if os.fork() != 0: os._exit(0)
31     os.setsid()
32     if os.fork() != 0: os._exit(0)
33     os.chdir('/')
34     os.umask(0)
35     devnull = os.open(os.devnull, os.O_RDWR)
36     for fd in range(3): os.dup2(devnull, fd)
37
38
39 def deepcopy(obj):
40     """Return a deep copy of obj."""
41     return cPickle.loads(cPickle.dumps(obj, -1))
42
43
44 def fork_as(su, function, *args):
45     """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."""
46     child_pid = os.fork()
47     if child_pid == 0:
48         try:
49             os.chdir('/')
50             close_nonstandard_fds()
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
64 def pid_file():
65     """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."""
66     other_pid = None
67     # check for a pid file
68     if os.access(PID_FILE, os.F_OK):
69         # pid file exists, read it
70         handle = open(PID_FILE)
71         other_pid = int(handle.read())
72         handle.close()
73         # check for a process with that pid by sending signal 0
74         try: os.kill(other_pid, 0)
75         except OSError, e:
76             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
77             else: raise  # who knows
78     if other_pid == None:
79         # write a new pid file
80         write_file(PID_FILE, lambda thefile: thefile.write(str(os.getpid())))
81     return other_pid
82
83
84 def write_file(filename, do_write):
85     """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
86     os.rename(write_temp_file(do_write), filename)
87
88
89 def write_temp_file(do_write):
90     fd, temporary_filename = tempfile.mkstemp()
91     thefile = os.fdopen(fd, 'w')
92     do_write(thefile)
93     thefile.close()
94     return temporary_filename