Added set_dlimit and get_dlimit to be used by NM to enforce disk 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 linuxcaps
13 import passfdimpl
14 import utmp
15 import vserverimpl, vduimpl
16
17 from util_vserver_vars import *
18
19 CAP_SAFE = (linuxcaps.CAP_CHOWN |
20             linuxcaps.CAP_DAC_OVERRIDE |
21             linuxcaps.CAP_DAC_READ_SEARCH |
22             linuxcaps.CAP_FOWNER |
23             linuxcaps.CAP_FSETID |
24             linuxcaps.CAP_KILL |
25             linuxcaps.CAP_SETGID |
26             linuxcaps.CAP_SETUID |
27             linuxcaps.CAP_SETPCAP |
28             linuxcaps.CAP_SYS_TTY_CONFIG |
29             linuxcaps.CAP_LEASE |
30             linuxcaps.CAP_SYS_CHROOT |
31             linuxcaps.CAP_SYS_PTRACE)
32
33 #
34 # these are the flags taken from the kernel linux/vserver/legacy.h
35 #
36 FLAGS_LOCK = 1
37 FLAGS_SCHED = 2  # XXX - defined in util-vserver/src/chcontext.c
38 FLAGS_NPROC = 4
39 FLAGS_PRIVATE = 8
40 FLAGS_INIT = 16
41 FLAGS_HIDEINFO = 32
42 FLAGS_ULIMIT = 64
43 FLAGS_NAMESPACE = 128
44
45
46               
47 class VServer:
48
49     INITSCRIPTS = [('/etc/rc.vinit', 'start'),
50                    ('/etc/rc.d/rc', '%(runlevel)d')]
51
52     def __init__(self, name):
53
54         self.name = name
55         self.config = self.__read_config_file("/etc/vservers.conf")
56         self.config.update(self.__read_config_file("/etc/vservers/%s.conf" %
57                                                    self.name))
58         self.flags = 0
59         flags = self.config["S_FLAGS"].split(" ")
60         if "lock" in flags:
61             self.flags |= FLAGS_LOCK
62         if "nproc" in flags:
63             self.flags |= FLAGS_NPROC
64         self.remove_caps = ~CAP_SAFE
65         self.ctx = int(self.config["S_CONTEXT"])
66
67     config_var_re = re.compile(r"^ *([A-Z_]+)=(.*)\n?$", re.MULTILINE)
68
69     def __read_config_file(self, filename):
70
71         f = open(filename, "r")
72         data = f.read()
73         f.close()
74         config = {}
75         for m in self.config_var_re.finditer(data):
76             (key, val) = m.groups()
77             config[key] = val.strip('"')
78         return config
79
80     def __do_chroot(self):
81
82         return os.chroot("%s/%s" % (VROOTDIR, self.name))
83
84     def set_dlimit(self, blocktotal):
85         path = "%s/%s" % (VROOTDIR, self.name)
86         inodes, blockcount, size = vduimpl.vdu(path)
87         vserverimpl.setdlimit(path, self.ctx, blockcount>>1, blocktotal, inodes, -1, 2)
88
89     def get_dlimit(self):
90         path = "%s/%s" % (VROOTDIR, self.name)
91         try:
92             blocksused, blocktotal, inodesused, inodestotal, reserved = \
93                         vserverimpl.getdlimit(path,self.ctx)
94         except OSError, ex:
95             if ex.errno == 3:
96                 # get here if no vserver disk limit has been set for xid
97                 # set blockused to -1 to indicate no limit
98                 blocktotal = -1
99
100         return blocktotal
101
102     def open(self, filename, mode = "r", bufsize = -1):
103
104         (sendsock, recvsock) = passfdimpl.socketpair()
105         child_pid = os.fork()
106         if child_pid == 0:
107             try:
108                 # child process
109                 self.__do_chroot()
110                 f = open(filename, mode)
111                 passfdimpl.sendmsg(f.fileno(), sendsock)
112                 os._exit(0)
113             except EnvironmentError, ex:
114                 (result, errmsg) = (ex.errno, ex.strerror)
115             except Exception, ex:
116                 (result, errmsg) = (255, str(ex))
117             os.write(sendsock, errmsg)
118             os._exit(result)
119
120         # parent process
121
122         # XXX - need this since a lambda can't raise an exception
123         def __throw(ex):
124             raise ex
125
126         os.close(sendsock)
127         throw = lambda : __throw(Exception(errmsg))
128         while True:
129             try:
130                 (pid, status) = os.waitpid(child_pid, 0)
131                 if os.WIFEXITED(status):
132                     result = os.WEXITSTATUS(status)
133                     if result != 255:
134                         errmsg = os.strerror(result)
135                         throw = lambda : __throw(IOError(result, errmsg))
136                     else:
137                         errmsg = "unexpected exception in child"
138                 else:
139                     result = -1
140                     errmsg = "child killed"
141                 break
142             except OSError, ex:
143                 if ex.errno != errno.EINTR:
144                     os.close(recvsock)
145                     raise ex
146         fcntl.fcntl(recvsock, fcntl.F_SETFL, os.O_NONBLOCK)
147         try:
148             (fd, errmsg) = passfdimpl.recvmsg(recvsock)
149         except OSError, ex:
150             if ex.errno != errno.EAGAIN:
151                 throw = lambda : __throw(ex)
152             fd = 0
153         os.close(recvsock)
154         if not fd:
155             throw()
156
157         return os.fdopen(fd, mode, bufsize)
158
159     def __do_chcontext(self, state_file = None):
160
161         vserverimpl.chcontext(self.ctx, self.remove_caps)
162         if not state_file:
163             return
164         print >>state_file, "S_CONTEXT=%d" % self.ctx
165         print >>state_file, "S_PROFILE=%s" % self.config.get("S_PROFILE", "")
166         state_file.close()
167
168     def __prep(self, runlevel, log):
169
170         """ Perform all the crap that the vserver script does before
171         actually executing the startup scripts. """
172
173         # remove /var/run and /var/lock/subsys files
174         # but don't remove utmp from the top-level /var/run
175         RUNDIR = "/var/run"
176         LOCKDIR = "/var/lock/subsys"
177         filter_fn = lambda fs: filter(lambda f: f != 'utmp', fs)
178         garbage = reduce((lambda (out, ff), (dir, subdirs, files):
179                           (out + map((dir + "/").__add__, ff(files)),
180                            lambda fs: fs)),
181                          list(os.walk(RUNDIR)),
182                          ([], filter_fn))[0]
183         garbage += filter(os.path.isfile, map((LOCKDIR + "/").__add__,
184                                               os.listdir(LOCKDIR)))
185         for f in garbage:
186             os.unlink(f)
187
188         # set the initial runlevel
189         f = open(RUNDIR + "/utmp", "w")
190         utmp.set_runlevel(f, runlevel)
191         f.close()
192
193         # mount /proc and /dev/pts
194         self.__do_mount("none", "/proc", "proc")
195         # XXX - magic mount options
196         self.__do_mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=0620")
197
198     def __do_mount(self, *mount_args):
199
200         try:
201             mountimpl.mount(*mount_args)
202         except OSError, ex:
203             if ex.errno == errno.EBUSY:
204                 # assume already mounted
205                 return
206             raise ex
207
208     def enter(self):
209
210         state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
211         self.__do_chroot()
212         self.__do_chcontext(state_file)
213
214     def start(self, wait, runlevel = 3):
215
216         child_pid = os.fork()
217         if child_pid == 0:
218             # child process
219             try:
220                 # get a new session
221                 os.setsid()
222
223                 # open state file to record vserver info
224                 state_file = open("/var/run/vservers/%s.ctx" % self.name, "w")
225
226                 # use /dev/null for stdin, /var/log/boot.log for stdout/err
227                 os.close(0)
228                 os.close(1)
229                 os.open("/dev/null", os.O_RDONLY)
230                 self.__do_chroot()
231                 log = open("/var/log/boot.log", "w", 0)
232                 os.dup2(1, 2)
233
234                 print >>log, ("%s: starting the virtual server %s" %
235                               (time.asctime(time.gmtime()), self.name))
236
237                 # perform pre-init cleanup
238                 self.__prep(runlevel, log)
239
240                 # execute each init script in turn
241                 # XXX - we don't support all scripts that vserver script does
242                 cmd_pid = 0
243                 for cmd in self.INITSCRIPTS + [None]:
244                     # wait for previous command to terminate, unless it
245                     # is the last one and the caller has specified to wait
246                     if cmd_pid and (cmd != None or wait):
247                         try:
248                             os.waitpid(cmd_pid, 0)
249                         except:
250                             print >>log, "error waiting for %s:" % cmd_pid
251                             traceback.print_exc()
252
253                     # end of list
254                     if cmd == None:
255                         os._exit(0)
256
257                     # fork and exec next command
258                     cmd_pid = os.fork()
259                     if cmd_pid == 0:
260                         try:
261                             # enter vserver context
262                             self.__do_chcontext(state_file)
263                             arg_subst = { 'runlevel': runlevel }
264                             cmd_args = [cmd[0]] + map(lambda x: x % arg_subst,
265                                                       cmd[1:])
266                             print >>log, "executing '%s'" % " ".join(cmd_args)
267                             os.execl(cmd[0], *cmd_args)
268                         except:
269                             traceback.print_exc()
270                             os._exit(1)
271                     else:
272                         # don't want to write state_file multiple times
273                         state_file = None
274
275             # we get here due to an exception in the top-level child process
276             except Exception, ex:
277                 traceback.print_exc()
278             os._exit(0)
279
280         # parent process
281         return child_pid