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, disk_usage_set = False):
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"])
61 self.disk_usage_set = disk_usage_set
63 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
65 def __read_config_file(self, filename):
67 f = open(filename, "r")
71 for m in self.config_var_re.finditer(data):
72 (key, val) = m.groups()
73 config[key] = val.strip('"')
76 def __update_config_file(self, filename, newvars):
78 # read old file, apply changes
79 f = open(filename, "r")
84 for m in self.config_var_re.finditer(data):
85 (key, val) = m.groups()
86 newval = todo.pop(key, None)
88 data = data[:m.start(2)] + str(newval) + data[m.end(2):]
90 for (newkey, newval) in todo.items():
91 data += "%s=%s\n" % (newkey, newval)
98 newfile = filename + ".new"
99 f = open(newfile, "w")
103 # 'copy' original file, rename new to original
104 backup = filename + ".old"
108 if ex.errno != errno.ENOENT:
110 os.link(filename, backup)
111 os.rename(newfile, filename)
113 def __do_chroot(self):
118 def set_disklimit(self, block_limit):
120 # block_limit is in kB
121 if self.disk_usage_set:
122 block_usage = vserverimpl.DLIMIT_KEEP
123 inode_usage = vserverimpl.DLIMIT_KEEP
125 # init_disk_info() must have been called to get usage values
126 block_usage = self.disk_blocks
127 inode_usage = self.disk_inodes
128 if block_limit < block_usage:
129 raise Exception, ("%s disk usage (%u blocks) > limit (%u)" %
130 (self.name, block_usage, block_limit))
131 self.disk_usage_set = True
133 vserverimpl.setdlimit(self.dir,
138 vserverimpl.DLIMIT_INF, # inode limit
139 2) # %age reserved for root
141 def get_disklimit(self):
144 blocksused, blocktotal, inodesused, inodestotal, reserved = \
145 vserverimpl.getdlimit(self.dir, self.ctx)
147 if ex.errno == errno.ESRCH:
148 # get here if no vserver disk limit has been set for xid
149 # set blockused to -1 to indicate no limit
154 def set_sched(self, shares = 32, besteffort = True):
155 # for the old CKRM scheduler
156 if cpulimit.checkckrm() is True:
158 cpulimit.vs2ckrm_on(self.name)
160 cpulimit.cpulimit(self.name,shares)
163 print "invalid shares argument"
164 # should re-raise exception?!
166 # for the new vserver scheduler
168 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX, SCHED_TOKENS, SCHED_INTERVAL
169 tokensmin = SCHED_TOKENS_MIN
170 tokensmax = SCHED_TOKENS_MAX
171 tokens = SCHED_TOKENS
172 interval = SCHED_INTERVAL
175 if besteffort is True:
181 vserverimpl.setsched(self.ctx,fillrate,interval,tokens,tokensmin,tokensmax,cpuguaranteed)
184 print "kernel does not support vserver scheduler"
189 # have no way of querying scheduler right now on a per vserver basis
192 def set_memlimit(self, limit):
193 ret = vserverimpl.setrlimit(self.ctx,5,limit)
196 def get_memlimit(self):
197 ret = vserverimpl.getrlimit(self.ctx,5)
200 def set_tasklimit(self, limit):
201 ret = vserverimpl.setrlimit(self.ctx,6,limit)
204 def get_tasklimit(self):
205 ret = vserverimpl.getrlimit(self.ctx,6)
208 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
210 bwlimit.off(self.ctx,eth)
212 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
214 def get_bwlimit(self, eth):
215 # not implemented yet
220 return (bwlimit, cap, minrate, maxrate)
222 def open(self, filename, mode = "r", bufsize = -1):
224 (sendsock, recvsock) = passfdimpl.socketpair()
225 child_pid = os.fork()
230 f = open(filename, mode)
231 passfdimpl.sendmsg(f.fileno(), sendsock)
233 except EnvironmentError, ex:
234 (result, errmsg) = (ex.errno, ex.strerror)
235 except Exception, ex:
236 (result, errmsg) = (255, str(ex))
237 os.write(sendsock, errmsg)
242 # XXX - need this since a lambda can't raise an exception
247 throw = lambda : __throw(Exception(errmsg))
250 (pid, status) = os.waitpid(child_pid, 0)
251 if os.WIFEXITED(status):
252 result = os.WEXITSTATUS(status)
254 errmsg = os.strerror(result)
255 throw = lambda : __throw(IOError(result, errmsg))
257 errmsg = "unexpected exception in child"
260 errmsg = "child killed"
263 if ex.errno != errno.EINTR:
266 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
268 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
270 if ex.errno != errno.EAGAIN:
271 throw = lambda : __throw(ex)
277 return os.fdopen(fd, mode, bufsize)
279 def __do_chcontext(self, state_file = None):
281 vserverimpl.chcontext(self.ctx)
285 print >>state_file, "S_CONTEXT=%d" % self.ctx
286 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
289 def __prep(self, runlevel, log):
291 """ Perform all the crap that the vserver script does before
292 actually executing the startup scripts. """
294 # remove /var/run and /var/lock/subsys files
295 # but don't remove utmp from the top-level /var/run
297 LOCKDIR = "/var/lock/subsys"
298 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
299 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
300 (out + map((dir + "/").__add__, ff(files)),
302 list(os.walk(RUNDIR)),
304 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
305 os.listdir(LOCKDIR)))
309 # set the initial runlevel
310 f = open(RUNDIR + "/utmp", "w")
311 utmp.set_runlevel(f, runlevel)
314 # mount /proc and /dev/pts
315 self.__do_mount("none", "/proc", "proc")
316 # XXX - magic mount options
317 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
319 def __do_mount(self, *mount_args):
322 mountimpl.mount(*mount_args)
324 if ex.errno == errno.EBUSY:
325 # assume already mounted
331 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
333 self.__do_chcontext(state_file)
335 def start(self, wait, runlevel = 3):
337 # XXX - temporary hack
338 self.set_disklimit(int(self.config.get("DISKLIMIT", 5000000)))
340 child_pid = os.fork()
347 # open state file to record vserver info
348 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
350 # use /dev/null for stdin, /var/log/boot.log for stdout/err
353 os.open("/dev/null", os.O_RDONLY)
355 log = open("/var/log/boot.log", "w", 0)
357 # XXX - close all other fds
359 print >>log, ("%s: starting the virtual server %s" %
360 (time.asctime(time.gmtime()), self.name))
362 # perform pre-init cleanup
363 self.__prep(runlevel, log)
365 # execute each init script in turn
366 # XXX - we don't support all scripts that vserver script does
369 for cmd in self.INITSCRIPTS + [None]:
370 # wait for previous command to terminate, unless it
371 # is the last one and the caller has specified to wait
372 if cmd_pid and (cmd != None or wait):
374 os.waitpid(cmd_pid, 0)
376 print >>log, "error waiting for %s:" % cmd_pid
377 traceback.print_exc()
383 # fork and exec next command
387 # enter vserver context
388 self.__do_chcontext(state_file)
389 arg_subst = { 'runlevel': runlevel }
390 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
392 print >>log, "executing '%s'" % " ".join(cmd_args)
393 os.execl(cmd[0], *cmd_args)
395 traceback.print_exc()
398 # don't want to write state_file multiple times
401 # we get here due to an exception in the top-level child process
402 except Exception, ex:
403 traceback.print_exc()
409 def update_resources(self, resources):
411 self.config.update(resources)
413 # write new values to configuration file
414 self.__update_config_file(self.config_file, resources)
416 # disklimit can be applied without a process in context
417 disklimit = resources.get("DISKLIMIT", 0)
419 self.set_disklimit(disklimit)
422 # Figure out if any processes are active in context, apply new
423 # values if there are.
426 def init_disk_info(self):
428 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)