]> git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
Add support for apt mirror and package list.
[forks/vmdebootstrap.git] / vmdebootstrap
1 #! /usr/bin/python
2 # Copyright 2011-2013 Lars Wirzenius
3 # Copyright 2012 Codethink Limited
4 # Copyright 2014 Neil Williams <codehelp@debian.org>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 import cliapp
20 import crypt
21 import logging
22 import os
23 import re
24 import shutil
25 import subprocess
26 import tempfile
27 import time
28
29
30 __version__ = '0.6'
31
32
33 class VmDebootstrap(cliapp.Application):
34
35 def add_settings(self):
36 default_arch = subprocess.check_output(
37 ["dpkg", "--print-architecture"]).strip()
38
39 self.settings.boolean(['verbose'], 'report what is going on')
40 self.settings.string(['image'], 'put created disk image in FILE',
41 metavar='FILE')
42 self.settings.bytesize(['size'],
43 'create a disk image of size SIZE (%default)',
44 metavar='SIZE',
45 default='1G')
46 self.settings.bytesize(['bootsize'],
47 'create boot partition of size SIZE (%default)',
48 metavar='BOOTSIZE',
49 default='0%')
50 self.settings.string(['boottype'],
51 'specify file system type for /boot/',
52 default='ext2')
53 self.settings.string(['foreign'],
54 'set up foreign debootstrap environment using provided program (ie binfmt handler)')
55 self.settings.string(['variant'],
56 'select debootstrap variant it not using the default')
57 self.settings.boolean(['extlinux'], 'install extlinux?', default=True)
58 self.settings.string(['tarball'], "tar up the disk's contents in FILE",
59 metavar='FILE')
60 self.settings.string(['apt-mirror'],
61 'configure apt to use MIRROR',
62 metavar='URL')
63 self.settings.string(['mirror'],
64 'use MIRROR as package source (%default)',
65 metavar='URL',
66 default='http://http.debian.net/debian/')
67 self.settings.string(['arch'], 'architecture to use (%default)',
68 metavar='ARCH',
69 default=default_arch)
70 self.settings.string(['distribution'],
71 'release to use (%default)',
72 metavar='NAME',
73 default='stable')
74 self.settings.string_list(['package'], 'install PACKAGE onto system')
75 self.settings.string_list(['custom-package'],
76 'install package in DEB file onto system '
77 '(not from mirror)',
78 metavar='DEB')
79 self.settings.boolean(['no-kernel'], 'do not install a linux package')
80 self.settings.boolean(['enable-dhcp'], 'enable DHCP on eth0')
81 self.settings.string(['root-password'], 'set root password',
82 metavar='PASSWORD')
83 self.settings.boolean(['lock-root-password'],
84 'lock root account so they cannot login?')
85 self.settings.string(['customize'],
86 'run SCRIPT after setting up system',
87 metavar='SCRIPT')
88 self.settings.string(['hostname'],
89 'set name to HOSTNAME (%default)',
90 metavar='HOSTNAME',
91 default='debian')
92 self.settings.string_list(['user'],
93 'create USER with PASSWORD',
94 metavar='USER/PASSWORD')
95 self.settings.boolean(['serial-console'],
96 'configure image to use a serial console')
97 self.settings.string(['serial-console-command'],
98 'command to manage the serial console, appended '
99 'to /etc/inittab (%default)',
100 metavar='COMMAND',
101 default='/sbin/getty -L ttyS0 115200 vt100')
102 self.settings.boolean(['sudo'],
103 'install sudo, and if user is created, add them '
104 'to sudo group')
105 self.settings.string(['owner'],
106 'the user who will own the image when the build '
107 'is complete.')
108 self.settings.boolean(['squash'],
109 'use squashfs on the final image.')
110 self.settings.boolean(['configure-apt'],
111 'Create an apt source based on the distribution '
112 'and mirror selected.')
113 self.settings.boolean(['mbr'],
114 'Run install-mbr (no longer done by default)')
115 self.settings.boolean(['grub'],
116 'Install and configure grub2 - disables '
117 'extlinux.')
118 self.settings.boolean(['sparse'],
119 'Dont fill the image with zeros to keep a sparse disk image',
120 default=False)
121 self.settings.boolean(['pkglist'],
122 'Create a list of package names included in '
123 'the image.')
124 self.remove_dirs = []
125 self.mount_points = []
126
127 def process_args(self, args):
128 if not self.settings['image'] and not self.settings['tarball']:
129 raise cliapp.AppException('You must give disk image filename, '
130 'or tarball filename')
131 if self.settings['image'] and not self.settings['size']:
132 raise cliapp.AppException('If disk image is specified, '
133 'You must give image size.')
134
135 self.remove_dirs = []
136 self.mount_points = []
137
138 try:
139 rootdev = None
140 roottype = 'ext4'
141 bootdev = None
142 boottype = None
143 rootdir = None
144 if self.settings['image']:
145 self.create_empty_image()
146 self.partition_image()
147 if self.settings['mbr']:
148 self.install_mbr()
149 (rootdev, bootdev) = self.setup_kpartx()
150 self.mkfs(rootdev, fstype=roottype)
151 rootdir = self.mount(rootdev)
152 if bootdev:
153 if self.settings['boottype']:
154 boottype = self.settings['boottype']
155 else:
156 boottype = 'ext2'
157 self.mkfs(bootdev, fstype=boottype)
158 bootdir = '%s/%s' % (rootdir, 'boot/')
159 os.mkdir(bootdir)
160 bootdir = self.mount(bootdev, bootdir)
161 else:
162 rootdir = self.mkdtemp()
163 self.debootstrap(rootdir)
164 self.set_hostname(rootdir)
165 self.create_fstab(rootdir, rootdev, roottype, bootdev, boottype)
166 self.install_debs(rootdir)
167 self.cleanup_apt_cache(rootdir)
168 self.set_root_password(rootdir)
169 self.create_users(rootdir)
170 self.remove_udev_persistent_rules(rootdir)
171 self.setup_networking(rootdir)
172 if self.settings['configure-apt'] or self.settings['apt-mirror']:
173 self.configure_apt(rootdir)
174 self.customize(rootdir)
175 self.update_initramfs(rootdir)
176
177 if self.settings['image']:
178 if self.settings['grub']:
179 self.install_grub2(rootdev, rootdir)
180 elif self.settings['extlinux']:
181 self.install_extlinux(rootdev, rootdir)
182 self.append_serial_console(rootdir)
183 self.optimize_image(rootdir)
184 if self.settings['squash']:
185 self.squash()
186 if self.settings['pkglist']:
187 self.list_installed_pkgs(rootdir)
188
189 if self.settings['foreign']:
190 os.unlink('%s/usr/bin/%s' %
191 (rootdir, os.path.basename(self.settings['foreign'])))
192
193 if self.settings['tarball']:
194 self.create_tarball(rootdir)
195
196 if self.settings['owner']:
197 self.chown(rootdir)
198 except BaseException, e:
199 self.message('EEEK! Something bad happened...')
200 if rootdir:
201 db_log = os.path.join(rootdir, 'debootstrap', 'debootstrap.log')
202 if os.path.exists(db_log):
203 shutil.copy(db_log, os.getcwd())
204 self.message(e)
205 self.cleanup_system()
206 raise
207 else:
208 self.cleanup_system()
209
210 def message(self, msg):
211 logging.info(msg)
212 if self.settings['verbose']:
213 print msg
214
215 def runcmd(self, argv, stdin='', ignore_fail=False, env=None, **kwargs):
216 logging.debug('runcmd: %s %s %s', argv, env, kwargs)
217 p = subprocess.Popen(argv, stdin=subprocess.PIPE,
218 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
219 env=env, **kwargs)
220 out, err = p.communicate(stdin)
221 if p.returncode != 0:
222 msg = 'command failed: %s\n%s\n%s' % (argv, out, err)
223 logging.error(msg)
224 if not ignore_fail:
225 raise cliapp.AppException(msg)
226 return out
227
228 def mkdtemp(self):
229 dirname = tempfile.mkdtemp()
230 self.remove_dirs.append(dirname)
231 logging.debug('mkdir %s', dirname)
232 return dirname
233
234 def mount(self, device, path=None):
235 if not path:
236 mount_point = self.mkdtemp()
237 else:
238 mount_point = path
239 self.message('Mounting %s on %s' % (device, mount_point))
240 self.runcmd(['mount', device, mount_point])
241 self.mount_points.append(mount_point)
242 logging.debug('mounted %s on %s', device, mount_point)
243 return mount_point
244
245 def create_empty_image(self):
246 self.message('Creating disk image')
247 self.runcmd(['qemu-img', 'create', '-f', 'raw',
248 self.settings['image'],
249 str(self.settings['size'])])
250
251 def partition_image(self):
252 self.message('Creating partitions')
253 self.runcmd(['parted', '-s', self.settings['image'],
254 'mklabel', 'msdos'])
255 if self.settings['bootsize'] and self.settings['bootsize'] is not '0%':
256 bootsize = str(self.settings['bootsize'] / (1024 * 1024))
257 self.runcmd(['parted', '-s', self.settings['image'],
258 'mkpart', 'primary', 'fat16', '0%', bootsize])
259 else:
260 bootsize = '0%'
261 self.runcmd(['parted', '-s', self.settings['image'],
262 'mkpart', 'primary', bootsize, '100%'])
263 self.runcmd(['parted', '-s', self.settings['image'],
264 'set', '1', 'boot', 'on'])
265
266 def update_initramfs(self, rootdir):
267 cmd = os.path.join('usr', 'sbin', 'update-initramfs')
268 if os.path.exists(os.path.join(rootdir, cmd)):
269 self.message("Updating the initramfs")
270 self.runcmd(['chroot', rootdir, cmd, '-u'])
271
272 def install_mbr(self):
273 if os.path.exists("/sbin/install-mbr"):
274 self.message('Installing MBR')
275 self.runcmd(['install-mbr', self.settings['image']])
276
277 def setup_kpartx(self):
278 out = self.runcmd(['kpartx', '-avs', self.settings['image']])
279 if self.settings['bootsize']:
280 bootindex = 0
281 rootindex = 1
282 parts = 2
283 else:
284 rootindex = 0
285 parts = 1
286 boot = None
287 devices = [line.split()[2]
288 for line in out.splitlines()
289 if line.startswith('add map ')]
290 if len(devices) != parts:
291 raise cliapp.AppException('Surprising number of partitions')
292 root = '/dev/mapper/%s' % devices[rootindex]
293 if self.settings['bootsize']:
294 boot = '/dev/mapper/%s' % devices[bootindex]
295 return (root, boot)
296
297 def mkfs(self, device, fstype):
298 self.message('Creating filesystem %s' % fstype)
299 self.runcmd(['mkfs', '-t', fstype, device])
300
301 def debootstrap(self, rootdir):
302 self.message('Debootstrapping')
303
304 if self.settings['foreign']:
305 necessary_packages = []
306 else:
307 necessary_packages = ['acpid']
308
309 if self.settings['grub']:
310 necessary_packages.append('grub2')
311
312 include = self.settings['package']
313
314 if not self.settings['no-kernel']:
315 if self.settings['arch'] == 'i386':
316 kernel_arch = '486'
317 else:
318 kernel_arch = self.settings['arch']
319 kernel_image = 'linux-image-%s' % kernel_arch
320 include.append(kernel_image)
321
322 if self.settings['sudo'] and 'sudo' not in include:
323 include.append('sudo')
324
325 args = ['debootstrap', '--arch=%s' % self.settings['arch']]
326 if self.settings['package'] and len(necessary_packages) > 0:
327 args.append(
328 '--include=%s' % ','.join(necessary_packages + include))
329 if self.settings['foreign']:
330 args.append('--foreign')
331 if self.settings['variant']:
332 args.append('--variant')
333 args.append(self.settings['variant'])
334 args += [self.settings['distribution'],
335 rootdir, self.settings['mirror']]
336 logging.debug(" ".join(args))
337 self.runcmd(args)
338 if self.settings['foreign']:
339 # set a noninteractive debconf environment for secondstage
340 env = {
341 "DEBIAN_FRONTEND": "noninteractive",
342 "DEBCONF_NONINTERACTIVE_SEEN": "true",
343 "LC_ALL": "C"
344 }
345 # add the mapping to the complete environment.
346 env.update(os.environ)
347 # First copy the binfmt handler over
348 self.message('Setting up binfmt handler')
349 shutil.copy(self.settings['foreign'], '%s/usr/bin/' % rootdir)
350 # Next, run the package install scripts etc.
351 self.message('Running debootstrap second stage')
352 self.runcmd(['chroot', rootdir,
353 '/debootstrap/debootstrap', '--second-stage'],
354 env=env)
355
356 def set_hostname(self, rootdir):
357 hostname = self.settings['hostname']
358 with open(os.path.join(rootdir, 'etc', 'hostname'), 'w') as f:
359 f.write('%s\n' % hostname)
360
361 etc_hosts = os.path.join(rootdir, 'etc', 'hosts')
362 try:
363 with open(etc_hosts, 'r') as f:
364 data = f.read()
365 with open(etc_hosts, 'w') as f:
366 for line in data.splitlines():
367 if line.startswith('127.0.0.1'):
368 line += ' %s' % hostname
369 f.write('%s\n' % line)
370 except IOError:
371 pass
372
373 def create_fstab(self, rootdir, rootdev, roottype, bootdev, boottype):
374 def fsuuid(device):
375 out = self.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
376 '-s', 'UUID', device])
377 return out.splitlines()[0].strip()
378
379 if rootdev:
380 rootdevstr = 'UUID=%s' % fsuuid(rootdev)
381 else:
382 rootdevstr = '/dev/sda1'
383
384 if bootdev:
385 bootdevstr = 'UUID=%s' % fsuuid(bootdev)
386 else:
387 bootdevstr = None
388
389 fstab = os.path.join(rootdir, 'etc', 'fstab')
390 with open(fstab, 'w') as f:
391 f.write('proc /proc proc defaults 0 0\n')
392 f.write('%s / %s errors=remount-ro 0 1\n' % (rootdevstr, roottype))
393 if bootdevstr:
394 f.write('%s /boot %s errors=remount-ro 0 2\n' % (bootdevstr, boottype))
395
396 def install_debs(self, rootdir):
397 if not self.settings['custom-package']:
398 return
399 self.message('Installing custom packages')
400 tmp = os.path.join(rootdir, 'tmp', 'install_debs')
401 os.mkdir(tmp)
402 for deb in self.settings['custom-package']:
403 shutil.copy(deb, tmp)
404 filenames = [os.path.join('/tmp/install_debs', os.path.basename(deb))
405 for deb in self.settings['custom-package']]
406 out, err, exitcode = \
407 self.runcmd_unchecked(['chroot', rootdir, 'dpkg', '-i'] + filenames)
408 logging.debug('stdout:\n%s', out)
409 logging.debug('stderr:\n%s', err)
410 out = self.runcmd(['chroot', rootdir,
411 'apt-get', '-f', '--no-remove', 'install'])
412 logging.debug('stdout:\n%s', out)
413 shutil.rmtree(tmp)
414
415 def cleanup_apt_cache(self, rootdir):
416 out = self.runcmd(['chroot', rootdir, 'apt-get', 'clean'])
417 logging.debug('stdout:\n%s', out)
418
419 def set_root_password(self, rootdir):
420 if self.settings['root-password']:
421 self.message('Setting root password')
422 self.set_password(rootdir, 'root', self.settings['root-password'])
423 elif self.settings['lock-root-password']:
424 self.message('Locking root password')
425 self.runcmd(['chroot', rootdir, 'passwd', '-l', 'root'])
426 else:
427 self.message('Give root an empty password')
428 self.delete_password(rootdir, 'root')
429
430 def create_users(self, rootdir):
431 def create_user(user):
432 self.runcmd(['chroot', rootdir, 'adduser', '--gecos', user,
433 '--disabled-password', user])
434 if self.settings['sudo']:
435 self.runcmd(['chroot', rootdir, 'adduser', user, 'sudo'])
436
437 for userpass in self.settings['user']:
438 if '/' in userpass:
439 user, password = userpass.split('/', 1)
440 create_user(user)
441 self.set_password(rootdir, user, password)
442 else:
443 create_user(userpass)
444 self.delete_password(rootdir, userpass)
445
446 def set_password(self, rootdir, user, password):
447 encrypted = crypt.crypt(password, '..')
448 self.runcmd(['chroot', rootdir, 'usermod', '-p', encrypted, user])
449
450 def delete_password(self, rootdir, user):
451 self.runcmd(['chroot', rootdir, 'passwd', '-d', user])
452
453 def remove_udev_persistent_rules(self, rootdir):
454 self.message('Removing udev persistent cd and net rules')
455 for x in ['70-persistent-cd.rules', '70-persistent-net.rules']:
456 pathname = os.path.join(rootdir, 'etc', 'udev', 'rules.d', x)
457 if os.path.exists(pathname):
458 logging.debug('rm %s', pathname)
459 os.remove(pathname)
460 else:
461 logging.debug('not removing non-existent %s', pathname)
462
463 def setup_networking(self, rootdir):
464 self.message('Setting up networking')
465
466 f = open(os.path.join(rootdir, 'etc', 'network', 'interfaces'), 'w')
467 f.write('auto lo\n')
468 f.write('iface lo inet loopback\n')
469
470 if self.settings['enable-dhcp']:
471 f.write('\n')
472 f.write('auto eth0\n')
473 f.write('iface eth0 inet dhcp\n')
474
475 f.close()
476
477 def append_serial_console(self, rootdir):
478 if self.settings['serial-console']:
479 serial_command = self.settings['serial-console-command']
480 logging.debug('adding getty to serial console')
481 inittab = os.path.join(rootdir, 'etc/inittab')
482 # to autologin, serial_command can contain '-a root'
483 with open(inittab, 'a') as f:
484 f.write('\nS0:23:respawn:%s\n' % serial_command)
485
486 def install_grub2(self, rootdev, rootdir):
487 self.message("Configuring grub2")
488 # rely on kpartx using consistent naming to map loop0p1 to loop0
489 install_dev = os.path.join('/dev', os.path.basename(rootdev)[:-2])
490 self.runcmd(['mount', '/dev', '-t', 'devfs', '-obind',
491 '%s' % os.path.join(rootdir, 'dev')])
492 self.runcmd(['mount', '/proc', '-t', 'proc', '-obind',
493 '%s' % os.path.join(rootdir, 'proc')])
494 self.runcmd(['mount', '/sys', '-t', 'sysfs', '-obind',
495 '%s' % os.path.join(rootdir, 'sys')])
496 try:
497 self.runcmd(['chroot', rootdir, 'update-grub'])
498 self.runcmd(['chroot', rootdir, 'grub-install', install_dev])
499 except cliapp.AppException as e:
500 self.message("Failed. Is grub2-common installed? Using extlinux.")
501 self.runcmd(['umount', os.path.join(rootdir, 'sys')])
502 self.runcmd(['umount', os.path.join(rootdir, 'proc')])
503 self.runcmd(['umount', os.path.join(rootdir, 'dev')])
504 self.install_extlinux(rootdev, rootdir)
505
506 def install_extlinux(self, rootdev, rootdir):
507 if not os.path.exists("/usr/bin/extlinux"):
508 self.message("extlinux not installed, skipping.")
509 return
510 self.message('Installing extlinux')
511
512 def find(pattern):
513 dirname = os.path.join(rootdir, 'boot')
514 basenames = os.listdir(dirname)
515 logging.debug('find: %s', basenames)
516 for basename in basenames:
517 if re.search(pattern, basename):
518 return os.path.join('boot', basename)
519 raise cliapp.AppException('Cannot find match: %s' % pattern)
520
521 try:
522 kernel_image = find('vmlinuz-.*')
523 initrd_image = find('initrd.img-.*')
524 except cliapp.AppException as e:
525 self.message("Unable to find kernel. Not installing extlinux.")
526 logging.debug("No kernel found. %s. Skipping install of extlinux.", e)
527 return
528
529 out = self.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
530 '-s', 'UUID', rootdev])
531 uuid = out.splitlines()[0].strip()
532
533 conf = os.path.join(rootdir, 'extlinux.conf')
534 logging.debug('configure extlinux %s', conf)
535 f = open(conf, 'w')
536 f.write('''
537 default linux
538 timeout 1
539
540 label linux
541 kernel %(kernel)s
542 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
543 %(extserial)s
544 ''' % {
545 'kernel': kernel_image,
546 'initrd': initrd_image,
547 'uuid': uuid,
548 'kserial':
549 'console=ttyS0,115200' if self.settings['serial-console'] else '',
550 'extserial': 'serial 0 115200' if self.settings['serial-console'] else '',
551 })
552 f.close()
553
554 self.runcmd(['extlinux', '--install', rootdir])
555 self.runcmd(['sync'])
556 time.sleep(2)
557
558 def optimize_image(self, rootdir):
559 """
560 Filing up the image with zeros will increase its compression rate
561 """
562 if not self.settings['sparse']:
563 zeros = os.path.join(rootdir, 'ZEROS')
564 self.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros, 'bs=1M'])
565 self.runcmd(['rm', '-f', zeros])
566
567 def squash(self):
568 """
569 Run squashfs on the image.
570 """
571 if not os.path.exists('/usr/bin/mksquashfs'):
572 logging.warning("Squash selected but mksquashfs not found!")
573 return
574 self.message("Running mksquashfs")
575 suffixed = "%s.squashfs" % self.settings['image']
576 self.runcmd(['mksquashfs', self.settings['image'],
577 suffixed,
578 '-no-progress', '-comp', 'xz'], ignore_fail=False)
579 os.unlink(self.settings['image'])
580 self.settings['image'] = suffixed
581
582 def cleanup_system(self):
583 # Clean up after any errors.
584
585 self.message('Cleaning up')
586
587 # Umount in the reverse mount order
588 if self.settings['image']:
589 for i in xrange(len(self.mount_points) - 1, -1, -1):
590 mount_point = self.mount_points[i]
591 try:
592 self.runcmd(['umount', mount_point], ignore_fail=False)
593 except cliapp.AppException:
594 logging.debug("umount failed, sleeping and trying again")
595 time.sleep(5)
596 self.runcmd(['umount', mount_point], ignore_fail=False)
597
598 self.runcmd(['kpartx', '-d', self.settings['image']], ignore_fail=True)
599
600 for dirname in self.remove_dirs:
601 shutil.rmtree(dirname)
602
603 def customize(self, rootdir):
604 script = self.settings['customize']
605 if not script:
606 return
607 if not os.path.exists(script):
608 example = os.path.join("/usr/share/vmdebootstrap/examples/", script)
609 if not os.path.exists(example):
610 self.message("Unable to find %s" % script)
611 return
612 script = example
613 self.message('Running customize script %s' % script)
614 with open('/dev/tty', 'w') as tty:
615 cliapp.runcmd([script, rootdir], stdout=tty, stderr=tty)
616
617 def create_tarball(self, rootdir):
618 # Create a tarball of the disk's contents
619 # shell out to runcmd since it more easily handles rootdir
620 self.message('Creating tarball of disk contents')
621 self.runcmd(['tar', '-cf', self.settings['tarball'], '-C', rootdir, '.'])
622
623 def chown(self, rootdir):
624 # Change image owner after completed build
625 self.message("Changing owner to %s" % self.settings["owner"])
626 subprocess.call(["chown",
627 self.settings["owner"],
628 self.settings["image"]])
629
630 def list_installed_pkgs(self, rootdir):
631 # output the list of installed packages for sources identification
632 self.message("Creating a list of installed binary package names")
633 out = self.runcmd(['chroot', rootdir,
634 'dpkg-query', '-W' "-f='${Package}.deb\n'"])
635 with open('dpkg.list', 'w') as dpkg:
636 dpkg.write(out)
637
638 def configure_apt(self, rootdir):
639 # use the distribution and mirror to create an apt source
640 self.message("Configuring apt to use distribution and mirror")
641 conf = os.path.join(rootdir, 'etc', 'apt', 'sources.list.d', 'base.list')
642 logging.debug('configure apt %s', conf)
643 mirror = self.settings['mirror']
644 if self.settings['apt-mirror']:
645 mirror = self.settings['apt-mirror']
646 self.message("Setting apt mirror to %s" % mirror)
647 os.unlink(os.path.join(rootdir, 'etc', 'apt', 'sources.list'))
648 f = open(conf, 'w')
649 f.write('''
650 deb %(mirror)s %(distribution)s main
651 #deb-src %(mirror)s %(distribution)s main
652 ''' % {
653 'mirror': mirror,
654 'distribution': self.settings['distribution']
655 })
656 f.close()
657
658 if __name__ == '__main__':
659 VmDebootstrap(version=__version__).run()