]>
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
.append_serial_console(rootdir
)
155 self
.optimize_image(rootdir
)
157 if self
.settings
['foreign']:
158 os
.unlink('%s/usr/bin/%s' %
159 (rootdir
, os
.path
.basename(self
.settings
['foreign'])))
161 if self
.settings
['tarball']:
162 self
.create_tarball(rootdir
)
164 if self
.settings
['owner']:
166 except BaseException
, e
:
167 self
.message('EEEK! Something bad happened...')
169 self
.cleanup_system()
172 self
.cleanup_system()
174 def message(self
, msg
):
176 if self
.settings
['verbose']:
179 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
180 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
181 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
182 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
184 out
, err
= p
.communicate(stdin
)
185 if p
.returncode
!= 0:
186 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
189 raise cliapp
.AppException(msg
)
193 dirname
= tempfile
.mkdtemp()
194 self
.remove_dirs
.append(dirname
)
195 logging
.debug('mkdir %s' % dirname
)
198 def mount(self
, device
, path
=None):
200 mount_point
= self
.mkdtemp()
203 self
.message('Mounting %s on %s' % (device
,mount_point
))
204 self
.runcmd(['mount', device
, mount_point
])
205 self
.mount_points
.append(mount_point
)
206 logging
.debug('mounted %s on %s' % (device
, mount_point
))
209 def create_empty_image(self
):
210 self
.message('Creating disk image')
211 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
212 self
.settings
['image'],
213 str(self
.settings
['size'])])
215 def partition_image(self
):
216 self
.message('Creating partitions')
217 self
.runcmd(['parted', '-s', self
.settings
['image'],
219 if self
.settings
['bootsize'] and self
.settings
['bootsize'] is not '0%':
220 bootsize
=str(self
.settings
['bootsize']/(1024*1024))
221 self
.runcmd(['parted', '-s', self
.settings
['image'],
222 'mkpart', 'primary', 'fat16', '0', bootsize
])
225 self
.runcmd(['parted', '-s', self
.settings
['image'],
226 'mkpart', 'primary', bootsize
, '100%'])
227 self
.runcmd(['parted', '-s', self
.settings
['image'],
228 'set', '1', 'boot', 'on'])
230 def install_mbr(self
):
231 self
.message('Installing MBR')
232 self
.runcmd(['install-mbr', self
.settings
['image']])
234 def setup_kpartx(self
):
235 out
= self
.runcmd(['kpartx', '-avs', self
.settings
['image']])
236 if self
.settings
['bootsize']:
244 devices
= [line
.split()[2]
245 for line
in out
.splitlines()
246 if line
.startswith('add map ')]
247 if len(devices
) != parts
:
248 raise cliapp
.AppException('Surprising number of partitions')
249 root
= '/dev/mapper/%s' % devices
[rootindex
]
250 if self
.settings
['bootsize']:
251 boot
= '/dev/mapper/%s' % devices
[bootindex
]
254 def mkfs(self
, device
, type):
255 self
.message('Creating filesystem %s' % type)
256 self
.runcmd(['mkfs', '-t', type, device
])
258 def debootstrap(self
, rootdir
):
259 self
.message('Debootstrapping')
261 if self
.settings
['foreign']:
262 necessary_packages
= []
264 necessary_packages
= ['acpid']
266 include
= self
.settings
['package']
268 if not self
.settings
['no-kernel']:
269 if self
.settings
['arch'] == 'i386':
272 kernel_arch
= self
.settings
['arch']
273 kernel_image
= 'linux-image-%s' % kernel_arch
274 include
.append(kernel_image
)
276 if self
.settings
['sudo'] and 'sudo' not in include
:
277 include
.append('sudo')
279 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
281 '--include=%s' % ','.join(necessary_packages
+ include
))
282 if self
.settings
['foreign']:
283 args
.append('--foreign')
284 if self
.settings
['variant']:
285 args
.append('--variant')
286 args
.append(self
.settings
['variant'])
287 args
+= [self
.settings
['distribution'],
288 rootdir
, self
.settings
['mirror']]
290 if self
.settings
['foreign']:
291 # First copy the binfmt handler over
292 shutil
.copy(self
.settings
['foreign'], '%s/usr/bin/' % rootdir
)
293 # Next, run the package install scripts etc.
294 self
.runcmd(['chroot', rootdir
,
295 '/debootstrap/debootstrap', '--second-stage'])
297 def set_hostname(self
, rootdir
):
298 hostname
= self
.settings
['hostname']
299 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
300 f
.write('%s\n' % hostname
)
302 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
304 with
open(etc_hosts
, 'r') as f
:
306 with
open(etc_hosts
, 'w') as f
:
307 for line
in data
.splitlines():
308 if line
.startswith('127.0.0.1'):
309 line
+= ' %s' % hostname
310 f
.write('%s\n' % line
)
314 def create_fstab(self
, rootdir
, rootdev
, roottype
, bootdev
, boottype
):
316 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
317 '-s', 'UUID', device
])
318 return out
.splitlines()[0].strip()
321 rootdevstr
= 'UUID=%s' % fsuuid(rootdev
)
323 rootdevstr
= '/dev/sda1'
326 bootdevstr
= 'UUID=%s' % fsuuid(bootdev
)
330 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
331 with
open(fstab
, 'w') as f
:
332 f
.write('proc /proc proc defaults 0 0\n')
333 f
.write('%s / %s errors=remount-ro 0 1\n' % (rootdevstr
, roottype
))
335 f
.write('%s /boot %s errors=remount-ro 0 2\n' % (bootdevstr
, boottype
))
337 def install_debs(self
, rootdir
):
338 if not self
.settings
['custom-package']:
340 self
.message('Installing custom packages')
341 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
343 for deb
in self
.settings
['custom-package']:
344 shutil
.copy(deb
, tmp
)
345 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
346 for deb
in self
.settings
['custom-package']]
348 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
349 logging
.debug('stdout:\n%s' % out
)
350 logging
.debug('stderr:\n%s' % err
)
351 out
= self
.runcmd(['chroot', rootdir
,
352 'apt-get', '-f', '--no-remove', 'install'])
353 logging
.debug('stdout:\n%s' % out
)
356 def cleanup_apt_cache(self
, rootdir
):
357 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
358 logging
.debug('stdout:\n%s' % out
)
360 def set_root_password(self
, rootdir
):
361 if self
.settings
['root-password']:
362 self
.message('Setting root password')
363 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
364 elif self
.settings
['lock-root-password']:
365 self
.message('Locking root password')
366 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
368 self
.message('Give root an empty password')
369 self
.delete_password(rootdir
, 'root')
371 def create_users(self
, rootdir
):
372 def create_user(user
):
373 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
374 '--disabled-password', user
])
375 if self
.settings
['sudo']:
376 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
378 for userpass
in self
.settings
['user']:
380 user
, password
= userpass
.split('/', 1)
382 self
.set_password(rootdir
, user
, password
)
384 create_user(userpass
)
385 self
.delete_password(rootdir
, userpass
)
387 def set_password(self
, rootdir
, user
, password
):
388 encrypted
= crypt
.crypt(password
, '..')
389 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
391 def delete_password(self
, rootdir
, user
):
392 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
394 def remove_udev_persistent_rules(self
, rootdir
):
395 self
.message('Removing udev persistent cd and net rules')
396 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
397 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
398 if os
.path
.exists(pathname
):
399 logging
.debug('rm %s' % pathname
)
402 logging
.debug('not removing non-existent %s' % pathname
)
404 def setup_networking(self
, rootdir
):
405 self
.message('Setting up networking')
407 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
409 f
.write('iface lo inet loopback\n')
411 if self
.settings
['enable-dhcp']:
413 f
.write('auto eth0\n')
414 f
.write('iface eth0 inet dhcp\n')
418 def append_serial_console(self
, rootdir
):
419 if self
.settings
['serial-console']:
420 serial_command
= self
.settings
['serial-console-command']
421 logging
.debug('adding getty to serial console')
422 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
423 with
open(inittab
, 'a') as f
:
424 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
426 def install_extlinux(self
, rootdev
, rootdir
):
427 self
.message('Installing extlinux')
430 dirname
= os
.path
.join(rootdir
, 'boot')
431 basenames
= os
.listdir(dirname
)
432 logging
.debug('find: %s' % basenames
)
433 for basename
in basenames
:
434 if re
.search(pattern
, basename
):
435 return os
.path
.join('boot', basename
)
436 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
438 kernel_image
= find('vmlinuz-.*')
439 initrd_image
= find('initrd.img-.*')
441 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
442 '-s', 'UUID', rootdev
])
443 uuid
= out
.splitlines()[0].strip()
445 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
446 logging
.debug('configure extlinux %s' % conf
)
454 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
457 'kernel': kernel_image
,
458 'initrd': initrd_image
,
461 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
462 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
466 self
.runcmd(['extlinux', '--install', rootdir
])
467 self
.runcmd(['sync'])
468 import time
; time
.sleep(2)
470 def optimize_image(self
, rootdir
):
472 Filing up the image with zeros will increase its compression rate
474 zeros
= os
.path
.join(rootdir
, 'ZEROS')
475 self
.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros
, 'bs=1M'])
476 self
.runcmd(['rm', '-f', zeros
])
479 def cleanup_system(self
):
480 # Clean up after any errors.
482 self
.message('Cleaning up')
484 # Umount in the reverse mount order
485 if self
.settings
['image']:
486 for i
in xrange(len(self
.mount_points
) - 1, -1, -1):
487 mount_point
= self
.mount_points
[i
]
489 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
490 except cliapp
.AppException
:
491 logging
.debug("umount failed, sleeping and trying again")
493 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
495 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
497 for dirname
in self
.remove_dirs
:
498 shutil
.rmtree(dirname
)
500 def customize(self
, rootdir
):
501 script
= self
.settings
['customize']
503 self
.message('Running customize script %s' % script
)
504 with
open('/dev/tty', 'w') as tty
:
505 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
507 def create_tarball(self
, rootdir
):
508 # Create a tarball of the disk's contents
509 # shell out to runcmd since it more easily handles rootdir
510 self
.message('Creating tarball of disk contents')
511 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
513 def chown(self
, rootdir
):
514 # Change image owner after completed build
515 self
.message("Changing owner to %s" % self
.settings
["owner"])
516 subprocess
.call(["chown",
517 self
.settings
["owner"],
518 self
.settings
["image"]])
521 if __name__
== '__main__':
522 VmDebootstrap(version
=__version__
).run()