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):
117 def set_disklimit(self, block_limit):
119 # block_limit is in kB, get_disk_usage() must have been called
120 if self.disk_usage_set:
121 block_usage = vserverimpl.DLIMIT_KEEP
122 inode_usage = vserverimpl.DLIMIT_KEEP
124 block_usage = self.disk_blocks
125 inode_usage = self.disk_inodes
126 if block_limit < block_usage:
127 raise Exception, ("%s disk usage (%u blocks) > limit (%u)" %
128 (self.name, block_usage, block_limit))
129 self.disk_usage_set = True
131 vserverimpl.setdlimit(self.dir,
136 vserverimpl.DLIMIT_INF, # inode limit
137 2) # %age reserved for root
139 def get_disklimit(self):
142 blocksused, blocktotal, inodesused, inodestotal, reserved = \
143 vserverimpl.getdlimit(self.dir, self.ctx)
145 if ex.errno == errno.ESRCH:
146 # get here if no vserver disk limit has been set for xid
147 # set blockused to -1 to indicate no limit
152 def set_sched(self, shares = 32, besteffort = True):
153 # for the old CKRM scheduler
154 if cpulimit.checkckrm() is True:
156 cpulimit.vs2ckrm_on(self.name)
158 cpulimit.cpulimit(self.name,shares)
161 print "invalid shares argument"
162 # should re-raise exception?!
164 # for the new vserver scheduler
166 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX, SCHED_TOKENS, SCHED_INTERVAL
167 tokensmin = SCHED_TOKENS_MIN
168 tokensmax = SCHED_TOKENS_MAX
169 tokens = SCHED_TOKENS
170 interval = SCHED_INTERVAL
173 if besteffort is True:
179 vserverimpl.setsched(self.ctx,fillrate,interval,tokens,tokensmin,tokensmax,cpuguaranteed)
182 print "kernel does not support vserver scheduler"
187 # have no way of querying scheduler right now on a per vserver basis
190 def set_memlimit(self, limit):
191 ret = vserverimpl.setrlimit(self.ctx,5,limit)
194 def get_memlimit(self):
195 ret = vserverimpl.getrlimit(self.ctx,5)
198 def set_tasklimit(self, limit):
199 ret = vserverimpl.setrlimit(self.ctx,6,limit)
202 def get_tasklimit(self):
203 ret = vserverimpl.getrlimit(self.ctx,6)
206 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
208 bwlimit.off(self.ctx,eth)
210 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
212 def get_bwlimit(self, eth):
213 # not implemented yet
218 return (bwlimit, cap, minrate, maxrate)
220 def open(self, filename, mode = "r", bufsize = -1):
222 (sendsock, recvsock) = passfdimpl.socketpair()
223 child_pid = os.fork()
228 f = open(filename, mode)
229 passfdimpl.sendmsg(f.fileno(), sendsock)
231 except EnvironmentError, ex:
232 (result, errmsg) = (ex.errno, ex.strerror)
233 except Exception, ex:
234 (result, errmsg) = (255, str(ex))
235 os.write(sendsock, errmsg)
240 # XXX - need this since a lambda can't raise an exception
245 throw = lambda : __throw(Exception(errmsg))
248 (pid, status) = os.waitpid(child_pid, 0)
249 if os.WIFEXITED(status):
250 result = os.WEXITSTATUS(status)
252 errmsg = os.strerror(result)
253 throw = lambda : __throw(IOError(result, errmsg))
255 errmsg = "unexpected exception in child"
258 errmsg = "child killed"
261 if ex.errno != errno.EINTR:
264 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
266 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
268 if ex.errno != errno.EAGAIN:
269 throw = lambda : __throw(ex)
275 return os.fdopen(fd, mode, bufsize)
277 def __do_chcontext(self, state_file = None):
279 vserverimpl.chcontext(self.ctx)
283 print >>state_file, "S_CONTEXT=%d" % self.ctx
284 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
287 def __prep(self, runlevel, log):
289 """ Perform all the crap that the vserver script does before
290 actually executing the startup scripts. """
292 # remove /var/run and /var/lock/subsys files
293 # but don't remove utmp from the top-level /var/run
295 LOCKDIR = "/var/lock/subsys"
296 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
297 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
298 (out + map((dir + "/").__add__, ff(files)),
300 list(os.walk(RUNDIR)),
302 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
303 os.listdir(LOCKDIR)))
307 # set the initial runlevel
308 f = open(RUNDIR + "/utmp", "w")
309 utmp.set_runlevel(f, runlevel)
312 # mount /proc and /dev/pts
313 self.__do_mount("none", "/proc", "proc")
314 # XXX - magic mount options
315 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
317 def __do_mount(self, *mount_args):
320 mountimpl.mount(*mount_args)
322 if ex.errno == errno.EBUSY:
323 # assume already mounted
329 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
331 self.__do_chcontext(state_file)
333 def start(self, wait, runlevel = 3):
335 # XXX - temporary hack
336 self.set_disklimit(int(self.config.get("DISKLIMIT", 5000000)))
338 child_pid = os.fork()
345 # open state file to record vserver info
346 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
348 # use /dev/null for stdin, /var/log/boot.log for stdout/err
351 os.open("/dev/null", os.O_RDONLY)
353 log = open("/var/log/boot.log", "w", 0)
355 # XXX - close all other fds
357 print >>log, ("%s: starting the virtual server %s" %
358 (time.asctime(time.gmtime()), self.name))
360 # perform pre-init cleanup
361 self.__prep(runlevel, log)
363 # execute each init script in turn
364 # XXX - we don't support all scripts that vserver script does
367 for cmd in self.INITSCRIPTS + [None]:
368 # wait for previous command to terminate, unless it
369 # is the last one and the caller has specified to wait
370 if cmd_pid and (cmd != None or wait):
372 os.waitpid(cmd_pid, 0)
374 print >>log, "error waiting for %s:" % cmd_pid
375 traceback.print_exc()
381 # fork and exec next command
385 # enter vserver context
386 self.__do_chcontext(state_file)
387 arg_subst = { 'runlevel': runlevel }
388 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
390 print >>log, "executing '%s'" % " ".join(cmd_args)
391 os.execl(cmd[0], *cmd_args)
393 traceback.print_exc()
396 # don't want to write state_file multiple times
399 # we get here due to an exception in the top-level child process
400 except Exception, ex:
401 traceback.print_exc()
407 def update_resources(self, resources):
409 self.config.update(resources)
411 # write new values to configuration file
412 self.__update_config_file(self.config_file, resources)
414 # disklimit can be applied without a process in context
415 disklimit = resources.get("DISKLIMIT", 0)
417 self.set_disklimit(disklimit)
420 # Figure out if any processes are active in context, apply new
421 # values if there are.
424 def init_disk_info(self):
426 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
427 self.disk_usage_set = False