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"
105 os.link(filename, backup)
106 os.rename(newfile, filename)
108 def __do_chroot(self):
110 return os.chroot(self.dir)
112 def set_disklimit(self, block_limit):
114 # block_limit is in kB, get_disk_usage() must have been called
115 if self.disk_usage_set:
116 block_usage = vserverimpl.DLIMIT_KEEP
117 inode_usage = vserverimpl.DLIMIT_KEEP
119 block_usage = self.disk_blocks
120 inode_usage = self.disk_inodes
121 if block_limit < block_usage:
122 raise Exception, ("%s disk usage (%u blocks) > limit (%u)" %
123 (self.name, block_usage, block_limit))
124 self.disk_usage_set = True
126 vserverimpl.setdlimit(self.dir,
132 2) # %age reserved for root
134 def get_disklimit(self):
137 blocksused, blocktotal, inodesused, inodestotal, reserved = \
138 vserverimpl.getdlimit(self.dir, self.ctx)
140 if ex.errno == errno.ESRCH:
141 # get here if no vserver disk limit has been set for xid
142 # set blockused to -1 to indicate no limit
147 def set_sched(self, shares = 32, besteffort = True):
148 # for the old CKRM scheduler
149 if cpulimit.checkckrm() is True:
151 cpulimit.vs2ckrm_on(self.name)
153 cpulimit.cpulimit(self.name,shares)
156 print "invalid shares argument"
157 # should re-raise exception?!
159 # for the new vserver scheduler
161 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX, SCHED_TOKENS, SCHED_INTERVAL
162 tokensmin = SCHED_TOKENS_MIN
163 tokensmax = SCHED_TOKENS_MAX
164 tokens = SCHED_TOKENS
165 interval = SCHED_INTERVAL
168 if besteffort is True:
174 vserverimpl.setsched(self.ctx,fillrate,interval,tokens,tokensmin,tokensmax,cpuguaranteed)
177 print "kernel does not support vserver scheduler"
182 # have no way of querying scheduler right now on a per vserver basis
185 def set_memlimit(self, limit):
186 ret = vserverimpl.setrlimit(self.ctx,5,limit)
189 def get_memlimit(self):
190 ret = vserverimpl.getrlimit(self.ctx,5)
193 def set_tasklimit(self, limit):
194 ret = vserverimpl.setrlimit(self.ctx,6,limit)
197 def get_tasklimit(self):
198 ret = vserverimpl.getrlimit(self.ctx,6)
201 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
203 bwlimit.off(self.ctx,eth)
205 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
207 def get_bwlimit(self, eth):
208 # not implemented yet
213 return (bwlimit, cap, minrate, maxrate)
215 def open(self, filename, mode = "r", bufsize = -1):
217 (sendsock, recvsock) = passfdimpl.socketpair()
218 child_pid = os.fork()
223 f = open(filename, mode)
224 passfdimpl.sendmsg(f.fileno(), sendsock)
226 except EnvironmentError, ex:
227 (result, errmsg) = (ex.errno, ex.strerror)
228 except Exception, ex:
229 (result, errmsg) = (255, str(ex))
230 os.write(sendsock, errmsg)
235 # XXX - need this since a lambda can't raise an exception
240 throw = lambda : __throw(Exception(errmsg))
243 (pid, status) = os.waitpid(child_pid, 0)
244 if os.WIFEXITED(status):
245 result = os.WEXITSTATUS(status)
247 errmsg = os.strerror(result)
248 throw = lambda : __throw(IOError(result, errmsg))
250 errmsg = "unexpected exception in child"
253 errmsg = "child killed"
256 if ex.errno != errno.EINTR:
259 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
261 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
263 if ex.errno != errno.EAGAIN:
264 throw = lambda : __throw(ex)
270 return os.fdopen(fd, mode, bufsize)
272 def __do_chcontext(self, state_file = None):
274 vserverimpl.chcontext(self.ctx)
278 print >>state_file, "S_CONTEXT=%d" % self.ctx
279 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
282 def __prep(self, runlevel, log):
284 """ Perform all the crap that the vserver script does before
285 actually executing the startup scripts. """
287 # remove /var/run and /var/lock/subsys files
288 # but don't remove utmp from the top-level /var/run
290 LOCKDIR = "/var/lock/subsys"
291 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
292 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
293 (out + map((dir + "/").__add__, ff(files)),
295 list(os.walk(RUNDIR)),
297 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
298 os.listdir(LOCKDIR)))
302 # set the initial runlevel
303 f = open(RUNDIR + "/utmp", "w")
304 utmp.set_runlevel(f, runlevel)
307 # mount /proc and /dev/pts
308 self.__do_mount("none", "/proc", "proc")
309 # XXX - magic mount options
310 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
312 def __do_mount(self, *mount_args):
315 mountimpl.mount(*mount_args)
317 if ex.errno == errno.EBUSY:
318 # assume already mounted
324 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
326 self.__do_chcontext(state_file)
328 def start(self, wait, runlevel = 3):
330 # XXX - temporary hack
331 self.set_disklimit(self.config.get("DISKLIMIT", 5000000))
333 child_pid = os.fork()
340 # open state file to record vserver info
341 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
343 # use /dev/null for stdin, /var/log/boot.log for stdout/err
346 os.open("/dev/null", os.O_RDONLY)
348 log = open("/var/log/boot.log", "w", 0)
350 # XXX - close all other fds
352 print >>log, ("%s: starting the virtual server %s" %
353 (time.asctime(time.gmtime()), self.name))
355 # perform pre-init cleanup
356 self.__prep(runlevel, log)
358 # execute each init script in turn
359 # XXX - we don't support all scripts that vserver script does
362 for cmd in self.INITSCRIPTS + [None]:
363 # wait for previous command to terminate, unless it
364 # is the last one and the caller has specified to wait
365 if cmd_pid and (cmd != None or wait):
367 os.waitpid(cmd_pid, 0)
369 print >>log, "error waiting for %s:" % cmd_pid
370 traceback.print_exc()
376 # fork and exec next command
380 # enter vserver context
381 self.__do_chcontext(state_file)
382 arg_subst = { 'runlevel': runlevel }
383 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
385 print >>log, "executing '%s'" % " ".join(cmd_args)
386 os.execl(cmd[0], *cmd_args)
388 traceback.print_exc()
391 # don't want to write state_file multiple times
394 # we get here due to an exception in the top-level child process
395 except Exception, ex:
396 traceback.print_exc()
402 def update_resources(self, resources):
404 self.config.update(resources)
406 # write new values to configuration file
407 self.__update_config_file(self.config_file, resources)
409 # disklimit can be applied without a process in context
410 disklimit = resources.get("DISKLIMIT", 0)
412 self.set_disklimit(disklimit)
415 # Figure out if any processes are active in context, apply new
416 # values if there are.
419 def init_disk_info(self):
421 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
422 self.disk_usage_set = False