updated scheduling and chcontext code to work with new vserverimpl
[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                 cpuguaranteed = 0 # need to set this from the conf file
141                 vserverimpl.setsched(self.ctx,fillrate,interval,tokensmin,tokensmax,cpuguaranteed)
142             except OSError, ex:
143                 if ex.errno == 22:
144                     print "kernel does not support vserver scheduler"
145                 else:
146                     raise ex
147
148     def get_sched(self):
149         # have no way of querying scheduler right now on a per vserver basis
150         return (-1, False)
151
152     def set_memlimit(self, limit):
153         ret = vserverimpl.setrlimit(self.ctx,5,limit)
154         return ret
155
156     def get_memlimit(self):
157         ret = vserverimpl.getrlimit(self.ctx,5)
158         return ret
159     
160     def set_tasklimit(self, limit):
161         ret = vserverimpl.setrlimit(self.ctx,6,limit)
162         return ret
163
164     def get_tasklimit(self):
165         ret = vserverimpl.getrlimit(self.ctx,6)
166         return ret
167
168     def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
169         if cap == "-1":
170             bwlimit.off(self.ctx,eth)
171         else:
172             bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
173
174     def get_bwlimit(self, eth):
175         # not implemented yet
176         bwlimit = -1
177         cap = "unknown"
178         minrate = "unknown"
179         maxrate = "unknown"
180         return (bwlimit, cap, minrate, maxrate)
181         
182     def open(self, filename, mode = "r", bufsize = -1):
183
184         (sendsock, recvsock) = passfdimpl.socketpair()
185         child_pid = os.fork()
186         if child_pid == 0:
187             try:
188                 # child process
189                 self.__do_chroot()
190                 f = open(filename, mode)
191                 passfdimpl.sendmsg(f.fileno(), sendsock)
192                 os._exit(0)
193             except EnvironmentError, ex:
194                 (result, errmsg) = (ex.errno, ex.strerror)
195             except Exception, ex:
196                 (result, errmsg) = (255, str(ex))
197             os.write(sendsock, errmsg)
198             os._exit(result)
199
200         # parent process
201
202         # XXX - need this since a lambda can't raise an exception
203         def __throw(ex):
204             raise ex
205
206         os.close(sendsock)
207         throw = lambda : __throw(Exception(errmsg))
208         while True:
209             try:
210                 (pid, status) = os.waitpid(child_pid, 0)
211                 if os.WIFEXITED(status):
212                     result = os.WEXITSTATUS(status)
213                     if result != 255:
214                         errmsg = os.strerror(result)
215                         throw = lambda : __throw(IOError(result, errmsg))
216                     else:
217                         errmsg = "unexpected exception in child"
218                 else:
219                     result = -1
220                     errmsg = "child killed"
221                 break
222             except OSError, ex:
223                 if ex.errno != errno.EINTR:
224                     os.close(recvsock)
225                     raise ex
226         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
227         try:
228             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
229         except OSError, ex:
230             if ex.errno != errno.EAGAIN:
231                 throw = lambda : __throw(ex)
232             fd = 0
233         os.close(recvsock)
234         if not fd:
235             throw()
236
237         return os.fdopen(fd, mode, bufsize)
238
239     def __do_chcontext(self, state_file = None):
240
241         vserverimpl.chcontext(self.ctx)
242         if not state_file:
243             return
244         print >>state_file, "S_CONTEXT=%d" % self.ctx
245         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
246         state_file.close()
247
248     def __prep(self, runlevel, log):
249
250         """ Perform all the crap that the vserver script does before
251         actually executing the startup scripts. """
252
253         # remove /var/run and /var/lock/subsys files
254         # but don't remove utmp from the top-level /var/run
255         RUNDIR = "/var/run"
256         LOCKDIR = "/var/lock/subsys"
257         filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
258         garbage = reduce((lambda (out, ff), (dir, subdirs, files):
259                           (out + map((dir + "/").__add__, ff(files)),
260                            lambda fs: fs)),
261                          list(os.walk(RUNDIR)),
262                          ([], filter_fn))[0]
263         garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
264                                               os.listdir(LOCKDIR)))
265         for f in garbage:
266             os.unlink(f)
267
268         # set the initial runlevel
269         f = open(RUNDIR + "/utmp", "w")
270         utmp.set_runlevel(f, runlevel)
271         f.close()
272
273         # mount /proc and /dev/pts
274         self.__do_mount("none", "/proc", "proc")
275         # XXX - magic mount options
276         self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
277
278     def __do_mount(self, *mount_args):
279
280         try:
281             mountimpl.mount(*mount_args)
282         except OSError, ex:
283             if ex.errno == errno.EBUSY:
284                 # assume already mounted
285                 return
286             raise ex
287
288     def enter(self):
289
290         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
291         self.__do_chroot()
292         self.__do_chcontext(state_file)
293
294     def start(self, wait, runlevel = 3):
295
296         child_pid = os.fork()
297         if child_pid == 0:
298             # child process
299             try:
300                 # get a new session
301                 os.setsid()
302
303                 # open state file to record vserver info
304                 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
305
306                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
307                 os.close(0)
308                 os.close(1)
309                 os.open("/dev/null", os.O_RDONLY)
310                 self.__do_chroot()
311                 log = open("/var/log/boot.log", "w", 0)
312                 os.dup2(1, 2)
313
314                 print >>log, ("%s: starting the virtual server %s" %
315                               (time.asctime(time.gmtime()), self.name))
316
317                 # perform pre-init cleanup
318                 self.__prep(runlevel, log)
319
320                 # execute each init script in turn
321                 # XXX - we don't support all scripts that vserver script does
322                 cmd_pid = 0
323                 for cmd in self.INITSCRIPTS + [None]:
324                     # wait for previous command to terminate, unless it
325                     # is the last one and the caller has specified to wait
326                     if cmd_pid and (cmd != None or wait):
327                         try:
328                             os.waitpid(cmd_pid, 0)
329                         except:
330                             print >>log, "error waiting for %s:" % cmd_pid
331                             traceback.print_exc()
332
333                     # end of list
334                     if cmd == None:
335                         os._exit(0)
336
337                     # fork and exec next command
338                     cmd_pid = os.fork()
339                     if cmd_pid == 0:
340                         try:
341                             # enter vserver context
342                             self.__do_chcontext(state_file)
343                             arg_subst = { 'runlevel': runlevel }
344                             cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
345                                                       cmd[1:])
346                             print >>log, "executing '%s'" % " ".join(cmd_args)
347                             os.execl(cmd[0], *cmd_args)
348                         except:
349                             traceback.print_exc()
350                             os._exit(1)
351                     else:
352                         # don't want to write state_file multiple times
353                         state_file = None
354
355             # we get here due to an exception in the top-level child process
356             except Exception, ex:
357                 traceback.print_exc()
358             os._exit(0)
359
360         # parent process
361         return child_pid