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