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