]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
2 # Copyright 2011-2013 Lars Wirzenius
3 # Copyright 2012 Codethink Limited
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.
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.
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/>.
32 class VmDebootstrap(cliapp
.Application
):
34 def add_settings(self
):
35 default_arch
= 'amd64'
37 self
.settings
.boolean(['verbose'], 'report what is going on')
38 self
.settings
.string(['image'], 'put created disk image in FILE',
40 self
.settings
.bytesize(['size'],
41 'create a disk image of size SIZE (%default)',
44 self
.settings
.bytesize(['bootsize'],
45 'create boot partition of size SIZE (%default)',
48 self
.settings
.string(['boottype'],
49 'specify file system type for /boot/',
51 self
.settings
.string(['foreign'],
52 'set up foreign debootstrap environment using provided program (ie binfmt handler)')
53 self
.settings
.string(['variant'],
54 'select debootstrap variant it not using the default')
55 self
.settings
.boolean(
59 self
.settings
.string(['tarball'], "tar up the disk's contents in FILE",
61 self
.settings
.string(['mirror'],
62 'use MIRROR as package source (%default)',
64 default
='http://cdn.debian.net/debian/')
65 self
.settings
.string(['arch'], 'architecture to use (%default)',
68 self
.settings
.string(['distribution'],
69 'release to use (%default)',
72 self
.settings
.string_list(['package'], 'install PACKAGE onto system')
73 self
.settings
.string_list(['custom-package'],
74 'install package in DEB file onto system '
77 self
.settings
.boolean(['no-kernel'], 'do not install a linux package')
78 self
.settings
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
79 self
.settings
.string(['root-password'], 'set root password',
81 self
.settings
.boolean(['lock-root-password'],
82 'lock root account so they cannot login?')
83 self
.settings
.string(['customize'],
84 'run SCRIPT after setting up system',
86 self
.settings
.string(['hostname'],
87 'set name to HOSTNAME (%default)',
90 self
.settings
.string_list(['user'],
91 'create USER with PASSWORD',
92 metavar
='USER/PASSWORD')
93 self
.settings
.boolean(['serial-console'],
94 'configure image to use a serial console')
95 self
.settings
.string(['serial-console-command'],
96 'command to manage the serial console, appended '
97 'to /etc/inittab (%default)',
99 default
='/sbin/getty -L ttyS0 115200 vt100')
100 self
.settings
.boolean(['sudo'],
101 'install sudo, and if user is created, add them '
103 self
.settings
.string(['owner'],
104 'the user who will own the image when the build '
107 def process_args(self
, args
):
108 if not self
.settings
['image'] and not self
.settings
['tarball']:
109 raise cliapp
.AppException('You must give disk image filename, '
110 'or tarball filename')
111 if self
.settings
['image'] and not self
.settings
['size']:
112 raise cliapp
.AppException('If disk image is specified, '
113 'You must give image size.')
115 self
.remove_dirs
= []
116 self
.mount_points
= []
123 if self
.settings
['image']:
124 self
.create_empty_image()
125 self
.partition_image()
127 (rootdev
,bootdev
) = self
.setup_kpartx()
128 self
.mkfs(rootdev
, type=roottype
)
129 rootdir
= self
.mount(rootdev
)
131 if self
.settings
['boottype']:
132 boottype
= self
.settings
['boottype']
135 self
.mkfs(bootdev
, type=boottype
)
136 bootdir
= '%s/%s' % (rootdir
, 'boot/')
138 bootdir
= self
.mount(bootdev
, bootdir
)
140 rootdir
= self
.mkdtemp()
141 self
.debootstrap(rootdir
)
142 self
.set_hostname(rootdir
)
143 self
.create_fstab(rootdir
, rootdev
, roottype
, bootdev
, boottype
)
144 self
.install_debs(rootdir
)
145 self
.cleanup_apt_cache(rootdir
)
146 self
.set_root_password(rootdir
)
147 self
.create_users(rootdir
)
148 self
.remove_udev_persistent_rules(rootdir
)
149 self
.setup_networking(rootdir
)
150 self
.customize(rootdir
)
151 if self
.settings
['image']:
152 if self
.settings
['extlinux']:
153 self
.install_extlinux(rootdev
, rootdir
)
154 self
.optimize_image(rootdir
)
156 if self
.settings
['foreign']:
157 os
.unlink('%s/usr/bin/%s' %
158 (rootdir
, os
.path
.basename(self
.settings
['foreign'])))
160 if self
.settings
['tarball']:
161 self
.create_tarball(rootdir
)
163 if self
.settings
['owner']:
165 except BaseException
, e
:
166 self
.message('EEEK! Something bad happened...')
168 self
.cleanup_system()
171 self
.cleanup_system()
173 def message(self
, msg
):
175 if self
.settings
['verbose']:
178 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
179 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
180 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
181 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
183 out
, err
= p
.communicate(stdin
)
184 if p
.returncode
!= 0:
185 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
188 raise cliapp
.AppException(msg
)
192 dirname
= tempfile
.mkdtemp()
193 self
.remove_dirs
.append(dirname
)
194 logging
.debug('mkdir %s' % dirname
)
197 def mount(self
, device
, path
=None):
199 mount_point
= self
.mkdtemp()
202 self
.message('Mounting %s on %s' % (device
,mount_point
))
203 self
.runcmd(['mount', device
, mount_point
])
204 self
.mount_points
.append(mount_point
)
205 logging
.debug('mounted %s on %s' % (device
, mount_point
))
208 def create_empty_image(self
):
209 self
.message('Creating disk image')
210 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
211 self
.settings
['image'],
212 str(self
.settings
['size'])])
214 def partition_image(self
):
215 self
.message('Creating partitions')
216 self
.runcmd(['parted', '-s', self
.settings
['image'],
218 if self
.settings
['bootsize'] and self
.settings
['bootsize'] is not '0%':
219 bootsize
=str(self
.settings
['bootsize']/(1024*1024))
220 self
.runcmd(['parted', '-s', self
.settings
['image'],
221 'mkpart', 'primary', 'fat16', '0', bootsize
])
224 self
.runcmd(['parted', '-s', self
.settings
['image'],
225 'mkpart', 'primary', bootsize
, '100%'])
226 self
.runcmd(['parted', '-s', self
.settings
['image'],
227 'set', '1', 'boot', 'on'])
229 def install_mbr(self
):
230 self
.message('Installing MBR')
231 self
.runcmd(['install-mbr', self
.settings
['image']])
233 def setup_kpartx(self
):
234 out
= self
.runcmd(['kpartx', '-avs', self
.settings
['image']])
235 if self
.settings
['bootsize']:
243 devices
= [line
.split()[2]
244 for line
in out
.splitlines()
245 if line
.startswith('add map ')]
246 if len(devices
) != parts
:
247 raise cliapp
.AppException('Surprising number of partitions')
248 root
= '/dev/mapper/%s' % devices
[rootindex
]
249 if self
.settings
['bootsize']:
250 boot
= '/dev/mapper/%s' % devices
[bootindex
]
253 def mkfs(self
, device
, type):
254 self
.message('Creating filesystem %s' % type)
255 self
.runcmd(['mkfs', '-t', type, device
])
257 def debootstrap(self
, rootdir
):
258 self
.message('Debootstrapping')
260 if self
.settings
['foreign']:
261 necessary_packages
= []
263 necessary_packages
= ['acpid']
265 include
= self
.settings
['package']
267 if not self
.settings
['no-kernel']:
268 if self
.settings
['arch'] == 'i386':
271 kernel_arch
= self
.settings
['arch']
272 kernel_image
= 'linux-image-%s' % kernel_arch
273 include
.append(kernel_image
)
275 if self
.settings
['sudo'] and 'sudo' not in include
:
276 include
.append('sudo')
278 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
280 '--include=%s' % ','.join(necessary_packages
+ include
))
281 if self
.settings
['foreign']:
282 args
.append('--foreign')
283 if self
.settings
['variant']:
284 args
.append('--variant')
285 args
.append(self
.settings
['variant'])
286 args
+= [self
.settings
['distribution'],
287 rootdir
, self
.settings
['mirror']]
289 if self
.settings
['foreign']:
290 # First copy the binfmt handler over
291 shutil
.copy(self
.settings
['foreign'], '%s/usr/bin/' % rootdir
)
292 # Next, run the package install scripts etc.
293 self
.runcmd(['chroot', rootdir
,
294 '/debootstrap/debootstrap', '--second-stage'])
296 def set_hostname(self
, rootdir
):
297 hostname
= self
.settings
['hostname']
298 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
299 f
.write('%s\n' % hostname
)
301 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
303 with
open(etc_hosts
, 'r') as f
:
305 with
open(etc_hosts
, 'w') as f
:
306 for line
in data
.splitlines():
307 if line
.startswith('127.0.0.1'):
308 line
+= ' %s' % hostname
309 f
.write('%s\n' % line
)
313 def create_fstab(self
, rootdir
, rootdev
, roottype
, bootdev
, boottype
):
315 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
316 '-s', 'UUID', device
])
317 return out
.splitlines()[0].strip()
320 rootdevstr
= 'UUID=%s' % fsuuid(rootdev
)
322 rootdevstr
= '/dev/sda1'
325 bootdevstr
= 'UUID=%s' % fsuuid(bootdev
)
329 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
330 with
open(fstab
, 'w') as f
:
331 f
.write('proc /proc proc defaults 0 0\n')
332 f
.write('%s / %s errors=remount-ro 0 1\n' % (rootdevstr
, roottype
))
334 f
.write('%s /boot %s errors=remount-ro 0 2\n' % (bootdevstr
, boottype
))
336 def install_debs(self
, rootdir
):
337 if not self
.settings
['custom-package']:
339 self
.message('Installing custom packages')
340 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
342 for deb
in self
.settings
['custom-package']:
343 shutil
.copy(deb
, tmp
)
344 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
345 for deb
in self
.settings
['custom-package']]
347 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
348 logging
.debug('stdout:\n%s' % out
)
349 logging
.debug('stderr:\n%s' % err
)
350 out
= self
.runcmd(['chroot', rootdir
,
351 'apt-get', '-f', '--no-remove', 'install'])
352 logging
.debug('stdout:\n%s' % out
)
355 def cleanup_apt_cache(self
, rootdir
):
356 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
357 logging
.debug('stdout:\n%s' % out
)
359 def set_root_password(self
, rootdir
):
360 if self
.settings
['root-password']:
361 self
.message('Setting root password')
362 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
363 elif self
.settings
['lock-root-password']:
364 self
.message('Locking root password')
365 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
367 self
.message('Give root an empty password')
368 self
.delete_password(rootdir
, 'root')
370 def create_users(self
, rootdir
):
371 def create_user(user
):
372 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
373 '--disabled-password', user
])
374 if self
.settings
['sudo']:
375 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
377 for userpass
in self
.settings
['user']:
379 user
, password
= userpass
.split('/', 1)
381 self
.set_password(rootdir
, user
, password
)
383 create_user(userpass
)
384 self
.delete_password(rootdir
, userpass
)
386 def set_password(self
, rootdir
, user
, password
):
387 encrypted
= crypt
.crypt(password
, '..')
388 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
390 def delete_password(self
, rootdir
, user
):
391 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
393 def remove_udev_persistent_rules(self
, rootdir
):
394 self
.message('Removing udev persistent cd and net rules')
395 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
396 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
397 if os
.path
.exists(pathname
):
398 logging
.debug('rm %s' % pathname
)
401 logging
.debug('not removing non-existent %s' % pathname
)
403 def setup_networking(self
, rootdir
):
404 self
.message('Setting up networking')
406 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
408 f
.write('iface lo inet loopback\n')
410 if self
.settings
['enable-dhcp']:
412 f
.write('auto eth0\n')
413 f
.write('iface eth0 inet dhcp\n')
417 def install_extlinux(self
, rootdev
, rootdir
):
418 self
.message('Installing extlinux')
421 dirname
= os
.path
.join(rootdir
, 'boot')
422 basenames
= os
.listdir(dirname
)
423 logging
.debug('find: %s' % basenames
)
424 for basename
in basenames
:
425 if re
.search(pattern
, basename
):
426 return os
.path
.join('boot', basename
)
427 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
429 kernel_image
= find('vmlinuz-.*')
430 initrd_image
= find('initrd.img-.*')
432 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
433 '-s', 'UUID', rootdev
])
434 uuid
= out
.splitlines()[0].strip()
436 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
437 logging
.debug('configure extlinux %s' % conf
)
445 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
448 'kernel': kernel_image
,
449 'initrd': initrd_image
,
452 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
453 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
457 if self
.settings
['serial-console']:
458 serial_command
= self
.settings
['serial-console-command']
459 logging
.debug('adding getty to serial console')
460 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
461 with
open(inittab
, 'a') as f
:
462 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
464 self
.runcmd(['extlinux', '--install', rootdir
])
465 self
.runcmd(['sync'])
466 import time
; time
.sleep(2)
468 def optimize_image(self
, rootdir
):
470 Filing up the image with zeros will increase its compression rate
472 zeros
= os
.path
.join(rootdir
, 'ZEROS')
473 self
.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros
, 'bs=1M'])
474 self
.runcmd(['rm', '-f', zeros
])
477 def cleanup_system(self
):
478 # Clean up after any errors.
480 self
.message('Cleaning up')
482 # Umount in the reverse mount order
483 if self
.settings
['image']:
484 for i
in xrange(len(self
.mount_points
) - 1, -1, -1):
485 mount_point
= self
.mount_points
[i
]
487 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
488 except cliapp
.AppException
:
489 logging
.debug("umount failed, sleeping and trying again")
491 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
493 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
495 for dirname
in self
.remove_dirs
:
496 shutil
.rmtree(dirname
)
498 def customize(self
, rootdir
):
499 script
= self
.settings
['customize']
501 self
.message('Running customize script %s' % script
)
502 with
open('/dev/tty', 'w') as tty
:
503 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
505 def create_tarball(self
, rootdir
):
506 # Create a tarball of the disk's contents
507 # shell out to runcmd since it more easily handles rootdir
508 self
.message('Creating tarball of disk contents')
509 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
511 def chown(self
, rootdir
):
512 # Change image owner after completed build
513 self
.message("Changing owner to %s" % self
.settings
["owner"])
514 subprocess
.call(["chown",
515 self
.settings
["owner"],
516 self
.settings
["image"]])
519 if __name__
== '__main__':
520 VmDebootstrap(version
=__version__
).run()