1 # Copyright 2005 Princeton University
3 #$Id: vserver.py,v 1.72 2007/08/02 16:01:59 dhozac Exp $
19 import cpulimit, bwlimit
21 from vserverimpl import DLIMIT_INF
22 from vserverimpl import VC_LIM_KEEP
23 from vserverimpl import VLIMIT_NSOCK
24 from vserverimpl import VLIMIT_OPENFD
25 from vserverimpl import VLIMIT_ANON
26 from vserverimpl import VLIMIT_SHMEM
29 # these are the flags taken from the kernel linux/vserver/legacy.h
32 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
40 RLIMITS = { "NSOCK": VLIMIT_NSOCK,
41 "OPENFD": VLIMIT_OPENFD,
43 "SHMEM": VLIMIT_SHMEM}
47 # add in the platform supported rlimits
48 for entry in resource.__dict__.keys():
49 if entry.find("RLIMIT_")==0:
50 k = entry[len("RLIMIT_"):]
51 if not RLIMITS.has_key(k):
52 RLIMITS[k]=resource.__dict__[entry]
54 print "WARNING: duplicate RLIMITS key %s" % k
56 class NoSuchVServer(Exception): pass
59 def __init__(self, name, directory):
63 if not (os.path.isdir(self.dir) and
64 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
65 raise NoSuchVServer, "%s does not exist" % self.dir
67 def get(self, option, default = None):
70 return self.cache[option]
72 f = open(os.path.join(self.dir, option), "r")
73 buf = f.read().rstrip()
77 if default is not None:
80 raise KeyError, "Key %s is not set for %s" % (option, self.name)
82 def update(self, option, value):
87 old_umask = os.umask(0022)
88 filename = os.path.join(self.dir, option)
90 os.makedirs(os.path.dirname(filename), 0755)
93 f = open(filename, 'w')
94 if isinstance(value, list):
95 f.write("%s\n" % "\n".join(value))
97 f.write("%s\n" % value)
103 def unset(self, option):
108 filename = os.path.join(self.dir, option)
111 os.removedirs(os.path.dirname(filename))
120 def add_to_cache(cache, dirname, fnames):
122 full_name = os.path.join(dirname, file)
123 if os.path.islink(full_name):
125 elif (os.path.isfile(full_name) and
126 os.access(full_name, os.R_OK)):
127 f = open(full_name, "r")
128 cache[full_name.replace(os.path.join(self.dir, ''),
129 '')] = f.read().rstrip()
131 os.path.walk(self.dir, add_to_cache, self.cache)
136 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
137 ('/etc/rc.d/rc', '%(runlevel)d')]
139 def __init__(self, name, vm_id = None, vm_running = None, logfile=None):
142 self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
143 if not (os.path.isdir(self.dir) and
144 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
145 raise NoSuchVServer, "no such vserver: " + name
146 self.config = VServerConfig(name, "/etc/vservers/%s" % name)
147 #self.remove_caps = ~vserverimpl.CAP_SAFE;
149 vm_id = int(self.config.get('context'))
151 if vm_running == None:
152 vm_running = self.is_running()
153 self.vm_running = vm_running
154 self.logfile = logfile
156 # inspired from nodemanager's logger
160 fd = os.open(self.logfile,os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
161 if not msg.endswith('\n'): msg += '\n'
162 os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
165 print '%s: (%s failed to open) %s'%(time.asctime(time.gmtime()),self.logfile,msg)
167 def set_rlimit(self, type, hard, soft, min):
168 """Generic set resource limit function for vserver"""
172 if hard <> VC_LIM_KEEP:
173 self.config.update('rlimits/%s.hard' % type.lower(), hard)
175 if soft <> VC_LIM_KEEP:
176 self.config.update('rlimits/%s.soft' % type.lower(), soft)
178 if min <> VC_LIM_KEEP:
179 self.config.update('rlimits/%s.min' % type.lower(), min)
182 if self.is_running() and update:
183 resource_type = RLIMITS[type]
185 vserverimpl.setrlimit(self.ctx, resource_type, hard, soft, min)
187 self.log("Error: setrlimit(%d, %s, %d, %d, %d): %s"
188 % (self.ctx, type.lower(), hard, soft, min))
192 def get_prefix_from_capabilities(self, capabilities, prefix):
193 split_caps = capabilities.split(',')
194 return ",".join(["%s" % (c) for c in split_caps if c.startswith(prefix.upper()) or c.startswith(prefix.lower())])
196 def get_bcaps_from_capabilities(self, capabilities):
197 return self.get_prefix_from_capabilities(capabilities, "cap_")
199 def get_ccaps_from_capabilities(self, capabilities):
200 return self.get_prefix_from_capabilities(capabilities, "vxc_")
202 def set_capabilities_config(self, capabilities):
203 bcaps = self.get_bcaps_from_capabilities(capabilities)
204 ccaps = self.get_ccaps_from_capabilities(capabilities)
207 bcaps += "CAP_NET_RAW"
208 self.config.update('bcapabilities', bcaps)
209 self.config.update('ccapabilities', ccaps)
210 ret = vserverimpl.setbcaps(self.ctx, vserverimpl.text2bcaps(bcaps))
213 return vserverimpl.setccaps(self.ctx, vserverimpl.text2ccaps(ccaps))
215 def get_capabilities(self):
216 bcaps = vserverimpl.bcaps2text(vserverimpl.getbcaps(self.ctx))
217 ccaps = vserverimpl.ccaps2text(vserverimpl.getccaps(self.ctx))
220 return (bcaps + ccaps)
222 def get_capabilities_config(self):
223 bcaps = self.config.get('bcapabilities', '')
224 ccaps = self.config.get('ccapabilities', '')
227 return (bcaps + ccaps)
229 def set_ipaddresses(self, addresses):
230 vserverimpl.netremove(self.ctx, "all")
231 for a in addresses.split(","):
232 vserverimpl.netadd(self.ctx, a)
234 def set_ipaddresses_config(self, addresses):
237 for a in addresses.split(","):
238 self.config.update("interfaces/%d/ip" % i, a)
240 while self.config.unset("interfaces/%d/ip" % i):
242 self.set_ipaddresses(addresses)
244 def get_ipaddresses_config(self):
248 r = self.config.get("interfaces/%d/ip" % i, '')
255 def get_ipaddresses(self):
256 # No clean way to do this right now.
257 self.log("Calling Vserver.get_ipaddresses for slice %s" % self.name)
260 def __do_chroot(self):
264 def chroot_call(self, fn, *args):
265 cwd_fd = os.open(".", os.O_RDONLY)
267 root_fd = os.open("/", os.O_RDONLY)
280 def set_disklimit(self, block_limit):
281 # block_limit is in kB
284 vserverimpl.unsetdlimit(self.dir, self.ctx)
286 self.log("Unexpected error with unsetdlimit for context %d" % self.ctx)
290 block_usage = vserverimpl.DLIMIT_KEEP
291 inode_usage = vserverimpl.DLIMIT_KEEP
293 # init_disk_info() must have been called to get usage values
294 block_usage = self.disk_blocks
295 inode_usage = self.disk_inodes
298 vserverimpl.setdlimit(self.dir,
303 vserverimpl.DLIMIT_INF, # inode limit
304 2) # %age reserved for root
306 self.log("Unexpected error with setdlimit for context %d" % self.ctx)
308 self.config.update('dlimits/0/space_total', block_limit)
310 def is_running(self):
311 status = subprocess.call(["/usr/sbin/vserver", self.name, "running"], shell=False)
314 def get_disklimit(self):
316 (self.disk_blocks, block_limit, self.disk_inodes, inode_limit,
317 reserved) = vserverimpl.getdlimit(self.dir, self.ctx)
319 if ex.errno != errno.ESRCH:
321 # get here if no vserver disk limit has been set for xid
326 def set_sched_config(self, cpu_min, cpu_share):
327 """ Write current CPU scheduler parameters to the vserver
328 configuration file. Currently, 'cpu_min' is not supported. """
329 self.config.update('cgroup/cpu.shares', cpu_share * CPU_SHARE_MULT)
330 if self.is_running():
331 self.set_sched(cpu_min, cpu_share)
333 def set_sched(self, cpu_min, cpu_share):
334 """ Update kernel CPU scheduling parameters for this context.
335 Currently, 'cpu_min' is not supported. """
337 cgroup = open('/dev/cgroup/%s/cpu.shares' % name, 'w')
338 cgroup.write('%s' % (cpu_share * CPU_SHARE_MULT))
345 cpu_share = int(int(self.config.get('cgroup/cpu.shares')) / CPU_SHARE_MULT)
348 return (-1, cpu_share)
350 def set_bwlimit(self, minrate = bwlimit.bwmin, maxrate = None,
351 exempt_min = None, exempt_max = None,
352 share = None, dev = "eth0"):
355 bwlimit.off(self.ctx, dev)
357 bwlimit.on(self.ctx, dev, share,
358 minrate, maxrate, exempt_min, exempt_max)
360 def get_bwlimit(self, dev = "eth0"):
362 result = bwlimit.get(self.ctx)
363 # result of bwlimit.get is (ctx, share, minrate, maxrate)
368 def open(self, filename, mode = "r", bufsize = -1):
370 return self.chroot_call(open, filename, mode, bufsize)
373 subprocess.call("/usr/sbin/vserver %s enter" % self.name, shell=True)
375 def start(self, runlevel = 3):
377 # Parent should just return.
378 self.vm_running = True
383 f = "/etc/vservers/%s/spaces/net" % self.name
384 # Always start vserver with a network namespace.
385 subprocess.call(["/bin/touch", f], shell=False)
386 subprocess.call("/usr/sbin/vserver %s start" % self.name,
388 #subprocess.call(["/bin/rm", f], shell=False)
389 # we get here due to an exception in the top-level child process
390 except Exception, ex:
391 self.log(traceback.format_exc())
394 def set_resources(self):
396 """ Called when vserver context is entered for first time,
397 should be overridden by subclass. """
401 def init_disk_info(self):
403 dlimit = vserverimpl.getdlimit(self.dir, self.ctx)
404 self.disk_blocks = dlimit[0]
405 self.disk_inodes = dlimit[2]
406 return self.disk_blocks * 1024
409 cmd = "/usr/sbin/vdu --script --space --inodes --blocksize 1024 --xid %d %s" % (self.ctx, self.dir)
410 p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
411 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
414 line = p.stdout.readline()
416 sys.stderr.write(p.stderr.read())
421 (space, inodes) = line.split()
422 self.disk_inodes = int(inodes)
423 self.disk_blocks = int(space)
425 return self.disk_blocks * 1024
427 def stop(self, signal = signal.SIGKILL):
428 self.vm_running = False
429 subprocess.call("/usr/sbin/vserver %s stop" % self.name, shell=True)
431 def setname(self, slice_id):
435 def create(vm_name, static = False, ctor = VServer):
437 options = ['vuseradd']
439 options += ['--static']
440 ret = os.spawnvp(os.P_WAIT, 'vuseradd', options + [vm_name])
441 if not os.WIFEXITED(ret) or os.WEXITSTATUS(ret) != 0:
442 out = "system command ('%s') " % options
443 if os.WIFEXITED(ret):
444 out += "failed, rc = %d" % os.WEXITSTATUS(ret)
446 out += "killed by signal %d" % os.WTERMSIG(ret)
447 raise SystemError, out
448 vm_id = pwd.getpwnam(vm_name)[2]
450 return ctor(vm_name, vm_id)
453 def close_nonstandard_fds():
454 """Close all open file descriptors other than 0, 1, and 2."""
456 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
458 except OSError: pass # most likely an fd that isn't open