1 # Copyright 2005 Princeton University
16 from util_vserver_vars import *
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 |
24 linuxcaps.CAP_SETGID |
25 linuxcaps.CAP_SETUID |
26 linuxcaps.CAP_SETPCAP |
27 linuxcaps.CAP_SYS_TTY_CONFIG |
29 linuxcaps.CAP_SYS_CHROOT |
30 linuxcaps.CAP_SYS_PTRACE)
33 # these are the flags taken from the kernel linux/vserver/legacy.h
36 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
48 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
49 ('/etc/rc.d/rc', '%(runlevel)d')]
51 def __init__(self, name):
54 self.config = self.__read_config_file("/etc/vservers.conf")
55 self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
58 flags = self.config["S_FLAGS"].split(" ")
60 self.flags |= FLAGS_LOCK
62 self.flags |= FLAGS_NPROC
63 self.remove_caps = ~CAP_SAFE
64 self.ctx = int(self.config["S_CONTEXT"])
66 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
68 def __read_config_file(self, filename):
70 f = open(filename, "r")
74 for m in self.config_var_re.finditer(data):
75 (key, val) = m.groups()
76 config[key] = val.strip('"')
79 def __do_chroot(self):
81 return os.chroot("%s/%s" % (VROOTDIR, self.name))
83 def open(self, filename, mode = "r", bufsize = -1):
85 (sendsock, recvsock) = passfdimpl.socketpair()
91 f = open(filename, mode)
92 passfdimpl.sendmsg(f.fileno(), sendsock)
94 except EnvironmentError, ex:
95 (result, errmsg) = (ex.errno, ex.strerror)
97 (result, errmsg) = (255, str(ex))
98 os.write(sendsock, errmsg)
103 # XXX - need this since a lambda can't raise an exception
108 throw = lambda : __throw(Exception(errmsg))
111 (pid, status) = os.waitpid(child_pid, 0)
112 if os.WIFEXITED(status):
113 result = os.WEXITSTATUS(status)
115 errmsg = os.strerror(result)
116 throw = lambda : __throw(IOError(result, errmsg))
118 errmsg = "unexpected exception in child"
121 errmsg = "child killed"
124 if ex.errno != errno.EINTR:
127 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
129 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
131 if ex.errno != errno.EAGAIN:
132 throw = lambda : __throw(ex)
138 return os.fdopen(fd, mode, bufsize)
140 def __do_chcontext(self, state_file = None):
142 vserverimpl.chcontext(self.ctx, self.remove_caps)
145 print >>state_file, "S_CONTEXT=%d" % self.ctx
146 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
149 def __prep(self, runlevel, log):
151 """ Perform all the crap that the vserver script does before
152 actually executing the startup scripts. """
154 # remove /var/run and /var/lock/subsys files
155 # but don't remove utmp from the top-level /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)),
162 list(os.walk(RUNDIR)),
164 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
165 os.listdir(LOCKDIR)))
167 print >>log, "removing " + f
170 # set the initial runlevel
172 # mount /proc and /dev/pts
176 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
178 self.__do_chcontext(state_file)
180 def start(self, runlevel = 3):
182 child_pid = os.fork()
189 # open state file to record vserver info
190 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
192 # use /dev/null for stdin, /var/log/boot.log for stdout/err
195 os.open("/dev/null", os.O_RDONLY)
197 log = open("/var/log/boot.log", "w", 0)
200 print >>log, ("%s: starting the virtual server %s" %
201 (time.asctime(time.gmtime()), self.name))
203 # perform pre-init cleanup
204 self.__prep(runlevel, log)
206 # execute each init script in turn
207 # XXX - we don't support all scripts that vserver script does
209 for cmd in self.INITSCRIPTS + [None]:
210 # don't bother waiting for last command to terminate
214 # wait for previous command to terminate
217 os.waitpid(cmd_pid, 0)
219 print >>log, "error waiting for %s:" % cmd_pid
220 traceback.print_exc()
222 # fork and exec next command
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,
231 print >>log, "executing '%s'" % " ".join(cmd_args)
232 os.execl(cmd[0], *cmd_args)
234 traceback.print_exc()
237 # don't want to write state_file multiple times
240 # we get here due to an exception in the top-level child process
241 except Exception, ex:
242 traceback.print_exc()