import fcntl
import os
import re
+import signal
import sys
import time
import traceback
import mountimpl
-import linuxcaps
import passfdimpl
import utmp
import vserverimpl, vduimpl
-import cpulimit
-
-from util_vserver_vars import *
-
-CAP_SAFE = (linuxcaps.CAP_CHOWN |
- linuxcaps.CAP_DAC_OVERRIDE |
- linuxcaps.CAP_DAC_READ_SEARCH |
- linuxcaps.CAP_FOWNER |
- linuxcaps.CAP_FSETID |
- linuxcaps.CAP_KILL |
- linuxcaps.CAP_SETGID |
- linuxcaps.CAP_SETUID |
- linuxcaps.CAP_SETPCAP |
- linuxcaps.CAP_SYS_TTY_CONFIG |
- linuxcaps.CAP_LEASE |
- linuxcaps.CAP_SYS_CHROOT |
- linuxcaps.CAP_SYS_PTRACE)
+import cpulimit, bwlimit
+
+
#
# these are the flags taken from the kernel linux/vserver/legacy.h
FLAGS_ULIMIT = 64
FLAGS_NAMESPACE = 128
-# default values for new vserver scheduler
-SCHED_TOKENS_MIN = 50
-SCHED_TOKENS_MAX = 100
class VServer:
INITSCRIPTS = [('/etc/rc.vinit', 'start'),
('/etc/rc.d/rc', '%(runlevel)d')]
- def __init__(self, name):
+ def __init__(self, name, vm_id, vm_running = False, resources = {}):
self.name = name
- self.config = self.__read_config_file("/etc/vservers.conf")
- self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
- self.name))
- self.flags = 0
- flags = self.config["S_FLAGS"].split(" ")
- if "lock" in flags:
- self.flags |= FLAGS_LOCK
- if "nproc" in flags:
- self.flags |= FLAGS_NPROC
- self.remove_caps = ~CAP_SAFE
- self.ctx = int(self.config["S_CONTEXT"])
+ self.config_file = "/etc/vservers/%s.conf" % name
+ self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
+ if not (os.path.isdir(self.dir) and
+ os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
+ raise Exception, "no such vserver: " + name
+ self.config = {}
+ for config_file in ["/etc/vservers.conf", self.config_file]:
+ try:
+ self.config.update(self.__read_config_file(config_file))
+ except IOError, ex:
+ if ex.errno != errno.ENOENT:
+ raise
+ self.remove_caps = ~vserverimpl.CAP_SAFE;
+ self.ctx = vm_id
+ self.vm_running = vm_running
+ self.resources = resources
config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
config[key] = val.strip('"')
return config
+ def __update_config_file(self, filename, newvars):
+
+ # read old file, apply changes
+ f = open(filename, "r")
+ data = f.read()
+ f.close()
+ todo = newvars.copy()
+ changed = False
+ for m in self.config_var_re.finditer(data):
+ (key, val) = m.groups()
+ newval = todo.pop(key, None)
+ if newval != None:
+ data = data[:m.start(2)] + str(newval) + data[m.end(2):]
+ changed = True
+ for (newkey, newval) in todo.items():
+ data += "%s=%s\n" % (newkey, newval)
+ changed = True
+
+ if not changed:
+ return
+
+ # write new file
+ newfile = filename + ".new"
+ f = open(newfile, "w")
+ f.write(data)
+ f.close()
+
+ # 'copy' original file, rename new to original
+ backup = filename + ".old"
+ try:
+ os.unlink(backup)
+ except OSError, ex:
+ if ex.errno != errno.ENOENT:
+ raise
+ os.link(filename, backup)
+ os.rename(newfile, filename)
+
def __do_chroot(self):
- return os.chroot("%s/%s" % (VROOTDIR, self.name))
+ os.chroot(self.dir)
+ os.chdir("/")
- def set_dlimit(self, blocktotal):
- path = "%s/%s" % (VROOTDIR, self.name)
- inodes, blockcount, size = vduimpl.vdu(path)
- blockcount = blockcount >> 1
+ def set_disklimit(self, block_limit):
- if blocktotal > blockcount:
- vserverimpl.setdlimit(path, self.ctx, blockcount>>1, \
- blocktotal, inodes, -1, 2)
+ # block_limit is in kB
+ if block_limit == 0:
+ vserverimpl.unsetdlimit(self.dir, self.ctx)
+ return
+
+ if self.vm_running:
+ block_usage = vserverimpl.DLIMIT_KEEP
+ inode_usage = vserverimpl.DLIMIT_KEEP
else:
- # should raise some error value
- print "block limit (%d) ignored for vserver %s" %(blocktotal,self.name)
+ # init_disk_info() must have been called to get usage values
+ block_usage = self.disk_blocks
+ inode_usage = self.disk_inodes
+
+ vserverimpl.setdlimit(self.dir,
+ self.ctx,
+ block_usage,
+ block_limit,
+ inode_usage,
+ vserverimpl.DLIMIT_INF, # inode limit
+ 2) # %age reserved for root
+
+ def get_disklimit(self):
- def get_dlimit(self):
- path = "%s/%s" % (VROOTDIR, self.name)
try:
- blocksused, blocktotal, inodesused, inodestotal, reserved = \
- vserverimpl.getdlimit(path,self.ctx)
+ (self.disk_blocks, block_limit, self.disk_inodes, inode_limit,
+ reserved) = vserverimpl.getdlimit(self.dir, self.ctx)
except OSError, ex:
- if ex.errno == 3:
- # get here if no vserver disk limit has been set for xid
- # set blockused to -1 to indicate no limit
- blocktotal = -1
-
- return blocktotal
-
- def set_sched(self, shares, besteffort = True):
- # for the old CKRM scheduler
- if cpulimit.checkckrm() is True:
- cpulimit.cpuinit()
- cpulimit.vs2ckrm_on(self.name)
- try:
- cpulimit.cpulimit(self.name,shares)
- except OSError, ex:
- if ex.errno == 22:
- print "invalid shares argument"
- # should re-raise exception?!
+ if ex.errno != errno.ESRCH:
+ raise
+ # get here if no vserver disk limit has been set for xid
+ block_limit = -1
- # for the new vserver scheduler
- else:
- global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX
- tokensmin = SCHED_TOKENS_MIN
- tokensmax = SCHED_TOKENS_MAX
-
- if besteffort is True:
- # magic "interval" value for Andy's scheduler to denote besteffort
- interval = 1000
- fillrate = shares
- else:
- interval = 1001
- fillrate = shares
+ return block_limit
- try:
- vserverimpl.setsched(self.ctx,fillrate,interval,tokensmin,tokensmax)
- except OSError, ex:
- if ex.errno == 22:
- print "kernel does not support vserver scheduler"
- else:
- raise ex
+ def set_sched(self, cpu_share):
+
+ if cpu_share == int(self.config.get("CPULIMIT", -1)):
+ return
+ # XXX - don't want to have to deal with nm_ flags here
+ cpu_guaranteed = int(self.resources.get("nm_sched_flags",
+ None) == "guaranteed")
+ cpu_config = { "CPULIMIT": cpu_share, "CPUGUARANTEED": cpu_guaranteed }
+ self.__update_config_file(self.config_file, cpu_config)
+ if self.vm_running:
+ # caller must ensure cpu_share is consistent with self.resources
+ vserverimpl.setsched(self.ctx, self.resources)
def get_sched(self):
# have no way of querying scheduler right now on a per vserver basis
- return -1, False
+ return (-1, False)
def set_memlimit(self, limit):
ret = vserverimpl.setrlimit(self.ctx,5,limit)
ret = vserverimpl.getrlimit(self.ctx,6)
return ret
+ def set_bwlimit(self, share, minrate = 1, maxrate = None, dev = "eth0"):
+
+ if share:
+ bwlimit.on(self.ctx, dev, share, minrate, maxrate)
+ else:
+ bwlimit.off(self.ctx, dev)
+
+ def get_bwlimit(self, eth):
+ # not implemented yet
+ bwlimit = -1
+ cap = "unknown"
+ minrate = "unknown"
+ maxrate = "unknown"
+ return (bwlimit, cap, minrate, maxrate)
+
def open(self, filename, mode = "r", bufsize = -1):
(sendsock, recvsock) = passfdimpl.socketpair()
return os.fdopen(fd, mode, bufsize)
- def __do_chcontext(self, state_file = None):
+ def __do_chcontext(self, state_file):
- vserverimpl.chcontext(self.ctx, self.remove_caps)
- if not state_file:
- return
- print >>state_file, "S_CONTEXT=%d" % self.ctx
- print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
- state_file.close()
+ if state_file:
+ print >>state_file, "S_CONTEXT=%u" % self.ctx
+ print >>state_file, "S_PROFILE="
+ state_file.close()
+
+ vserverimpl.chcontext(self.ctx, self.resources)
def __prep(self, runlevel, log):
def start(self, wait, runlevel = 3):
+ self.vm_running = True
+
child_pid = os.fork()
if child_pid == 0:
# child process
# execute each init script in turn
# XXX - we don't support all scripts that vserver script does
cmd_pid = 0
+ first_child = True
for cmd in self.INITSCRIPTS + [None]:
# wait for previous command to terminate, unless it
# is the last one and the caller has specified to wait
# parent process
return child_pid
+
+ def update_resources(self, resources):
+
+ self.config.update(resources)
+
+ # write new values to configuration file
+ self.__update_config_file(self.config_file, resources)
+
+ def init_disk_info(self):
+
+ (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
+
+ return size
+
+ def stop(self, signal = signal.SIGKILL):
+
+ vserverimpl.killall(self.ctx, signal)
+ self.vm_running = False