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"])
66 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
68 def __read_config_file(self, filename):
70 f = open(filename, "r")
74 for m in self.config_var_re.finditer(data):
75 (key, val) = m.groups()
76 config[key] = val.strip('"')
79 def __update_config_file(self, filename, newvars):
81 # read old file, apply changes
82 f = open(filename, "r")
87 for m in self.config_var_re.finditer(data):
88 (key, val) = m.groups()
89 newval = todo.pop(key, None)
91 data = data[:m.start(2)] + newval + data[m.end(2):]
93 for (newkey, newval) in todo.items():
94 data += "%s=%s\n" % (newkey, newval)
101 newfile = filename + ".new"
102 f = open(newfile, "w")
106 # 'copy' original file, rename new to original
107 os.link(filename, filename + ".old")
108 os.rename(newfile, filename)
110 def __do_chroot(self):
112 return os.chroot(self.dir)
114 def set_disklimit(self, block_limit):
116 # block_limit is in kB, get_disk_usage() must have been called
117 if self.disk_usage_set:
118 block_usage = vserverimpl.DLIMIT_KEEP
119 inode_usage = vserverimpl.DLIMIT_KEEP
121 block_usage = self.disk_blocks
122 inode_usage = self.disk_inodes
123 if block_limit < block_usage:
124 raise Exception, ("%s disk usage (%u blocks) > limit (%u)" %
125 (self.name, block_usage, block_limit))
126 self.disk_usage_set = True
128 vserverimpl.setdlimit(self.dir,
134 2) # %age reserved for root
136 def get_disklimit(self):
139 blocksused, blocktotal, inodesused, inodestotal, reserved = \
140 vserverimpl.getdlimit(self.dir, self.ctx)
142 if ex.errno == errno.ESRCH:
143 # get here if no vserver disk limit has been set for xid
144 # set blockused to -1 to indicate no limit
149 def set_sched(self, shares = 32, besteffort = True):
150 # for the old CKRM scheduler
151 if cpulimit.checkckrm() is True:
153 cpulimit.vs2ckrm_on(self.name)
155 cpulimit.cpulimit(self.name,shares)
158 print "invalid shares argument"
159 # should re-raise exception?!
161 # for the new vserver scheduler
163 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX, SCHED_TOKENS, SCHED_INTERVAL
164 tokensmin = SCHED_TOKENS_MIN
165 tokensmax = SCHED_TOKENS_MAX
166 tokens = SCHED_TOKENS
167 interval = SCHED_INTERVAL
170 if besteffort is True:
176 vserverimpl.setsched(self.ctx,fillrate,interval,tokens,tokensmin,tokensmax,cpuguaranteed)
179 print "kernel does not support vserver scheduler"
184 # have no way of querying scheduler right now on a per vserver basis
187 def set_memlimit(self, limit):
188 ret = vserverimpl.setrlimit(self.ctx,5,limit)
191 def get_memlimit(self):
192 ret = vserverimpl.getrlimit(self.ctx,5)
195 def set_tasklimit(self, limit):
196 ret = vserverimpl.setrlimit(self.ctx,6,limit)
199 def get_tasklimit(self):
200 ret = vserverimpl.getrlimit(self.ctx,6)
203 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
205 bwlimit.off(self.ctx,eth)
207 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
209 def get_bwlimit(self, eth):
210 # not implemented yet
215 return (bwlimit, cap, minrate, maxrate)
217 def open(self, filename, mode = "r", bufsize = -1):
219 (sendsock, recvsock) = passfdimpl.socketpair()
220 child_pid = os.fork()
225 f = open(filename, mode)
226 passfdimpl.sendmsg(f.fileno(), sendsock)
228 except EnvironmentError, ex:
229 (result, errmsg) = (ex.errno, ex.strerror)
230 except Exception, ex:
231 (result, errmsg) = (255, str(ex))
232 os.write(sendsock, errmsg)
237 # XXX - need this since a lambda can't raise an exception
242 throw = lambda : __throw(Exception(errmsg))
245 (pid, status) = os.waitpid(child_pid, 0)
246 if os.WIFEXITED(status):
247 result = os.WEXITSTATUS(status)
249 errmsg = os.strerror(result)
250 throw = lambda : __throw(IOError(result, errmsg))
252 errmsg = "unexpected exception in child"
255 errmsg = "child killed"
258 if ex.errno != errno.EINTR:
261 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
263 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
265 if ex.errno != errno.EAGAIN:
266 throw = lambda : __throw(ex)
272 return os.fdopen(fd, mode, bufsize)
274 def __do_chcontext(self, state_file = None):
276 vserverimpl.chcontext(self.ctx)
280 print >>state_file, "S_CONTEXT=%d" % self.ctx
281 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
284 def __prep(self, runlevel, log):
286 """ Perform all the crap that the vserver script does before
287 actually executing the startup scripts. """
289 # remove /var/run and /var/lock/subsys files
290 # but don't remove utmp from the top-level /var/run
292 LOCKDIR = "/var/lock/subsys"
293 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
294 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
295 (out + map((dir + "/").__add__, ff(files)),
297 list(os.walk(RUNDIR)),
299 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
300 os.listdir(LOCKDIR)))
304 # set the initial runlevel
305 f = open(RUNDIR + "/utmp", "w")
306 utmp.set_runlevel(f, runlevel)
309 # mount /proc and /dev/pts
310 self.__do_mount("none", "/proc", "proc")
311 # XXX - magic mount options
312 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
314 def __do_mount(self, *mount_args):
317 mountimpl.mount(*mount_args)
319 if ex.errno == errno.EBUSY:
320 # assume already mounted
326 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
328 self.__do_chcontext(state_file)
330 def start(self, wait, runlevel = 3):
332 child_pid = os.fork()
339 # open state file to record vserver info
340 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
342 # use /dev/null for stdin, /var/log/boot.log for stdout/err
345 os.open("/dev/null", os.O_RDONLY)
347 log = open("/var/log/boot.log", "w", 0)
350 print >>log, ("%s: starting the virtual server %s" %
351 (time.asctime(time.gmtime()), self.name))
353 # perform pre-init cleanup
354 self.__prep(runlevel, log)
356 # execute each init script in turn
357 # XXX - we don't support all scripts that vserver script does
359 for cmd in self.INITSCRIPTS + [None]:
360 # wait for previous command to terminate, unless it
361 # is the last one and the caller has specified to wait
362 if cmd_pid and (cmd != None or wait):
364 os.waitpid(cmd_pid, 0)
366 print >>log, "error waiting for %s:" % cmd_pid
367 traceback.print_exc()
373 # fork and exec next command
377 # enter vserver context
378 self.__do_chcontext(state_file)
379 arg_subst = { 'runlevel': runlevel }
380 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
382 print >>log, "executing '%s'" % " ".join(cmd_args)
383 os.execl(cmd[0], *cmd_args)
385 traceback.print_exc()
388 # don't want to write state_file multiple times
391 # we get here due to an exception in the top-level child process
392 except Exception, ex:
393 traceback.print_exc()
399 def update_resources(self, resources):
401 # write new values to configuration file
402 self.__update_config_file(self.config_file, resources)
405 # Figure out if any processes are active in context, apply new
406 # values if there are.
409 def init_disk_info(self):
411 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
412 self.disk_usage_set = False