Tidy up handling of network parameters, don't rely upon config files
[util-vserver.git] / python / vserver.py
1 # Copyright 2005 Princeton University
2
3 import errno
4 import fcntl
5 import os
6 import re
7 import sys
8 import time
9 import traceback
10
11 import mountimpl
12 import passfdimpl
13 import utmp
14 import vserverimpl, vduimpl
15 import cpulimit, bwlimit
16
17
18
19 #
20 # these are the flags taken from the kernel linux/vserver/legacy.h
21 #
22 FLAGS_LOCK = 1
23 FLAGS_SCHED = 2  # XXX - defined in util-vserver/src/chcontext.c
24 FLAGS_NPROC = 4
25 FLAGS_PRIVATE = 8
26 FLAGS_INIT = 16
27 FLAGS_HIDEINFO = 32
28 FLAGS_ULIMIT = 64
29 FLAGS_NAMESPACE = 128
30
31
32               
33 class VServer:
34
35     INITSCRIPTS = [('/etc/rc.vinit', 'start'),
36                    ('/etc/rc.d/rc', '%(runlevel)d')]
37
38     def __init__(self, name, vm_id, vm_running = False, resources = {}):
39
40         self.name = name
41         self.config_file = "/etc/vservers/%s.conf" % name
42         self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
43         if not (os.path.isdir(self.dir) and
44                 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
45             raise Exception, "no such vserver: " + name
46         self.config = {}
47         for config_file in ["/etc/vservers.conf", self.config_file]:
48             try:
49                 self.config.update(self.__read_config_file(config_file))
50             except IOError, ex:
51                 if ex.errno != errno.ENOENT:
52                     raise
53         self.flags = 0
54         flags = self.config.get("S_FLAGS", "").split(" ")
55         if "lock" in flags:
56             self.flags |= FLAGS_LOCK
57         if "nproc" in flags:
58             self.flags |= FLAGS_NPROC
59         self.remove_caps = ~vserverimpl.CAP_SAFE;
60         self.ctx = vm_id
61         self.vm_running = vm_running
62         self.resources = resources
63
64     config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
65
66     def __read_config_file(self, filename):
67
68         f = open(filename, "r")
69         data = f.read()
70         f.close()
71         config = {}
72         for m in self.config_var_re.finditer(data):
73             (key, val) = m.groups()
74             config[key] = val.strip('"')
75         return config
76
77     def __update_config_file(self, filename, newvars):
78
79         # read old file, apply changes
80         f = open(filename, "r")
81         data = f.read()
82         f.close()
83         todo = newvars.copy()
84         changed = False
85         for m in self.config_var_re.finditer(data):
86             (key, val) = m.groups()
87             newval = todo.pop(key, None)
88             if newval != None:
89                 data = data[:m.start(2)] + str(newval) + data[m.end(2):]
90                 changed = True
91         for (newkey, newval) in todo.items():
92             data += "%s=%s\n" % (newkey, newval)
93             changed = True
94
95         if not changed:
96             return
97
98         # write new file
99         newfile = filename + ".new"
100         f = open(newfile, "w")
101         f.write(data)
102         f.close()
103
104         # 'copy' original file, rename new to original
105         backup = filename + ".old"
106         try:
107             os.unlink(backup)
108         except OSError, ex:
109             if ex.errno != errno.ENOENT:
110                 raise
111         os.link(filename, backup)
112         os.rename(newfile, filename)
113
114     def __do_chroot(self):
115
116         os.chroot(self.dir)
117         os.chdir("/")
118
119     def set_disklimit(self, block_limit):
120
121         # block_limit is in kB
122         if self.vm_running:
123             block_usage = vserverimpl.DLIMIT_KEEP
124             inode_usage = vserverimpl.DLIMIT_KEEP
125         else:
126             # init_disk_info() must have been called to get usage values
127             block_usage = self.disk_blocks
128             inode_usage = self.disk_inodes
129
130         vserverimpl.setdlimit(self.dir,
131                               self.ctx,
132                               block_usage,
133                               block_limit,
134                               inode_usage,
135                               vserverimpl.DLIMIT_INF,  # inode limit
136                               2)   # %age reserved for root
137
138     def get_disklimit(self):
139
140         try:
141             blocksused, blocktotal, inodesused, inodestotal, reserved = \
142                         vserverimpl.getdlimit(self.dir, self.ctx)
143         except OSError, ex:
144             if ex.errno == errno.ESRCH:
145                 # get here if no vserver disk limit has been set for xid
146                 blocktotal = -1
147
148         return blocktotal
149
150     def set_sched(self, cpu_share):
151
152         if cpu_share == int(self.config.get("CPULIMIT", -1)):
153             return
154
155         self.__update_config_file(self.config_file, { "CPULIMIT": cpu_share })
156         if self.vm_running:
157             vserverimpl.setsched(self.ctx, self.resources)
158
159     def get_sched(self):
160         # have no way of querying scheduler right now on a per vserver basis
161         return (-1, False)
162
163     def set_memlimit(self, limit):
164         ret = vserverimpl.setrlimit(self.ctx,5,limit)
165         return ret
166
167     def get_memlimit(self):
168         ret = vserverimpl.getrlimit(self.ctx,5)
169         return ret
170     
171     def set_tasklimit(self, limit):
172         ret = vserverimpl.setrlimit(self.ctx,6,limit)
173         return ret
174
175     def get_tasklimit(self):
176         ret = vserverimpl.getrlimit(self.ctx,6)
177         return ret
178
179     def set_bwlimit(self, share, minrate, maxrate = None, dev = "eth0"):
180
181         if False:
182             bwlimit.off(self.ctx, dev)
183         else:
184             bwlimit.on(self.ctx, dev, share, minrate, maxrate)
185
186     def get_bwlimit(self, eth):
187         # not implemented yet
188         bwlimit = -1
189         cap = "unknown"
190         minrate = "unknown"
191         maxrate = "unknown"
192         return (bwlimit, cap, minrate, maxrate)
193         
194     def open(self, filename, mode = "r", bufsize = -1):
195
196         (sendsock, recvsock) = passfdimpl.socketpair()
197         child_pid = os.fork()
198         if child_pid == 0:
199             try:
200                 # child process
201                 self.__do_chroot()
202                 f = open(filename, mode)
203                 passfdimpl.sendmsg(f.fileno(), sendsock)
204                 os._exit(0)
205             except EnvironmentError, ex:
206                 (result, errmsg) = (ex.errno, ex.strerror)
207             except Exception, ex:
208                 (result, errmsg) = (255, str(ex))
209             os.write(sendsock, errmsg)
210             os._exit(result)
211
212         # parent process
213
214         # XXX - need this since a lambda can't raise an exception
215         def __throw(ex):
216             raise ex
217
218         os.close(sendsock)
219         throw = lambda : __throw(Exception(errmsg))
220         while True:
221             try:
222                 (pid, status) = os.waitpid(child_pid, 0)
223                 if os.WIFEXITED(status):
224                     result = os.WEXITSTATUS(status)
225                     if result != 255:
226                         errmsg = os.strerror(result)
227                         throw = lambda : __throw(IOError(result, errmsg))
228                     else:
229                         errmsg = "unexpected exception in child"
230                 else:
231                     result = -1
232                     errmsg = "child killed"
233                 break
234             except OSError, ex:
235                 if ex.errno != errno.EINTR:
236                     os.close(recvsock)
237                     raise ex
238         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
239         try:
240             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
241         except OSError, ex:
242             if ex.errno != errno.EAGAIN:
243                 throw = lambda : __throw(ex)
244             fd = 0
245         os.close(recvsock)
246         if not fd:
247             throw()
248
249         return os.fdopen(fd, mode, bufsize)
250
251     def __do_chcontext(self, state_file):
252
253         vserverimpl.chcontext(self.ctx, self.resources)
254
255         if not state_file:
256             return
257         print >>state_file, "S_CONTEXT=%d" % self.ctx
258         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
259         state_file.close()
260
261     def __prep(self, runlevel, log):
262
263         """ Perform all the crap that the vserver script does before
264         actually executing the startup scripts. """
265
266         # remove /var/run and /var/lock/subsys files
267         # but don't remove utmp from the top-level /var/run
268         RUNDIR = "/var/run"
269         LOCKDIR = "/var/lock/subsys"
270         filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
271         garbage = reduce((lambda (out, ff), (dir, subdirs, files):
272                           (out + map((dir + "/").__add__, ff(files)),
273                            lambda fs: fs)),
274                          list(os.walk(RUNDIR)),
275                          ([], filter_fn))[0]
276         garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
277                                               os.listdir(LOCKDIR)))
278         for f in garbage:
279             os.unlink(f)
280
281         # set the initial runlevel
282         f = open(RUNDIR + "/utmp", "w")
283         utmp.set_runlevel(f, runlevel)
284         f.close()
285
286         # mount /proc and /dev/pts
287         self.__do_mount("none", "/proc", "proc")
288         # XXX - magic mount options
289         self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
290
291     def __do_mount(self, *mount_args):
292
293         try:
294             mountimpl.mount(*mount_args)
295         except OSError, ex:
296             if ex.errno == errno.EBUSY:
297                 # assume already mounted
298                 return
299             raise ex
300
301     def enter(self):
302
303         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
304         self.__do_chroot()
305         self.__do_chcontext(state_file)
306
307     def start(self, wait, runlevel = 3):
308
309         self.vm_running = True
310
311         child_pid = os.fork()
312         if child_pid == 0:
313             # child process
314             try:
315                 # get a new session
316                 os.setsid()
317
318                 # open state file to record vserver info
319                 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
320
321                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
322                 os.close(0)
323                 os.close(1)
324                 os.open("/dev/null", os.O_RDONLY)
325                 self.__do_chroot()
326                 log = open("/var/log/boot.log", "w", 0)
327                 os.dup2(1, 2)
328                 # XXX - close all other fds
329
330                 print >>log, ("%s: starting the virtual server %s" %
331                               (time.asctime(time.gmtime()), self.name))
332
333                 # perform pre-init cleanup
334                 self.__prep(runlevel, log)
335
336                 # execute each init script in turn
337                 # XXX - we don't support all scripts that vserver script does
338                 cmd_pid = 0
339                 first_child = True
340                 for cmd in self.INITSCRIPTS + [None]:
341                     # wait for previous command to terminate, unless it
342                     # is the last one and the caller has specified to wait
343                     if cmd_pid and (cmd != None or wait):
344                         try:
345                             os.waitpid(cmd_pid, 0)
346                         except:
347                             print >>log, "error waiting for %s:" % cmd_pid
348                             traceback.print_exc()
349
350                     # end of list
351                     if cmd == None:
352                         os._exit(0)
353
354                     # fork and exec next command
355                     cmd_pid = os.fork()
356                     if cmd_pid == 0:
357                         try:
358                             # enter vserver context
359                             self.__do_chcontext(state_file)
360                             arg_subst = { 'runlevel': runlevel }
361                             cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
362                                                       cmd[1:])
363                             print >>log, "executing '%s'" % " ".join(cmd_args)
364                             os.execl(cmd[0], *cmd_args)
365                         except:
366                             traceback.print_exc()
367                             os._exit(1)
368                     else:
369                         # don't want to write state_file multiple times
370                         state_file = None
371
372             # we get here due to an exception in the top-level child process
373             except Exception, ex:
374                 traceback.print_exc()
375             os._exit(0)
376
377         # parent process
378         return child_pid
379
380     def update_resources(self, resources):
381
382         self.config.update(resources)
383
384         # write new values to configuration file
385         self.__update_config_file(self.config_file, resources)
386
387     def init_disk_info(self):
388
389         (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
390
391         return size