Fixes for F16.
[nodemanager.git] / tools.py
1 # $Id$
2 # $URL$
3
4 """A few things that didn't seem to fit anywhere else."""
5
6 import os, os.path
7 import pwd
8 import tempfile
9 import fcntl
10 import errno
11 import threading
12 import subprocess
13 import shutil
14
15 import logger
16
17 PID_FILE = '/var/run/nodemanager.pid'
18
19 ####################
20 def get_default_if():
21     interface = get_if_from_hwaddr(get_hwaddr_from_plnode())
22     if not interface: interface = "eth0"
23     return interface
24
25 def get_hwaddr_from_plnode():
26     try:
27         for line in open("/usr/boot/plnode.txt", 'r').readlines():
28             if line.startswith("NET_DEVICE"):
29                 return line.split("=")[1].strip().strip('"')
30     except:
31         pass
32     return None
33
34 def get_if_from_hwaddr(hwaddr):
35     import sioc
36     devs = sioc.gifconf()
37     for dev in devs:
38         dev_hwaddr = sioc.gifhwaddr(dev)
39         if dev_hwaddr == hwaddr: return dev
40     return None
41
42 ####################
43 # daemonizing
44 def as_daemon_thread(run):
45     """Call function <run> with no arguments in its own thread."""
46     thr = threading.Thread(target=run)
47     thr.setDaemon(True)
48     thr.start()
49
50 def close_nonstandard_fds():
51     """Close all open file descriptors other than 0, 1, and 2."""
52     _SC_OPEN_MAX = 4
53     for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
54         try: os.close(fd)
55         except OSError: pass  # most likely an fd that isn't open
56
57 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
58 def daemon():
59     """Daemonize the current process."""
60     if os.fork() != 0: os._exit(0)
61     os.setsid()
62     if os.fork() != 0: os._exit(0)
63     os.chdir('/')
64     os.umask(0022)
65     devnull = os.open(os.devnull, os.O_RDWR)
66     os.dup2(devnull, 0)
67     # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
68     crashlog = os.open('/var/log/nodemanager.daemon', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
69     os.dup2(crashlog, 1)
70     os.dup2(crashlog, 2)
71
72 def fork_as(su, function, *args):
73     """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."""
74     child_pid = os.fork()
75     if child_pid == 0:
76         try:
77             os.chdir('/')
78             close_nonstandard_fds()
79             if su:
80                 pw_ent = pwd.getpwnam(su)
81                 os.setegid(pw_ent[3])
82                 os.seteuid(pw_ent[2])
83             child_pid = os.fork()
84             if child_pid == 0: function(*args)
85         except:
86             os.seteuid(os.getuid())  # undo su so we can write the log file
87             os.setegid(os.getgid())
88             logger.log_exc("tools: fork_as")
89         os._exit(0)
90     else: os.waitpid(child_pid, 0)
91
92 ####################
93 # manage files
94 def pid_file():
95     """We use a pid file to ensure that only one copy of NM is running at a given time.
96 If successful, this function will write a pid file containing the pid of the current process.
97 The return value is the pid of the other running process, or None otherwise."""
98     other_pid = None
99     if os.access(PID_FILE, os.F_OK):  # check for a pid file
100         handle = open(PID_FILE)  # pid file exists, read it
101         other_pid = int(handle.read())
102         handle.close()
103         # check for a process with that pid by sending signal 0
104         try: os.kill(other_pid, 0)
105         except OSError, e:
106             if e.errno == errno.ESRCH: other_pid = None  # doesn't exist
107             else: raise  # who knows
108     if other_pid == None:
109         # write a new pid file
110         write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
111     return other_pid
112
113 def write_file(filename, do_write, **kw_args):
114     """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
115     shutil.move(write_temp_file(do_write, **kw_args), filename)
116
117 def write_temp_file(do_write, mode=None, uidgid=None):
118     fd, temporary_filename = tempfile.mkstemp()
119     if mode: os.chmod(temporary_filename, mode)
120     if uidgid: os.chown(temporary_filename, *uidgid)
121     f = os.fdopen(fd, 'w')
122     try: do_write(f)
123     finally: f.close()
124     return temporary_filename
125
126 # replace a target file with a new contents - checks for changes
127 # can handle chmod if requested
128 # can also remove resulting file if contents are void, if requested
129 # performs atomically:
130 #    writes in a tmp file, which is then renamed (from sliverauth originally)
131 # returns True if a change occurred, or the file is deleted
132 def replace_file_with_string (target, new_contents, chmod=None, remove_if_empty=False):
133     try:
134         current=file(target).read()
135     except:
136         current=""
137     if current==new_contents:
138         # if turns out to be an empty string, and remove_if_empty is set,
139         # then make sure to trash the file if it exists
140         if remove_if_empty and not new_contents and os.path.isfile(target):
141             logger.verbose("tools.replace_file_with_string: removing file %s"%target)
142             try: os.unlink(target)
143             finally: return True
144         return False
145     # overwrite target file: create a temp in the same directory
146     path=os.path.dirname(target) or '.'
147     fd, name = tempfile.mkstemp('','repl',path)
148     os.write(fd,new_contents)
149     os.close(fd)
150     if os.path.exists(target):
151         os.unlink(target)
152     shutil.move(name,target)
153     if chmod: os.chmod(target,chmod)
154     return True
155
156
157 ####################
158 # utilities functions to get (cached) information from the node
159
160 # get node_id from /etc/planetlab/node_id and cache it
161 _node_id=None
162 def node_id():
163     global _node_id
164     if _node_id is None:
165         try:
166             _node_id=int(file("/etc/planetlab/node_id").read())
167         except:
168             _node_id=""
169     return _node_id
170
171 _root_context_arch=None
172 def root_context_arch():
173     global _root_context_arch
174     if not _root_context_arch:
175         sp=subprocess.Popen(["uname","-i"],stdout=subprocess.PIPE)
176         (_root_context_arch,_)=sp.communicate()
177         _root_context_arch=_root_context_arch.strip()
178     return _root_context_arch
179
180
181 ####################
182 class NMLock:
183     def __init__(self, file):
184         logger.log("tools: Lock %s initialized." % file, 2)
185         self.fd = os.open(file, os.O_RDWR|os.O_CREAT, 0600)
186         flags = fcntl.fcntl(self.fd, fcntl.F_GETFD)
187         flags |= fcntl.FD_CLOEXEC
188         fcntl.fcntl(self.fd, fcntl.F_SETFD, flags)
189     def __del__(self):
190         os.close(self.fd)
191     def acquire(self):
192         logger.log("tools: Lock acquired.", 2)
193         fcntl.lockf(self.fd, fcntl.LOCK_SH)
194     def release(self):
195         logger.log("tools: Lock released.", 2)
196         fcntl.lockf(self.fd, fcntl.LOCK_UN)