]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
77da850c1b2a627ca06d7bd1bbf4970dfa515d8e
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 '
104 def process_args(self
, args
):
105 if not self
.settings
['image'] and not self
.settings
['tarball']:
106 raise cliapp
.AppException('You must give disk image filename, '
107 'or tarball filename')
108 if self
.settings
['image'] and not self
.settings
['size']:
109 raise cliapp
.AppException('If disk image is specified, '
110 'You must give image size.')
112 self
.remove_dirs
= []
113 self
.mount_points
= []
120 if self
.settings
['image']:
121 self
.create_empty_image()
122 self
.partition_image()
124 (rootdev
,bootdev
) = self
.setup_kpartx()
125 self
.mkfs(rootdev
, type=roottype
)
126 rootdir
= self
.mount(rootdev
)
128 if self
.settings
['boottype']:
129 boottype
= self
.settings
['boottype']
132 self
.mkfs(bootdev
, type=boottype
)
133 bootdir
= '%s/%s' % (rootdir
, 'boot/')
135 bootdir
= self
.mount(bootdev
, bootdir
)
137 rootdir
= self
.mkdtemp()
138 self
.debootstrap(rootdir
)
139 self
.set_hostname(rootdir
)
140 self
.create_fstab(rootdir
, rootdev
, roottype
, bootdev
, boottype
)
141 self
.install_debs(rootdir
)
142 self
.cleanup_apt_cache(rootdir
)
143 self
.set_root_password(rootdir
)
144 self
.create_users(rootdir
)
145 self
.remove_udev_persistent_rules(rootdir
)
146 self
.setup_networking(rootdir
)
147 self
.customize(rootdir
)
148 if self
.settings
['image']:
149 if not self
.settings
['no-extlinux']:
150 self
.install_extlinux(rootdev
, rootdir
)
151 self
.optimize_image(rootdir
)
153 if self
.settings
['foreign']:
154 os
.unlink('%s/usr/bin/%s' %
155 (rootdir
, os
.path
.basename(self
.settings
['foreign'])))
157 if self
.settings
['tarball']:
158 self
.create_tarball(rootdir
)
159 except BaseException
, e
:
160 self
.message('EEEK! Something bad happened...')
161 self
.cleanup_system()
164 self
.cleanup_system()
166 def message(self
, msg
):
168 if self
.settings
['verbose']:
171 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
172 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
173 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
174 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
176 out
, err
= p
.communicate(stdin
)
177 if p
.returncode
!= 0:
178 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
181 raise cliapp
.AppException(msg
)
185 dirname
= tempfile
.mkdtemp()
186 self
.remove_dirs
.append(dirname
)
187 logging
.debug('mkdir %s' % dirname
)
190 def mount(self
, device
, path
=None):
192 mount_point
= self
.mkdtemp()
195 self
.message('Mounting %s on %s' % (device
,mount_point
))
196 self
.runcmd(['mount', device
, mount_point
])
197 self
.mount_points
.append(mount_point
)
198 logging
.debug('mounted %s on %s' % (device
, mount_point
))
201 def create_empty_image(self
):
202 self
.message('Creating disk image')
203 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
204 self
.settings
['image'],
205 str(self
.settings
['size'])])
207 def partition_image(self
):
208 self
.message('Creating partitions')
209 self
.runcmd(['parted', '-s', self
.settings
['image'],
211 if self
.settings
['bootsize'] and self
.settings
['bootsize'] is not '0%':
212 bootsize
=str(self
.settings
['bootsize']/(1024*1024))
213 self
.runcmd(['parted', '-s', self
.settings
['image'],
214 'mkpart', 'primary', 'fat16', '0', bootsize
])
217 self
.runcmd(['parted', '-s', self
.settings
['image'],
218 'mkpart', 'primary', bootsize
, '100%'])
219 self
.runcmd(['parted', '-s', self
.settings
['image'],
220 'set', '1', 'boot', 'on'])
222 def install_mbr(self
):
223 self
.message('Installing MBR')
224 self
.runcmd(['install-mbr', self
.settings
['image']])
226 def setup_kpartx(self
):
227 out
= self
.runcmd(['kpartx', '-avs', self
.settings
['image']])
228 if self
.settings
['bootsize']:
236 devices
= [line
.split()[2]
237 for line
in out
.splitlines()
238 if line
.startswith('add map ')]
239 if len(devices
) != parts
:
240 raise cliapp
.AppException('Surprising number of partitions')
241 root
= '/dev/mapper/%s' % devices
[rootindex
]
242 if self
.settings
['bootsize']:
243 boot
= '/dev/mapper/%s' % devices
[bootindex
]
246 def mkfs(self
, device
, type):
247 self
.message('Creating filesystem %s' % type)
248 self
.runcmd(['mkfs', '-t', type, device
])
250 def debootstrap(self
, rootdir
):
251 self
.message('Debootstrapping')
253 if self
.settings
['foreign']:
254 necessary_packages
= []
256 necessary_packages
= ['acpid']
258 include
= self
.settings
['package']
260 if not self
.settings
['no-kernel']:
261 if self
.settings
['arch'] == 'i386':
264 kernel_arch
= self
.settings
['arch']
265 kernel_image
= 'linux-image-%s' % kernel_arch
266 include
.append(kernel_image
)
268 if self
.settings
['sudo'] and 'sudo' not in include
:
269 include
.append('sudo')
271 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
273 '--include=%s' % ','.join(necessary_packages
+ include
))
274 if self
.settings
['foreign']:
275 args
.append('--foreign')
276 if self
.settings
['variant']:
277 args
.append('--variant')
278 args
.append(self
.settings
['variant'])
279 args
+= [self
.settings
['distribution'],
280 rootdir
, self
.settings
['mirror']]
282 if self
.settings
['foreign']:
283 # First copy the binfmt handler over
284 shutil
.copy(self
.settings
['foreign'], '%s/usr/bin/' % rootdir
)
285 # Next, run the package install scripts etc.
286 self
.runcmd(['chroot', rootdir
,
287 '/debootstrap/debootstrap', '--second-stage'])
289 def set_hostname(self
, rootdir
):
290 hostname
= self
.settings
['hostname']
291 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
292 f
.write('%s\n' % hostname
)
294 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
295 with
open(etc_hosts
, 'r') as f
:
297 with
open(etc_hosts
, 'w') as f
:
298 for line
in data
.splitlines():
299 if line
.startswith('127.0.0.1'):
300 line
+= ' %s' % hostname
301 f
.write('%s\n' % line
)
303 def create_fstab(self
, rootdir
, rootdev
, roottype
, bootdev
, boottype
):
305 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
306 '-s', 'UUID', device
])
307 return out
.splitlines()[0].strip()
310 rootdevstr
= 'UUID=%s' % fsuuid(rootdev
)
312 rootdevstr
= '/dev/sda1'
315 bootdevstr
= 'UUID=%s' % fsuuid(bootdev
)
319 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
320 with
open(fstab
, 'w') as f
:
321 f
.write('proc /proc proc defaults 0 0\n')
322 f
.write('%s / %s errors=remount-ro 0 1\n' % (rootdevstr
, roottype
))
324 f
.write('%s /boot %s errors=remount-ro 0 2\n' % (bootdevstr
, boottype
))
326 def install_debs(self
, rootdir
):
327 if not self
.settings
['custom-package']:
329 self
.message('Installing custom packages')
330 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
332 for deb
in self
.settings
['custom-package']:
333 shutil
.copy(deb
, tmp
)
334 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
335 for deb
in self
.settings
['custom-package']]
337 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
338 logging
.debug('stdout:\n%s' % out
)
339 logging
.debug('stderr:\n%s' % err
)
340 out
= self
.runcmd(['chroot', rootdir
,
341 'apt-get', '-f', '--no-remove', 'install'])
342 logging
.debug('stdout:\n%s' % out
)
345 def cleanup_apt_cache(self
, rootdir
):
346 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
347 logging
.debug('stdout:\n%s' % out
)
349 def set_root_password(self
, rootdir
):
350 if self
.settings
['root-password']:
351 self
.message('Setting root password')
352 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
353 elif self
.settings
['lock-root-password']:
354 self
.message('Locking root password')
355 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
357 self
.message('Give root an empty password')
358 self
.delete_password(rootdir
, 'root')
360 def create_users(self
, rootdir
):
361 def create_user(user
):
362 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
363 '--disabled-password', user
])
364 if self
.settings
['sudo']:
365 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
367 for userpass
in self
.settings
['user']:
369 user
, password
= userpass
.split('/', 1)
371 self
.set_password(rootdir
, user
, password
)
373 create_user(userpass
)
374 self
.delete_password(rootdir
, userpass
)
376 def set_password(self
, rootdir
, user
, password
):
377 encrypted
= crypt
.crypt(password
, '..')
378 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
380 def delete_password(self
, rootdir
, user
):
381 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
383 def remove_udev_persistent_rules(self
, rootdir
):
384 self
.message('Removing udev persistent cd and net rules')
385 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
386 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
387 if os
.path
.exists(pathname
):
388 logging
.debug('rm %s' % pathname
)
391 logging
.debug('not removing non-existent %s' % pathname
)
393 def setup_networking(self
, rootdir
):
394 self
.message('Setting up networking')
396 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
398 f
.write('iface lo inet loopback\n')
400 if self
.settings
['enable-dhcp']:
402 f
.write('auto eth0\n')
403 f
.write('iface eth0 inet dhcp\n')
407 def install_extlinux(self
, rootdev
, rootdir
):
408 self
.message('Installing extlinux')
411 dirname
= os
.path
.join(rootdir
, 'boot')
412 basenames
= os
.listdir(dirname
)
413 logging
.debug('find: %s' % basenames
)
414 for basename
in basenames
:
415 if re
.search(pattern
, basename
):
416 return os
.path
.join('boot', basename
)
417 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
419 kernel_image
= find('vmlinuz-.*')
420 initrd_image
= find('initrd.img-.*')
422 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
423 '-s', 'UUID', rootdev
])
424 uuid
= out
.splitlines()[0].strip()
426 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
427 logging
.debug('configure extlinux %s' % conf
)
435 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
438 'kernel': kernel_image
,
439 'initrd': initrd_image
,
442 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
443 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
447 if self
.settings
['serial-console']:
448 serial_command
= self
.settings
['serial-console-command']
449 logging
.debug('adding getty to serial console')
450 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
451 with
open(inittab
, 'a') as f
:
452 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
454 self
.runcmd(['extlinux', '--install', rootdir
])
455 self
.runcmd(['sync'])
456 import time
; time
.sleep(2)
458 def optimize_image(self
, rootdir
):
460 Filing up the image with zeros will increase its compression rate
462 zeros
= os
.path
.join(rootdir
, 'ZEROS')
463 self
.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros
, 'bs=1M'])
464 self
.runcmd(['rm', '-f', zeros
])
467 def cleanup_system(self
):
468 # Clean up after any errors.
470 self
.message('Cleaning up')
472 # Umount in the reverse mount order
473 if self
.settings
['image']:
474 for i
in xrange(len(self
.mount_points
) - 1, -1, -1):
475 mount_point
= self
.mount_points
[i
]
477 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
478 except cliapp
.AppException
:
479 logging
.debug("umount failed, sleeping and trying again")
481 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
483 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
485 for dirname
in self
.remove_dirs
:
486 shutil
.rmtree(dirname
)
488 def customize(self
, rootdir
):
489 script
= self
.settings
['customize']
491 self
.message('Running customize script %s' % script
)
492 with
open('/dev/tty', 'w') as tty
:
493 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
495 def create_tarball(self
, rootdir
):
496 # Create a tarball of the disk's contents
497 # shell out to runcmd since it more easily handles rootdir
498 self
.message('Creating tarball of disk contents')
499 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
502 if __name__
== '__main__':
503 VmDebootstrap(version
=__version__
).run()