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 blockcount = blockcount >> 1
89 if blocktotal > blockcount:
90 vserverimpl.setdlimit(path, self.ctx, blockcount>>1, \
91 blocktotal, inodes, -1, 2)
93 # should raise some error value
94 print "block limit (%d) ignored for vserver %s" %(blocktotal,self.name)
97 path = "%s/%s" % (VROOTDIR, self.name)
99 blocksused, blocktotal, inodesused, inodestotal, reserved = \
100 vserverimpl.getdlimit(path,self.ctx)
103 # get here if no vserver disk limit has been set for xid
104 # set blockused to -1 to indicate no limit
109 def open(self, filename, mode = "r", bufsize = -1):
111 (sendsock, recvsock) = passfdimpl.socketpair()
112 child_pid = os.fork()
117 f = open(filename, mode)
118 passfdimpl.sendmsg(f.fileno(), sendsock)
120 except EnvironmentError, ex:
121 (result, errmsg) = (ex.errno, ex.strerror)
122 except Exception, ex:
123 (result, errmsg) = (255, str(ex))
124 os.write(sendsock, errmsg)
129 # XXX - need this since a lambda can't raise an exception
134 throw = lambda : __throw(Exception(errmsg))
137 (pid, status) = os.waitpid(child_pid, 0)
138 if os.WIFEXITED(status):
139 result = os.WEXITSTATUS(status)
141 errmsg = os.strerror(result)
142 throw = lambda : __throw(IOError(result, errmsg))
144 errmsg = "unexpected exception in child"
147 errmsg = "child killed"
150 if ex.errno != errno.EINTR:
153 fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
155 (fd, errmsg) = passfdimpl.recvmsg(recvsock)
157 if ex.errno != errno.EAGAIN:
158 throw = lambda : __throw(ex)
164 return os.fdopen(fd, mode, bufsize)
166 def __do_chcontext(self, state_file = None):
168 vserverimpl.chcontext(self.ctx, self.remove_caps)
171 print >>state_file, "S_CONTEXT=%d" % self.ctx
172 print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
175 def __prep(self, runlevel, log):
177 """ Perform all the crap that the vserver script does before
178 actually executing the startup scripts. """
180 # remove /var/run and /var/lock/subsys files
181 # but don't remove utmp from the top-level /var/run
183 LOCKDIR = "/var/lock/subsys"
184 filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
185 garbage = reduce((lambda (out, ff), (dir, subdirs, files):
186 (out + map((dir + "/").__add__, ff(files)),
188 list(os.walk(RUNDIR)),
190 garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
191 os.listdir(LOCKDIR)))
195 # set the initial runlevel
196 f = open(RUNDIR + "/utmp", "w")
197 utmp.set_runlevel(f, runlevel)
200 # mount /proc and /dev/pts
201 self.__do_mount("none", "/proc", "proc")
202 # XXX - magic mount options
203 self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
205 def __do_mount(self, *mount_args):
208 mountimpl.mount(*mount_args)
210 if ex.errno == errno.EBUSY:
211 # assume already mounted
217 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
219 self.__do_chcontext(state_file)
221 def start(self, wait, runlevel = 3):
223 child_pid = os.fork()
230 # open state file to record vserver info
231 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
233 # use /dev/null for stdin, /var/log/boot.log for stdout/err
236 os.open("/dev/null", os.O_RDONLY)
238 log = open("/var/log/boot.log", "w", 0)
241 print >>log, ("%s: starting the virtual server %s" %
242 (time.asctime(time.gmtime()), self.name))
244 # perform pre-init cleanup
245 self.__prep(runlevel, log)
247 # execute each init script in turn
248 # XXX - we don't support all scripts that vserver script does
250 for cmd in self.INITSCRIPTS + [None]:
251 # wait for previous command to terminate, unless it
252 # is the last one and the caller has specified to wait
253 if cmd_pid and (cmd != None or wait):
255 os.waitpid(cmd_pid, 0)
257 print >>log, "error waiting for %s:" % cmd_pid
258 traceback.print_exc()
264 # fork and exec next command
268 # enter vserver context
269 self.__do_chcontext(state_file)
270 arg_subst = { 'runlevel': runlevel }
271 cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
273 print >>log, "executing '%s'" % " ".join(cmd_args)
274 os.execl(cmd[0], *cmd_args)
276 traceback.print_exc()
279 # don't want to write state_file multiple times
282 # we get here due to an exception in the top-level child process
283 except Exception, ex:
284 traceback.print_exc()