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