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