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:
54 flags = self.config.get("S_FLAGS", "").split(" ")
56 self.flags |= FLAGS_LOCK
58 self.flags |= FLAGS_NPROC
59 self.remove_caps = ~vserverimpl.CAP_SAFE;
61 self.vm_running = vm_running
62 self.resources = resources
64 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
66 def __read_config_file(self, filename):
68 f = open(filename, "r")
72 for m in self.config_var_re.finditer(data):
73 (key, val) = m.groups()
74 config[key] = val.strip('"')
77 def __update_config_file(self, filename, newvars):
79 # read old file, apply changes
80 f = open(filename, "r")
85 for m in self.config_var_re.finditer(data):
86 (key, val) = m.groups()
87 newval = todo.pop(key, None)
89 data = data[:m.start(2)] + str(newval) + data[m.end(2):]
91 for (newkey, newval) in todo.items():
92 data += "%s=%s\n" % (newkey, newval)
99 newfile = filename + ".new"
100 f = open(newfile, "w")
104 # 'copy' original file, rename new to original
105 backup = filename + ".old"
109 if ex.errno != errno.ENOENT:
111 os.link(filename, backup)
112 os.rename(newfile, filename)
114 def __do_chroot(self):
119 def set_disklimit(self, block_limit):
121 # block_limit is in kB
123 block_usage = vserverimpl.DLIMIT_KEEP
124 inode_usage = vserverimpl.DLIMIT_KEEP
126 # init_disk_info() must have been called to get usage values
127 block_usage = self.disk_blocks
128 inode_usage = self.disk_inodes
130 vserverimpl.setdlimit(self.dir,
135 vserverimpl.DLIMIT_INF, # inode limit
136 2) # %age reserved for root
138 def get_disklimit(self):
141 blocksused, blocktotal, inodesused, inodestotal, reserved = \
142 vserverimpl.getdlimit(self.dir, self.ctx)
144 if ex.errno == errno.ESRCH:
145 # get here if no vserver disk limit has been set for xid
150 def set_sched(self, cpu_share):
152 if cpu_share == int(self.config.get("CPULIMIT", -1)):
155 self.__update_config_file(self.config_file, { "CPULIMIT": cpu_share })
157 vserverimpl.setsched(self.ctx, self.resources)
160 # have no way of querying scheduler right now on a per vserver basis
163 def set_memlimit(self, limit):
164 ret = vserverimpl.setrlimit(self.ctx,5,limit)
167 def get_memlimit(self):
168 ret = vserverimpl.getrlimit(self.ctx,5)
171 def set_tasklimit(self, limit):
172 ret = vserverimpl.setrlimit(self.ctx,6,limit)
175 def get_tasklimit(self):
176 ret = vserverimpl.getrlimit(self.ctx,6)
179 def set_bwlimit(self, share, minrate, maxrate = None, dev = "eth0"):
182 bwlimit.off(self.ctx, dev)
184 bwlimit.on(self.ctx, dev, share, minrate, maxrate)
186 def get_bwlimit(self, eth):
187 # not implemented yet
192 return (bwlimit, cap, minrate, maxrate)
194 def open(self, filename, mode = "r", bufsize = -1):
196 (sendsock, recvsock) = passfdimpl.socketpair()
197 child_pid = os.fork()
202 f = open(filename, mode)
203 passfdimpl.sendmsg(f.fileno(), sendsock)
205 except EnvironmentError, ex:
206 (result, errmsg) = (ex.errno, ex.strerror)
207 except Exception, ex:
208 (result, errmsg) = (255, str(ex))
209 os.write(sendsock, errmsg)
214 # XXX - need this since a lambda can't raise an exception
219 throw = lambda : __throw(Exception(errmsg))
222 (pid, status) = os.waitpid(child_pid, 0)
223 if os.WIFEXITED(status):
224 result = os.WEXITSTATUS(status)
226 errmsg = os.strerror(result)
227 throw = lambda : __throw(IOError(result, errmsg))
229 errmsg = "unexpected exception in child"
232 errmsg = "child killed"
235 if ex.errno != errno.EINTR:
238 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
240 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
242 if ex.errno != errno.EAGAIN:
243 throw = lambda : __throw(ex)
249 return os.fdopen(fd, mode, bufsize)
251 def __do_chcontext(self, state_file):
253 vserverimpl.chcontext(self.ctx, self.resources)
257 print >>state_file, "S_CONTEXT=%d" % self.ctx
258 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
261 def __prep(self, runlevel, log):
263 """ Perform all the crap that the vserver script does before
264 actually executing the startup scripts. """
266 # remove /var/run and /var/lock/subsys files
267 # but don't remove utmp from the top-level /var/run
269 LOCKDIR = "/var/lock/subsys"
270 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
271 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
272 (out + map((dir + "/").__add__, ff(files)),
274 list(os.walk(RUNDIR)),
276 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
277 os.listdir(LOCKDIR)))
281 # set the initial runlevel
282 f = open(RUNDIR + "/utmp", "w")
283 utmp.set_runlevel(f, runlevel)
286 # mount /proc and /dev/pts
287 self.__do_mount("none", "/proc", "proc")
288 # XXX - magic mount options
289 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
291 def __do_mount(self, *mount_args):
294 mountimpl.mount(*mount_args)
296 if ex.errno == errno.EBUSY:
297 # assume already mounted
303 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
305 self.__do_chcontext(state_file)
307 def start(self, wait, runlevel = 3):
309 self.vm_running = True
311 child_pid = os.fork()
318 # open state file to record vserver info
319 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
321 # use /dev/null for stdin, /var/log/boot.log for stdout/err
324 os.open("/dev/null", os.O_RDONLY)
326 log = open("/var/log/boot.log", "w", 0)
328 # XXX - close all other fds
330 print >>log, ("%s: starting the virtual server %s" %
331 (time.asctime(time.gmtime()), self.name))
333 # perform pre-init cleanup
334 self.__prep(runlevel, log)
336 # execute each init script in turn
337 # XXX - we don't support all scripts that vserver script does
340 for cmd in self.INITSCRIPTS + [None]:
341 # wait for previous command to terminate, unless it
342 # is the last one and the caller has specified to wait
343 if cmd_pid and (cmd != None or wait):
345 os.waitpid(cmd_pid, 0)
347 print >>log, "error waiting for %s:" % cmd_pid
348 traceback.print_exc()
354 # fork and exec next command
358 # enter vserver context
359 self.__do_chcontext(state_file)
360 arg_subst = { 'runlevel': runlevel }
361 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
363 print >>log, "executing '%s'" % " ".join(cmd_args)
364 os.execl(cmd[0], *cmd_args)
366 traceback.print_exc()
369 # don't want to write state_file multiple times
372 # we get here due to an exception in the top-level child process
373 except Exception, ex:
374 traceback.print_exc()
380 def update_resources(self, resources):
382 self.config.update(resources)
384 # write new values to configuration file
385 self.__update_config_file(self.config_file, resources)
387 def init_disk_info(self):
389 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)