First version. Most definitely a work in progress.
[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     thr = threading.Thread(target=run)
14     thr.setDaemon(True)
15     thr.start()
16
17
18 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
19 def daemon():
20     """Daemonize the current process."""
21     if os.fork() != 0: os._exit(0)
22     os.setsid()
23     if os.fork() != 0: os._exit(0)
24     os.chdir('/')
25     os.umask(0)
26     devnull = os.open(os.devnull, os.O_RDWR)
27     for fd in range(3): os.dup2(devnull, fd)
28
29
30 def deepcopy(obj):
31     """Return a deep copy of obj."""
32     return cPickle.loads(cPickle.dumps(obj, -1))
33
34
35 def fork_as(su, function, *args):
36     """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."""
37     child_pid = os.fork()
38     if child_pid == 0:
39         try:
40             os.chdir('/')
41             # close all nonstandard file descriptors
42             _SC_OPEN_MAX = 4
43             for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
44                 try: os.close(fd)
45                 except OSError: pass  # most likely an fd that isn't open
46             pw_ent = pwd.getpwnam(su)
47             os.setegid(pw_ent[3])
48             os.seteuid(pw_ent[2])
49             child_pid = os.fork()
50             if child_pid == 0: function(*args)
51         except:
52             os.seteuid(os.getuid())  # undo su so we can write the log file
53             os.setegid(os.getgid())
54             logger.log_exc()
55         os._exit(0)
56     else: os.waitpid(child_pid, 0)
57
58
59 def pid_file():
60     """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."""
61     other_pid = None
62     # check for a pid file
63     if os.access(PID_FILE, os.F_OK):
64         # pid file exists, read it
65         handle = open(PID_FILE)
66         other_pid = int(handle.read())
67         handle.close()
68         # check for a process with that pid by sending signal 0
69         try: os.kill(other_pid, 0)
70         except OSError, e:
71             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
72             else: raise  # who knows
73     if other_pid == None:
74         # write a new pid file
75         write_file(PID_FILE, lambda thefile: thefile.write(str(os.getpid())))
76     return other_pid
77
78
79 def write_file(filename, do_write):
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), filename)
82
83
84 def write_temp_file(do_write):
85     fd, temporary_filename = tempfile.mkstemp()
86     thefile = os.fdopen(fd, 'w')
87     do_write(thefile)
88     thefile.close()
89     return temporary_filename