Modified set_dlimit to print a warning message when trying to set a
[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 mountimpl
12 import linuxcaps
13 import passfdimpl
14 import utmp
15 import vserverimpl, vduimpl
16
17 from util_vserver_vars import *
18
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 |
24             linuxcaps.CAP_KILL |
25             linuxcaps.CAP_SETGID |
26             linuxcaps.CAP_SETUID |
27             linuxcaps.CAP_SETPCAP |
28             linuxcaps.CAP_SYS_TTY_CONFIG |
29             linuxcaps.CAP_LEASE |
30             linuxcaps.CAP_SYS_CHROOT |
31             linuxcaps.CAP_SYS_PTRACE)
32
33 #
34 # these are the flags taken from the kernel linux/vserver/legacy.h
35 #
36 FLAGS_LOCK = 1
37 FLAGS_SCHED = 2  # XXX - defined in util-vserver/src/chcontext.c
38 FLAGS_NPROC = 4
39 FLAGS_PRIVATE = 8
40 FLAGS_INIT = 16
41 FLAGS_HIDEINFO = 32
42 FLAGS_ULIMIT = 64
43 FLAGS_NAMESPACE = 128
44
45
46               
47 class VServer:
48
49     INITSCRIPTS = [('/etc/rc.vinit', 'start'),
50                    ('/etc/rc.d/rc', '%(runlevel)d')]
51
52     def __init__(self, name):
53
54         self.name = name
55         self.config = self.__read_config_file("/etc/vservers.conf")
56         self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
57                                                    self.name))
58         self.flags = 0
59         flags = self.config["S_FLAGS"].split(" ")
60         if "lock" in flags:
61             self.flags |= FLAGS_LOCK
62         if "nproc" in flags:
63             self.flags |= FLAGS_NPROC
64         self.remove_caps = ~CAP_SAFE
65         self.ctx = int(self.config["S_CONTEXT"])
66
67     config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
68
69     def __read_config_file(self, filename):
70
71         f = open(filename, "r")
72         data = f.read()
73         f.close()
74         config = {}
75         for m in self.config_var_re.finditer(data):
76             (key, val) = m.groups()
77             config[key] = val.strip('"')
78         return config
79
80     def __do_chroot(self):
81
82         return os.chroot("%s/%s" % (VROOTDIR, self.name))
83
84     def set_dlimit(self, blocktotal):
85         path = "%s/%s" % (VROOTDIR, self.name)
86         inodes, blockcount, size = vduimpl.vdu(path)
87         blockcount = blockcount >> 1
88
89         if blocktotal > blockcount:
90             vserverimpl.setdlimit(path, self.ctx, blockcount>>1, \
91                                   blocktotal, inodes, -1, 2)
92         else:
93             # should raise some error value
94             print "block limit (%d) ignored for vserver %s" %(blocktotal,self.name)
95
96     def get_dlimit(self):
97         path = "%s/%s" % (VROOTDIR, self.name)
98         try:
99             blocksused, blocktotal, inodesused, inodestotal, reserved = \
100                         vserverimpl.getdlimit(path,self.ctx)
101         except OSError, ex:
102             if ex.errno == 3:
103                 # get here if no vserver disk limit has been set for xid
104                 # set blockused to -1 to indicate no limit
105                 blocktotal = -1
106
107         return blocktotal
108
109     def open(self, filename, mode = "r", bufsize = -1):
110
111         (sendsock, recvsock) = passfdimpl.socketpair()
112         child_pid = os.fork()
113         if child_pid == 0:
114             try:
115                 # child process
116                 self.__do_chroot()
117                 f = open(filename, mode)
118                 passfdimpl.sendmsg(f.fileno(), sendsock)
119                 os._exit(0)
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)
125             os._exit(result)
126
127         # parent process
128
129         # XXX - need this since a lambda can't raise an exception
130         def __throw(ex):
131             raise ex
132
133         os.close(sendsock)
134         throw = lambda : __throw(Exception(errmsg))
135         while True:
136             try:
137                 (pid, status) = os.waitpid(child_pid, 0)
138                 if os.WIFEXITED(status):
139                     result = os.WEXITSTATUS(status)
140                     if result != 255:
141                         errmsg = os.strerror(result)
142                         throw = lambda : __throw(IOError(result, errmsg))
143                     else:
144                         errmsg = "unexpected exception in child"
145                 else:
146                     result = -1
147                     errmsg = "child killed"
148                 break
149             except OSError, ex:
150                 if ex.errno != errno.EINTR:
151                     os.close(recvsock)
152                     raise ex
153         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
154         try:
155             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
156         except OSError, ex:
157             if ex.errno != errno.EAGAIN:
158                 throw = lambda : __throw(ex)
159             fd = 0
160         os.close(recvsock)
161         if not fd:
162             throw()
163
164         return os.fdopen(fd, mode, bufsize)
165
166     def __do_chcontext(self, state_file = None):
167
168         vserverimpl.chcontext(self.ctx, self.remove_caps)
169         if not state_file:
170             return
171         print >>state_file, "S_CONTEXT=%d" % self.ctx
172         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
173         state_file.close()
174
175     def __prep(self, runlevel, log):
176
177         """ Perform all the crap that the vserver script does before
178         actually executing the startup scripts. """
179
180         # remove /var/run and /var/lock/subsys files
181         # but don't remove utmp from the top-level /var/run
182         RUNDIR = "/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)),
187                            lambda fs: fs)),
188                          list(os.walk(RUNDIR)),
189                          ([], filter_fn))[0]
190         garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
191                                               os.listdir(LOCKDIR)))
192         for f in garbage:
193             os.unlink(f)
194
195         # set the initial runlevel
196         f = open(RUNDIR + "/utmp", "w")
197         utmp.set_runlevel(f, runlevel)
198         f.close()
199
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")
204
205     def __do_mount(self, *mount_args):
206
207         try:
208             mountimpl.mount(*mount_args)
209         except OSError, ex:
210             if ex.errno == errno.EBUSY:
211                 # assume already mounted
212                 return
213             raise ex
214
215     def enter(self):
216
217         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
218         self.__do_chroot()
219         self.__do_chcontext(state_file)
220
221     def start(self, wait, runlevel = 3):
222
223         child_pid = os.fork()
224         if child_pid == 0:
225             # child process
226             try:
227                 # get a new session
228                 os.setsid()
229
230                 # open state file to record vserver info
231                 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
232
233                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
234                 os.close(0)
235                 os.close(1)
236                 os.open("/dev/null", os.O_RDONLY)
237                 self.__do_chroot()
238                 log = open("/var/log/boot.log", "w", 0)
239                 os.dup2(1, 2)
240
241                 print >>log, ("%s: starting the virtual server %s" %
242                               (time.asctime(time.gmtime()), self.name))
243
244                 # perform pre-init cleanup
245                 self.__prep(runlevel, log)
246
247                 # execute each init script in turn
248                 # XXX - we don't support all scripts that vserver script does
249                 cmd_pid = 0
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):
254                         try:
255                             os.waitpid(cmd_pid, 0)
256                         except:
257                             print >>log, "error waiting for %s:" % cmd_pid
258                             traceback.print_exc()
259
260                     # end of list
261                     if cmd == None:
262                         os._exit(0)
263
264                     # fork and exec next command
265                     cmd_pid = os.fork()
266                     if cmd_pid == 0:
267                         try:
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,
272                                                       cmd[1:])
273                             print >>log, "executing '%s'" % " ".join(cmd_args)
274                             os.execl(cmd[0], *cmd_args)
275                         except:
276                             traceback.print_exc()
277                             os._exit(1)
278                     else:
279                         # don't want to write state_file multiple times
280                         state_file = None
281
282             # we get here due to an exception in the top-level child process
283             except Exception, ex:
284                 traceback.print_exc()
285             os._exit(0)
286
287         # parent process
288         return child_pid