1 # Copyright 2005 Princeton University
15 import vserverimpl, vduimpl
16 import cpulimit, bwlimit
18 from util_vserver_vars import *
20 CAP_SAFE = (linuxcaps.CAP_CHOWN |
21 linuxcaps.CAP_DAC_OVERRIDE |
22 linuxcaps.CAP_DAC_READ_SEARCH |
23 linuxcaps.CAP_FOWNER |
24 linuxcaps.CAP_FSETID |
26 linuxcaps.CAP_SETGID |
27 linuxcaps.CAP_SETUID |
28 linuxcaps.CAP_SETPCAP |
29 linuxcaps.CAP_SYS_TTY_CONFIG |
31 linuxcaps.CAP_SYS_CHROOT |
32 linuxcaps.CAP_SYS_PTRACE)
35 # these are the flags taken from the kernel linux/vserver/legacy.h
38 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
46 # default values for new vserver scheduler
48 SCHED_TOKENS_MAX = 100
53 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
54 ('/etc/rc.d/rc', '%(runlevel)d')]
56 def __init__(self, name):
59 self.config = self.__read_config_file("/etc/vservers.conf")
60 self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
63 flags = self.config["S_FLAGS"].split(" ")
65 self.flags |= FLAGS_LOCK
67 self.flags |= FLAGS_NPROC
68 self.remove_caps = ~CAP_SAFE
69 self.ctx = int(self.config["S_CONTEXT"])
71 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
73 def __read_config_file(self, filename):
75 f = open(filename, "r")
79 for m in self.config_var_re.finditer(data):
80 (key, val) = m.groups()
81 config[key] = val.strip('"')
84 def __do_chroot(self):
86 return os.chroot("%s/%s" % (__DEFAULT_VSERVERDIR, self.name))
88 def set_disklimit(self, blocktotal):
89 path = "%s/%s" % (__DEFAULT_VSERVERDIR, self.name)
90 inodes, blockcount, size = vduimpl.vdu(path)
91 blockcount = blockcount >> 1
93 if blocktotal > blockcount:
94 vserverimpl.setdlimit(path, self.ctx, blockcount>>1, \
95 blocktotal, inodes, -1, 2)
97 # should raise some error value
98 print "block limit (%d) ignored for vserver %s" %(blocktotal,self.name)
100 def get_disklimit(self):
101 path = "%s/%s" % (__DEFAULT_VSERVERDIR, self.name)
103 blocksused, blocktotal, inodesused, inodestotal, reserved = \
104 vserverimpl.getdlimit(path,self.ctx)
107 # get here if no vserver disk limit has been set for xid
108 # set blockused to -1 to indicate no limit
113 def set_sched(self, shares, besteffort = True):
114 # for the old CKRM scheduler
115 if cpulimit.checkckrm() is True:
117 cpulimit.vs2ckrm_on(self.name)
119 cpulimit.cpulimit(self.name,shares)
122 print "invalid shares argument"
123 # should re-raise exception?!
125 # for the new vserver scheduler
127 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX
128 tokensmin = SCHED_TOKENS_MIN
129 tokensmax = SCHED_TOKENS_MAX
131 if besteffort is True:
132 # magic "interval" value for Andy's scheduler to denote besteffort
140 vserverimpl.setsched(self.ctx,fillrate,interval,tokensmin,tokensmax)
143 print "kernel does not support vserver scheduler"
148 # have no way of querying scheduler right now on a per vserver basis
151 def set_memlimit(self, limit):
152 ret = vserverimpl.setrlimit(self.ctx,5,limit)
155 def get_memlimit(self):
156 ret = vserverimpl.getrlimit(self.ctx,5)
159 def set_tasklimit(self, limit):
160 ret = vserverimpl.setrlimit(self.ctx,6,limit)
163 def get_tasklimit(self):
164 ret = vserverimpl.getrlimit(self.ctx,6)
167 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
169 bwlimit.off(self.ctx,eth)
171 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
173 def get_bwlimit(self, eth):
174 # not implemented yet
179 return (bwlimit, cap, minrate, maxrate)
181 def open(self, filename, mode = "r", bufsize = -1):
183 (sendsock, recvsock) = passfdimpl.socketpair()
184 child_pid = os.fork()
189 f = open(filename, mode)
190 passfdimpl.sendmsg(f.fileno(), sendsock)
192 except EnvironmentError, ex:
193 (result, errmsg) = (ex.errno, ex.strerror)
194 except Exception, ex:
195 (result, errmsg) = (255, str(ex))
196 os.write(sendsock, errmsg)
201 # XXX - need this since a lambda can't raise an exception
206 throw = lambda : __throw(Exception(errmsg))
209 (pid, status) = os.waitpid(child_pid, 0)
210 if os.WIFEXITED(status):
211 result = os.WEXITSTATUS(status)
213 errmsg = os.strerror(result)
214 throw = lambda : __throw(IOError(result, errmsg))
216 errmsg = "unexpected exception in child"
219 errmsg = "child killed"
222 if ex.errno != errno.EINTR:
225 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
227 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
229 if ex.errno != errno.EAGAIN:
230 throw = lambda : __throw(ex)
236 return os.fdopen(fd, mode, bufsize)
238 def __do_chcontext(self, state_file = None):
240 vserverimpl.chcontext(self.ctx, self.remove_caps)
243 print >>state_file, "S_CONTEXT=%d" % self.ctx
244 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
247 def __prep(self, runlevel, log):
249 """ Perform all the crap that the vserver script does before
250 actually executing the startup scripts. """
252 # remove /var/run and /var/lock/subsys files
253 # but don't remove utmp from the top-level /var/run
255 LOCKDIR = "/var/lock/subsys"
256 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
257 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
258 (out + map((dir + "/").__add__, ff(files)),
260 list(os.walk(RUNDIR)),
262 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
263 os.listdir(LOCKDIR)))
267 # set the initial runlevel
268 f = open(RUNDIR + "/utmp", "w")
269 utmp.set_runlevel(f, runlevel)
272 # mount /proc and /dev/pts
273 self.__do_mount("none", "/proc", "proc")
274 # XXX - magic mount options
275 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
277 def __do_mount(self, *mount_args):
280 mountimpl.mount(*mount_args)
282 if ex.errno == errno.EBUSY:
283 # assume already mounted
289 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
291 self.__do_chcontext(state_file)
293 def start(self, wait, runlevel = 3):
295 child_pid = os.fork()
302 # open state file to record vserver info
303 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
305 # use /dev/null for stdin, /var/log/boot.log for stdout/err
308 os.open("/dev/null", os.O_RDONLY)
310 log = open("/var/log/boot.log", "w", 0)
313 print >>log, ("%s: starting the virtual server %s" %
314 (time.asctime(time.gmtime()), self.name))
316 # perform pre-init cleanup
317 self.__prep(runlevel, log)
319 # execute each init script in turn
320 # XXX - we don't support all scripts that vserver script does
322 for cmd in self.INITSCRIPTS + [None]:
323 # wait for previous command to terminate, unless it
324 # is the last one and the caller has specified to wait
325 if cmd_pid and (cmd != None or wait):
327 os.waitpid(cmd_pid, 0)
329 print >>log, "error waiting for %s:" % cmd_pid
330 traceback.print_exc()
336 # fork and exec next command
340 # enter vserver context
341 self.__do_chcontext(state_file)
342 arg_subst = { 'runlevel': runlevel }
343 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
345 print >>log, "executing '%s'" % " ".join(cmd_args)
346 os.execl(cmd[0], *cmd_args)
348 traceback.print_exc()
351 # don't want to write state_file multiple times
354 # we get here due to an exception in the top-level child process
355 except Exception, ex:
356 traceback.print_exc()