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