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