Added set_dlimit and get_dlimit to be used by NM to enforce disk limits.
[util-vserver.git] / python / vserver.py
index 9d194b5..2d72bd0 100644 (file)
@@ -8,9 +8,11 @@ import sys
 import time
 import traceback
 
+import mountimpl
 import linuxcaps
 import passfdimpl
-import vserverimpl
+import utmp
+import vserverimpl, vduimpl
 
 from util_vserver_vars import *
 
@@ -44,7 +46,8 @@ FLAGS_NAMESPACE = 128
               
 class VServer:
 
-    INITSCRIPTS = [('/etc/rc.vinit', 'start'), ('/etc/rc.d/rc', '3')]
+    INITSCRIPTS = [('/etc/rc.vinit', 'start'),
+                   ('/etc/rc.d/rc', '%(runlevel)d')]
 
     def __init__(self, name):
 
@@ -78,6 +81,24 @@ class VServer:
 
         return os.chroot("%s/%s" % (VROOTDIR, self.name))
 
+    def set_dlimit(self, blocktotal):
+        path = "%s/%s" % (VROOTDIR, self.name)
+        inodes, blockcount, size = vduimpl.vdu(path)
+        vserverimpl.setdlimit(path, self.ctx, blockcount>>1, blocktotal, inodes, -1, 2)
+
+    def get_dlimit(self):
+        path = "%s/%s" % (VROOTDIR, self.name)
+        try:
+            blocksused, blocktotal, inodesused, inodestotal, reserved = \
+                        vserverimpl.getdlimit(path,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 open(self, filename, mode = "r", bufsize = -1):
 
         (sendsock, recvsock) = passfdimpl.socketpair()
@@ -144,13 +165,53 @@ class VServer:
         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
         state_file.close()
 
+    def __prep(self, runlevel, log):
+
+        """ Perform all the crap that the vserver script does before
+        actually executing the startup scripts. """
+
+        # remove /var/run and /var/lock/subsys files
+        # but don't remove utmp from the top-level /var/run
+        RUNDIR = "/var/run"
+        LOCKDIR = "/var/lock/subsys"
+        filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
+        garbage = reduce((lambda (out, ff), (dir, subdirs, files):
+                          (out + map((dir + "/").__add__, ff(files)),
+                           lambda fs: fs)),
+                         list(os.walk(RUNDIR)),
+                         ([], filter_fn))[0]
+        garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
+                                              os.listdir(LOCKDIR)))
+        for f in garbage:
+            os.unlink(f)
+
+        # set the initial runlevel
+        f = open(RUNDIR + "/utmp", "w")
+        utmp.set_runlevel(f, runlevel)
+        f.close()
+
+        # mount /proc and /dev/pts
+        self.__do_mount("none", "/proc", "proc")
+        # XXX - magic mount options
+        self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
+
+    def __do_mount(self, *mount_args):
+
+        try:
+            mountimpl.mount(*mount_args)
+        except OSError, ex:
+            if ex.errno == errno.EBUSY:
+                # assume already mounted
+                return
+            raise ex
+
     def enter(self):
 
         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
         self.__do_chroot()
         self.__do_chcontext(state_file)
 
-    def start(self):
+    def start(self, wait, runlevel = 3):
 
         child_pid = os.fork()
         if child_pid == 0:
@@ -170,35 +231,41 @@ class VServer:
                 log = open("/var/log/boot.log", "w", 0)
                 os.dup2(1, 2)
 
-                # write same output that vserver script does
                 print >>log, ("%s: starting the virtual server %s" %
                               (time.asctime(time.gmtime()), self.name))
 
+                # perform pre-init cleanup
+                self.__prep(runlevel, log)
+
                 # execute each init script in turn
                 # XXX - we don't support all scripts that vserver script does
                 cmd_pid = 0
                 for cmd in self.INITSCRIPTS + [None]:
-                    # don't bother waiting for last command to terminate
-                    if cmd == None:
-                        os._exit(0)
-
-                    # wait for previous command to terminate
-                    if cmd_pid:
+                    # wait for previous command to terminate, unless it
+                    # is the last one and the caller has specified to wait
+                    if cmd_pid and (cmd != None or wait):
                         try:
                             os.waitpid(cmd_pid, 0)
                         except:
                             print >>log, "error waiting for %s:" % cmd_pid
                             traceback.print_exc()
 
+                    # end of list
+                    if cmd == None:
+                        os._exit(0)
+
                     # fork and exec next command
                     cmd_pid = os.fork()
                     if cmd_pid == 0:
                         try:
                             # enter vserver context
                             self.__do_chcontext(state_file)
-                            print >>log, "executing '%s'" % " ".join(cmd)
-                            os.execl(cmd[0], *cmd)
-                        finally:
+                            arg_subst = { 'runlevel': runlevel }
+                            cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
+                                                      cmd[1:])
+                            print >>log, "executing '%s'" % " ".join(cmd_args)
+                            os.execl(cmd[0], *cmd_args)
+                        except:
                             traceback.print_exc()
                             os._exit(1)
                     else: