1 # Copyright 2005 Princeton University
15 import vserverimpl, vduimpl
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" % (VROOTDIR, self.name))
88 def set_dlimit(self, blocktotal):
89 path = "%s/%s" % (VROOTDIR, 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_dlimit(self):
101 path = "%s/%s" % (VROOTDIR, 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 open(self, filename, mode = "r", bufsize = -1):
169 (sendsock, recvsock) = passfdimpl.socketpair()
170 child_pid = os.fork()
175 f = open(filename, mode)
176 passfdimpl.sendmsg(f.fileno(), sendsock)
178 except EnvironmentError, ex:
179 (result, errmsg) = (ex.errno, ex.strerror)
180 except Exception, ex:
181 (result, errmsg) = (255, str(ex))
182 os.write(sendsock, errmsg)
187 # XXX - need this since a lambda can't raise an exception
192 throw = lambda : __throw(Exception(errmsg))
195 (pid, status) = os.waitpid(child_pid, 0)
196 if os.WIFEXITED(status):
197 result = os.WEXITSTATUS(status)
199 errmsg = os.strerror(result)
200 throw = lambda : __throw(IOError(result, errmsg))
202 errmsg = "unexpected exception in child"
205 errmsg = "child killed"
208 if ex.errno != errno.EINTR:
211 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
213 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
215 if ex.errno != errno.EAGAIN:
216 throw = lambda : __throw(ex)
222 return os.fdopen(fd, mode, bufsize)
224 def __do_chcontext(self, state_file = None):
226 vserverimpl.chcontext(self.ctx, self.remove_caps)
229 print >>state_file, "S_CONTEXT=%d" % self.ctx
230 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
233 def __prep(self, runlevel, log):
235 """ Perform all the crap that the vserver script does before
236 actually executing the startup scripts. """
238 # remove /var/run and /var/lock/subsys files
239 # but don't remove utmp from the top-level /var/run
241 LOCKDIR = "/var/lock/subsys"
242 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
243 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
244 (out + map((dir + "/").__add__, ff(files)),
246 list(os.walk(RUNDIR)),
248 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
249 os.listdir(LOCKDIR)))
253 # set the initial runlevel
254 f = open(RUNDIR + "/utmp", "w")
255 utmp.set_runlevel(f, runlevel)
258 # mount /proc and /dev/pts
259 self.__do_mount("none", "/proc", "proc")
260 # XXX - magic mount options
261 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
263 def __do_mount(self, *mount_args):
266 mountimpl.mount(*mount_args)
268 if ex.errno == errno.EBUSY:
269 # assume already mounted
275 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
277 self.__do_chcontext(state_file)
279 def start(self, wait, runlevel = 3):
281 child_pid = os.fork()
288 # open state file to record vserver info
289 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
291 # use /dev/null for stdin, /var/log/boot.log for stdout/err
294 os.open("/dev/null", os.O_RDONLY)
296 log = open("/var/log/boot.log", "w", 0)
299 print >>log, ("%s: starting the virtual server %s" %
300 (time.asctime(time.gmtime()), self.name))
302 # perform pre-init cleanup
303 self.__prep(runlevel, log)
305 # execute each init script in turn
306 # XXX - we don't support all scripts that vserver script does
308 for cmd in self.INITSCRIPTS + [None]:
309 # wait for previous command to terminate, unless it
310 # is the last one and the caller has specified to wait
311 if cmd_pid and (cmd != None or wait):
313 os.waitpid(cmd_pid, 0)
315 print >>log, "error waiting for %s:" % cmd_pid
316 traceback.print_exc()
322 # fork and exec next command
326 # enter vserver context
327 self.__do_chcontext(state_file)
328 arg_subst = { 'runlevel': runlevel }
329 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
331 print >>log, "executing '%s'" % " ".join(cmd_args)
332 os.execl(cmd[0], *cmd_args)
334 traceback.print_exc()
337 # don't want to write state_file multiple times
340 # we get here due to an exception in the top-level child process
341 except Exception, ex:
342 traceback.print_exc()