1 # Copyright 2005 Princeton University
17 from util_vserver_vars import *
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 |
25 linuxcaps.CAP_SETGID |
26 linuxcaps.CAP_SETUID |
27 linuxcaps.CAP_SETPCAP |
28 linuxcaps.CAP_SYS_TTY_CONFIG |
30 linuxcaps.CAP_SYS_CHROOT |
31 linuxcaps.CAP_SYS_PTRACE)
34 # these are the flags taken from the kernel linux/vserver/legacy.h
37 FLAGS_SCHED = 2 # XXX - defined in util-vserver/src/chcontext.c
49 INITSCRIPTS = [('/etc/rc.vinit', 'start'),
50 ('/etc/rc.d/rc', '%(runlevel)d')]
52 def __init__(self, name):
55 self.config = self.__read_config_file("/etc/vservers.conf")
56 self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
59 flags = self.config["S_FLAGS"].split(" ")
61 self.flags |= FLAGS_LOCK
63 self.flags |= FLAGS_NPROC
64 self.remove_caps = ~CAP_SAFE
65 self.ctx = int(self.config["S_CONTEXT"])
67 config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
69 def __read_config_file(self, filename):
71 f = open(filename, "r")
75 for m in self.config_var_re.finditer(data):
76 (key, val) = m.groups()
77 config[key] = val.strip('"')
80 def __do_chroot(self):
82 return os.chroot("%s/%s" % (VROOTDIR, self.name))
84 def open(self, filename, mode = "r", bufsize = -1):
86 (sendsock, recvsock) = passfdimpl.socketpair()
92 f = open(filename, mode)
93 passfdimpl.sendmsg(f.fileno(), sendsock)
95 except EnvironmentError, ex:
96 (result, errmsg) = (ex.errno, ex.strerror)
98 (result, errmsg) = (255, str(ex))
99 os.write(sendsock, errmsg)
104 # XXX - need this since a lambda can't raise an exception
109 throw = lambda : __throw(Exception(errmsg))
112 (pid, status) = os.waitpid(child_pid, 0)
113 if os.WIFEXITED(status):
114 result = os.WEXITSTATUS(status)
116 errmsg = os.strerror(result)
117 throw = lambda : __throw(IOError(result, errmsg))
119 errmsg = "unexpected exception in child"
122 errmsg = "child killed"
125 if ex.errno != errno.EINTR:
128 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
130 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
132 if ex.errno != errno.EAGAIN:
133 throw = lambda : __throw(ex)
139 return os.fdopen(fd, mode, bufsize)
141 def __do_chcontext(self, state_file = None):
143 vserverimpl.chcontext(self.ctx, self.remove_caps)
146 print >>state_file, "S_CONTEXT=%d" % self.ctx
147 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
150 def __prep(self, runlevel, log):
152 """ Perform all the crap that the vserver script does before
153 actually executing the startup scripts. """
155 # remove /var/run and /var/lock/subsys files
156 # but don't remove utmp from the top-level /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)),
163 list(os.walk(RUNDIR)),
165 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
166 os.listdir(LOCKDIR)))
170 # set the initial runlevel
171 f = open(RUNDIR + "/utmp", "w")
172 utmp.set_runlevel(f, runlevel)
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")
180 def __do_mount(self, *mount_args):
183 mountimpl.mount(*mount_args)
185 if ex.errno == errno.EBUSY:
186 # assume already mounted
192 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
194 self.__do_chcontext(state_file)
196 def start(self, runlevel = 3):
198 child_pid = os.fork()
205 # open state file to record vserver info
206 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
208 # use /dev/null for stdin, /var/log/boot.log for stdout/err
211 os.open("/dev/null", os.O_RDONLY)
213 log = open("/var/log/boot.log", "w", 0)
216 print >>log, ("%s: starting the virtual server %s" %
217 (time.asctime(time.gmtime()), self.name))
219 # perform pre-init cleanup
220 self.__prep(runlevel, log)
222 # execute each init script in turn
223 # XXX - we don't support all scripts that vserver script does
225 for cmd in self.INITSCRIPTS + [None]:
226 # don't bother waiting for last command to terminate
230 # wait for previous command to terminate
233 os.waitpid(cmd_pid, 0)
235 print >>log, "error waiting for %s:" % cmd_pid
236 traceback.print_exc()
238 # fork and exec next command
242 # enter vserver context
243 self.__do_chcontext(state_file)
244 arg_subst = { 'runlevel': runlevel }
245 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
247 print >>log, "executing '%s'" % " ".join(cmd_args)
248 os.execl(cmd[0], *cmd_args)
250 traceback.print_exc()
253 # don't want to write state_file multiple times
256 # we get here due to an exception in the top-level child process
257 except Exception, ex:
258 traceback.print_exc()