expects the 'interfaces' key in GetSlivers - review logs to always mention module
[nodemanager.git] / tools.py
1 # $Id$
2 # $URL$
3
4 """A few things that didn't seem to fit anywhere else."""
5
6 import cPickle
7 import errno
8 import os
9 import pwd
10 import tempfile
11 import threading
12 import fcntl
13 import commands
14 import logger
15
16 PID_FILE = '/var/run/nm.pid'
17
18 def get_default_if():
19     interface = get_if_from_hwaddr(get_hwaddr_from_plnode())
20     if not interface: interface = "eth0"
21     return interface
22
23 def get_hwaddr_from_plnode():
24     try:
25         for line in open("/usr/boot/plnode.txt", 'r').readlines():
26             if line.startswith("NET_DEVICE"):
27                 return line.split("=")[1].strip().strip('"')
28     except:
29         pass
30     return None
31
32 def get_if_from_hwaddr(hwaddr):
33     import sioc
34     devs = sioc.gifconf()
35     for dev in devs:
36         dev_hwaddr = sioc.gifhwaddr(dev)
37         if dev_hwaddr == hwaddr: return dev
38     return None
39
40 def as_daemon_thread(run):
41     """Call function <run> with no arguments in its own thread."""
42     thr = threading.Thread(target=run)
43     thr.setDaemon(True)
44     thr.start()
45
46 def close_nonstandard_fds():
47     """Close all open file descriptors other than 0, 1, and 2."""
48     _SC_OPEN_MAX = 4
49     for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
50         try: os.close(fd)
51         except OSError: pass  # most likely an fd that isn't open
52
53 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
54 def daemon():
55     """Daemonize the current process."""
56     if os.fork() != 0: os._exit(0)
57     os.setsid()
58     if os.fork() != 0: os._exit(0)
59     os.chdir('/')
60     os.umask(0)
61     devnull = os.open(os.devnull, os.O_RDWR)
62     os.dup2(devnull, 0)
63     # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
64     crashlog = os.open('/var/log/nm.daemon', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
65     os.dup2(crashlog, 1)
66     os.dup2(crashlog, 2)
67
68 def fork_as(su, function, *args):
69     """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."""
70     child_pid = os.fork()
71     if child_pid == 0:
72         try:
73             os.chdir('/')
74             close_nonstandard_fds()
75             if su:
76                 pw_ent = pwd.getpwnam(su)
77                 os.setegid(pw_ent[3])
78                 os.seteuid(pw_ent[2])
79             child_pid = os.fork()
80             if child_pid == 0: function(*args)
81         except:
82             os.seteuid(os.getuid())  # undo su so we can write the log file
83             os.setegid(os.getgid())
84             logger.log_exc("tools: fork_as")
85         os._exit(0)
86     else: os.waitpid(child_pid, 0)
87
88 def pid_file():
89     """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."""
90     other_pid = None
91     if os.access(PID_FILE, os.F_OK):  # check for a pid file
92         handle = open(PID_FILE)  # pid file exists, read it
93         other_pid = int(handle.read())
94         handle.close()
95         # check for a process with that pid by sending signal 0
96         try: os.kill(other_pid, 0)
97         except OSError, e:
98             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
99             else: raise  # who knows
100     if other_pid == None:
101         # write a new pid file
102         write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
103     return other_pid
104
105 def write_file(filename, do_write, **kw_args):
106     """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
107     os.rename(write_temp_file(do_write, **kw_args), filename)
108
109 def write_temp_file(do_write, mode=None, uidgid=None):
110     fd, temporary_filename = tempfile.mkstemp()
111     if mode: os.chmod(temporary_filename, mode)
112     if uidgid: os.chown(temporary_filename, *uidgid)
113     f = os.fdopen(fd, 'w')
114     try: do_write(f)
115     finally: f.close()
116     return temporary_filename
117
118 # utilities functions to get (cached) information from the node
119
120 # get node_id from /etc/planetlab/node_id and cache it
121 _node_id=None
122 def node_id():
123     global _node_id
124     if _node_id is None:
125         try:
126             _node_id=int(file("/etc/planetlab/node_id").read())
127         except:
128             _node_id=""
129     return _node_id
130
131 _root_context_arch=None
132 def root_context_arch():
133     global _root_context_arch
134     if not _root_context_arch:
135         _root_context_arch=commands.getoutput("uname -i")
136     return _root_context_arch
137
138
139 class NMLock:
140     def __init__(self, file):
141         logger.log("tools: Lock %s initialized." % file, 2)
142         self.fd = os.open(file, os.O_RDWR|os.O_CREAT, 0600)
143         flags = fcntl.fcntl(self.fd, fcntl.F_GETFD)
144         flags |= fcntl.FD_CLOEXEC
145         fcntl.fcntl(self.fd, fcntl.F_SETFD, flags)
146     def __del__(self):
147         os.close(self.fd)
148     def acquire(self):
149         logger.log("tools: Lock acquired.", 2)
150         fcntl.lockf(self.fd, fcntl.LOCK_SH)
151     def release(self):
152         logger.log("tools: Lock released.", 2)
153         fcntl.lockf(self.fd, fcntl.LOCK_UN)