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 def __init__(self, name, vm_id = None, vm_running = None, logfile=None):
139 self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
140 if not (os.path.isdir(self.dir) and
141 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
142 raise NoSuchVServer, "no such vserver: " + name
143 self.config = VServerConfig(name, "/etc/vservers/%s" % name)
144 #self.remove_caps = ~vserverimpl.CAP_SAFE;
146 vm_id = int(self.config.get('context'))
148 if vm_running == None:
149 vm_running = self.is_running()
150 self.vm_running = vm_running
151 self.logfile = logfile
153 # inspired from nodemanager's logger
154 def log_in_file (self, fd, msg):
156 if not msg.endswith('\n'): msg += '\n'
157 os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
162 fd = os.open(self.logfile,os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
163 self.log_in_file(fd,msg)
166 print '%s: (%s failed to open) %s'%(time.asctime(time.gmtime()),self.logfile,msg)
168 def set_rlimit(self, type, hard, soft, min):
169 """Generic set resource limit function for vserver"""
173 if hard <> VC_LIM_KEEP:
174 self.config.update('rlimits/%s.hard' % type.lower(), hard)
176 if soft <> VC_LIM_KEEP:
177 self.config.update('rlimits/%s.soft' % type.lower(), soft)
179 if min <> VC_LIM_KEEP:
180 self.config.update('rlimits/%s.min' % type.lower(), min)
183 if self.is_running() and update:
184 resource_type = RLIMITS[type]
186 vserverimpl.setrlimit(self.ctx, resource_type, hard, soft, min)
188 self.log("Error: setrlimit(%d, %s, %d, %d, %d): %s"
189 % (self.ctx, type.lower(), hard, soft, min, e))
193 def get_prefix_from_capabilities(self, capabilities, prefix):
194 split_caps = capabilities.split(',')
195 return ",".join(["%s" % (c) for c in split_caps if c.startswith(prefix.upper()) or c.startswith(prefix.lower())])
197 def get_bcaps_from_capabilities(self, capabilities):
198 return self.get_prefix_from_capabilities(capabilities, "cap_")
200 def get_ccaps_from_capabilities(self, capabilities):
201 return self.get_prefix_from_capabilities(capabilities, "vxc_")
203 def set_capabilities_config(self, capabilities):
204 bcaps = self.get_bcaps_from_capabilities(capabilities)
205 ccaps = self.get_ccaps_from_capabilities(capabilities)
208 bcaps += "CAP_NET_RAW"
209 self.config.update('bcapabilities', bcaps)
210 self.config.update('ccapabilities', ccaps)
211 ret = vserverimpl.setbcaps(self.ctx, vserverimpl.text2bcaps(bcaps))
214 return vserverimpl.setccaps(self.ctx, vserverimpl.text2ccaps(ccaps))
216 def get_capabilities(self):
217 bcaps = vserverimpl.bcaps2text(vserverimpl.getbcaps(self.ctx))
218 ccaps = vserverimpl.ccaps2text(vserverimpl.getccaps(self.ctx))
221 return (bcaps + ccaps)
223 def get_capabilities_config(self):
224 bcaps = self.config.get('bcapabilities', '')
225 ccaps = self.config.get('ccapabilities', '')
228 return (bcaps + ccaps)
230 def set_ipaddresses(self, addresses):
231 vserverimpl.netremove(self.ctx, "all")
232 for a in addresses.split(","):
233 vserverimpl.netadd(self.ctx, a)
235 def set_ipaddresses_config(self, addresses):
238 for a in addresses.split(","):
239 self.config.update("interfaces/%d/ip" % i, a)
241 while self.config.unset("interfaces/%d/ip" % i):
243 self.set_ipaddresses(addresses)
245 def get_ipaddresses_config(self):
249 r = self.config.get("interfaces/%d/ip" % i, '')
256 def get_ipaddresses(self):
257 # No clean way to do this right now.
258 self.log("Calling Vserver.get_ipaddresses for slice %s" % self.name)
261 def __do_chroot(self):
265 def chroot_call(self, fn, *args, **kwargs):
266 cwd_fd = os.open(".", os.O_RDONLY)
268 root_fd = os.open("/", os.O_RDONLY)
271 result = fn(*args, **kwargs)
281 def set_disklimit(self, block_limit):
282 # block_limit is in kB
285 vserverimpl.unsetdlimit(self.dir, self.ctx)
287 self.log("Unexpected error with unsetdlimit for context %d" % self.ctx)
291 block_usage = vserverimpl.DLIMIT_KEEP
292 inode_usage = vserverimpl.DLIMIT_KEEP
294 # init_disk_info() must have been called to get usage values
295 block_usage = self.disk_blocks
296 inode_usage = self.disk_inodes
299 vserverimpl.setdlimit(self.dir,
304 vserverimpl.DLIMIT_INF, # inode limit
305 2) # %age reserved for root
307 self.log("Unexpected error with setdlimit for context %d" % self.ctx)
309 self.config.update('dlimits/0/space_total', block_limit)
311 def is_running(self):
312 status = subprocess.call(["/usr/sbin/vserver", self.name, "running"], shell=False)
315 def get_disklimit(self):
317 (self.disk_blocks, block_limit, self.disk_inodes, inode_limit,
318 reserved) = vserverimpl.getdlimit(self.dir, self.ctx)
320 if ex.errno != errno.ESRCH:
322 # get here if no vserver disk limit has been set for xid
327 def set_sched_config(self, cpu_min, cpu_share):
328 """ Write current CPU scheduler parameters to the vserver
329 configuration file. Currently, 'cpu_min' is not supported. """
330 self.config.update('cgroup/cpu.shares', int(cpu_share) * CPU_SHARE_MULT)
331 if self.is_running():
332 self.set_sched(cpu_min, cpu_share)
334 def set_sched(self, cpu_min, cpu_share):
335 """ Update kernel CPU scheduling parameters for this context.
336 Currently, 'cpu_min' is not supported. """
338 cgroup = open('/dev/cgroup/%s/cpu.shares' % self.name, 'w')
339 cgroup.write('%s' % (int(cpu_share) * CPU_SHARE_MULT))
346 cpu_share = int(int(self.config.get('cgroup/cpu.shares')) / CPU_SHARE_MULT)
349 return (-1, cpu_share)
351 def set_bwlimit(self, minrate = bwlimit.bwmin, maxrate = None,
352 exempt_min = None, exempt_max = None,
353 share = None, dev = "eth0"):
356 bwlimit.off(self.ctx, dev)
358 bwlimit.on(self.ctx, dev, share,
359 minrate, maxrate, exempt_min, exempt_max)
361 def get_bwlimit(self, dev = "eth0"):
363 result = bwlimit.get(self.ctx)
364 # result of bwlimit.get is (ctx, share, minrate, maxrate)
369 def open(self, filename, mode = "r", bufsize = -1):
371 return self.chroot_call(open, filename, mode, bufsize)
374 subprocess.call("/usr/sbin/vserver %s enter" % self.name, shell=True)
376 # 2010 June 21 - Thierry
377 # the slice initscript now gets invoked through rc - see sliver_vs.py in nodemanager
378 # and, rc is triggered as part of vserver .. start
379 # so we don't have to worry about initscripts at all anymore here
380 def start(self, runlevel = 3):
382 # Parent should just return.
383 self.vm_running = True
387 # first child process: fork again
389 os._exit(0) # Exit parent (the first child) of the second child.
390 # the grandson is the working one
395 subprocess.call(["/usr/sbin/vserver",self.name,"start"])
397 # we get here due to an exception in the grandson process
398 except Exception, ex:
399 self.log(traceback.format_exc())
402 def set_resources(self):
404 """ Called when vserver context is entered for first time,
405 should be overridden by subclass. """
409 def init_disk_info(self):
411 dlimit = vserverimpl.getdlimit(self.dir, self.ctx)
412 self.disk_blocks = dlimit[0]
413 self.disk_inodes = dlimit[2]
414 return self.disk_blocks * 1024
417 cmd = "/usr/sbin/vdu --script --space --inodes --blocksize 1024 --xid %d %s" % (self.ctx, self.dir)
418 p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
419 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
422 line = p.stdout.readline()
424 sys.stderr.write(p.stderr.read())
429 (space, inodes) = line.split()
430 self.disk_inodes = int(inodes)
431 self.disk_blocks = int(space)
433 return self.disk_blocks * 1024
435 def stop(self, signal = signal.SIGKILL):
436 self.vm_running = False
437 subprocess.call("/usr/sbin/vserver %s stop" % self.name, shell=True)
439 def setname(self, slice_id):
443 '''Get vcVHI_CONTEXT field in kernel'''
444 return vserverimpl.getname(self.ctx)
447 def create(vm_name, static = False, ctor = VServer):
449 options = ['vuseradd']
451 options += ['--static']
452 ret = os.spawnvp(os.P_WAIT, 'vuseradd', options + [vm_name])
453 if not os.WIFEXITED(ret) or os.WEXITSTATUS(ret) != 0:
454 out = "system command ('%s') " % options
455 if os.WIFEXITED(ret):
456 out += "failed, rc = %d" % os.WEXITSTATUS(ret)
458 out += "killed by signal %d" % os.WTERMSIG(ret)
459 raise SystemError, out
460 vm_id = pwd.getpwnam(vm_name)[2]
462 return ctor(vm_name, vm_id)
465 def close_nonstandard_fds():
466 """Close all open file descriptors other than 0, 1, and 2."""
468 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
470 except OSError: pass # most likely an fd that isn't open