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"
133 def open(self, filename, mode = "r", bufsize = -1):
135 (sendsock, recvsock) = passfdimpl.socketpair()
136 child_pid = os.fork()
141 f = open(filename, mode)
142 passfdimpl.sendmsg(f.fileno(), sendsock)
144 except EnvironmentError, ex:
145 (result, errmsg) = (ex.errno, ex.strerror)
146 except Exception, ex:
147 (result, errmsg) = (255, str(ex))
148 os.write(sendsock, errmsg)
153 # XXX - need this since a lambda can't raise an exception
158 throw = lambda : __throw(Exception(errmsg))
161 (pid, status) = os.waitpid(child_pid, 0)
162 if os.WIFEXITED(status):
163 result = os.WEXITSTATUS(status)
165 errmsg = os.strerror(result)
166 throw = lambda : __throw(IOError(result, errmsg))
168 errmsg = "unexpected exception in child"
171 errmsg = "child killed"
174 if ex.errno != errno.EINTR:
177 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
179 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
181 if ex.errno != errno.EAGAIN:
182 throw = lambda : __throw(ex)
188 return os.fdopen(fd, mode, bufsize)
190 def __do_chcontext(self, state_file = None):
192 vserverimpl.chcontext(self.ctx, self.remove_caps)
195 print >>state_file, "S_CONTEXT=%d" % self.ctx
196 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
199 def __prep(self, runlevel, log):
201 """ Perform all the crap that the vserver script does before
202 actually executing the startup scripts. """
204 # remove /var/run and /var/lock/subsys files
205 # but don't remove utmp from the top-level /var/run
207 LOCKDIR = "/var/lock/subsys"
208 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
209 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
210 (out + map((dir + "/").__add__, ff(files)),
212 list(os.walk(RUNDIR)),
214 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
215 os.listdir(LOCKDIR)))
219 # set the initial runlevel
220 f = open(RUNDIR + "/utmp", "w")
221 utmp.set_runlevel(f, runlevel)
224 # mount /proc and /dev/pts
225 self.__do_mount("none", "/proc", "proc")
226 # XXX - magic mount options
227 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
229 def __do_mount(self, *mount_args):
232 mountimpl.mount(*mount_args)
234 if ex.errno == errno.EBUSY:
235 # assume already mounted
241 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
243 self.__do_chcontext(state_file)
245 def start(self, wait, runlevel = 3):
247 child_pid = os.fork()
254 # open state file to record vserver info
255 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
257 # use /dev/null for stdin, /var/log/boot.log for stdout/err
260 os.open("/dev/null", os.O_RDONLY)
262 log = open("/var/log/boot.log", "w", 0)
265 print >>log, ("%s: starting the virtual server %s" %
266 (time.asctime(time.gmtime()), self.name))
268 # perform pre-init cleanup
269 self.__prep(runlevel, log)
271 # execute each init script in turn
272 # XXX - we don't support all scripts that vserver script does
274 for cmd in self.INITSCRIPTS + [None]:
275 # wait for previous command to terminate, unless it
276 # is the last one and the caller has specified to wait
277 if cmd_pid and (cmd != None or wait):
279 os.waitpid(cmd_pid, 0)
281 print >>log, "error waiting for %s:" % cmd_pid
282 traceback.print_exc()
288 # fork and exec next command
292 # enter vserver context
293 self.__do_chcontext(state_file)
294 arg_subst = { 'runlevel': runlevel }
295 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
297 print >>log, "executing '%s'" % " ".join(cmd_args)
298 os.execl(cmd[0], *cmd_args)
300 traceback.print_exc()
303 # don't want to write state_file multiple times
306 # we get here due to an exception in the top-level child process
307 except Exception, ex:
308 traceback.print_exc()