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