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