]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
2 # Copyright 2011, 2012 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/>.
31 class VmDebootstrap(cliapp
.Application
):
33 def add_settings(self
):
34 default_arch
= 'amd64'
36 self
.settings
.boolean(['verbose'], 'report what is going on')
37 self
.settings
.string(['image'], 'put created disk image in FILE',
39 self
.settings
.bytesize(['size'],
40 'create a disk image of size SIZE (%default)',
43 self
.settings
.bytesize(['bootsize'],
44 'create boot partition of size SIZE (%default)',
47 self
.settings
.string(['boottype'],
48 'specify file system type for /boot/',
50 self
.settings
.string(['foreign'],
51 'set up foreign debootstrap environment using provided program (ie binfmt handler)')
52 self
.settings
.string(['variant'],
53 'select debootstrap variant it not using the default')
54 self
.settings
.boolean(['no-extlinux'], 'do not install extlinux')
55 self
.settings
.string(['tarball'], "tar up the disk's contents in FILE",
57 self
.settings
.string(['mirror'],
58 'use MIRROR as package source (%default)',
60 default
='http://cdn.debian.net/debian/')
61 self
.settings
.string(['arch'], 'architecture to use (%default)',
64 self
.settings
.string(['distribution'],
65 'release to use (%default)',
68 self
.settings
.string_list(['package'], 'install PACKAGE onto system')
69 self
.settings
.string_list(['custom-package'],
70 'install package in DEB file onto system '
73 self
.settings
.boolean(['no-kernel'], 'do not install a linux package')
74 self
.settings
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
75 self
.settings
.string(['root-password'], 'set root password',
77 self
.settings
.boolean(['lock-root-password'],
78 'lock root account so they cannot login?')
79 self
.settings
.string(['customize'],
80 'run SCRIPT after setting up system',
82 self
.settings
.string(['hostname'],
83 'set name to HOSTNAME (%default)',
86 self
.settings
.string_list(['user'],
87 'create USER with PASSWORD',
88 metavar
='USER/PASSWORD')
89 self
.settings
.boolean(['serial-console'],
90 'configure image to use a serial console')
91 self
.settings
.string(['serial-console-command'],
92 'command to manage the serial console, appended '
93 'to /etc/inittab (%default)',
95 default
='/sbin/getty -L ttyS0 115200 vt100')
96 self
.settings
.boolean(['sudo'],
97 'install sudo, and if user is created, add them '
100 def process_args(self
, args
):
101 if not self
.settings
['image'] and not self
.settings
['tarball']:
102 raise cliapp
.AppException('You must give disk image filename, '
103 'or tarball filename')
104 if self
.settings
['image'] and not self
.settings
['size']:
105 raise cliapp
.AppException('If disk image is specified, '
106 'You must give image size.')
108 self
.remove_dirs
= []
109 self
.mount_points
= []
112 if self
.settings
['image']:
113 self
.create_empty_image()
114 self
.partition_image()
116 (rootdev
,bootdev
) = self
.setup_kpartx()
118 rootdir
= self
.mount(rootdev
)
120 if self
.settings
['boottype']:
121 fstype
= self
.settings
['boottype']
124 self
.mkfs(bootdev
, type=fstype
)
125 bootdir
= '%s/%s' % (rootdir
, 'boot/')
127 bootdir
= self
.mount(bootdev
, bootdir
)
129 rootdir
= self
.mkdtemp()
130 self
.debootstrap(rootdir
)
131 self
.set_hostname(rootdir
)
132 self
.create_fstab(rootdir
)
133 self
.install_debs(rootdir
)
134 self
.cleanup_apt_cache(rootdir
)
135 self
.set_root_password(rootdir
)
136 self
.create_users(rootdir
)
137 self
.remove_udev_persistent_rules(rootdir
)
138 self
.setup_networking(rootdir
)
139 self
.customize(rootdir
)
140 if self
.settings
['image']:
141 if not self
.settings
['no-extlinux']:
142 self
.install_extlinux(rootdev
, rootdir
)
143 self
.optimize_image(rootdir
)
145 if self
.settings
['foreign']:
146 os
.unlink('%s/usr/bin/%s' %
147 (rootdir
, os
.path
.basename(self
.settings
['foreign'])))
149 if self
.settings
['tarball']:
150 self
.create_tarball(rootdir
)
151 except BaseException
, e
:
152 self
.message('EEEK! Something bad happened...')
153 self
.cleanup_system()
156 self
.cleanup_system()
158 def message(self
, msg
):
160 if self
.settings
['verbose']:
163 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
164 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
165 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
166 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
168 out
, err
= p
.communicate(stdin
)
169 if p
.returncode
!= 0:
170 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
173 raise cliapp
.AppException(msg
)
177 dirname
= tempfile
.mkdtemp()
178 self
.remove_dirs
.append(dirname
)
179 logging
.debug('mkdir %s' % dirname
)
182 def mount(self
, device
, path
=None):
183 self
.message('Mounting %s' % device
)
185 mount_point
= self
.mkdtemp()
188 self
.runcmd(['mount', device
, mount_point
])
189 self
.mount_points
.append(mount_point
)
190 logging
.debug('mounted %s on %s' % (device
, mount_point
))
193 def create_empty_image(self
):
194 self
.message('Creating disk image')
195 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
196 self
.settings
['image'],
197 str(self
.settings
['size'])])
199 def partition_image(self
):
200 self
.message('Creating partitions')
201 self
.runcmd(['parted', '-s', self
.settings
['image'],
203 if self
.settings
['bootsize'] and self
.settings
['bootsize'] is not '0%':
204 bootsize
=str(self
.settings
['bootsize']/(1024*1024))
205 self
.runcmd(['parted', '-s', self
.settings
['image'],
206 'mkpart', 'primary', 'fat16', '0', bootsize
])
209 self
.runcmd(['parted', '-s', self
.settings
['image'],
210 'mkpart', 'primary', bootsize
, '100%'])
211 self
.runcmd(['parted', '-s', self
.settings
['image'],
212 'set', '1', 'boot', 'on'])
214 def install_mbr(self
):
215 self
.message('Installing MBR')
216 self
.runcmd(['install-mbr', self
.settings
['image']])
218 def setup_kpartx(self
):
219 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
220 if self
.settings
['bootsize']:
228 devices
= [line
.split()[2]
229 for line
in out
.splitlines()
230 if line
.startswith('add map ')]
231 if len(devices
) != parts
:
232 raise cliapp
.AppException('Surprising number of partitions')
233 root
= '/dev/mapper/%s' % devices
[rootindex
]
234 if self
.settings
['bootsize']:
235 boot
= '/dev/mapper/%s' % devices
[bootindex
]
238 def mkfs(self
, device
, type='ext2'):
239 self
.message('Creating filesystem')
240 self
.runcmd(['mkfs', '-t', type, device
])
242 def debootstrap(self
, rootdir
):
243 self
.message('Debootstrapping')
245 if self
.settings
['foreign']:
246 necessary_packages
= []
248 necessary_packages
= ['acpid']
250 include
= self
.settings
['package']
252 if not self
.settings
['no-kernel']:
253 if self
.settings
['arch'] == 'i386':
256 kernel_arch
= self
.settings
['arch']
257 kernel_image
= 'linux-image-%s' % kernel_arch
258 include
.append(kernel_image
)
260 if self
.settings
['sudo'] and 'sudo' not in include
:
261 include
.append('sudo')
263 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
265 '--include=%s' % ','.join(necessary_packages
+ include
))
266 if self
.settings
['foreign']:
267 args
.append('--foreign')
268 if self
.settings
['variant']:
269 args
.append('--variant')
270 args
.append(self
.settings
['variant'])
271 args
+= [self
.settings
['distribution'],
272 rootdir
, self
.settings
['mirror']]
274 if self
.settings
['foreign']:
275 # First copy the binfmt handler over
276 shutil
.copy(self
.settings
['foreign'], '%s/usr/bin/' % rootdir
)
277 # Next, run the package install scripts etc.
278 self
.runcmd(['chroot', rootdir
,
279 '/debootstrap/debootstrap', '--second-stage'])
281 def set_hostname(self
, rootdir
):
282 hostname
= self
.settings
['hostname']
283 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
284 f
.write('%s\n' % hostname
)
286 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
287 with
open(etc_hosts
, 'r') as f
:
289 with
open(etc_hosts
, 'w') as f
:
290 for line
in data
.splitlines():
291 if line
.startswith('127.0.0.1'):
292 line
+= ' %s' % hostname
293 f
.write('%s\n' % line
)
295 def create_fstab(self
, rootdir
):
296 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
297 with
open(fstab
, 'w') as f
:
298 f
.write('proc /proc proc defaults 0 0\n')
299 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
301 def install_debs(self
, rootdir
):
302 if not self
.settings
['custom-package']:
304 self
.message('Installing custom packages')
305 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
307 for deb
in self
.settings
['custom-package']:
308 shutil
.copy(deb
, tmp
)
309 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
310 for deb
in self
.settings
['custom-package']]
312 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
313 logging
.debug('stdout:\n%s' % out
)
314 logging
.debug('stderr:\n%s' % err
)
315 out
= self
.runcmd(['chroot', rootdir
,
316 'apt-get', '-f', '--no-remove', 'install'])
317 logging
.debug('stdout:\n%s' % out
)
320 def cleanup_apt_cache(self
, rootdir
):
321 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
322 logging
.debug('stdout:\n%s' % out
)
324 def set_root_password(self
, rootdir
):
325 if self
.settings
['root-password']:
326 self
.message('Setting root password')
327 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
328 elif self
.settings
['lock-root-password']:
329 self
.message('Locking root password')
330 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
332 self
.message('Give root an empty password')
333 self
.delete_password(rootdir
, 'root')
335 def create_users(self
, rootdir
):
336 def create_user(user
):
337 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
338 '--disabled-password', user
])
339 if self
.settings
['sudo']:
340 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
342 for userpass
in self
.settings
['user']:
344 user
, password
= userpass
.split('/', 1)
346 self
.set_password(rootdir
, user
, password
)
348 create_user(userpass
)
349 self
.delete_password(rootdir
, userpass
)
351 def set_password(self
, rootdir
, user
, password
):
352 encrypted
= crypt
.crypt(password
, '..')
353 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
355 def delete_password(self
, rootdir
, user
):
356 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
358 def remove_udev_persistent_rules(self
, rootdir
):
359 self
.message('Removing udev persistent cd and net rules')
360 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
361 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
362 if os
.path
.exists(pathname
):
363 logging
.debug('rm %s' % pathname
)
366 logging
.debug('not removing non-existent %s' % pathname
)
368 def setup_networking(self
, rootdir
):
369 self
.message('Setting up networking')
371 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
373 f
.write('iface lo inet loopback\n')
375 if self
.settings
['enable-dhcp']:
377 f
.write('auto eth0\n')
378 f
.write('iface eth0 inet dhcp\n')
382 def install_extlinux(self
, rootdev
, rootdir
):
383 self
.message('Installing extlinux')
386 dirname
= os
.path
.join(rootdir
, 'boot')
387 basenames
= os
.listdir(dirname
)
388 logging
.debug('find: %s' % basenames
)
389 for basename
in basenames
:
390 if re
.search(pattern
, basename
):
391 return os
.path
.join('boot', basename
)
392 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
394 kernel_image
= find('vmlinuz-.*')
395 initrd_image
= find('initrd.img-.*')
397 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
398 '-s', 'UUID', rootdev
])
399 uuid
= out
.splitlines()[0].strip()
401 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
402 logging
.debug('configure extlinux %s' % conf
)
410 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
413 'kernel': kernel_image
,
414 'initrd': initrd_image
,
417 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
418 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
422 if self
.settings
['serial-console']:
423 serial_command
= self
.settings
['serial-console-command']
424 logging
.debug('adding getty to serial console')
425 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
426 with
open(inittab
, 'a') as f
:
427 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
429 self
.runcmd(['extlinux', '--install', rootdir
])
430 self
.runcmd(['sync'])
431 import time
; time
.sleep(2)
433 def optimize_image(self
, rootdir
):
435 Filing up the image with zeros will increase its compression rate
437 zeros
= os
.path
.join(rootdir
, 'ZEROS')
438 self
.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros
, 'bs=1M'])
439 self
.runcmd(['rm', '-f', zeros
])
442 def cleanup_system(self
):
443 # Clean up after any errors.
445 self
.message('Cleaning up')
447 # Umount in the reverse mount order
448 if self
.settings
['image']:
449 for i
in xrange(len(self
.mount_points
) - 1, -1, -1):
450 mount_point
= self
.mount_points
[i
]
451 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
453 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
455 for dirname
in self
.remove_dirs
:
456 shutil
.rmtree(dirname
)
458 def customize(self
, rootdir
):
459 script
= self
.settings
['customize']
461 self
.message('Running customize script %s' % script
)
462 with
open('/dev/tty', 'w') as tty
:
463 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
465 def create_tarball(self
, rootdir
):
466 # Create a tarball of the disk's contents
467 # shell out to runcmd since it more easily handles rootdir
468 self
.message('Creating tarball of disk contents')
469 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
472 if __name__
== '__main__':
473 VmDebootstrap(version
=__version__
).run()