4 """A few things that didn't seem to fit anywhere else."""
16 PID_FILE = '/var/run/nm.pid'
20 interface = get_if_from_hwaddr(get_hwaddr_from_plnode())
21 if not interface: interface = "eth0"
24 def get_hwaddr_from_plnode():
26 for line in open("/usr/boot/plnode.txt", 'r').readlines():
27 if line.startswith("NET_DEVICE"):
28 return line.split("=")[1].strip().strip('"')
33 def get_if_from_hwaddr(hwaddr):
37 dev_hwaddr = sioc.gifhwaddr(dev)
38 if dev_hwaddr == hwaddr: return dev
43 def as_daemon_thread(run):
44 """Call function <run> with no arguments in its own thread."""
45 thr = threading.Thread(target=run)
49 def close_nonstandard_fds():
50 """Close all open file descriptors other than 0, 1, and 2."""
52 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
54 except OSError: pass # most likely an fd that isn't open
56 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
58 """Daemonize the current process."""
59 if os.fork() != 0: os._exit(0)
61 if os.fork() != 0: os._exit(0)
64 devnull = os.open(os.devnull, os.O_RDWR)
66 # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
67 crashlog = os.open('/var/log/nm.daemon', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
71 def fork_as(su, function, *args):
72 """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."""
77 close_nonstandard_fds()
79 pw_ent = pwd.getpwnam(su)
83 if child_pid == 0: function(*args)
85 os.seteuid(os.getuid()) # undo su so we can write the log file
86 os.setegid(os.getgid())
87 logger.log_exc("tools: fork_as")
89 else: os.waitpid(child_pid, 0)
94 """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."""
96 if os.access(PID_FILE, os.F_OK): # check for a pid file
97 handle = open(PID_FILE) # pid file exists, read it
98 other_pid = int(handle.read())
100 # check for a process with that pid by sending signal 0
101 try: os.kill(other_pid, 0)
103 if e.errno == errno.ESRCH: other_pid = None # doesn't exist
104 else: raise # who knows
105 if other_pid == None:
106 # write a new pid file
107 write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
110 def write_file(filename, do_write, **kw_args):
111 """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
112 os.rename(write_temp_file(do_write, **kw_args), filename)
114 def write_temp_file(do_write, mode=None, uidgid=None):
115 fd, temporary_filename = tempfile.mkstemp()
116 if mode: os.chmod(temporary_filename, mode)
117 if uidgid: os.chown(temporary_filename, *uidgid)
118 f = os.fdopen(fd, 'w')
121 return temporary_filename
123 # replace a target file with a new contents - checks for changes
124 # return True if a change occurred, in which case
125 # chown/chmod settings should be taken care of
126 def replace_file_with_string (target, new_contents):
128 current=file(target).read()
131 # xxx if verbose, report diffs...
132 if current==new_contents:
134 # overwrite target file
136 f.write(new_contents)
140 # not needed yet - should that unlink the new file ?
141 #def replace_file_with_file (target, new):
142 # return replace_file_with_string (target, file(new).read())
145 # utilities functions to get (cached) information from the node
147 # get node_id from /etc/planetlab/node_id and cache it
153 _node_id=int(file("/etc/planetlab/node_id").read())
158 _root_context_arch=None
159 def root_context_arch():
160 global _root_context_arch
161 if not _root_context_arch:
162 sp=subprocess.Popen(["uname","-i"],stdout=subprocess.PIPE)
163 (_root_context_arch,_)=sp.communicate()
164 _root_context_arch=_root_context_arch.strip()
165 return _root_context_arch
170 def __init__(self, file):
171 logger.log("tools: Lock %s initialized." % file, 2)
172 self.fd = os.open(file, os.O_RDWR|os.O_CREAT, 0600)
173 flags = fcntl.fcntl(self.fd, fcntl.F_GETFD)
174 flags |= fcntl.FD_CLOEXEC
175 fcntl.fcntl(self.fd, fcntl.F_SETFD, flags)
179 logger.log("tools: Lock acquired.", 2)
180 fcntl.lockf(self.fd, fcntl.LOCK_SH)
182 logger.log("tools: Lock released.", 2)
183 fcntl.lockf(self.fd, fcntl.LOCK_UN)