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