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
55 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
56 ('/etc/rc.d/rc', '%(runlevel)d')]
58 def __init__(self, name):
61 self.config = self.__read_config_file("/etc/vservers.conf")
62 self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
65 flags = self.config["S_FLAGS"].split(" ")
67 self.flags |= FLAGS_LOCK
69 self.flags |= FLAGS_NPROC
70 self.remove_caps = ~CAP_SAFE
71 self.ctx = int(self.config["S_CONTEXT"])
73 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
75 def __read_config_file(self, filename):
77 f = open(filename, "r")
81 for m in self.config_var_re.finditer(data):
82 (key, val) = m.groups()
83 config[key] = val.strip('"')
86 def __do_chroot(self):
88 return os.chroot("%s/%s" % (DEFAULT_VSERVERDIR, self.name))
90 def set_disklimit(self, blocktotal):
91 path = "%s/%s" % (DEFAULT_VSERVERDIR, self.name)
92 inodes, blockcount, size = vduimpl.vdu(path)
93 blockcount = blockcount >> 1
95 if blocktotal > blockcount:
96 vserverimpl.setdlimit(path, self.ctx, blockcount>>1, \
97 blocktotal, inodes, -1, 2)
99 # should raise some error value
100 print "block limit (%d) ignored for vserver %s" %(blocktotal,self.name)
102 def get_disklimit(self):
103 path = "%s/%s" % (DEFAULT_VSERVERDIR, self.name)
105 blocksused, blocktotal, inodesused, inodestotal, reserved = \
106 vserverimpl.getdlimit(path,self.ctx)
109 # get here if no vserver disk limit has been set for xid
110 # set blockused to -1 to indicate no limit
115 def set_sched(self, shares = 32, besteffort = True):
116 # for the old CKRM scheduler
117 if cpulimit.checkckrm() is True:
119 cpulimit.vs2ckrm_on(self.name)
121 cpulimit.cpulimit(self.name,shares)
124 print "invalid shares argument"
125 # should re-raise exception?!
127 # for the new vserver scheduler
129 global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX, SCHED_TOKENS, SCHED_INTERVAL
130 tokensmin = SCHED_TOKENS_MIN
131 tokensmax = SCHED_TOKENS_MAX
132 tokens = SCHED_TOKENS
133 interval = SCHED_INTERVAL
136 if besteffort is True:
142 vserverimpl.setsched(self.ctx,fillrate,interval,tokens,tokensmin,tokensmax,cpuguaranteed)
145 print "kernel does not support vserver scheduler"
150 # have no way of querying scheduler right now on a per vserver basis
153 def set_memlimit(self, limit):
154 ret = vserverimpl.setrlimit(self.ctx,5,limit)
157 def get_memlimit(self):
158 ret = vserverimpl.getrlimit(self.ctx,5)
161 def set_tasklimit(self, limit):
162 ret = vserverimpl.setrlimit(self.ctx,6,limit)
165 def get_tasklimit(self):
166 ret = vserverimpl.getrlimit(self.ctx,6)
169 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
171 bwlimit.off(self.ctx,eth)
173 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
175 def get_bwlimit(self, eth):
176 # not implemented yet
181 return (bwlimit, cap, minrate, maxrate)
183 def open(self, filename, mode = "r", bufsize = -1):
185 (sendsock, recvsock) = passfdimpl.socketpair()
186 child_pid = os.fork()
191 f = open(filename, mode)
192 passfdimpl.sendmsg(f.fileno(), sendsock)
194 except EnvironmentError, ex:
195 (result, errmsg) = (ex.errno, ex.strerror)
196 except Exception, ex:
197 (result, errmsg) = (255, str(ex))
198 os.write(sendsock, errmsg)
203 # XXX - need this since a lambda can't raise an exception
208 throw = lambda : __throw(Exception(errmsg))
211 (pid, status) = os.waitpid(child_pid, 0)
212 if os.WIFEXITED(status):
213 result = os.WEXITSTATUS(status)
215 errmsg = os.strerror(result)
216 throw = lambda : __throw(IOError(result, errmsg))
218 errmsg = "unexpected exception in child"
221 errmsg = "child killed"
224 if ex.errno != errno.EINTR:
227 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
229 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
231 if ex.errno != errno.EAGAIN:
232 throw = lambda : __throw(ex)
238 return os.fdopen(fd, mode, bufsize)
240 def __do_chcontext(self, state_file = None):
242 vserverimpl.create(self.ctx)
243 vserverimpl.flags(self.ctx)
245 vserverimpl.enter(self.ctx)
249 print >>state_file, "S_CONTEXT=%d" % self.ctx
250 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
253 def __prep(self, runlevel, log):
255 """ Perform all the crap that the vserver script does before
256 actually executing the startup scripts. """
258 # remove /var/run and /var/lock/subsys files
259 # but don't remove utmp from the top-level /var/run
261 LOCKDIR = "/var/lock/subsys"
262 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
263 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
264 (out + map((dir + "/").__add__, ff(files)),
266 list(os.walk(RUNDIR)),
268 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
269 os.listdir(LOCKDIR)))
273 # set the initial runlevel
274 f = open(RUNDIR + "/utmp", "w")
275 utmp.set_runlevel(f, runlevel)
278 # mount /proc and /dev/pts
279 self.__do_mount("none", "/proc", "proc")
280 # XXX - magic mount options
281 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
283 def __do_mount(self, *mount_args):
286 mountimpl.mount(*mount_args)
288 if ex.errno == errno.EBUSY:
289 # assume already mounted
295 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
297 self.__do_chcontext(state_file)
299 def start(self, wait, runlevel = 3):
301 child_pid = os.fork()
308 # open state file to record vserver info
309 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
311 # use /dev/null for stdin, /var/log/boot.log for stdout/err
314 os.open("/dev/null", os.O_RDONLY)
316 log = open("/var/log/boot.log", "w", 0)
319 print >>log, ("%s: starting the virtual server %s" %
320 (time.asctime(time.gmtime()), self.name))
322 # perform pre-init cleanup
323 self.__prep(runlevel, log)
325 # execute each init script in turn
326 # XXX - we don't support all scripts that vserver script does
328 for cmd in self.INITSCRIPTS + [None]:
329 # wait for previous command to terminate, unless it
330 # is the last one and the caller has specified to wait
331 if cmd_pid and (cmd != None or wait):
333 os.waitpid(cmd_pid, 0)
335 print >>log, "error waiting for %s:" % cmd_pid
336 traceback.print_exc()
342 # fork and exec next command
346 # enter vserver context
347 self.__do_chcontext(state_file)
348 arg_subst = { 'runlevel': runlevel }
349 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
351 print >>log, "executing '%s'" % " ".join(cmd_args)
352 os.execl(cmd[0], *cmd_args)
354 traceback.print_exc()
357 # don't want to write state_file multiple times
360 # we get here due to an exception in the top-level child process
361 except Exception, ex:
362 traceback.print_exc()