1 # Copyright 2005 Princeton University
15 import vserverimpl, vduimpl
16 import cpulimit, bwlimit
21 # these are the flags taken from the kernel linux/vserver/legacy.h
24 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
36 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
37 ('/etc/rc.d/rc', '%(runlevel)d')]
39 def __init__(self, name, vm_id, vm_running = False, resources = {}):
42 self.config_file = "/etc/vservers/%s.conf" % name
43 self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
44 if not (os.path.isdir(self.dir) and
45 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
46 raise Exception, "no such vserver: " + name
48 for config_file in ["/etc/vservers.conf", self.config_file]:
50 self.config.update(self.__read_config_file(config_file))
52 if ex.errno != errno.ENOENT:
54 self.remove_caps = ~vserverimpl.CAP_SAFE;
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 vserverimpl.unsetdlimit(self.dir, self.ctx)
122 block_usage = vserverimpl.DLIMIT_KEEP
123 inode_usage = vserverimpl.DLIMIT_KEEP
125 # init_disk_info() must have been called to get usage values
126 block_usage = self.disk_blocks
127 inode_usage = self.disk_inodes
129 vserverimpl.setdlimit(self.dir,
134 vserverimpl.DLIMIT_INF, # inode limit
135 2) # %age reserved for root
137 def get_disklimit(self):
140 (self.disk_blocks, block_limit, self.disk_inodes, inode_limit,
141 reserved) = vserverimpl.getdlimit(self.dir, self.ctx)
143 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 = 1, maxrate = None, dev = "eth0"):
182 bwlimit.on(self.ctx, dev, share, minrate, maxrate)
184 bwlimit.off(self.ctx, dev)
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):
254 print >>state_file, "S_CONTEXT=%u" % self.ctx
255 print >>state_file, "S_PROFILE="
258 vserverimpl.chcontext(self.ctx, self.resources)
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)
328 print >>log, ("%s: starting the virtual server %s" %
329 (time.asctime(time.gmtime()), self.name))
331 # perform pre-init cleanup
332 self.__prep(runlevel, log)
334 # execute each init script in turn
335 # XXX - we don't support all scripts that vserver script does
338 for cmd in self.INITSCRIPTS + [None]:
339 # wait for previous command to terminate, unless it
340 # is the last one and the caller has specified to wait
341 if cmd_pid and (cmd != None or wait):
343 os.waitpid(cmd_pid, 0)
345 print >>log, "error waiting for %s:" % cmd_pid
346 traceback.print_exc()
352 # fork and exec next command
356 # enter vserver context
357 self.__do_chcontext(state_file)
358 arg_subst = { 'runlevel': runlevel }
359 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
361 print >>log, "executing '%s'" % " ".join(cmd_args)
362 os.execl(cmd[0], *cmd_args)
364 traceback.print_exc()
367 # don't want to write state_file multiple times
370 # we get here due to an exception in the top-level child process
371 except Exception, ex:
372 traceback.print_exc()
378 def update_resources(self, resources):
380 self.config.update(resources)
382 # write new values to configuration file
383 self.__update_config_file(self.config_file, resources)
385 def init_disk_info(self):
387 (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
391 def stop(self, signal = signal.SIGKILL):
393 vserverimpl.killall(self.ctx, signal)
394 self.vm_running = False