1 # Copyright 2005 Princeton University
14 import vserverimpl, vduimpl
15 import cpulimit, bwlimit
20 # these are the flags taken from the kernel linux/vserver/legacy.h
23 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
31 # default values for new vserver scheduler
33 SCHED_TOKENS_MAX = 100
40 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
41 ('/etc/rc.d/rc', '%(runlevel)d')]
43 def __init__(self, name):
46 self.config_file = "/etc/vservers/%s.conf" % name
47 self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
48 if not (os.path.isdir(self.dir) and
49 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
50 raise Exception, "no such vserver: " + name
51 self.config = self.__read_config_file("/etc/vservers.conf")
52 self.config.update(self.__read_config_file(self.config_file))
54 flags = self.config["S_FLAGS"].split(" ")
56 self.flags |= FLAGS_LOCK
58 self.flags |= FLAGS_NPROC
59 self.remove_caps = ~vserverimpl.CAP_SAFE;
60 self.ctx = int(self.config["S_CONTEXT"])
62 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
64 def __read_config_file(self, filename):
66 f = open(filename, "r")
70 for m in self.config_var_re.finditer(data):
71 (key, val) = m.groups()
72 config[key] = val.strip('"')
75 def __update_config_file(self, filename, newvars):
77 # read old file, apply changes
78 f = open(filename, "r")
83 for m in self.config_var_re.finditer(data):
84 (key, val) = m.groups()
85 newval = todo.pop(key, None)
87 data = data[:m.start(2)] + newval + data[m.end(2):]
89 for (newkey, newval) in todo.items():
90 data += "%s=%s\n" % (newkey, newval)
97 newfile = filename + ".new"
98 f = open(newfile, "w")
102 # 'copy' original file, rename new to original
103 backup = filename + ".old"
107 if ex.errno != errno.ENOENT:
109 os.link(filename, backup)
110 os.rename(newfile, filename)
112 def __do_chroot(self):
114 return os.chroot(self.dir)
116 def set_disklimit(self, block_limit):
118 # block_limit is in kB, get_disk_usage() must have been called
119 if self.disk_usage_set:
120 block_usage = vserverimpl.DLIMIT_KEEP
121 inode_usage = vserverimpl.DLIMIT_KEEP
123 block_usage = self.disk_blocks
124 inode_usage = self.disk_inodes
125 if block_limit < block_usage:
126 raise Exception, ("%s disk usage (%u blocks) > limit (%u)" %
127 (self.name, block_usage, block_limit))
128 self.disk_usage_set = True
130 vserverimpl.setdlimit(self.dir,
136 2) # %age reserved for root
138 def get_disklimit(self):
141 blocksused, blocktotal, inodesused, inodestotal, reserved = \
142 vserverimpl.getdlimit(self.dir, self.ctx)
144 if ex.errno == errno.ESRCH:
145 # get here if no vserver disk limit has been set for xid
146 # set blockused to -1 to indicate no limit
151 def set_sched(self, shares = 32, besteffort = True):
152 # for the old CKRM scheduler
153 if cpulimit.checkckrm() is True:
155 cpulimit.vs2ckrm_on(self.name)
157 cpulimit.cpulimit(self.name,shares)
160 print "invalid shares argument"
161 # should re-raise exception?!
163 # for the new vserver scheduler
165 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX, SCHED_TOKENS, SCHED_INTERVAL
166 tokensmin = SCHED_TOKENS_MIN
167 tokensmax = SCHED_TOKENS_MAX
168 tokens = SCHED_TOKENS
169 interval = SCHED_INTERVAL
172 if besteffort is True:
178 vserverimpl.setsched(self.ctx,fillrate,interval,tokens,tokensmin,tokensmax,cpuguaranteed)
181 print "kernel does not support vserver scheduler"
186 # have no way of querying scheduler right now on a per vserver basis
189 def set_memlimit(self, limit):
190 ret = vserverimpl.setrlimit(self.ctx,5,limit)
193 def get_memlimit(self):
194 ret = vserverimpl.getrlimit(self.ctx,5)
197 def set_tasklimit(self, limit):
198 ret = vserverimpl.setrlimit(self.ctx,6,limit)
201 def get_tasklimit(self):
202 ret = vserverimpl.getrlimit(self.ctx,6)
205 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
207 bwlimit.off(self.ctx,eth)
209 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
211 def get_bwlimit(self, eth):
212 # not implemented yet
217 return (bwlimit, cap, minrate, maxrate)
219 def open(self, filename, mode = "r", bufsize = -1):
221 (sendsock, recvsock) = passfdimpl.socketpair()
222 child_pid = os.fork()
227 f = open(filename, mode)
228 passfdimpl.sendmsg(f.fileno(), sendsock)
230 except EnvironmentError, ex:
231 (result, errmsg) = (ex.errno, ex.strerror)
232 except Exception, ex:
233 (result, errmsg) = (255, str(ex))
234 os.write(sendsock, errmsg)
239 # XXX - need this since a lambda can't raise an exception
244 throw = lambda : __throw(Exception(errmsg))
247 (pid, status) = os.waitpid(child_pid, 0)
248 if os.WIFEXITED(status):
249 result = os.WEXITSTATUS(status)
251 errmsg = os.strerror(result)
252 throw = lambda : __throw(IOError(result, errmsg))
254 errmsg = "unexpected exception in child"
257 errmsg = "child killed"
260 if ex.errno != errno.EINTR:
263 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
265 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
267 if ex.errno != errno.EAGAIN:
268 throw = lambda : __throw(ex)
274 return os.fdopen(fd, mode, bufsize)
276 def __do_chcontext(self, state_file = None):
278 vserverimpl.chcontext(self.ctx)
282 print >>state_file, "S_CONTEXT=%d" % self.ctx
283 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
286 def __prep(self, runlevel, log):
288 """ Perform all the crap that the vserver script does before
289 actually executing the startup scripts. """
291 # remove /var/run and /var/lock/subsys files
292 # but don't remove utmp from the top-level /var/run
294 LOCKDIR = "/var/lock/subsys"
295 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
296 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
297 (out + map((dir + "/").__add__, ff(files)),
299 list(os.walk(RUNDIR)),
301 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
302 os.listdir(LOCKDIR)))
306 # set the initial runlevel
307 f = open(RUNDIR + "/utmp", "w")
308 utmp.set_runlevel(f, runlevel)
311 # mount /proc and /dev/pts
312 self.__do_mount("none", "/proc", "proc")
313 # XXX - magic mount options
314 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
316 def __do_mount(self, *mount_args):
319 mountimpl.mount(*mount_args)
321 if ex.errno == errno.EBUSY:
322 # assume already mounted
328 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
330 self.__do_chcontext(state_file)
332 def start(self, wait, runlevel = 3):
334 # XXX - temporary hack
335 self.set_disklimit(self.config.get("DISKLIMIT", 5000000))
337 child_pid = os.fork()
344 # open state file to record vserver info
345 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
347 # use /dev/null for stdin, /var/log/boot.log for stdout/err
350 os.open("/dev/null", os.O_RDONLY)
352 log = open("/var/log/boot.log", "w", 0)
354 # XXX - close all other fds
356 print >>log, ("%s: starting the virtual server %s" %
357 (time.asctime(time.gmtime()), self.name))
359 # perform pre-init cleanup
360 self.__prep(runlevel, log)
362 # execute each init script in turn
363 # XXX - we don't support all scripts that vserver script does
366 for cmd in self.INITSCRIPTS + [None]:
367 # wait for previous command to terminate, unless it
368 # is the last one and the caller has specified to wait
369 if cmd_pid and (cmd != None or wait):
371 os.waitpid(cmd_pid, 0)
373 print >>log, "error waiting for %s:" % cmd_pid
374 traceback.print_exc()
380 # fork and exec next command
384 # enter vserver context
385 self.__do_chcontext(state_file)
386 arg_subst = { 'runlevel': runlevel }
387 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
389 print >>log, "executing '%s'" % " ".join(cmd_args)
390 os.execl(cmd[0], *cmd_args)
392 traceback.print_exc()
395 # don't want to write state_file multiple times
398 # we get here due to an exception in the top-level child process
399 except Exception, ex:
400 traceback.print_exc()
406 def update_resources(self, resources):
408 self.config.update(resources)
410 # write new values to configuration file
411 self.__update_config_file(self.config_file, resources)
413 # disklimit can be applied without a process in context
414 disklimit = resources.get("DISKLIMIT", 0)
416 self.set_disklimit(disklimit)
419 # Figure out if any processes are active in context, apply new
420 # values if there are.
423 def init_disk_info(self):
425 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
426 self.disk_usage_set = False