Closer approximation to how the vserver script starts a vserver; still
[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 sys
8 import time
9 import traceback
10
11 #import mount
12 import linuxcaps
13 import passfdimpl
14 import vserverimpl
15
16 from util_vserver_vars import *
17
18 CAP_SAFE = (linuxcaps.CAP_CHOWN |
19             linuxcaps.CAP_DAC_OVERRIDE |
20             linuxcaps.CAP_DAC_READ_SEARCH |
21             linuxcaps.CAP_FOWNER |
22             linuxcaps.CAP_FSETID |
23             linuxcaps.CAP_KILL |
24             linuxcaps.CAP_SETGID |
25             linuxcaps.CAP_SETUID |
26             linuxcaps.CAP_SETPCAP |
27             linuxcaps.CAP_SYS_TTY_CONFIG |
28             linuxcaps.CAP_LEASE |
29             linuxcaps.CAP_SYS_CHROOT |
30             linuxcaps.CAP_SYS_PTRACE)
31
32 #
33 # these are the flags taken from the kernel linux/vserver/legacy.h
34 #
35 FLAGS_LOCK = 1
36 FLAGS_SCHED = 2  # XXX - defined in util-vserver/src/chcontext.c
37 FLAGS_NPROC = 4
38 FLAGS_PRIVATE = 8
39 FLAGS_INIT = 16
40 FLAGS_HIDEINFO = 32
41 FLAGS_ULIMIT = 64
42 FLAGS_NAMESPACE = 128
43
44
45               
46 class VServer:
47
48     INITSCRIPTS = [('/etc/rc.vinit', 'start'),
49                    ('/etc/rc.d/rc', '%(runlevel)d')]
50
51     def __init__(self, name):
52
53         self.name = name
54         self.config = self.__read_config_file("/etc/vservers.conf")
55         self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
56                                                    self.name))
57         self.flags = 0
58         flags = self.config["S_FLAGS"].split(" ")
59         if "lock" in flags:
60             self.flags |= FLAGS_LOCK
61         if "nproc" in flags:
62             self.flags |= FLAGS_NPROC
63         self.remove_caps = ~CAP_SAFE
64         self.ctx = int(self.config["S_CONTEXT"])
65
66     config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
67
68     def __read_config_file(self, filename):
69
70         f = open(filename, "r")
71         data = f.read()
72         f.close()
73         config = {}
74         for m in self.config_var_re.finditer(data):
75             (key, val) = m.groups()
76             config[key] = val.strip('"')
77         return config
78
79     def __do_chroot(self):
80
81         return os.chroot("%s/%s" % (VROOTDIR, self.name))
82
83     def open(self, filename, mode = "r", bufsize = -1):
84
85         (sendsock, recvsock) = passfdimpl.socketpair()
86         child_pid = os.fork()
87         if child_pid == 0:
88             try:
89                 # child process
90                 self.__do_chroot()
91                 f = open(filename, mode)
92                 passfdimpl.sendmsg(f.fileno(), sendsock)
93                 os._exit(0)
94             except EnvironmentError, ex:
95                 (result, errmsg) = (ex.errno, ex.strerror)
96             except Exception, ex:
97                 (result, errmsg) = (255, str(ex))
98             os.write(sendsock, errmsg)
99             os._exit(result)
100
101         # parent process
102
103         # XXX - need this since a lambda can't raise an exception
104         def __throw(ex):
105             raise ex
106
107         os.close(sendsock)
108         throw = lambda : __throw(Exception(errmsg))
109         while True:
110             try:
111                 (pid, status) = os.waitpid(child_pid, 0)
112                 if os.WIFEXITED(status):
113                     result = os.WEXITSTATUS(status)
114                     if result != 255:
115                         errmsg = os.strerror(result)
116                         throw = lambda : __throw(IOError(result, errmsg))
117                     else:
118                         errmsg = "unexpected exception in child"
119                 else:
120                     result = -1
121                     errmsg = "child killed"
122                 break
123             except OSError, ex:
124                 if ex.errno != errno.EINTR:
125                     os.close(recvsock)
126                     raise ex
127         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
128         try:
129             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
130         except OSError, ex:
131             if ex.errno != errno.EAGAIN:
132                 throw = lambda : __throw(ex)
133             fd = 0
134         os.close(recvsock)
135         if not fd:
136             throw()
137
138         return os.fdopen(fd, mode, bufsize)
139
140     def __do_chcontext(self, state_file = None):
141
142         vserverimpl.chcontext(self.ctx, self.remove_caps)
143         if not state_file:
144             return
145         print >>state_file, "S_CONTEXT=%d" % self.ctx
146         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
147         state_file.close()
148
149     def __prep(self, runlevel, log):
150
151         """ Perform all the crap that the vserver script does before
152         actually executing the startup scripts. """
153
154         # remove /var/run and /var/lock/subsys files
155         # but don't remove utmp from the top-level /var/run
156         RUNDIR = "/var/run"
157         LOCKDIR = "/var/lock/subsys"
158         filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
159         garbage = reduce((lambda (out, ff), (dir, subdirs, files):
160                           (out + map((dir + "/").__add__, ff(files)),
161                            lambda fs: fs)),
162                          list(os.walk(RUNDIR)),
163                          ([], filter_fn))[0]
164         garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
165                                               os.listdir(LOCKDIR)))
166         for f in garbage:
167             print >>log, "removing " + f
168             os.unlink(f)
169
170         # set the initial runlevel
171
172         # mount /proc and /dev/pts
173
174     def enter(self):
175
176         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
177         self.__do_chroot()
178         self.__do_chcontext(state_file)
179
180     def start(self, runlevel = 3):
181
182         child_pid = os.fork()
183         if child_pid == 0:
184             # child process
185             try:
186                 # get a new session
187                 os.setsid()
188
189                 # open state file to record vserver info
190                 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
191
192                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
193                 os.close(0)
194                 os.close(1)
195                 os.open("/dev/null", os.O_RDONLY)
196                 self.__do_chroot()
197                 log = open("/var/log/boot.log", "w", 0)
198                 os.dup2(1, 2)
199
200                 print >>log, ("%s: starting the virtual server %s" %
201                               (time.asctime(time.gmtime()), self.name))
202
203                 # perform pre-init cleanup
204                 self.__prep(runlevel, log)
205
206                 # execute each init script in turn
207                 # XXX - we don't support all scripts that vserver script does
208                 cmd_pid = 0
209                 for cmd in self.INITSCRIPTS + [None]:
210                     # don't bother waiting for last command to terminate
211                     if cmd == None:
212                         os._exit(0)
213
214                     # wait for previous command to terminate
215                     if cmd_pid:
216                         try:
217                             os.waitpid(cmd_pid, 0)
218                         except:
219                             print >>log, "error waiting for %s:" % cmd_pid
220                             traceback.print_exc()
221
222                     # fork and exec next command
223                     cmd_pid = os.fork()
224                     if cmd_pid == 0:
225                         try:
226                             # enter vserver context
227                             self.__do_chcontext(state_file)
228                             arg_subst = { 'runlevel': runlevel }
229                             cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
230                                                       cmd[1:])
231                             print >>log, "executing '%s'" % " ".join(cmd_args)
232                             os.execl(cmd[0], *cmd_args)
233                         except:
234                             traceback.print_exc()
235                             os._exit(1)
236                     else:
237                         # don't want to write state_file multiple times
238                         state_file = None
239
240             # we get here due to an exception in the top-level child process
241             except Exception, ex:
242                 traceback.print_exc()
243             os._exit(0)
244
245         # parent process
246         return child_pid