log subprocess calls.
[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 import fcntl
10 import commands
11
12 import logger
13
14
15 PID_FILE = '/var/run/nm.pid'
16
17 def as_daemon_thread(run):
18     """Call function <run> with no arguments in its own thread."""
19     thr = threading.Thread(target=run)
20     thr.setDaemon(True)
21     thr.start()
22
23 def close_nonstandard_fds():
24     """Close all open file descriptors other than 0, 1, and 2."""
25     _SC_OPEN_MAX = 4
26     for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
27         try: os.close(fd)
28         except OSError: pass  # most likely an fd that isn't open
29
30 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
31 def daemon():
32     """Daemonize the current process."""
33     if os.fork() != 0: os._exit(0)
34     os.setsid()
35     if os.fork() != 0: os._exit(0)
36     os.chdir('/')
37     os.umask(0)
38     devnull = os.open(os.devnull, os.O_RDWR)
39     os.dup2(devnull, 0)
40     # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
41     crashlog = os.open('/var/log/nm.daemon', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
42     os.dup2(crashlog, 1)
43     os.dup2(crashlog, 2)
44
45 def fork_as(su, function, *args):
46     """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."""
47     child_pid = os.fork()
48     if child_pid == 0:
49         try:
50             os.chdir('/')
51             close_nonstandard_fds()
52             if su:
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 def pid_file():
66     """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."""
67     other_pid = None
68     if os.access(PID_FILE, os.F_OK):  # check for a pid file
69         handle = open(PID_FILE)  # pid file exists, read it
70         other_pid = int(handle.read())
71         handle.close()
72         # check for a process with that pid by sending signal 0
73         try: os.kill(other_pid, 0)
74         except OSError, e:
75             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
76             else: raise  # who knows
77     if other_pid == None:
78         # write a new pid file
79         write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
80     return other_pid
81
82 def write_file(filename, do_write, **kw_args):
83     """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
84     os.rename(write_temp_file(do_write, **kw_args), filename)
85
86 def write_temp_file(do_write, mode=None, uidgid=None):
87     fd, temporary_filename = tempfile.mkstemp()
88     if mode: os.chmod(temporary_filename, mode)
89     if uidgid: os.chown(temporary_filename, *uidgid)
90     f = os.fdopen(fd, 'w')
91     try: do_write(f)
92     finally: f.close()
93     return temporary_filename
94
95 # utilities functions to get (cached) information from the node
96
97 # get node_id from /etc/planetlab/node_id and cache it
98 _node_id=None
99 def node_id():
100     global _node_id
101     if _node_id is None:
102         try:
103             _node_id=int(file("/etc/planetlab/node_id").read())
104         except:
105             _node_id=""
106     return _node_id
107
108 # get slicefamily from /etc/planetlab/slicefamily and cache it
109 # http://svn.planet-lab.org/wiki/SliceFamily
110 _slicefamily=None
111 def slicefamily():
112     global _slicefamily
113     if _slicefamily is None:
114         try:
115             _slicefamily=file("/etc/planetlab/slicefamily").read().strip()
116         except:
117             _slicefamily=""
118     return _slicefamily
119
120 _root_context_arch=None
121 def root_context_arch():
122     global _root_context_arch
123     if not _root_context_arch:
124         _root_context_arch=commands.getoutput("uname -i")
125     return _root_context_arch
126
127
128 class NMLock:
129     def __init__(self, file):
130         logger.log("Lock %s initialized." % file, 2)
131         self.fd = os.open(file, os.O_RDWR|os.O_CREAT, 0600)
132         flags = fcntl.fcntl(self.fd, fcntl.F_GETFD)
133         flags |= fcntl.FD_CLOEXEC
134         fcntl.fcntl(self.fd, fcntl.F_SETFD, flags)
135     def __del__(self):
136         os.close(self.fd)
137     def acquire(self):
138         logger.log("Lock acquired.", 2)
139         fcntl.lockf(self.fd, fcntl.LOCK_SH)
140     def release(self):
141         logger.log("Lock released.", 2)
142         fcntl.lockf(self.fd, fcntl.LOCK_UN)