Refactoring 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 import logger
9
10
11 PID_FILE = '/var/run/pl_node_mgr.pid'
12
13
14 def as_daemon_thread(run):
15     """Call function <run> with no arguments in its own thread."""
16     thr = threading.Thread(target=run)
17     thr.setDaemon(True)
18     thr.start()
19
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
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     for fd in range(3): os.dup2(devnull, fd)
39
40
41 def deepcopy(obj):
42     """Return a deep copy of obj."""
43     return cPickle.loads(cPickle.dumps(obj, -1))
44
45
46 def fork_as(su, function, *args):
47     """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."""
48     child_pid = os.fork()
49     if child_pid == 0:
50         try:
51             os.chdir('/')
52             close_nonstandard_fds()
53             pw_ent = pwd.getpwnam(su)
54             os.setegid(pw_ent[3])
55             os.seteuid(pw_ent[2])
56             child_pid = os.fork()
57             if child_pid == 0: function(*args)
58         except:
59             os.seteuid(os.getuid())  # undo su so we can write the log file
60             os.setegid(os.getgid())
61             logger.log_exc()
62         os._exit(0)
63     else: os.waitpid(child_pid, 0)
64
65
66 def pid_file():
67     """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."""
68     other_pid = None
69     if os.access(PID_FILE, os.F_OK):  # check for a pid file
70         handle = open(PID_FILE)  # pid file exists, read it
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