1 # Copyright 2005 Princeton University
14 import vserverimpl, vduimpl
15 import cpulimit, bwlimit
20 # these are the flags taken from the kernel linux/vserver/legacy.h
23 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
35 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
36 ('/etc/rc.d/rc', '%(runlevel)d')]
38 def __init__(self, name, vm_running = False, resources = {}):
41 self.config_file = "/etc/vservers/%s.conf" % name
42 self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
43 if not (os.path.isdir(self.dir) and
44 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
45 raise Exception, "no such vserver: " + name
46 self.config = self.__read_config_file("/etc/vservers.conf")
47 self.config.update(self.__read_config_file(self.config_file))
49 flags = self.config["S_FLAGS"].split(" ")
51 self.flags |= FLAGS_LOCK
53 self.flags |= FLAGS_NPROC
54 self.remove_caps = ~vserverimpl.CAP_SAFE;
55 self.ctx = int(self.config["S_CONTEXT"])
56 self.vm_running = vm_running
57 self.resources = resources
59 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
61 def __read_config_file(self, filename):
63 f = open(filename, "r")
67 for m in self.config_var_re.finditer(data):
68 (key, val) = m.groups()
69 config[key] = val.strip('"')
72 def __update_config_file(self, filename, newvars):
74 # read old file, apply changes
75 f = open(filename, "r")
80 for m in self.config_var_re.finditer(data):
81 (key, val) = m.groups()
82 newval = todo.pop(key, None)
84 data = data[:m.start(2)] + str(newval) + data[m.end(2):]
86 for (newkey, newval) in todo.items():
87 data += "%s=%s\n" % (newkey, newval)
94 newfile = filename + ".new"
95 f = open(newfile, "w")
99 # 'copy' original file, rename new to original
100 backup = filename + ".old"
104 if ex.errno != errno.ENOENT:
106 os.link(filename, backup)
107 os.rename(newfile, filename)
109 def __do_chroot(self):
114 def set_disklimit(self, block_limit):
116 # block_limit is in kB
118 block_usage = vserverimpl.DLIMIT_KEEP
119 inode_usage = vserverimpl.DLIMIT_KEEP
121 # init_disk_info() must have been called to get usage values
122 block_usage = self.disk_blocks
123 inode_usage = self.disk_inodes
125 vserverimpl.setdlimit(self.dir,
130 vserverimpl.DLIMIT_INF, # inode limit
131 2) # %age reserved for root
133 def get_disklimit(self):
136 blocksused, blocktotal, inodesused, inodestotal, reserved = \
137 vserverimpl.getdlimit(self.dir, self.ctx)
139 if ex.errno == errno.ESRCH:
140 # get here if no vserver disk limit has been set for xid
145 def set_sched(self, cpu_share):
147 if cpu_share == int(self.config.get("CPULIMIT", -1)):
150 self.__update_config_file(self.config_file, { "CPULIMIT": cpu_share })
152 vserverimpl.setsched(self.ctx, self.resources)
155 # have no way of querying scheduler right now on a per vserver basis
158 def set_memlimit(self, limit):
159 ret = vserverimpl.setrlimit(self.ctx,5,limit)
162 def get_memlimit(self):
163 ret = vserverimpl.getrlimit(self.ctx,5)
166 def set_tasklimit(self, limit):
167 ret = vserverimpl.setrlimit(self.ctx,6,limit)
170 def get_tasklimit(self):
171 ret = vserverimpl.getrlimit(self.ctx,6)
174 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
176 bwlimit.off(self.ctx,eth)
178 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
180 def get_bwlimit(self, eth):
181 # not implemented yet
186 return (bwlimit, cap, minrate, maxrate)
188 def open(self, filename, mode = "r", bufsize = -1):
190 (sendsock, recvsock) = passfdimpl.socketpair()
191 child_pid = os.fork()
196 f = open(filename, mode)
197 passfdimpl.sendmsg(f.fileno(), sendsock)
199 except EnvironmentError, ex:
200 (result, errmsg) = (ex.errno, ex.strerror)
201 except Exception, ex:
202 (result, errmsg) = (255, str(ex))
203 os.write(sendsock, errmsg)
208 # XXX - need this since a lambda can't raise an exception
213 throw = lambda : __throw(Exception(errmsg))
216 (pid, status) = os.waitpid(child_pid, 0)
217 if os.WIFEXITED(status):
218 result = os.WEXITSTATUS(status)
220 errmsg = os.strerror(result)
221 throw = lambda : __throw(IOError(result, errmsg))
223 errmsg = "unexpected exception in child"
226 errmsg = "child killed"
229 if ex.errno != errno.EINTR:
232 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
234 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
236 if ex.errno != errno.EAGAIN:
237 throw = lambda : __throw(ex)
243 return os.fdopen(fd, mode, bufsize)
245 def __do_chcontext(self, state_file):
247 vserverimpl.chcontext(self.ctx, self.resources)
251 print >>state_file, "S_CONTEXT=%d" % self.ctx
252 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
255 def __prep(self, runlevel, log):
257 """ Perform all the crap that the vserver script does before
258 actually executing the startup scripts. """
260 # remove /var/run and /var/lock/subsys files
261 # but don't remove utmp from the top-level /var/run
263 LOCKDIR = "/var/lock/subsys"
264 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
265 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
266 (out + map((dir + "/").__add__, ff(files)),
268 list(os.walk(RUNDIR)),
270 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
271 os.listdir(LOCKDIR)))
275 # set the initial runlevel
276 f = open(RUNDIR + "/utmp", "w")
277 utmp.set_runlevel(f, runlevel)
280 # mount /proc and /dev/pts
281 self.__do_mount("none", "/proc", "proc")
282 # XXX - magic mount options
283 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
285 def __do_mount(self, *mount_args):
288 mountimpl.mount(*mount_args)
290 if ex.errno == errno.EBUSY:
291 # assume already mounted
297 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
299 self.__do_chcontext(state_file)
301 def start(self, wait, runlevel = 3):
303 self.vm_running = True
305 child_pid = os.fork()
312 # open state file to record vserver info
313 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
315 # use /dev/null for stdin, /var/log/boot.log for stdout/err
318 os.open("/dev/null", os.O_RDONLY)
320 log = open("/var/log/boot.log", "w", 0)
322 # XXX - close all other fds
324 print >>log, ("%s: starting the virtual server %s" %
325 (time.asctime(time.gmtime()), self.name))
327 # perform pre-init cleanup
328 self.__prep(runlevel, log)
330 # execute each init script in turn
331 # XXX - we don't support all scripts that vserver script does
334 for cmd in self.INITSCRIPTS + [None]:
335 # wait for previous command to terminate, unless it
336 # is the last one and the caller has specified to wait
337 if cmd_pid and (cmd != None or wait):
339 os.waitpid(cmd_pid, 0)
341 print >>log, "error waiting for %s:" % cmd_pid
342 traceback.print_exc()
348 # fork and exec next command
352 # enter vserver context
353 self.__do_chcontext(state_file)
354 arg_subst = { 'runlevel': runlevel }
355 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
357 print >>log, "executing '%s'" % " ".join(cmd_args)
358 os.execl(cmd[0], *cmd_args)
360 traceback.print_exc()
363 # don't want to write state_file multiple times
366 # we get here due to an exception in the top-level child process
367 except Exception, ex:
368 traceback.print_exc()
374 def update_resources(self, resources):
376 self.config.update(resources)
378 # write new values to configuration file
379 self.__update_config_file(self.config_file, resources)
381 def init_disk_info(self):
383 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)