shorten cgroups-related code, and try as much sysfs related stuff before exiting
[lxc-userspace.git] / lxcsu
diff --git a/lxcsu b/lxcsu
index 9880360..8fa6a09 100755 (executable)
--- a/lxcsu
+++ b/lxcsu
@@ -11,6 +11,131 @@ drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
 # can set to True here, but also use the -d option
 debug = False
 
+#################### should go into a separate libvirtsystemd.py
+# but we want to keep packaging simple for now
+
+# reproducing libvirt's systemd-oriented escaping mechanism
+# http://code.metager.de/source/xref/lib/virt/src/util/virsystemd.c
+# (see original code at the end of this file)
+
+def virSystemdEscapeName (name):
+    result=''
+    def ESCAPE(c,s):
+        # replace hex's output '0x..' into '\x..' 
+        return s+hex(ord(c)).replace('0','\\',1)
+    VALID_CHARS = \
+        "0123456789" + \
+        "abcdefghijklmnopqrstuvwxyz" + \
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + \
+        ":-_.\\"
+    for c in name:
+        if c=='/': 
+            result += '-'
+        elif c in '-\\' or c not in VALID_CHARS:
+            result=ESCAPE(c,result)
+        else:
+            result += c
+    return result
+
+#35static void virSystemdEscapeName(virBufferPtr buf,
+#36                                 const char *name)
+#37{
+#38    static const char hextable[16] = "0123456789abcdef";
+#39
+#40#define ESCAPE(c)                                                       \
+#41    do {                                                                \
+#42        virBufferAddChar(buf, '\\');                                    \
+#43        virBufferAddChar(buf, 'x');                                     \
+#44        virBufferAddChar(buf, hextable[(c >> 4) & 15]);                 \
+#45        virBufferAddChar(buf, hextable[c & 15]);                        \
+#46    } while (0)
+#47
+#48#define VALID_CHARS                             \
+#49        "0123456789"                            \
+#50        "abcdefghijklmnopqrstuvwxyz"            \
+#51        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"            \
+#52        ":-_.\\"
+#53
+#54    if (*name == '.') {
+#55        ESCAPE(*name);
+#56        name++;
+#57    }
+#58
+#59    while (*name) {
+#60        if (*name == '/')
+#61            virBufferAddChar(buf, '-');
+#62        else if (*name == '-' ||
+#63                 *name == '\\' ||
+#64                 !strchr(VALID_CHARS, *name))
+#65            ESCAPE(*name);
+#66        else
+#67            virBufferAddChar(buf, *name);
+#68        name++;
+#69    }
+#70
+#71#undef ESCAPE
+#72#undef VALID_CHARS
+#73}
+
+def virSystemdMakeScopeName (name, drivername, partition):
+    result=''
+    result += virSystemdEscapeName (partition)
+    result += '-'
+    result += virSystemdEscapeName (drivername)
+    result += '\\x2d'
+    result += virSystemdEscapeName (name)
+    result += '.scope'
+    return result
+
+#76char *virSystemdMakeScopeName(const char *name,
+#77                              const char *drivername,
+#78                              const char *partition)
+#79{
+#80    virBuffer buf = VIR_BUFFER_INITIALIZER;
+#81
+#82    if (*partition == '/')
+#83        partition++;
+#84
+#85    virSystemdEscapeName(&buf, partition);
+#86    virBufferAddChar(&buf, '-');
+#87    virSystemdEscapeName(&buf, drivername);
+#88    virBufferAddLit(&buf, "\\x2d");
+#89    virSystemdEscapeName(&buf, name);
+#90    virBufferAddLit(&buf, ".scope");
+#91
+#92    if (virBufferError(&buf)) {
+#93        virReportOOMError();
+#94        return NULL;
+#95    }
+#96
+#97    return virBufferContentAndReset(&buf);
+#98}
+
+### our own additions
+# heuristics to locate /sys/fs/cgroup stuff
+import os.path
+def find_first_dir (candidates):
+    for candidate in candidates:
+        if os.path.isdir(candidate): return candidate
+    raise Exception,"Cannot find valid dir among\n" + "\n".join([" ->"+c for c in candidates])
+
+def find_sysfs_scope (subsystem, slice_name):
+    subsystem1=subsystem
+    subsystem2=subsystem
+    if subsystem=='cpuacct':
+        subsystem2='cpu,cpuacct'
+    candidates = [ 
+        # for f16 and our locally brewed libvirt 1.0.4
+        "/sys/fs/cgroup/%s/libvirt/lxc/%s"%(subsystem1, slice_name),
+        "/sys/fs/cgroup/%s/system/libvirtd.service/libvirt/lxc/%s"%(subsystem1, slice_name),
+        # f20 and libvirt 1.1.3
+        "/sys/fs/cgroup/%s/machine.slice/%s"%(subsystem2, 
+                                              virSystemdMakeScopeName(slice_name,'lxc','machine')),
+        ]
+    return find_first_dir (candidates)
+
+#################### end of libvirtsystemd.py
+
 def getarch(f):
     output = os.popen('readelf -h %s 2>&1'%f).readlines()
     classlines = [x for x in output if ('Class' in x.split(':')[0])]
@@ -23,32 +148,41 @@ def getarch(f):
     else:
         raise Exception('Could not determine architecture')
 
-def umount(fs_dir):
-    output = os.popen('/bin/umount %s 2>&1'%fs_dir).read()
+def umount(fs_dir, opts=''):
+    output = os.popen('/bin/umount %s %s 2>&1'%(opts, fs_dir)).read()
     return ('device is busy' not in output)
 
 def main ():
     parser = ArgumentParser()
     parser.add_argument("-n", "--nonet",
-                        action="store_true", dest="netns", default=False,
-                        help="Don't enter network namespace")
+                                       action="store_true", dest="netns", default=False,
+                                       help="Don't enter network namespace")
     parser.add_argument("-m", "--nomnt",
-                        action="store_true", dest="mntns", default=False,
-                        help="Don't enter mount namespace")
+                                       action="store_true", dest="mntns", default=False,
+                                       help="Don't enter mount namespace")
     parser.add_argument("-p", "--nopid",
-                        action="store_true", dest="pidns", default=False,
-                        help="Don't enter pid namespace")
+                                       action="store_true", dest="pidns", default=False,
+                                       help="Don't enter pid namespace")
     parser.add_argument("-r", "--root",
-                        action="store_true", dest="root", default=False,
-                        help="Enter as root: be careful")
+                                       action="store_true", dest="root", default=False,
+                                       help="Enter as root: be careful")
     parser.add_argument("-i","--internal",
-                        action="store_true", dest="internal", default=False,
-                        help="does *not* prepend '-- -c' to arguments - or invoke lxcsu-internal")
+                                       action="store_true", dest="internal", default=False,
+                                       help="does *not* prepend '-- -c' to arguments - or invoke lxcsu-internal")
     parser.add_argument("-d","--debug",
-                        action='store_true', dest='debug', default=False,
-                        help="debug option")
-    parser.add_argument("-s","--nosliceuid", dest="nosliceuid", default=False,
-                        help="do not change to slice uid inside of slice")
+                                       action='store_true', dest='debug', default=False,
+                                       help="debug option")
+    parser.add_argument("-s","--nosliceuid",
+                                       action='store_true', dest="nosliceuid", default=False,
+                                       help="do not change to slice uid inside of slice")
+    parser.add_argument("-o","--noslicehome",
+                                       action='store_true', dest="noslicehome", default=False,
+                                       help="do not change to slice home directory inside of slice")
+
+    if os.path.exists("/etc/lxcsu_default"):
+        defaults = parser.parse_args(file("/etc/lxcsu_default","r").read().split())
+        parser.set_defaults(**defaults.__dict__)
+
     parser.add_argument ("slice_name")
     parser.add_argument ("command_to_run",nargs="*")
 
@@ -65,140 +199,117 @@ def main ():
 
     # plain lxcsu
     if not args.internal:
-        # no command given: enter interactive shell
-        if not args.command_to_run: args.command_to_run=['/bin/sh']
-        args.command_to_run = [ '-c' ] + [" ".join(args.command_to_run)]
+       # no command given: enter interactive shell
+       if not args.command_to_run: args.command_to_run=['/bin/sh']
+       args.command_to_run = [ '-c' ] + [" ".join(args.command_to_run)]
 
     # support for either setting debug at the top of this file, or on the command-line
     if args.debug:
         global debug
-        debug=True
+       debug=True
 
     try:
-        cmd = 'grep %s /proc/*/cgroup | grep freezer'%slice_name
-        output = os.popen(cmd).readlines()
+        cmd = '/usr/bin/virsh --connect lxc:/// domid %s'%slice_name
+       pidnum = int(os.popen(cmd).read().rstrip())
     except:
-        print "Error finding slice %s"%slice_name
-        exit(1)
+        print "Domain %s not found"%slice_name
+       exit(1)
 
-    slice_spec = None
+    pid = '%s'%pidnum
+    if debug: print "Found pidnum",pidnum
+    cmdline = open('/proc/%s/cmdline'%pidnum).read().rstrip('\n\x00')
+    arch = getarch('/proc/%s/exe'%pid)
 
-    # provide a default as this is not always properly computed
-    arch = None
-
-    for e in output:
-        try:
-            l = e.rstrip()
-            path = l.split(':')[0]  
-            comp = l.rsplit(':')[-1]
-            slice_name_check = comp.rsplit('/')[-1]
-            if debug: print "dealing with >%s<"%slice_name_check
-            
-            if (slice_name_check == slice_name):
-                if debug: print "found %s"%slice_name
-                slice_path = path
-                pid = slice_path.split('/')[2]
-                cmdline = open('/proc/%s/cmdline'%pid).read().rstrip('\n\x00')
-                if (cmdline == '/sbin/init') or (cmdline.startswith("init [")):
-                    slice_spec = slice_path
-                    arch = getarch('/proc/%s/exe'%pid)
-                    break
-        except Exception,e:
-            if debug: 
-                import traceback
-                print "BEG lxcsu - ignoring exception"
-                traceback.print_exc()
-                print "END lxcsu - ignoring exception"
-            pass
-
-    if (not slice_spec or not pid):
-        print "Not started: %s"%slice_name
-        exit(1)
+    if (not pid):
+        print "Domain %s not started"%slice_name
+       exit(1)
 
     if arch is None:
-        arch = 'x86_64'
+       arch = 'x86_64'
 
     # Set sysctls specific to slice
     sysctls = []
     sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
     if (os.access(sysctl_dir,0)):
         entries = os.listdir(sysctl_dir)
-        for e in entries:
+       for e in entries:
             prefix = 'vsys_sysctl.'
-            if (e.startswith(prefix)):
-                sysctl_file = '/'.join([sysctl_dir,e])
-                sysctl_name = e[len(prefix):]
-                sysctl_val = open(sysctl_file).read()
-                sysctls.append((sysctl_file, sysctl_name, sysctl_val))
+           if (e.startswith(prefix)):
+               sysctl_file = '/'.join([sysctl_dir,e])
+               sysctl_name = e[len(prefix):]
+               sysctl_val = open(sysctl_file).read()
+               sysctls.append((sysctl_file, sysctl_name, sysctl_val))
 
     # Enter cgroups
-    try:
-        for subsystem in ['cpuset','memory','blkio']:
-            open('/sys/fs/cgroup/%s/libvirt/lxc/%s/tasks'%(subsystem,slice_name),'w').write(str(os.getpid()))
-
-    except:
-        print "Error assigning resources: %s"%slice_name
-        exit(1)
-
-    try:
-        open('/sys/fs/cgroup/cpuacct/system/libvirtd.service/libvirt/lxc/%s/tasks'%slice_name,'w').write(str(os.getpid()))
-    except:
-        print "Error assigning cpuacct: %s" % slice_name
-        exit(1)
+    # do not exit right away when something goes wrong
+    # check as much as we can and only then exit
+    cgroups_ok=True
+    for subsystem in ['cpuset' ,'memory' ,'blkio', 'cpuacct']:
+        try:
+            open( find_sysfs_scope (subsystem, slice_name)+"/tasks", 'w').write(str(os.getpid()))
+        except Exception,e:
+            if debug: print e 
+            print "ERROR assigning resources for %s in subsystem %s - bailing out"%(slice_name,subsystem)
+            cgroups_ok=False
 
     # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
     # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
     # in this case to error out the shell. (an alternative would be to un-freeze it,
     # add the task, and re-freeze it)
     try:
-        f=open('/sys/fs/cgroup/freezer/libvirt/lxc/%s/tasks'%(slice_name),'w')
-        f.write(str(os.getpid()))
-        # note: we need to call f.close() explicitly, or we'll get an exception in
-        # the object destructor, which will not be caught
-        f.close()
-    except:
-        print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
-        exit(1)
+       f=open( find_sysfs_scope ('freezer', slice_name)+"/tasks", 'w')
+       f.write(str(os.getpid()))
+       # note: we need to call f.close() explicitly, or we'll get an exception in
+       # the object destructor, which will not be caught
+       f.close()
+    except Exception,e:
+       if debug: print e 
+       print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
+        cgroups_ok=False
 
     setns.chcontext('/proc/%s/ns/uts'%pid)
     setns.chcontext('/proc/%s/ns/ipc'%pid)
-    
+       
     if (not args.pidns):
-        setns.chcontext('/proc/%s/ns/pid'%pid)
+       setns.chcontext('/proc/%s/ns/pid'%pid)
 
     if (not args.netns):
-        setns.chcontext('/proc/%s/ns/net'%pid)
+       setns.chcontext('/proc/%s/ns/net'%pid)
 
     if (not args.mntns):
-        setns.chcontext('/proc/%s/ns/mnt'%pid)
+       setns.chcontext('/proc/%s/ns/mnt'%pid)
 
     proc_mounted = False
     if (not os.access('/proc/self',0)):
-        proc_mounted = True
-        setns.proc_mount()
+       proc_mounted = True
+       setns.proc_mount()
 
     for (sysctl_file, sysctl_name, sysctl_val) in sysctls:
-                for fn in ["/sbin/sysctl", "/usr/sbin/sysctl", "/bin/sysctl", "/usr/bin/sysctl"]:
-                    if os.path.exists(fn):
-                        os.system("mount -o remount,rw none /proc/sys")
-                        os.system('%s -w %s=%s'%(fn, sysctl_name,sysctl_val))
-                        os.system("mount -o remount,ro none /proc/sys")
-                        break
-                else:
-                    print "Error: image does not have a sysctl binary"
+       for fn in ["/sbin/sysctl", "/usr/sbin/sysctl", "/bin/sysctl", "/usr/bin/sysctl"]:
+           if os.path.exists(fn):
+               os.system('%s -w %s=%s  >/dev/null 2>&1'%(fn, sysctl_name,sysctl_val))
+               break
+           else:
+               print "Error: image does not have a sysctl binary"
 
     # cgroups is not yet LXC-safe, so we need to use the coarse grained access control
     # strategy of unmounting the filesystem
 
     umount_result = True
-    for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event']:
-        fs_path = '/sys/fs/cgroup/%s'%subsystem
-        if (not umount(fs_path)):
-            print "Error disabling cgroup access"
-            exit(1)
+    for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event','systemd']:
+       fs_path = '/sys/fs/cgroup/%s'%subsystem
+       if (not umount(fs_path,'-l')):
+           pass
+           # Leaving these comments for historical reference
+           #print "Error disabling cgroup access"
+           #exit(1) - Don't need this because failure here implies failure in the call to umount /sys/fs/cgroup
 
     if (not umount('/sys/fs/cgroup')):
         print "Error disabling cgroup access"
+        cgroups_ok=False
+
+    if not cgroups_ok:
+        print 'exiting'
         exit(1)
 
     pid = os.fork()
@@ -207,12 +318,12 @@ def main ():
     # so if only for f12 we need to fake this one
     #
     # capsh.c does essentially the following when invoked with --user:
-    #      pwd = getpwnam(user); ...
-    #      ngroups = MAX_GROUPS; 
-    #      status = getgrouplist(user, pwd->pw_gid, groups, &ngroups); ...
-    #      status = setgroups(ngroups, groups); ...
-    #      status = setgid(pwd->pw_gid); ...
-    #      status = setuid(pwd->pw_uid); ...
+    #          pwd = getpwnam(user); ...
+    #          ngroups = MAX_GROUPS; 
+    #          status = getgrouplist(user, pwd->pw_gid, groups, &ngroups); ...
+    #          status = setgroups(ngroups, groups); ...
+    #          status = setgid(pwd->pw_gid); ...
+    #          status = setuid(pwd->pw_uid); ...
     # however we cannot simulate that ourselves because if we did in this process then
     # capsh could not be allowed to mess with caps any more
 
@@ -237,14 +348,16 @@ def main ():
                     exit(1)
                 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--uid=%s'%uid,'--','--login',]+args.command_to_run
 # once we can drop f12, it would be nicer to instead go for
-#                exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--','--login',]+args.command_to_run
+# exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--','--login',]+args.command_to_run
         else:
             exec_args = [arch,'/usr/sbin/capsh','--','--login']+args.command_to_run
 
         os.environ['SHELL'] = '/bin/sh'
-        os.environ['HOME'] = '/home/%s'%slice_name
-        os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
-        os.chdir("/home/%s"%(slice_name))
+        if os.path.exists('/etc/planetlab/lib/bind_public.so'):
+            os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
+        if not args.noslicehome:
+            os.environ['HOME'] = '/home/%s'%slice_name
+            os.chdir("/home/%s"%(slice_name))
         if debug: print 'lxcsu:execv:','/usr/bin/setarch',exec_args
         os.execv('/usr/bin/setarch',exec_args)
     else:
@@ -253,4 +366,4 @@ def main ():
         exit(os.WEXITSTATUS(status))
 
 if __name__ == '__main__':
-    main()
+       main()