...
[nodemanager.git] / tools.py
1 import cPickle
2 import errno
3 import os
4 import pwd
5 import tempfile
6 import threading
7
8 import logger
9
10
11 PID_FILE = '/var/run/node_mgr.pid'
12
13 def as_daemon_thread(run):
14     """Call function <run> with no arguments in its own thread."""
15     thr = threading.Thread(target=run)
16     thr.setDaemon(True)
17     thr.start()
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 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
27 def daemon():
28     """Daemonize the current process."""
29     if os.fork() != 0: os._exit(0)
30     os.setsid()
31     if os.fork() != 0: os._exit(0)
32     os.chdir('/')
33     os.umask(0)
34     devnull = os.open(os.devnull, os.O_RDWR)
35     for fd in range(3): os.dup2(devnull, fd)
36
37 def deepcopy(obj):
38     """Return a deep copy of obj."""
39     return cPickle.loads(cPickle.dumps(obj, -1))
40
41 def fork_as(su, function, *args):
42     """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."""
43     child_pid = os.fork()
44     if child_pid == 0:
45         try:
46             os.chdir('/')
47             close_nonstandard_fds()
48             pw_ent = pwd.getpwnam(su)
49             os.setegid(pw_ent[3])
50             os.seteuid(pw_ent[2])
51             child_pid = os.fork()
52             if child_pid == 0: function(*args)
53         except:
54             os.seteuid(os.getuid())  # undo su so we can write the log file
55             os.setegid(os.getgid())
56             logger.log_exc()
57         os._exit(0)
58     else: os.waitpid(child_pid, 0)
59
60 def pid_file():
61     """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."""
62     other_pid = None
63     if os.access(PID_FILE, os.F_OK):  # check for a pid file
64         handle = open(PID_FILE)  # pid file exists, read it
65         other_pid = int(handle.read())
66         handle.close()
67         # check for a process with that pid by sending signal 0
68         try: os.kill(other_pid, 0)
69         except OSError, e:
70             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
71             else: raise  # who knows
72     if other_pid == None:
73         # write a new pid file
74         write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
75     return other_pid
76
77 def write_file(filename, do_write):
78     """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
79     os.rename(write_temp_file(do_write), filename)
80
81 def write_temp_file(do_write):
82     fd, temporary_filename = tempfile.mkstemp()
83     f = os.fdopen(fd, 'w')
84     try: do_write(f)
85     finally: f.close()
86     return temporary_filename