1 # Copyright 2005 Princeton University
15 import vserverimpl, vduimpl
17 from util_vserver_vars import *
19 CAP_SAFE = (linuxcaps.CAP_CHOWN |
20 linuxcaps.CAP_DAC_OVERRIDE |
21 linuxcaps.CAP_DAC_READ_SEARCH |
22 linuxcaps.CAP_FOWNER |
23 linuxcaps.CAP_FSETID |
25 linuxcaps.CAP_SETGID |
26 linuxcaps.CAP_SETUID |
27 linuxcaps.CAP_SETPCAP |
28 linuxcaps.CAP_SYS_TTY_CONFIG |
30 linuxcaps.CAP_SYS_CHROOT |
31 linuxcaps.CAP_SYS_PTRACE)
34 # these are the flags taken from the kernel linux/vserver/legacy.h
37 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
45 # default values for new vserver scheduler
47 SCHED_TOKENS_MAX = 100
52 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
53 ('/etc/rc.d/rc', '%(runlevel)d')]
55 def __init__(self, name):
58 self.config = self.__read_config_file("/etc/vservers.conf")
59 self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
62 flags = self.config["S_FLAGS"].split(" ")
64 self.flags |= FLAGS_LOCK
66 self.flags |= FLAGS_NPROC
67 self.remove_caps = ~CAP_SAFE
68 self.ctx = int(self.config["S_CONTEXT"])
70 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
72 def __read_config_file(self, filename):
74 f = open(filename, "r")
78 for m in self.config_var_re.finditer(data):
79 (key, val) = m.groups()
80 config[key] = val.strip('"')
83 def __do_chroot(self):
85 return os.chroot("%s/%s" % (VROOTDIR, self.name))
87 def set_dlimit(self, blocktotal):
88 path = "%s/%s" % (VROOTDIR, self.name)
89 inodes, blockcount, size = vduimpl.vdu(path)
90 blockcount = blockcount >> 1
92 if blocktotal > blockcount:
93 vserverimpl.setdlimit(path, self.ctx, blockcount>>1, \
94 blocktotal, inodes, -1, 2)
96 # should raise some error value
97 print "block limit (%d) ignored for vserver %s" %(blocktotal,self.name)
100 path = "%s/%s" % (VROOTDIR, self.name)
102 blocksused, blocktotal, inodesused, inodestotal, reserved = \
103 vserverimpl.getdlimit(path,self.ctx)
106 # get here if no vserver disk limit has been set for xid
107 # set blockused to -1 to indicate no limit
112 def set_sched(self, shares, besteffort = True):
113 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX
114 tokensmin = SCHED_TOKENS_MIN
115 tokensmax = SCHED_TOKENS_MAX
117 if besteffort is True:
118 # magic "interval" value for Andy's scheduler to denote besteffort
126 vserverimpl.setsched(self.ctx,fillrate,interval,tokensmin,tokensmax)
129 print "kernel does not support vserver scheduler"
134 # have no way of querying scheduler right now on a per vserver basis
137 def set_memlimit(self, limit):
138 ret = vserverimpl.setrlimit(self.ctx,5,limit)
141 def get_memlimit(self):
142 ret = vserverimpl.getrlimit(self.ctx,5)
145 def set_tasklimit(self, limit):
146 ret = vserverimpl.setrlimit(self.ctx,6,limit)
149 def get_tasklimit(self):
150 ret = vserverimpl.getrlimit(self.ctx,6)
153 def open(self, filename, mode = "r", bufsize = -1):
155 (sendsock, recvsock) = passfdimpl.socketpair()
156 child_pid = os.fork()
161 f = open(filename, mode)
162 passfdimpl.sendmsg(f.fileno(), sendsock)
164 except EnvironmentError, ex:
165 (result, errmsg) = (ex.errno, ex.strerror)
166 except Exception, ex:
167 (result, errmsg) = (255, str(ex))
168 os.write(sendsock, errmsg)
173 # XXX - need this since a lambda can't raise an exception
178 throw = lambda : __throw(Exception(errmsg))
181 (pid, status) = os.waitpid(child_pid, 0)
182 if os.WIFEXITED(status):
183 result = os.WEXITSTATUS(status)
185 errmsg = os.strerror(result)
186 throw = lambda : __throw(IOError(result, errmsg))
188 errmsg = "unexpected exception in child"
191 errmsg = "child killed"
194 if ex.errno != errno.EINTR:
197 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
199 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
201 if ex.errno != errno.EAGAIN:
202 throw = lambda : __throw(ex)
208 return os.fdopen(fd, mode, bufsize)
210 def __do_chcontext(self, state_file = None):
212 vserverimpl.chcontext(self.ctx, self.remove_caps)
215 print >>state_file, "S_CONTEXT=%d" % self.ctx
216 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
219 def __prep(self, runlevel, log):
221 """ Perform all the crap that the vserver script does before
222 actually executing the startup scripts. """
224 # remove /var/run and /var/lock/subsys files
225 # but don't remove utmp from the top-level /var/run
227 LOCKDIR = "/var/lock/subsys"
228 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
229 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
230 (out + map((dir + "/").__add__, ff(files)),
232 list(os.walk(RUNDIR)),
234 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
235 os.listdir(LOCKDIR)))
239 # set the initial runlevel
240 f = open(RUNDIR + "/utmp", "w")
241 utmp.set_runlevel(f, runlevel)
244 # mount /proc and /dev/pts
245 self.__do_mount("none", "/proc", "proc")
246 # XXX - magic mount options
247 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
249 def __do_mount(self, *mount_args):
252 mountimpl.mount(*mount_args)
254 if ex.errno == errno.EBUSY:
255 # assume already mounted
261 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
263 self.__do_chcontext(state_file)
265 def start(self, wait, runlevel = 3):
267 child_pid = os.fork()
274 # open state file to record vserver info
275 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
277 # use /dev/null for stdin, /var/log/boot.log for stdout/err
280 os.open("/dev/null", os.O_RDONLY)
282 log = open("/var/log/boot.log", "w", 0)
285 print >>log, ("%s: starting the virtual server %s" %
286 (time.asctime(time.gmtime()), self.name))
288 # perform pre-init cleanup
289 self.__prep(runlevel, log)
291 # execute each init script in turn
292 # XXX - we don't support all scripts that vserver script does
294 for cmd in self.INITSCRIPTS + [None]:
295 # wait for previous command to terminate, unless it
296 # is the last one and the caller has specified to wait
297 if cmd_pid and (cmd != None or wait):
299 os.waitpid(cmd_pid, 0)
301 print >>log, "error waiting for %s:" % cmd_pid
302 traceback.print_exc()
308 # fork and exec next command
312 # enter vserver context
313 self.__do_chcontext(state_file)
314 arg_subst = { 'runlevel': runlevel }
315 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
317 print >>log, "executing '%s'" % " ".join(cmd_args)
318 os.execl(cmd[0], *cmd_args)
320 traceback.print_exc()
323 # don't want to write state_file multiple times
326 # we get here due to an exception in the top-level child process
327 except Exception, ex:
328 traceback.print_exc()