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