Return child's PID when starting a vserver
[util-vserver.git] / python / vserver.py
1 # Copyright 2005 Princeton University
2
3 import errno
4 import fcntl
5 import os
6 import re
7 import traceback
8
9 import linuxcaps
10 import passfdimpl
11 import vserverimpl
12
13 from util_vserver_vars import *
14
15 CAP_SAFE = (linuxcaps.CAP_CHOWN |
16             linuxcaps.CAP_DAC_OVERRIDE |
17             linuxcaps.CAP_DAC_READ_SEARCH |
18             linuxcaps.CAP_FOWNER |
19             linuxcaps.CAP_FSETID |
20             linuxcaps.CAP_KILL |
21             linuxcaps.CAP_SETGID |
22             linuxcaps.CAP_SETUID |
23             linuxcaps.CAP_SETPCAP |
24             linuxcaps.CAP_SYS_TTY_CONFIG |
25             linuxcaps.CAP_LEASE |
26             linuxcaps.CAP_SYS_CHROOT |
27             linuxcaps.CAP_SYS_PTRACE)
28
29 #
30 # these are the flags taken from the kernel linux/vserver/legacy.h
31 #
32 FLAGS_LOCK = 1
33 FLAGS_SCHED = 2  # XXX - defined in util-vserver/src/chcontext.c
34 FLAGS_NPROC = 4
35 FLAGS_PRIVATE = 8
36 FLAGS_INIT = 16
37 FLAGS_HIDEINFO = 32
38 FLAGS_ULIMIT = 64
39 FLAGS_NAMESPACE = 128
40
41
42               
43 class VServer:
44
45     INITSCRIPTS = [('/etc/rc.vinit', 'start'), ('/etc/rc.d/rc', '3')]
46
47     def __init__(self, name):
48
49         self.name = name
50         self.config = self.__read_config_file("/etc/vservers.conf")
51         self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
52                                                    self.name))
53         self.flags = 0
54         flags = self.config["S_FLAGS"].split(" ")
55         if "lock" in flags:
56             self.flags |= FLAGS_LOCK
57         if "nproc" in flags:
58             self.flags |= FLAGS_NPROC
59         self.remove_caps = ~CAP_SAFE
60         self.ctx = int(self.config["S_CONTEXT"])
61
62     config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
63
64     def __read_config_file(self, filename):
65
66         f = open(filename, "r")
67         data = f.read()
68         f.close()
69         config = {}
70         for m in self.config_var_re.finditer(data):
71             (key, val) = m.groups()
72             config[key] = val.strip('"')
73         return config
74
75     def __do_chroot(self):
76
77         return os.chroot("%s/%s" % (VROOTDIR, self.name))
78
79     def open(self, filename, mode = "r"):
80
81         (sendsock, recvsock) = passfdimpl.socketpair()
82         child_pid = os.fork()
83         if child_pid == 0:
84             try:
85                 # child process
86                 self.__do_chroot()
87                 f = open(filename, mode)
88                 passfdimpl.sendmsg(f.fileno(), sendsock)
89                 os._exit(0)
90             except EnvironmentError, ex:
91                 (result, errmsg) = (ex.errno, ex.strerror)
92             except Exception, ex:
93                 (result, errmsg) = (255, str(ex))
94             os.write(sendsock, errmsg)
95             os._exit(result)
96
97         # parent process
98
99         # XXX - need this since a lambda can't raise an exception
100         def __throw(ex):
101             raise ex
102
103         os.close(sendsock)
104         throw = lambda : __throw(Exception(errmsg))
105         while True:
106             try:
107                 (pid, status) = os.waitpid(child_pid, 0)
108                 if os.WIFEXITED(status):
109                     result = os.WEXITSTATUS(status)
110                     if result != 255:
111                         errmsg = os.strerror(result)
112                         throw = lambda : __throw(IOError(result, errmsg))
113                     else:
114                         errmsg = "unexpected exception in child"
115                 else:
116                     result = -1
117                     errmsg = "child killed"
118                 break
119             except OSError, ex:
120                 if ex.errno != errno.EINTR:
121                     os.close(recvsock)
122                     raise ex
123         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
124         try:
125             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
126         except OSError, ex:
127             if ex.errno != errno.EAGAIN:
128                 throw = lambda : __throw(ex)
129             fd = 0
130         os.close(recvsock)
131         if not fd:
132             throw()
133
134         return os.fdopen(fd)
135
136     def enter(self):
137
138         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
139         self.__do_chroot()
140         vserverimpl.chcontext(self.ctx, self.remove_caps)
141         print >>state_file, "S_CONTEXT=%d" % self.ctx
142         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
143         state_file.close()
144
145     def start(self):
146
147         child_pid = os.fork()
148         if child_pid == 0:
149             # child process
150             try:
151                 # get a new session
152                 os.setsid()
153
154                 # enter vserver context
155                 self.enter()
156
157                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
158                 os.close(0)
159                 os.close(1)
160                 os.open("/dev/null", os.O_RDONLY)
161                 os.open("/var/log/boot.log",
162                         os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
163                 os.dup2(1, 2)
164
165                 # write same output that vserver script does
166                 os.write(1, "Starting the virtual server %s\n" % self.name)
167                 os.write(1, "Server %s is not running\n" % self.name)
168
169                 # execute each init script in turn
170                 # XXX - we don't support all the possible scripts
171                 for cmd in self.INITSCRIPTS:
172                     os.spawnl(os.P_WAIT, *cmd)
173             except Exception, ex:
174                 traceback.print_exc()
175             os._exit(0)
176
177         # parent process
178         return child_pid