]> git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
clean up APT cache after installing packages
[forks/vmdebootstrap.git] / vmdebootstrap
1 #!/usr/bin/python
2 # Copyright 2011, 2012 Lars Wirzenius
3 # Copyright 2012 Codethink Limited
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 import cliapp
19 import crypt
20 import logging
21 import os
22 import re
23 import shutil
24 import subprocess
25 import tempfile
26
27
28 class VmDebootstrap(cliapp.Application):
29
30 def add_settings(self):
31 default_arch = 'amd64'
32
33 self.settings.boolean(['verbose'], 'report what is going on')
34 self.settings.string(['image'], 'put created disk image in FILE',
35 metavar='FILE')
36 self.settings.bytesize(['size'],
37 'create a disk image of size SIZE (%default)',
38 metavar='SIZE',
39 default='1G')
40 self.settings.string(['tarball'], "tar up the disk's contents in FILE",
41 metavar='FILE')
42 self.settings.string(['mirror'],
43 'use MIRROR as package source (%default)',
44 metavar='URL',
45 default='http://cdn.debian.net/debian/')
46 self.settings.string(['arch'], 'architecture to use (%default)',
47 metavar='ARCH',
48 default=default_arch)
49 self.settings.string(['distribution'],
50 'release to use (%default)',
51 metavar='NAME',
52 default='stable')
53 self.settings.string_list(['package'], 'install PACKAGE onto system')
54 self.settings.string_list(['custom-package'],
55 'install package in DEB file onto system '
56 '(not from mirror)',
57 metavar='DEB')
58 self.settings.boolean(['no-kernel'], 'do not install a linux package')
59 self.settings.boolean(['enable-dhcp'], 'enable DHCP on eth0')
60 self.settings.string(['root-password'], 'set root password',
61 metavar='PASSWORD')
62 self.settings.boolean(['lock-root-password'],
63 'lock root account so they cannot login?')
64 self.settings.string(['customize'],
65 'run SCRIPT after setting up system',
66 metavar='SCRIPT')
67 self.settings.string(['hostname'],
68 'set name to HOSTNAME (%default)',
69 metavar='HOSTNAME',
70 default='debian')
71 self.settings.string_list(['user'],
72 'create USER with PASSWORD',
73 metavar='USER/PASSWORD')
74 self.settings.boolean(['serial-console'],
75 'configure image to use a serial console')
76 self.settings.string(['serial-console-command'],
77 'command to manage the serial console, appended '
78 'to /etc/inittab (%default)',
79 metavar='COMMAND',
80 default='/sbin/getty -L ttyS0 115200 vt100')
81 self.settings.boolean(['sudo'],
82 'install sudo, and if user is created, add them '
83 'to sudo group')
84
85 def process_args(self, args):
86 if not self.settings['image'] and not self.settings['tarball']:
87 raise cliapp.AppException('You must give disk image filename, '
88 'or tarball filename')
89 if self.settings['image'] and not self.settings['size']:
90 raise cliapp.AppException('If disk image is specified, '
91 'You must give image size.')
92
93 self.remove_dirs = []
94 self.mount_points = []
95
96 try:
97 if self.settings['image']:
98 self.create_empty_image()
99 self.partition_image()
100 self.install_mbr()
101 rootdev = self.setup_kpartx()
102 self.mkfs(rootdev)
103 rootdir = self.mount(rootdev)
104 else:
105 rootdir = self.mkdtemp()
106 self.debootstrap(rootdir)
107 self.set_hostname(rootdir)
108 self.create_fstab(rootdir)
109 self.install_debs(rootdir)
110 self.cleanup_apt_cache(rootdir)
111 self.set_root_password(rootdir)
112 self.create_users(rootdir)
113 self.remove_udev_persistent_rules(rootdir)
114 self.setup_networking(rootdir)
115 self.customize(rootdir)
116 if self.settings['image']:
117 self.install_extlinux(rootdev, rootdir)
118 if self.settings['tarball']:
119 self.create_tarball(rootdir)
120 except BaseException, e:
121 self.message('EEEK! Something bad happened...')
122 self.cleanup_system()
123 raise
124 else:
125 self.cleanup_system()
126
127 def message(self, msg):
128 logging.info(msg)
129 if self.settings['verbose']:
130 print msg
131
132 def runcmd(self, argv, stdin='', ignore_fail=False, **kwargs):
133 logging.debug('runcmd: %s %s' % (argv, kwargs))
134 p = subprocess.Popen(argv, stdin=subprocess.PIPE,
135 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
136 **kwargs)
137 out, err = p.communicate(stdin)
138 if p.returncode != 0:
139 msg = 'command failed: %s\n%s\n%s' % (argv, out, err)
140 logging.error(msg)
141 if not ignore_fail:
142 raise cliapp.AppException(msg)
143 return out
144
145 def mkdtemp(self):
146 dirname = tempfile.mkdtemp()
147 self.remove_dirs.append(dirname)
148 logging.debug('mkdir %s' % dirname)
149 return dirname
150
151 def mount(self, device):
152 self.message('Mounting %s' % device)
153 mount_point = self.mkdtemp()
154 self.runcmd(['mount', device, mount_point])
155 self.mount_points.append(mount_point)
156 logging.debug('mounted %s on %s' % (device, mount_point))
157 return mount_point
158
159 def create_empty_image(self):
160 self.message('Creating disk image')
161 self.runcmd(['qemu-img', 'create', '-f', 'raw',
162 self.settings['image'],
163 str(self.settings['size'])])
164
165 def partition_image(self):
166 self.message('Creating partitions')
167 self.runcmd(['parted', '-s', self.settings['image'],
168 'mklabel', 'msdos'])
169 self.runcmd(['parted', '-s', self.settings['image'],
170 'mkpart', 'primary', '0%', '100%'])
171 self.runcmd(['parted', '-s', self.settings['image'],
172 'set', '1', 'boot', 'on'])
173
174 def install_mbr(self):
175 self.message('Installing MBR')
176 self.runcmd(['install-mbr', self.settings['image']])
177
178 def setup_kpartx(self):
179 out = self.runcmd(['kpartx', '-av', self.settings['image']])
180 devices = [line.split()[2]
181 for line in out.splitlines()
182 if line.startswith('add map ')]
183 if len(devices) != 1:
184 raise cliapp.AppException('Surprising number of partitions')
185 return '/dev/mapper/%s' % devices[0]
186
187 def mkfs(self, device):
188 self.message('Creating filesystem')
189 self.runcmd(['mkfs', '-t', 'ext2', device])
190
191 def debootstrap(self, rootdir):
192 self.message('Debootstrapping')
193
194 necessary_packages = ['acpid']
195
196 include = self.settings['package']
197
198 if not self.settings['no-kernel']:
199 if self.settings['arch'] == 'i386':
200 kernel_arch = '486'
201 else:
202 kernel_arch = self.settings['arch']
203 kernel_image = 'linux-image-%s' % kernel_arch
204 include.append(kernel_image)
205
206 if self.settings['sudo'] and 'sudo' not in include:
207 include.append('sudo')
208
209 args = ['debootstrap', '--arch=%s' % self.settings['arch']]
210 args.append(
211 '--include=%s' % ','.join(necessary_packages + include))
212 args += [self.settings['distribution'],
213 rootdir, self.settings['mirror']]
214 self.runcmd(args)
215
216 def set_hostname(self, rootdir):
217 hostname = self.settings['hostname']
218 with open(os.path.join(rootdir, 'etc', 'hostname'), 'w') as f:
219 f.write('%s\n' % hostname)
220
221 etc_hosts = os.path.join(rootdir, 'etc', 'hosts')
222 with open(etc_hosts, 'r') as f:
223 data = f.read()
224 with open(etc_hosts, 'w') as f:
225 for line in data.splitlines():
226 if line.startswith('127.0.0.1'):
227 line += ' %s' % hostname
228 f.write('%s\n' % line)
229
230 def create_fstab(self, rootdir):
231 fstab = os.path.join(rootdir, 'etc', 'fstab')
232 with open(fstab, 'w') as f:
233 f.write('proc /proc proc defaults 0 0\n')
234 f.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
235
236 def install_debs(self, rootdir):
237 if not self.settings['custom-package']:
238 return
239 self.message('Installing custom packages')
240 tmp = os.path.join(rootdir, 'tmp', 'install_debs')
241 os.mkdir(tmp)
242 for deb in self.settings['custom-package']:
243 shutil.copy(deb, tmp)
244 filenames = [os.path.join('/tmp/install_debs', os.path.basename(deb))
245 for deb in self.settings['custom-package']]
246 out, err, exit = \
247 self.runcmd_unchecked(['chroot', rootdir, 'dpkg', '-i'] + filenames)
248 logging.debug('stdout:\n%s' % out)
249 logging.debug('stderr:\n%s' % err)
250 out = self.runcmd(['chroot', rootdir,
251 'apt-get', '-f', '--no-remove', 'install'])
252 logging.debug('stdout:\n%s' % out)
253 shutil.rmtree(tmp)
254
255 def cleanup_apt_cache(self, rootdir):
256 out = self.runcmd(['chroot', rootdir, 'apt-get', 'clean'])
257 logging.debug('stdout:\n%s' % out)
258
259 def set_root_password(self, rootdir):
260 if self.settings['root-password']:
261 self.message('Setting root password')
262 self.set_password(rootdir, 'root', self.settings['root-password'])
263 elif self.settings['lock-root-password']:
264 self.message('Locking root password')
265 self.runcmd(['chroot', rootdir, 'passwd', '-l', 'root'])
266 else:
267 self.message('Give root an empty password')
268 self.delete_password(rootdir, 'root')
269
270 def create_users(self, rootdir):
271 def create_user(user):
272 self.runcmd(['chroot', rootdir, 'adduser', '--gecos', user,
273 '--disabled-password', user])
274 if self.settings['sudo']:
275 self.runcmd(['chroot', rootdir, 'adduser', user, 'sudo'])
276
277 for userpass in self.settings['user']:
278 if '/' in userpass:
279 user, password = userpass.split('/', 1)
280 create_user(user)
281 self.set_password(rootdir, user, password)
282 else:
283 create_user(userpass)
284 self.delete_password(rootdir, userpass)
285
286 def set_password(self, rootdir, user, password):
287 encrypted = crypt.crypt(password, '..')
288 self.runcmd(['chroot', rootdir, 'usermod', '-p', encrypted, user])
289
290 def delete_password(self, rootdir, user):
291 self.runcmd(['chroot', rootdir, 'passwd', '-d', user])
292
293 def remove_udev_persistent_rules(self, rootdir):
294 self.message('Removing udev persistent cd and net rules')
295 for x in ['70-persistent-cd.rules', '70-persistent-net.rules']:
296 pathname = os.path.join(rootdir, 'etc', 'udev', 'rules.d', x)
297 if os.path.exists(pathname):
298 logging.debug('rm %s' % pathname)
299 os.remove(pathname)
300 else:
301 logging.debug('not removing non-existent %s' % pathname)
302
303 def setup_networking(self, rootdir):
304 self.message('Setting up networking')
305
306 f = open(os.path.join(rootdir, 'etc', 'network', 'interfaces'), 'w')
307 f.write('auto lo\n')
308 f.write('iface lo inet loopback\n')
309
310 if self.settings['enable-dhcp']:
311 f.write('\n')
312 f.write('allow-hotplug eth0\n')
313 f.write('iface eth0 inet dhcp\n')
314
315 f.close()
316
317 def install_extlinux(self, rootdev, rootdir):
318 self.message('Installing extlinux')
319
320 def find(pattern):
321 dirname = os.path.join(rootdir, 'boot')
322 basenames = os.listdir(dirname)
323 logging.debug('find: %s' % basenames)
324 for basename in basenames:
325 if re.search(pattern, basename):
326 return os.path.join('boot', basename)
327 raise cliapp.AppException('Cannot find match: %s' % pattern)
328
329 kernel_image = find('vmlinuz-.*')
330 initrd_image = find('initrd.img-.*')
331
332 out = self.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
333 '-s', 'UUID', rootdev])
334 uuid = out.splitlines()[0].strip()
335
336 conf = os.path.join(rootdir, 'extlinux.conf')
337 logging.debug('configure extlinux %s' % conf)
338 f = open(conf, 'w')
339 f.write('''
340 default linux
341 timeout 1
342
343 label linux
344 kernel %(kernel)s
345 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
346 %(extserial)s
347 ''' % {
348 'kernel': kernel_image,
349 'initrd': initrd_image,
350 'uuid': uuid,
351 'kserial':
352 'console=ttyS0,115200' if self.settings['serial-console'] else '',
353 'extserial': 'serial 0 115200' if self.settings['serial-console'] else '',
354 })
355 f.close()
356
357 if self.settings['serial-console']:
358 serial_command = self.settings['serial-console-command']
359 logging.debug('adding getty to serial console')
360 inittab = os.path.join(rootdir, 'etc/inittab')
361 with open(inittab, 'a') as f:
362 f.write('\nS0:23:respawn:%s\n' % serial_command)
363
364 self.runcmd(['extlinux', '--install', rootdir])
365 self.runcmd(['sync'])
366 import time; time.sleep(2)
367
368 def cleanup_system(self):
369 # Clean up after any errors.
370
371 self.message('Cleaning up')
372
373 if self.settings['image']:
374 for mount_point in self.mount_points:
375 self.runcmd(['umount', mount_point], ignore_fail=True)
376
377 self.runcmd(['kpartx', '-d', self.settings['image']], ignore_fail=True)
378
379 for dirname in self.remove_dirs:
380 shutil.rmtree(dirname)
381
382 def customize(self, rootdir):
383 script = self.settings['customize']
384 if script:
385 self.message('Running customize script %s' % script)
386 with open('/dev/tty', 'w') as tty:
387 cliapp.runcmd([script, rootdir], stdout=tty, stderr=tty)
388
389 def create_tarball(self, rootdir):
390 # Create a tarball of the disk's contents
391 # shell out to runcmd since it more easily handles rootdir
392 self.message('Creating tarball of disk contents')
393 self.runcmd(['tar', '-cf', self.settings['tarball'], '-C', rootdir, '.'])
394
395
396 if __name__ == '__main__':
397 VmDebootstrap().run()
398