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_id, 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
47 for config_file in ["/etc/vservers.conf", self.config_file]:
49 self.config.update(self.__read_config_file(config_file))
51 if ex.errno != errno.ENOENT:
53 self.remove_caps = ~vserverimpl.CAP_SAFE;
55 self.vm_running = vm_running
56 self.resources = resources
58 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
60 def __read_config_file(self, filename):
62 f = open(filename, "r")
66 for m in self.config_var_re.finditer(data):
67 (key, val) = m.groups()
68 config[key] = val.strip('"')
71 def __update_config_file(self, filename, newvars):
73 # read old file, apply changes
74 f = open(filename, "r")
79 for m in self.config_var_re.finditer(data):
80 (key, val) = m.groups()
81 newval = todo.pop(key, None)
83 data = data[:m.start(2)] + str(newval) + data[m.end(2):]
85 for (newkey, newval) in todo.items():
86 data += "%s=%s\n" % (newkey, newval)
93 newfile = filename + ".new"
94 f = open(newfile, "w")
98 # 'copy' original file, rename new to original
99 backup = filename + ".old"
103 if ex.errno != errno.ENOENT:
105 os.link(filename, backup)
106 os.rename(newfile, filename)
108 def __do_chroot(self):
113 def set_disklimit(self, block_limit):
115 # block_limit is in kB
117 vserverimpl.unsetdlimit(self.dir, self.ctx)
121 block_usage = vserverimpl.DLIMIT_KEEP
122 inode_usage = vserverimpl.DLIMIT_KEEP
124 # init_disk_info() must have been called to get usage values
125 block_usage = self.disk_blocks
126 inode_usage = self.disk_inodes
128 vserverimpl.setdlimit(self.dir,
133 vserverimpl.DLIMIT_INF, # inode limit
134 2) # %age reserved for root
136 def get_disklimit(self):
139 blocksused, blocktotal, inodesused, inodestotal, reserved = \
140 vserverimpl.getdlimit(self.dir, self.ctx)
142 if ex.errno != errno.ESRCH:
144 # get here if no vserver disk limit has been set for xid
149 def set_sched(self, cpu_share):
151 if cpu_share == int(self.config.get("CPULIMIT", -1)):
154 self.__update_config_file(self.config_file, { "CPULIMIT": cpu_share })
156 vserverimpl.setsched(self.ctx, self.resources)
159 # have no way of querying scheduler right now on a per vserver basis
162 def set_memlimit(self, limit):
163 ret = vserverimpl.setrlimit(self.ctx,5,limit)
166 def get_memlimit(self):
167 ret = vserverimpl.getrlimit(self.ctx,5)
170 def set_tasklimit(self, limit):
171 ret = vserverimpl.setrlimit(self.ctx,6,limit)
174 def get_tasklimit(self):
175 ret = vserverimpl.getrlimit(self.ctx,6)
178 def set_bwlimit(self, share, minrate = 1, maxrate = None, dev = "eth0"):
181 bwlimit.on(self.ctx, dev, share, minrate, maxrate)
183 bwlimit.off(self.ctx, dev)
185 def get_bwlimit(self, eth):
186 # not implemented yet
191 return (bwlimit, cap, minrate, maxrate)
193 def open(self, filename, mode = "r", bufsize = -1):
195 (sendsock, recvsock) = passfdimpl.socketpair()
196 child_pid = os.fork()
201 f = open(filename, mode)
202 passfdimpl.sendmsg(f.fileno(), sendsock)
204 except EnvironmentError, ex:
205 (result, errmsg) = (ex.errno, ex.strerror)
206 except Exception, ex:
207 (result, errmsg) = (255, str(ex))
208 os.write(sendsock, errmsg)
213 # XXX - need this since a lambda can't raise an exception
218 throw = lambda : __throw(Exception(errmsg))
221 (pid, status) = os.waitpid(child_pid, 0)
222 if os.WIFEXITED(status):
223 result = os.WEXITSTATUS(status)
225 errmsg = os.strerror(result)
226 throw = lambda : __throw(IOError(result, errmsg))
228 errmsg = "unexpected exception in child"
231 errmsg = "child killed"
234 if ex.errno != errno.EINTR:
237 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
239 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
241 if ex.errno != errno.EAGAIN:
242 throw = lambda : __throw(ex)
248 return os.fdopen(fd, mode, bufsize)
250 def __do_chcontext(self, state_file):
252 vserverimpl.chcontext(self.ctx, self.resources)
256 print >>state_file, "S_CONTEXT=%d" % self.ctx
257 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
260 def __prep(self, runlevel, log):
262 """ Perform all the crap that the vserver script does before
263 actually executing the startup scripts. """
265 # remove /var/run and /var/lock/subsys files
266 # but don't remove utmp from the top-level /var/run
268 LOCKDIR = "/var/lock/subsys"
269 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
270 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
271 (out + map((dir + "/").__add__, ff(files)),
273 list(os.walk(RUNDIR)),
275 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
276 os.listdir(LOCKDIR)))
280 # set the initial runlevel
281 f = open(RUNDIR + "/utmp", "w")
282 utmp.set_runlevel(f, runlevel)
285 # mount /proc and /dev/pts
286 self.__do_mount("none", "/proc", "proc")
287 # XXX - magic mount options
288 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
290 def __do_mount(self, *mount_args):
293 mountimpl.mount(*mount_args)
295 if ex.errno == errno.EBUSY:
296 # assume already mounted
302 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
304 self.__do_chcontext(state_file)
306 def start(self, wait, runlevel = 3):
308 self.vm_running = True
310 child_pid = os.fork()
317 # open state file to record vserver info
318 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
320 # use /dev/null for stdin, /var/log/boot.log for stdout/err
323 os.open("/dev/null", os.O_RDONLY)
325 log = open("/var/log/boot.log", "w", 0)
327 # XXX - close all other fds
329 print >>log, ("%s: starting the virtual server %s" %
330 (time.asctime(time.gmtime()), self.name))
332 # perform pre-init cleanup
333 self.__prep(runlevel, log)
335 # execute each init script in turn
336 # XXX - we don't support all scripts that vserver script does
339 for cmd in self.INITSCRIPTS + [None]:
340 # wait for previous command to terminate, unless it
341 # is the last one and the caller has specified to wait
342 if cmd_pid and (cmd != None or wait):
344 os.waitpid(cmd_pid, 0)
346 print >>log, "error waiting for %s:" % cmd_pid
347 traceback.print_exc()
353 # fork and exec next command
357 # enter vserver context
358 self.__do_chcontext(state_file)
359 arg_subst = { 'runlevel': runlevel }
360 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
362 print >>log, "executing '%s'" % " ".join(cmd_args)
363 os.execl(cmd[0], *cmd_args)
365 traceback.print_exc()
368 # don't want to write state_file multiple times
371 # we get here due to an exception in the top-level child process
372 except Exception, ex:
373 traceback.print_exc()
379 def update_resources(self, resources):
381 self.config.update(resources)
383 # write new values to configuration file
384 self.__update_config_file(self.config_file, resources)
386 def init_disk_info(self):
388 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)