1 # Copyright 2005 Princeton University
3 #$Id: vserver.py,v 1.72 2007/08/02 16:01:59 dhozac Exp $
18 import cpulimit, bwlimit
20 from vserverimpl import DLIMIT_INF
21 from vserverimpl import VC_LIM_KEEP
22 from vserverimpl import VLIMIT_NSOCK
23 from vserverimpl import VLIMIT_OPENFD
24 from vserverimpl import VLIMIT_ANON
25 from vserverimpl import VLIMIT_SHMEM
28 # these are the flags taken from the kernel linux/vserver/legacy.h
31 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
39 RLIMITS = { "NSOCK": VLIMIT_NSOCK,
40 "OPENFD": VLIMIT_OPENFD,
42 "SHMEM": VLIMIT_SHMEM}
44 # add in the platform supported rlimits
45 for entry in resource.__dict__.keys():
46 if entry.find("RLIMIT_")==0:
47 k = entry[len("RLIMIT_"):]
48 if not RLIMITS.has_key(k):
49 RLIMITS[k]=resource.__dict__[entry]
51 print "WARNING: duplicate RLIMITS key %s" % k
53 class NoSuchVServer(Exception): pass
57 def __init__(self, name, directory):
61 if not (os.path.isdir(self.dir) and
62 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
63 raise NoSuchVServer, "%s does not exist" % self.dir
65 def get(self, option, default = None):
68 return self.cache[option]
70 f = open(os.path.join(self.dir, option), "r")
71 buf = f.read().rstrip()
75 if default is not None:
78 raise KeyError, "Key %s is not set for %s" % (option, self.name)
80 def update(self, option, value):
85 old_umask = os.umask(0022)
86 filename = os.path.join(self.dir, option)
88 os.makedirs(os.path.dirname(filename), 0755)
91 f = open(filename, 'w')
92 if isinstance(value, list):
93 f.write("%s\n" % "\n".join(value))
95 f.write("%s\n" % value)
101 def unset(self, option):
106 filename = os.path.join(self.dir, option)
109 os.removedirs(os.path.dirname(filename))
118 def add_to_cache(cache, dirname, fnames):
120 full_name = os.path.join(dirname, file)
121 if os.path.islink(full_name):
123 elif (os.path.isfile(full_name) and
124 os.access(full_name, os.R_OK)):
125 f = open(full_name, "r")
126 cache[full_name.replace(os.path.join(self.dir, ''),
127 '')] = f.read().rstrip()
129 os.path.walk(self.dir, add_to_cache, self.cache)
132 def adjust_lim(goal, curr):
138 if gm != VC_LIM_KEEP:
139 if gm > soft or gm == resource.RLIM_INFINITY:
141 if gm > hard or gm == resource.RLIM_INFINITY:
143 if gs != VC_LIM_KEEP:
144 if gs > soft or gs == resource.RLIM_INFINITY:
146 if gh != VC_LIM_KEEP:
147 if gh > hard or gh == resource.RLIM_INFINITY:
154 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
155 ('/etc/rc.d/rc', '%(runlevel)d')]
157 def __init__(self, name, vm_id = None, vm_running = None, logfile=None):
160 self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
161 if not (os.path.isdir(self.dir) and
162 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
163 raise NoSuchVServer, "no such vserver: " + name
164 self.config = VServerConfig(name, "/etc/vservers/%s" % name)
165 self.remove_caps = ~vserverimpl.CAP_SAFE;
167 vm_id = int(self.config.get('context'))
169 if vm_running == None:
170 vm_running = self.is_running()
171 self.vm_running = vm_running
172 self.logfile = logfile
174 # inspired from nodemanager's logger
178 fd = os.open(self.logfile,os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
179 if not msg.endswith('\n'): msg += '\n'
180 os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
183 print '%s: (%s failed to open) %s'%(time.asctime(time.gmtime()),self.logfile,msg)
185 def set_rlimit(self, type, hard, soft, min):
186 """Generic set resource limit function for vserver"""
190 if hard <> VC_LIM_KEEP:
191 self.config.update('rlimits/%s.hard' % type.lower(), hard)
193 if soft <> VC_LIM_KEEP:
194 self.config.update('rlimits/%s.soft' % type.lower(), soft)
196 if min <> VC_LIM_KEEP:
197 self.config.update('rlimits/%s.min' % type.lower(), min)
200 if self.is_running() and update:
201 resource_type = RLIMITS[type]
203 vserverimpl.setrlimit(self.ctx, resource_type, hard, soft, min)
204 if hasattr(resource, 'RLIMIT_' + type):
205 lim = resource.getrlimit(resource_type)
206 lim = adjust_lim((hard, soft, min), lim)
207 resource.setrlimit(resource_type, lim)
209 self.log("Error: setrlimit(%d, %s, %d, %d, %d): %s"
210 % (self.ctx, type.lower(), hard, soft, min, e))
214 def get_prefix_from_capabilities(self, capabilities, prefix):
215 split_caps = capabilities.split(',')
216 return ",".join(["%s" % (c) for c in split_caps if c.startswith(prefix.upper()) or c.startswith(prefix.lower())])
218 def get_bcaps_from_capabilities(self, capabilities):
219 return self.get_prefix_from_capabilities(capabilities, "cap_")
221 def get_ccaps_from_capabilities(self, capabilities):
222 return self.get_prefix_from_capabilities(capabilities, "vxc_")
224 def set_capabilities_config(self, capabilities):
225 bcaps = self.get_bcaps_from_capabilities(capabilities)
226 ccaps = self.get_ccaps_from_capabilities(capabilities)
227 self.config.update('bcapabilities', bcaps)
228 self.config.update('ccapabilities', ccaps)
229 ret = vserverimpl.setbcaps(self.ctx, vserverimpl.text2bcaps(bcaps))
232 return vserverimpl.setccaps(self.ctx, vserverimpl.text2ccaps(ccaps))
234 def get_capabilities(self):
235 bcaps = vserverimpl.bcaps2text(vserverimpl.getbcaps(self.ctx))
236 ccaps = vserverimpl.ccaps2text(vserverimpl.getccaps(self.ctx))
239 return (bcaps + ccaps)
241 def get_capabilities_config(self):
242 bcaps = self.config.get('bcapabilities', '')
243 ccaps = self.config.get('ccapabilities', '')
246 return (bcaps + ccaps)
248 def set_ipaddresses(self, addresses):
249 vserverimpl.netremove(self.ctx, "all")
250 for a in addresses.split(","):
251 vserverimpl.netadd(self.ctx, a)
253 def set_ipaddresses_config(self, addresses):
255 for a in addresses.split(","):
256 self.config.update("interfaces/%d/ip" % i, a)
258 while self.config.unset("interfaces/%d/ip" % i):
260 self.set_ipaddresses(addresses)
262 def get_ipaddresses_config(self):
266 r = self.config.get("interfaces/%d/ip" % i, '')
273 def get_ipaddresses(self):
274 # No clean way to do this right now.
277 def __do_chroot(self):
281 def chroot_call(self, fn, *args, **kwargs={}):
283 cwd_fd = os.open(".", os.O_RDONLY)
285 root_fd = os.open("/", os.O_RDONLY)
288 result = fn(*args, **kwargs)
298 def set_disklimit(self, block_limit):
299 # block_limit is in kB
302 vserverimpl.unsetdlimit(self.dir, self.ctx)
304 self.log("Unexpected error with unsetdlimit for context %d: %r" % (self.ctx,e))
308 block_usage = vserverimpl.DLIMIT_KEEP
309 inode_usage = vserverimpl.DLIMIT_KEEP
311 # init_disk_info() must have been called to get usage values
312 block_usage = self.disk_blocks
313 inode_usage = self.disk_inodes
316 vserverimpl.setdlimit(self.dir,
321 vserverimpl.DLIMIT_INF, # inode limit
322 2) # %age reserved for root
324 self.log("Unexpected error with setdlimit for context %d: %r" % (self.ctx, e))
327 self.config.update('dlimits/0/space_total', block_limit)
329 def is_running(self):
330 return vserverimpl.isrunning(self.ctx)
332 def get_disklimit(self):
335 (self.disk_blocks, block_limit, self.disk_inodes, inode_limit,
336 reserved) = vserverimpl.getdlimit(self.dir, self.ctx)
338 if ex.errno != errno.ESRCH:
340 # get here if no vserver disk limit has been set for xid
345 def set_sched_config(self, cpu_min, cpu_share):
347 """ Write current CPU scheduler parameters to the vserver
348 configuration file. This method does not modify the kernel CPU
349 scheduling parameters for this context. """
351 self.config.update('sched/fill-rate', cpu_min)
352 self.config.update('sched/fill-rate2', cpu_share)
354 self.config.unset('sched/idle-time')
356 if self.is_running():
357 self.set_sched(cpu_min, cpu_share)
359 def set_sched(self, cpu_min, cpu_share):
360 """ Update kernel CPU scheduling parameters for this context. """
361 vserverimpl.setsched(self.ctx, cpu_min, cpu_share)
364 # have no way of querying scheduler right now on a per vserver basis
367 def set_bwlimit(self, minrate = bwlimit.bwmin, maxrate = None,
368 exempt_min = None, exempt_max = None,
369 share = None, dev = "eth0"):
372 bwlimit.off(self.ctx, dev)
374 bwlimit.on(self.ctx, dev, share,
375 minrate, maxrate, exempt_min, exempt_max)
377 def get_bwlimit(self, dev = "eth0"):
379 result = bwlimit.get(self.ctx)
380 # result of bwlimit.get is (ctx, share, minrate, maxrate)
385 def open(self, filename, mode = "r", bufsize = -1):
387 return self.chroot_call(open, filename, mode, bufsize)
389 def __do_chcontext(self, state_file):
392 print >>state_file, "%u" % self.ctx
395 if vserverimpl.chcontext(self.ctx, vserverimpl.text2bcaps(self.get_capabilities_config())):
396 self.set_resources(True)
397 vserverimpl.setup_done(self.ctx)
400 def __prep(self, runlevel):
402 """ Perform all the crap that the vserver script does before
403 actually executing the startup scripts. """
406 # set the initial runlevel
407 vserverimpl.setrunlevel(self.dir + "/var/run/utmp", runlevel)
409 # mount /proc and /dev/pts
410 self.__do_mount("none", self.dir, "/proc", "proc")
411 # XXX - magic mount options
412 self.__do_mount("none", self.dir, "/dev/pts", "devpts", 0, "gid=5,mode=0620")
415 def __cleanvar(self):
417 Clean the /var/ directory so RH startup scripts can run
421 LOCKDIR = "/var/lock/subsys"
425 for topdir in [RUNDIR, LOCKDIR]:
426 #os.walk() = (dirpath, dirnames, filenames)
427 for root, dirs, files in os.walk(topdir):
429 if not file in filter:
430 garbage.append(root + "/" + file)
432 for f in garbage: os.unlink(f)
436 def __do_mount(self, *mount_args):
438 vserverimpl.mount(*mount_args)
440 if ex.errno == errno.EBUSY:
441 # assume already mounted
447 self.config.cache_it()
449 self.__do_chcontext(None)
452 def start(self, runlevel = 3):
454 # Parent should just return.
455 self.vm_running = True
460 subprocess.call("/usr/sbin/vserver %s start" % self.name,
463 # execute initscripts
464 for cmd in self.INITSCRIPTS:
466 # enter vserver context
467 arg_subst = { 'runlevel': runlevel }
468 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst, cmd[1:])
469 cmd_file = "/vservers/" + self.name + cmd[0]
471 if os.path.isfile(cmd_file):
472 self.log("executing '%s'" % " ".join(cmd_args))
473 self.chroot_call(subprocess.call, " ".join(cmd_args), shell=True)
475 self.log("WARNING: could not run %s on %s" % (cmd[0], self.name))
477 self.log(traceback.format_exc())
479 # we get here due to an exception in the top-level child process
480 except Exception, ex:
481 self.log(traceback.format_exc())
485 def set_resources(self,setup=False):
487 """ Called when vserver context is entered for first time,
488 should be overridden by subclass. """
492 def init_disk_info(self):
494 dlimit = vserverimpl.getdlimit(self.dir, self.ctx)
495 self.disk_blocks = dlimit[0]
496 self.disk_inodes = dlimit[2]
497 return self.disk_blocks * 1024
500 cmd = "/usr/sbin/vdu --script --space --inodes --blocksize 1024 --xid %d %s" % (self.ctx, self.dir)
501 p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
502 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
505 line = p.stdout.readline()
507 sys.stderr.write(p.stderr.read())
512 (space, inodes) = line.split()
513 self.disk_inodes = int(inodes)
514 self.disk_blocks = int(space)
515 #(self.disk_inodes, self.disk_blocks) = vduimpl.vdu(self.dir)
517 return self.disk_blocks * 1024
519 def stop(self, signal = signal.SIGKILL):
520 vserverimpl.killall(self.ctx, signal)
521 self.vm_running = False
523 def setname(self, slice_id):
524 '''Set vcVHI_CONTEXT field in kernel to slice_id'''
525 vserverimpl.setname(self.ctx, slice_id)
528 '''Get vcVHI_CONTEXT field in kernel'''
529 return vserverimpl.getname(self.ctx)
532 def create(vm_name, static = False, ctor = VServer):
534 options = ['vuseradd']
536 options += ['--static']
537 ret = os.spawnvp(os.P_WAIT, 'vuseradd', options + [vm_name])
538 if not os.WIFEXITED(ret) or os.WEXITSTATUS(ret) != 0:
539 out = "system command ('%s') " % options
540 if os.WIFEXITED(ret):
541 out += "failed, rc = %d" % os.WEXITSTATUS(ret)
543 out += "killed by signal %d" % os.WTERMSIG(ret)
544 raise SystemError, out
545 vm_id = pwd.getpwnam(vm_name)[2]
547 return ctor(vm_name, vm_id)
550 def close_nonstandard_fds():
551 """Close all open file descriptors other than 0, 1, and 2."""
553 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
555 except OSError: pass # most likely an fd that isn't open