Apply disklimit when starting vservers.
[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 passfdimpl
13 import utmp
14 import vserverimpl, vduimpl
15 import cpulimit, bwlimit
16
17
18
19 #
20 # these are the flags taken from the kernel linux/vserver/legacy.h
21 #
22 FLAGS_LOCK = 1
23 FLAGS_SCHED = 2  # XXX - defined in util-vserver/src/chcontext.c
24 FLAGS_NPROC = 4
25 FLAGS_PRIVATE = 8
26 FLAGS_INIT = 16
27 FLAGS_HIDEINFO = 32
28 FLAGS_ULIMIT = 64
29 FLAGS_NAMESPACE = 128
30
31 # default values for new vserver scheduler
32 SCHED_TOKENS_MIN = 50
33 SCHED_TOKENS_MAX = 100
34 SCHED_TOKENS = 100
35 SCHED_INTERVAL = 1000
36
37               
38 class VServer:
39
40     INITSCRIPTS = [('/etc/rc.vinit', 'start'),
41                    ('/etc/rc.d/rc', '%(runlevel)d')]
42
43     def __init__(self, name):
44
45         self.name = name
46         self.config_file = "/etc/vservers/%s.conf" % name
47         self.dir = "%s/%s" % (vserverimpl.VSERVER_BASEDIR, name)
48         if not (os.path.isdir(self.dir) and
49                 os.access(self.dir, os.R_OK | os.W_OK | os.X_OK)):
50             raise Exception, "no such vserver: " + name
51         self.config = self.__read_config_file("/etc/vservers.conf")
52         self.config.update(self.__read_config_file(self.config_file))
53         self.flags = 0
54         flags = self.config["S_FLAGS"].split(" ")
55         if "lock" in flags:
56             self.flags |= FLAGS_LOCK
57         if "nproc" in flags:
58             self.flags |= FLAGS_NPROC
59         self.remove_caps = ~vserverimpl.CAP_SAFE;
60         self.ctx = int(self.config["S_CONTEXT"])
61
62     config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
63
64     def __read_config_file(self, filename):
65
66         f = open(filename, "r")
67         data = f.read()
68         f.close()
69         config = {}
70         for m in self.config_var_re.finditer(data):
71             (key, val) = m.groups()
72             config[key] = val.strip('"')
73         return config
74
75     def __update_config_file(self, filename, newvars):
76
77         # read old file, apply changes
78         f = open(filename, "r")
79         data = f.read()
80         f.close()
81         todo = newvars.copy()
82         changed = False
83         for m in self.config_var_re.finditer(data):
84             (key, val) = m.groups()
85             newval = todo.pop(key, None)
86             if newval != None:
87                 data = data[:m.start(2)] + newval + data[m.end(2):]
88                 changed = True
89         for (newkey, newval) in todo.items():
90             data += "%s=%s\n" % (newkey, newval)
91             changed = True
92
93         if not changed:
94             return
95
96         # write new file
97         newfile = filename + ".new"
98         f = open(newfile, "w")
99         f.write(data)
100         f.close()
101
102         # 'copy' original file, rename new to original
103         backup = filename + ".old"
104         os.unlink(backup)
105         os.link(filename, backup)
106         os.rename(newfile, filename)
107
108     def __do_chroot(self):
109
110         return os.chroot(self.dir)
111
112     def set_disklimit(self, block_limit):
113
114         # block_limit is in kB, get_disk_usage() must have been called
115         if self.disk_usage_set:
116             block_usage = vserverimpl.DLIMIT_KEEP
117             inode_usage = vserverimpl.DLIMIT_KEEP
118         else:
119             block_usage = self.disk_blocks
120             inode_usage = self.disk_inodes
121             if block_limit < block_usage:
122                 raise Exception, ("%s disk usage (%u blocks) > limit (%u)" %
123                                   (self.name, block_usage, block_limit))
124             self.disk_usage_set = True
125
126         vserverimpl.setdlimit(self.dir,
127                               self.ctx,
128                               block_usage,
129                               block_limit,
130                               inode_usage,
131                               -1,  # inode limit
132                               2)   # %age reserved for root
133
134     def get_disklimit(self):
135
136         try:
137             blocksused, blocktotal, inodesused, inodestotal, reserved = \
138                         vserverimpl.getdlimit(self.dir, self.ctx)
139         except OSError, ex:
140             if ex.errno == errno.ESRCH:
141                 # get here if no vserver disk limit has been set for xid
142                 # set blockused to -1 to indicate no limit
143                 blocktotal = -1
144
145         return blocktotal
146
147     def set_sched(self, shares = 32, besteffort = True):
148         # for the old CKRM scheduler
149         if cpulimit.checkckrm() is True:
150             cpulimit.cpuinit()
151             cpulimit.vs2ckrm_on(self.name)
152             try:
153                 cpulimit.cpulimit(self.name,shares)
154             except OSError, ex:
155                 if ex.errno == 22:
156                     print "invalid shares argument"
157                     # should re-raise exception?!
158
159         # for the new vserver scheduler
160         else:
161             global SCHED_TOKENS_MIN, SCHED_TOKENS_MAX, SCHED_TOKENS, SCHED_INTERVAL
162             tokensmin = SCHED_TOKENS_MIN
163             tokensmax = SCHED_TOKENS_MAX
164             tokens    = SCHED_TOKENS
165             interval  = SCHED_INTERVAL
166             fillrate = shares
167
168             if besteffort is True:
169                 cpuguaranteed = 0
170             else:
171                 cpuguaranteed = 1
172
173             try:
174                 vserverimpl.setsched(self.ctx,fillrate,interval,tokens,tokensmin,tokensmax,cpuguaranteed)
175             except OSError, ex:
176                 if ex.errno == 22:
177                     print "kernel does not support vserver scheduler"
178                 else:
179                     raise ex
180
181     def get_sched(self):
182         # have no way of querying scheduler right now on a per vserver basis
183         return (-1, False)
184
185     def set_memlimit(self, limit):
186         ret = vserverimpl.setrlimit(self.ctx,5,limit)
187         return ret
188
189     def get_memlimit(self):
190         ret = vserverimpl.getrlimit(self.ctx,5)
191         return ret
192     
193     def set_tasklimit(self, limit):
194         ret = vserverimpl.setrlimit(self.ctx,6,limit)
195         return ret
196
197     def get_tasklimit(self):
198         ret = vserverimpl.getrlimit(self.ctx,6)
199         return ret
200
201     def set_bwlimit(self, eth, limit, cap, minrate, maxrate):
202         if cap == "-1":
203             bwlimit.off(self.ctx,eth)
204         else:
205             bwlimit.on(self.ctx, eth, limit, cap, minrate, maxrate)
206
207     def get_bwlimit(self, eth):
208         # not implemented yet
209         bwlimit = -1
210         cap = "unknown"
211         minrate = "unknown"
212         maxrate = "unknown"
213         return (bwlimit, cap, minrate, maxrate)
214         
215     def open(self, filename, mode = "r", bufsize = -1):
216
217         (sendsock, recvsock) = passfdimpl.socketpair()
218         child_pid = os.fork()
219         if child_pid == 0:
220             try:
221                 # child process
222                 self.__do_chroot()
223                 f = open(filename, mode)
224                 passfdimpl.sendmsg(f.fileno(), sendsock)
225                 os._exit(0)
226             except EnvironmentError, ex:
227                 (result, errmsg) = (ex.errno, ex.strerror)
228             except Exception, ex:
229                 (result, errmsg) = (255, str(ex))
230             os.write(sendsock, errmsg)
231             os._exit(result)
232
233         # parent process
234
235         # XXX - need this since a lambda can't raise an exception
236         def __throw(ex):
237             raise ex
238
239         os.close(sendsock)
240         throw = lambda : __throw(Exception(errmsg))
241         while True:
242             try:
243                 (pid, status) = os.waitpid(child_pid, 0)
244                 if os.WIFEXITED(status):
245                     result = os.WEXITSTATUS(status)
246                     if result != 255:
247                         errmsg = os.strerror(result)
248                         throw = lambda : __throw(IOError(result, errmsg))
249                     else:
250                         errmsg = "unexpected exception in child"
251                 else:
252                     result = -1
253                     errmsg = "child killed"
254                 break
255             except OSError, ex:
256                 if ex.errno != errno.EINTR:
257                     os.close(recvsock)
258                     raise ex
259         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
260         try:
261             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
262         except OSError, ex:
263             if ex.errno != errno.EAGAIN:
264                 throw = lambda : __throw(ex)
265             fd = 0
266         os.close(recvsock)
267         if not fd:
268             throw()
269
270         return os.fdopen(fd, mode, bufsize)
271
272     def __do_chcontext(self, state_file = None):
273
274         vserverimpl.chcontext(self.ctx)
275
276         if not state_file:
277             return
278         print >>state_file, "S_CONTEXT=%d" % self.ctx
279         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
280         state_file.close()
281
282     def __prep(self, runlevel, log):
283
284         """ Perform all the crap that the vserver script does before
285         actually executing the startup scripts. """
286
287         # remove /var/run and /var/lock/subsys files
288         # but don't remove utmp from the top-level /var/run
289         RUNDIR = "/var/run"
290         LOCKDIR = "/var/lock/subsys"
291         filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
292         garbage = reduce((lambda (out, ff), (dir, subdirs, files):
293                           (out + map((dir + "/").__add__, ff(files)),
294                            lambda fs: fs)),
295                          list(os.walk(RUNDIR)),
296                          ([], filter_fn))[0]
297         garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
298                                               os.listdir(LOCKDIR)))
299         for f in garbage:
300             os.unlink(f)
301
302         # set the initial runlevel
303         f = open(RUNDIR + "/utmp", "w")
304         utmp.set_runlevel(f, runlevel)
305         f.close()
306
307         # mount /proc and /dev/pts
308         self.__do_mount("none", "/proc", "proc")
309         # XXX - magic mount options
310         self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
311
312     def __do_mount(self, *mount_args):
313
314         try:
315             mountimpl.mount(*mount_args)
316         except OSError, ex:
317             if ex.errno == errno.EBUSY:
318                 # assume already mounted
319                 return
320             raise ex
321
322     def enter(self):
323
324         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
325         self.__do_chroot()
326         self.__do_chcontext(state_file)
327
328     def start(self, wait, runlevel = 3):
329
330         # XXX - temporary hack
331         self.set_disklimit(self.config.get("DISKLIMIT", 5000000))
332
333         child_pid = os.fork()
334         if child_pid == 0:
335             # child process
336             try:
337                 # get a new session
338                 os.setsid()
339
340                 # open state file to record vserver info
341                 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
342
343                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
344                 os.close(0)
345                 os.close(1)
346                 os.open("/dev/null", os.O_RDONLY)
347                 self.__do_chroot()
348                 log = open("/var/log/boot.log", "w", 0)
349                 os.dup2(1, 2)
350                 # XXX - close all other fds
351
352                 print >>log, ("%s: starting the virtual server %s" %
353                               (time.asctime(time.gmtime()), self.name))
354
355                 # perform pre-init cleanup
356                 self.__prep(runlevel, log)
357
358                 # execute each init script in turn
359                 # XXX - we don't support all scripts that vserver script does
360                 cmd_pid = 0
361                 first_child = True
362                 for cmd in self.INITSCRIPTS + [None]:
363                     # wait for previous command to terminate, unless it
364                     # is the last one and the caller has specified to wait
365                     if cmd_pid and (cmd != None or wait):
366                         try:
367                             os.waitpid(cmd_pid, 0)
368                         except:
369                             print >>log, "error waiting for %s:" % cmd_pid
370                             traceback.print_exc()
371
372                     # end of list
373                     if cmd == None:
374                         os._exit(0)
375
376                     # fork and exec next command
377                     cmd_pid = os.fork()
378                     if cmd_pid == 0:
379                         try:
380                             # enter vserver context
381                             self.__do_chcontext(state_file)
382                             arg_subst = { 'runlevel': runlevel }
383                             cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
384                                                       cmd[1:])
385                             print >>log, "executing '%s'" % " ".join(cmd_args)
386                             os.execl(cmd[0], *cmd_args)
387                         except:
388                             traceback.print_exc()
389                             os._exit(1)
390                     else:
391                         # don't want to write state_file multiple times
392                         state_file = None
393
394             # we get here due to an exception in the top-level child process
395             except Exception, ex:
396                 traceback.print_exc()
397             os._exit(0)
398
399         # parent process
400         return child_pid
401
402     def update_resources(self, resources):
403
404         self.config.update(resources)
405
406         # write new values to configuration file
407         self.__update_config_file(self.config_file, resources)
408
409         # disklimit can be applied without a process in context
410         disklimit = resources.get("DISKLIMIT", 0)
411         if disklimit:
412             self.set_disklimit(disklimit)
413
414         #
415         # Figure out if any processes are active in context, apply new
416         # values if there are.
417         #
418
419     def init_disk_info(self):
420
421         (self.disk_inodes, self.disk_blocks, size) = vduimpl.vdu(self.dir)
422         self.disk_usage_set = False
423
424         return size