1 """A few things that didn't seem to fit anywhere else."""
13 PID_FILE = '/var/run/nm.pid'
16 interface = get_if_from_hwaddr(get_hwaddr_from_plnode())
17 if not interface: interface = "eth0"
20 def get_hwaddr_from_plnode():
21 for line in open("/usr/boot/plnode.txt", 'r').readlines():
22 if line.startswith("NET_DEVICE"):
23 return line.split("=")[1].strip().strip('"')
26 def get_if_from_hwaddr(hwaddr):
30 dev_hwaddr = sioc.gifhwaddr(dev)
31 if dev_hwaddr == hwaddr: return dev
34 def as_daemon_thread(run):
35 """Call function <run> with no arguments in its own thread."""
36 thr = threading.Thread(target=run)
40 def close_nonstandard_fds():
41 """Close all open file descriptors other than 0, 1, and 2."""
43 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
45 except OSError: pass # most likely an fd that isn't open
47 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
49 """Daemonize the current process."""
50 if os.fork() != 0: os._exit(0)
52 if os.fork() != 0: os._exit(0)
55 devnull = os.open(os.devnull, os.O_RDWR)
57 # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
58 crashlog = os.open('/var/log/nm.daemon', os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
62 def fork_as(su, function, *args):
63 """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."""
68 close_nonstandard_fds()
70 pw_ent = pwd.getpwnam(su)
74 if child_pid == 0: function(*args)
76 os.seteuid(os.getuid()) # undo su so we can write the log file
77 os.setegid(os.getgid())
80 else: os.waitpid(child_pid, 0)
83 """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."""
85 if os.access(PID_FILE, os.F_OK): # check for a pid file
86 handle = open(PID_FILE) # pid file exists, read it
87 other_pid = int(handle.read())
89 # check for a process with that pid by sending signal 0
90 try: os.kill(other_pid, 0)
92 if e.errno == errno.ESRCH: other_pid = None # doesn't exist
93 else: raise # who knows
95 # write a new pid file
96 write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
99 def write_file(filename, do_write, **kw_args):
100 """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
101 os.rename(write_temp_file(do_write, **kw_args), filename)
103 def write_temp_file(do_write, mode=None, uidgid=None):
104 fd, temporary_filename = tempfile.mkstemp()
105 if mode: os.chmod(temporary_filename, mode)
106 if uidgid: os.chown(temporary_filename, *uidgid)
107 f = os.fdopen(fd, 'w')
110 return temporary_filename
112 # utilities functions to get (cached) information from the node
114 # get node_id from /etc/planetlab/node_id and cache it
120 _node_id=int(file("/etc/planetlab/node_id").read())
125 # get slicefamily from /etc/planetlab/slicefamily and cache it
126 # http://svn.planet-lab.org/wiki/SliceFamily
130 if _slicefamily is None:
132 _slicefamily=file("/etc/planetlab/slicefamily").read().strip()
137 _root_context_arch=None
138 def root_context_arch():
139 global _root_context_arch
140 if not _root_context_arch:
141 _root_context_arch=commands.getoutput("uname -i")
142 return _root_context_arch
146 def __init__(self, file):
147 logger.log("Lock %s initialized." % file, 2)
148 self.fd = os.open(file, os.O_RDWR|os.O_CREAT, 0600)
149 flags = fcntl.fcntl(self.fd, fcntl.F_GETFD)
150 flags |= fcntl.FD_CLOEXEC
151 fcntl.fcntl(self.fd, fcntl.F_SETFD, flags)
155 logger.log("Lock acquired.", 2)
156 fcntl.lockf(self.fd, fcntl.LOCK_SH)
158 logger.log("Lock released.", 2)
159 fcntl.lockf(self.fd, fcntl.LOCK_UN)