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
119 block_usage = vserverimpl.DLIMIT_KEEP
120 inode_usage = vserverimpl.DLIMIT_KEEP
122 # init_disk_info() must have been called to get usage values
123 block_usage = self.disk_blocks
124 inode_usage = self.disk_inodes
125 if block_limit < block_usage:
128 vserverimpl.setdlimit(self.dir,
133 vserverimpl.DLIMIT_INF, # inode limit
134 2) # %age reserved for root
137 raise Exception, ("%s disk usage (%u blocks) > limit (%u)" %
138 (self.name, block_usage, block_limit))
140 def get_disklimit(self):
143 blocksused, blocktotal, inodesused, inodestotal, reserved = \
144 vserverimpl.getdlimit(self.dir, self.ctx)
146 if ex.errno == errno.ESRCH:
147 # get here if no vserver disk limit has been set for xid
148 # set blockused to -1 to indicate no limit
153 def set_sched(self, cpu_share):
155 if cpu_share == int(self.config.get("CPULIMIT", -1)):
158 self.__update_config_file(self.config_file, { "CPULIMIT": cpu_share })
160 vserverimpl.setsched(self.ctx, cpu_share, True)
163 # have no way of querying scheduler right now on a per vserver basis
166 def set_memlimit(self, limit):
167 ret = vserverimpl.setrlimit(self.ctx,5,limit)
170 def get_memlimit(self):
171 ret = vserverimpl.getrlimit(self.ctx,5)
174 def set_tasklimit(self, limit):
175 ret = vserverimpl.setrlimit(self.ctx,6,limit)
178 def get_tasklimit(self):
179 ret = vserverimpl.getrlimit(self.ctx,6)
182 def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
184 bwlimit.off(self.ctx,eth)
186 bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
188 def get_bwlimit(self, eth):
189 # not implemented yet
194 return (bwlimit, cap, minrate, maxrate)
196 def open(self, filename, mode = "r", bufsize = -1):
198 (sendsock, recvsock) = passfdimpl.socketpair()
199 child_pid = os.fork()
204 f = open(filename, mode)
205 passfdimpl.sendmsg(f.fileno(), sendsock)
207 except EnvironmentError, ex:
208 (result, errmsg) = (ex.errno, ex.strerror)
209 except Exception, ex:
210 (result, errmsg) = (255, str(ex))
211 os.write(sendsock, errmsg)
216 # XXX - need this since a lambda can't raise an exception
221 throw = lambda : __throw(Exception(errmsg))
224 (pid, status) = os.waitpid(child_pid, 0)
225 if os.WIFEXITED(status):
226 result = os.WEXITSTATUS(status)
228 errmsg = os.strerror(result)
229 throw = lambda : __throw(IOError(result, errmsg))
231 errmsg = "unexpected exception in child"
234 errmsg = "child killed"
237 if ex.errno != errno.EINTR:
240 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
242 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
244 if ex.errno != errno.EAGAIN:
245 throw = lambda : __throw(ex)
251 return os.fdopen(fd, mode, bufsize)
253 def __do_chcontext(self, state_file):
255 vserverimpl.chcontext(self.ctx, self.resources)
259 print >>state_file, "S_CONTEXT=%d" % self.ctx
260 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
263 def __prep(self, runlevel, log):
265 """ Perform all the crap that the vserver script does before
266 actually executing the startup scripts. """
268 # remove /var/run and /var/lock/subsys files
269 # but don't remove utmp from the top-level /var/run
271 LOCKDIR = "/var/lock/subsys"
272 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
273 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
274 (out + map((dir + "/").__add__, ff(files)),
276 list(os.walk(RUNDIR)),
278 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
279 os.listdir(LOCKDIR)))
283 # set the initial runlevel
284 f = open(RUNDIR + "/utmp", "w")
285 utmp.set_runlevel(f, runlevel)
288 # mount /proc and /dev/pts
289 self.__do_mount("none", "/proc", "proc")
290 # XXX - magic mount options
291 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
293 def __do_mount(self, *mount_args):
296 mountimpl.mount(*mount_args)
298 if ex.errno == errno.EBUSY:
299 # assume already mounted
305 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
307 self.__do_chcontext(state_file)
309 def start(self, wait, runlevel = 3):
311 self.vm_running = True
313 child_pid = os.fork()
320 # open state file to record vserver info
321 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
323 # use /dev/null for stdin, /var/log/boot.log for stdout/err
326 os.open("/dev/null", os.O_RDONLY)
328 log = open("/var/log/boot.log", "w", 0)
330 # XXX - close all other fds
332 print >>log, ("%s: starting the virtual server %s" %
333 (time.asctime(time.gmtime()), self.name))
335 # perform pre-init cleanup
336 self.__prep(runlevel, log)
338 # execute each init script in turn
339 # XXX - we don't support all scripts that vserver script does
342 for cmd in self.INITSCRIPTS + [None]:
343 # wait for previous command to terminate, unless it
344 # is the last one and the caller has specified to wait
345 if cmd_pid and (cmd != None or wait):
347 os.waitpid(cmd_pid, 0)
349 print >>log, "error waiting for %s:" % cmd_pid
350 traceback.print_exc()
356 # fork and exec next command
360 # enter vserver context
361 self.__do_chcontext(state_file)
362 arg_subst = { 'runlevel': runlevel }
363 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
365 print >>log, "executing '%s'" % " ".join(cmd_args)
366 os.execl(cmd[0], *cmd_args)
368 traceback.print_exc()
371 # don't want to write state_file multiple times
374 # we get here due to an exception in the top-level child process
375 except Exception, ex:
376 traceback.print_exc()
382 def update_resources(self, resources):
384 self.config.update(resources)
386 # write new values to configuration file
387 self.__update_config_file(self.config_file, resources)
389 def init_disk_info(self):
391 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)