VROOTDIR changed to __DEFAULT_VSERVERDIR
[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 import cpulimit, bwlimit
17
18 from util_vserver_vars import *
19
20 CAP_SAFE = (linuxcaps.CAP_CHOWN |
21             linuxcaps.CAP_DAC_OVERRIDE |
22             linuxcaps.CAP_DAC_READ_SEARCH |
23             linuxcaps.CAP_FOWNER |
24             linuxcaps.CAP_FSETID |
25             linuxcaps.CAP_KILL |
26             linuxcaps.CAP_SETGID |
27             linuxcaps.CAP_SETUID |
28             linuxcaps.CAP_SETPCAP |
29             linuxcaps.CAP_SYS_TTY_CONFIG |
30             linuxcaps.CAP_LEASE |
31             linuxcaps.CAP_SYS_CHROOT |
32             linuxcaps.CAP_SYS_PTRACE)
33
34 #
35 # these are the flags taken from the kernel linux/vserver/legacy.h
36 #
37 FLAGS_LOCK = 1
38 FLAGS_SCHED = 2  # XXX - defined in util-vserver/src/chcontext.c
39 FLAGS_NPROC = 4
40 FLAGS_PRIVATE = 8
41 FLAGS_INIT = 16
42 FLAGS_HIDEINFO = 32
43 FLAGS_ULIMIT = 64
44 FLAGS_NAMESPACE = 128
45
46 # default values for new vserver scheduler
47 SCHED_TOKENS_MIN = 50
48 SCHED_TOKENS_MAX = 100
49
50               
51 class VServer:
52
53     INITSCRIPTS = [('/etc/rc.vinit', 'start'),
54                    ('/etc/rc.d/rc', '%(runlevel)d')]
55
56     def __init__(self, name):
57
58         self.name = name
59         self.config = self.__read_config_file("/etc/vservers.conf")
60         self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
61                                                    self.name))
62         self.flags = 0
63         flags = self.config["S_FLAGS"].split(" ")
64         if "lock" in flags:
65             self.flags |= FLAGS_LOCK
66         if "nproc" in flags:
67             self.flags |= FLAGS_NPROC
68         self.remove_caps = ~CAP_SAFE
69         self.ctx = int(self.config["S_CONTEXT"])
70
71     config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
72
73     def __read_config_file(self, filename):
74
75         f = open(filename, "r")
76         data = f.read()
77         f.close()
78         config = {}
79         for m in self.config_var_re.finditer(data):
80             (key, val) = m.groups()
81             config[key] = val.strip('"')
82         return config
83
84     def __do_chroot(self):
85
86         return os.chroot("%s/%s" % (__DEFAULT_VSERVERDIR, self.name))
87
88     def set_disklimit(self, blocktotal):
89         path = "%s/%s" % (__DEFAULT_VSERVERDIR, self.name)
90         inodes, blockcount, size = vduimpl.vdu(path)
91         blockcount = blockcount >> 1
92
93         if blocktotal > blockcount:
94             vserverimpl.setdlimit(path, self.ctx, blockcount>>1, \
95                                   blocktotal, inodes, -1, 2)
96         else:
97             # should raise some error value
98             print "block limit (%d) ignored for vserver %s" %(blocktotal,self.name)
99
100     def get_disklimit(self):
101         path = "%s/%s" % (__DEFAULT_VSERVERDIR, self.name)
102         try:
103             blocksused, blocktotal, inodesused, inodestotal, reserved = \
104                         vserverimpl.getdlimit(path,self.ctx)
105         except OSError, ex:
106             if ex.errno == 3:
107                 # get here if no vserver disk limit has been set for xid
108                 # set blockused to -1 to indicate no limit
109                 blocktotal = -1
110
111         return blocktotal
112
113     def set_sched(self, shares, besteffort = True):
114         # for the old CKRM scheduler
115         if cpulimit.checkckrm() is True:
116             cpulimit.cpuinit()
117             cpulimit.vs2ckrm_on(self.name)
118             try:
119                 cpulimit.cpulimit(self.name,shares)
120             except OSError, ex:
121                 if ex.errno == 22:
122                     print "invalid shares argument"
123                     # should re-raise exception?!
124
125         # for the new vserver scheduler
126         else:
127             global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX
128             tokensmin = SCHED_TOKENS_MIN
129             tokensmax = SCHED_TOKENS_MAX
130
131             if besteffort is True:
132                 # magic "interval" value for Andy's scheduler to denote besteffort
133                 interval = 1000
134                 fillrate = shares
135             else:
136                 interval = 1001
137                 fillrate = shares
138
139             try:
140                 vserverimpl.setsched(self.ctx,fillrate,interval,tokensmin,tokensmax)
141             except OSError, ex:
142                 if ex.errno == 22:
143                     print "kernel does not support vserver scheduler"
144                 else:
145                     raise ex
146
147     def get_sched(self):
148         # have no way of querying scheduler right now on a per vserver basis
149         return (-1, False)
150
151     def set_memlimit(self, limit):
152         ret = vserverimpl.setrlimit(self.ctx,5,limit)
153         return ret
154
155     def get_memlimit(self):
156         ret = vserverimpl.getrlimit(self.ctx,5)
157         return ret
158     
159     def set_tasklimit(self, limit):
160         ret = vserverimpl.setrlimit(self.ctx,6,limit)
161         return ret
162
163     def get_tasklimit(self):
164         ret = vserverimpl.getrlimit(self.ctx,6)
165         return ret
166
167     def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
168         if cap == "-1":
169             bwlimit.off(self.ctx,eth)
170         else:
171             bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
172
173     def get_bwlimit(self, eth):
174         # not implemented yet
175         bwlimit = -1
176         cap = "unknown"
177         minrate = "unknown"
178         maxrate = "unknown"
179         return (bwlimit, cap, minrate, maxrate)
180         
181     def open(self, filename, mode = "r", bufsize = -1):
182
183         (sendsock, recvsock) = passfdimpl.socketpair()
184         child_pid = os.fork()
185         if child_pid == 0:
186             try:
187                 # child process
188                 self.__do_chroot()
189                 f = open(filename, mode)
190                 passfdimpl.sendmsg(f.fileno(), sendsock)
191                 os._exit(0)
192             except EnvironmentError, ex:
193                 (result, errmsg) = (ex.errno, ex.strerror)
194             except Exception, ex:
195                 (result, errmsg) = (255, str(ex))
196             os.write(sendsock, errmsg)
197             os._exit(result)
198
199         # parent process
200
201         # XXX - need this since a lambda can't raise an exception
202         def __throw(ex):
203             raise ex
204
205         os.close(sendsock)
206         throw = lambda : __throw(Exception(errmsg))
207         while True:
208             try:
209                 (pid, status) = os.waitpid(child_pid, 0)
210                 if os.WIFEXITED(status):
211                     result = os.WEXITSTATUS(status)
212                     if result != 255:
213                         errmsg = os.strerror(result)
214                         throw = lambda : __throw(IOError(result, errmsg))
215                     else:
216                         errmsg = "unexpected exception in child"
217                 else:
218                     result = -1
219                     errmsg = "child killed"
220                 break
221             except OSError, ex:
222                 if ex.errno != errno.EINTR:
223                     os.close(recvsock)
224                     raise ex
225         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
226         try:
227             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
228         except OSError, ex:
229             if ex.errno != errno.EAGAIN:
230                 throw = lambda : __throw(ex)
231             fd = 0
232         os.close(recvsock)
233         if not fd:
234             throw()
235
236         return os.fdopen(fd, mode, bufsize)
237
238     def __do_chcontext(self, state_file = None):
239
240         vserverimpl.chcontext(self.ctx, self.remove_caps)
241         if not state_file:
242             return
243         print >>state_file, "S_CONTEXT=%d" % self.ctx
244         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
245         state_file.close()
246
247     def __prep(self, runlevel, log):
248
249         """ Perform all the crap that the vserver script does before
250         actually executing the startup scripts. """
251
252         # remove /var/run and /var/lock/subsys files
253         # but don't remove utmp from the top-level /var/run
254         RUNDIR = "/var/run"
255         LOCKDIR = "/var/lock/subsys"
256         filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
257         garbage = reduce((lambda (out, ff), (dir, subdirs, files):
258                           (out + map((dir + "/").__add__, ff(files)),
259                            lambda fs: fs)),
260                          list(os.walk(RUNDIR)),
261                          ([], filter_fn))[0]
262         garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
263                                               os.listdir(LOCKDIR)))
264         for f in garbage:
265             os.unlink(f)
266
267         # set the initial runlevel
268         f = open(RUNDIR + "/utmp", "w")
269         utmp.set_runlevel(f, runlevel)
270         f.close()
271
272         # mount /proc and /dev/pts
273         self.__do_mount("none", "/proc", "proc")
274         # XXX - magic mount options
275         self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
276
277     def __do_mount(self, *mount_args):
278
279         try:
280             mountimpl.mount(*mount_args)
281         except OSError, ex:
282             if ex.errno == errno.EBUSY:
283                 # assume already mounted
284                 return
285             raise ex
286
287     def enter(self):
288
289         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
290         self.__do_chroot()
291         self.__do_chcontext(state_file)
292
293     def start(self, wait, runlevel = 3):
294
295         child_pid = os.fork()
296         if child_pid == 0:
297             # child process
298             try:
299                 # get a new session
300                 os.setsid()
301
302                 # open state file to record vserver info
303                 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
304
305                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
306                 os.close(0)
307                 os.close(1)
308                 os.open("/dev/null", os.O_RDONLY)
309                 self.__do_chroot()
310                 log = open("/var/log/boot.log", "w", 0)
311                 os.dup2(1, 2)
312
313                 print >>log, ("%s: starting the virtual server %s" %
314                               (time.asctime(time.gmtime()), self.name))
315
316                 # perform pre-init cleanup
317                 self.__prep(runlevel, log)
318
319                 # execute each init script in turn
320                 # XXX - we don't support all scripts that vserver script does
321                 cmd_pid = 0
322                 for cmd in self.INITSCRIPTS + [None]:
323                     # wait for previous command to terminate, unless it
324                     # is the last one and the caller has specified to wait
325                     if cmd_pid and (cmd != None or wait):
326                         try:
327                             os.waitpid(cmd_pid, 0)
328                         except:
329                             print >>log, "error waiting for %s:" % cmd_pid
330                             traceback.print_exc()
331
332                     # end of list
333                     if cmd == None:
334                         os._exit(0)
335
336                     # fork and exec next command
337                     cmd_pid = os.fork()
338                     if cmd_pid == 0:
339                         try:
340                             # enter vserver context
341                             self.__do_chcontext(state_file)
342                             arg_subst = { 'runlevel': runlevel }
343                             cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
344                                                       cmd[1:])
345                             print >>log, "executing '%s'" % " ".join(cmd_args)
346                             os.execl(cmd[0], *cmd_args)
347                         except:
348                             traceback.print_exc()
349                             os._exit(1)
350                     else:
351                         # don't want to write state_file multiple times
352                         state_file = None
353
354             # we get here due to an exception in the top-level child process
355             except Exception, ex:
356                 traceback.print_exc()
357             os._exit(0)
358
359         # parent process
360         return child_pid