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