1 # Copyright 2005 Princeton University
15 import vserverimpl, vduimpl
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 set_dlimit(self, blocktotal):
85 path = "%s/%s" % (VROOTDIR, self.name)
86 inodes, blockcount, size = vduimpl.vdu(path)
87 vserverimpl.setdlimit(path, self.ctx, blockcount>>1, blocktotal, inodes, -1, 2)
90 path = "%s/%s" % (VROOTDIR, self.name)
92 blocksused, blocktotal, inodesused, inodestotal, reserved = \
93 vserverimpl.getdlimit(path,self.ctx)
96 # get here if no vserver disk limit has been set for xid
97 # set blockused to -1 to indicate no limit
102 def open(self, filename, mode = "r", bufsize = -1):
104 (sendsock, recvsock) = passfdimpl.socketpair()
105 child_pid = os.fork()
110 f = open(filename, mode)
111 passfdimpl.sendmsg(f.fileno(), sendsock)
113 except EnvironmentError, ex:
114 (result, errmsg) = (ex.errno, ex.strerror)
115 except Exception, ex:
116 (result, errmsg) = (255, str(ex))
117 os.write(sendsock, errmsg)
122 # XXX - need this since a lambda can't raise an exception
127 throw = lambda : __throw(Exception(errmsg))
130 (pid, status) = os.waitpid(child_pid, 0)
131 if os.WIFEXITED(status):
132 result = os.WEXITSTATUS(status)
134 errmsg = os.strerror(result)
135 throw = lambda : __throw(IOError(result, errmsg))
137 errmsg = "unexpected exception in child"
140 errmsg = "child killed"
143 if ex.errno != errno.EINTR:
146 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
148 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
150 if ex.errno != errno.EAGAIN:
151 throw = lambda : __throw(ex)
157 return os.fdopen(fd, mode, bufsize)
159 def __do_chcontext(self, state_file = None):
161 vserverimpl.chcontext(self.ctx, self.remove_caps)
164 print >>state_file, "S_CONTEXT=%d" % self.ctx
165 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
168 def __prep(self, runlevel, log):
170 """ Perform all the crap that the vserver script does before
171 actually executing the startup scripts. """
173 # remove /var/run and /var/lock/subsys files
174 # but don't remove utmp from the top-level /var/run
176 LOCKDIR = "/var/lock/subsys"
177 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
178 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
179 (out + map((dir + "/").__add__, ff(files)),
181 list(os.walk(RUNDIR)),
183 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
184 os.listdir(LOCKDIR)))
188 # set the initial runlevel
189 f = open(RUNDIR + "/utmp", "w")
190 utmp.set_runlevel(f, runlevel)
193 # mount /proc and /dev/pts
194 self.__do_mount("none", "/proc", "proc")
195 # XXX - magic mount options
196 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
198 def __do_mount(self, *mount_args):
201 mountimpl.mount(*mount_args)
203 if ex.errno == errno.EBUSY:
204 # assume already mounted
210 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
212 self.__do_chcontext(state_file)
214 def start(self, wait, runlevel = 3):
216 child_pid = os.fork()
223 # open state file to record vserver info
224 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
226 # use /dev/null for stdin, /var/log/boot.log for stdout/err
229 os.open("/dev/null", os.O_RDONLY)
231 log = open("/var/log/boot.log", "w", 0)
234 print >>log, ("%s: starting the virtual server %s" %
235 (time.asctime(time.gmtime()), self.name))
237 # perform pre-init cleanup
238 self.__prep(runlevel, log)
240 # execute each init script in turn
241 # XXX - we don't support all scripts that vserver script does
243 for cmd in self.INITSCRIPTS + [None]:
244 # wait for previous command to terminate, unless it
245 # is the last one and the caller has specified to wait
246 if cmd_pid and (cmd != None or wait):
248 os.waitpid(cmd_pid, 0)
250 print >>log, "error waiting for %s:" % cmd_pid
251 traceback.print_exc()
257 # fork and exec next command
261 # enter vserver context
262 self.__do_chcontext(state_file)
263 arg_subst = { 'runlevel': runlevel }
264 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
266 print >>log, "executing '%s'" % " ".join(cmd_args)
267 os.execl(cmd[0], *cmd_args)
269 traceback.print_exc()
272 # don't want to write state_file multiple times
275 # we get here due to an exception in the top-level child process
276 except Exception, ex:
277 traceback.print_exc()