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