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