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