]>
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(['no-extlinux'], 'do not install extlinux')
56 self
.settings
.string(['tarball'], "tar up the disk's contents in FILE",
58 self
.settings
.string(['mirror'],
59 'use MIRROR as package source (%default)',
61 default
='http://cdn.debian.net/debian/')
62 self
.settings
.string(['arch'], 'architecture to use (%default)',
65 self
.settings
.string(['distribution'],
66 'release to use (%default)',
69 self
.settings
.string_list(['package'], 'install PACKAGE onto system')
70 self
.settings
.string_list(['custom-package'],
71 'install package in DEB file onto system '
74 self
.settings
.boolean(['no-kernel'], 'do not install a linux package')
75 self
.settings
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
76 self
.settings
.string(['root-password'], 'set root password',
78 self
.settings
.boolean(['lock-root-password'],
79 'lock root account so they cannot login?')
80 self
.settings
.string(['customize'],
81 'run SCRIPT after setting up system',
83 self
.settings
.string(['hostname'],
84 'set name to HOSTNAME (%default)',
87 self
.settings
.string_list(['user'],
88 'create USER with PASSWORD',
89 metavar
='USER/PASSWORD')
90 self
.settings
.boolean(['serial-console'],
91 'configure image to use a serial console')
92 self
.settings
.string(['serial-console-command'],
93 'command to manage the serial console, appended '
94 'to /etc/inittab (%default)',
96 default
='/sbin/getty -L ttyS0 115200 vt100')
97 self
.settings
.boolean(['sudo'],
98 'install sudo, and if user is created, add them '
101 def process_args(self
, args
):
102 if not self
.settings
['image'] and not self
.settings
['tarball']:
103 raise cliapp
.AppException('You must give disk image filename, '
104 'or tarball filename')
105 if self
.settings
['image'] and not self
.settings
['size']:
106 raise cliapp
.AppException('If disk image is specified, '
107 'You must give image size.')
109 self
.remove_dirs
= []
110 self
.mount_points
= []
117 if self
.settings
['image']:
118 self
.create_empty_image()
119 self
.partition_image()
121 (rootdev
,bootdev
) = self
.setup_kpartx()
122 self
.mkfs(rootdev
, type=roottype
)
123 rootdir
= self
.mount(rootdev
)
125 if self
.settings
['boottype']:
126 boottype
= self
.settings
['boottype']
129 self
.mkfs(bootdev
, type=boottype
)
130 bootdir
= '%s/%s' % (rootdir
, 'boot/')
132 bootdir
= self
.mount(bootdev
, bootdir
)
134 rootdir
= self
.mkdtemp()
135 self
.debootstrap(rootdir
)
136 self
.set_hostname(rootdir
)
137 self
.create_fstab(rootdir
, rootdev
, roottype
, bootdev
, boottype
)
138 self
.install_debs(rootdir
)
139 self
.cleanup_apt_cache(rootdir
)
140 self
.set_root_password(rootdir
)
141 self
.create_users(rootdir
)
142 self
.remove_udev_persistent_rules(rootdir
)
143 self
.setup_networking(rootdir
)
144 self
.customize(rootdir
)
145 if self
.settings
['image']:
146 if not self
.settings
['no-extlinux']:
147 self
.install_extlinux(rootdev
, rootdir
)
148 self
.optimize_image(rootdir
)
150 if self
.settings
['foreign']:
151 os
.unlink('%s/usr/bin/%s' %
152 (rootdir
, os
.path
.basename(self
.settings
['foreign'])))
154 if self
.settings
['tarball']:
155 self
.create_tarball(rootdir
)
156 except BaseException
, e
:
157 self
.message('EEEK! Something bad happened...')
158 self
.cleanup_system()
161 self
.cleanup_system()
163 def message(self
, msg
):
165 if self
.settings
['verbose']:
168 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
169 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
170 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
171 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
173 out
, err
= p
.communicate(stdin
)
174 if p
.returncode
!= 0:
175 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
178 raise cliapp
.AppException(msg
)
182 dirname
= tempfile
.mkdtemp()
183 self
.remove_dirs
.append(dirname
)
184 logging
.debug('mkdir %s' % dirname
)
187 def mount(self
, device
, path
=None):
189 mount_point
= self
.mkdtemp()
192 self
.message('Mounting %s on %s' % (device
,mount_point
))
193 self
.runcmd(['mount', device
, mount_point
])
194 self
.mount_points
.append(mount_point
)
195 logging
.debug('mounted %s on %s' % (device
, mount_point
))
198 def create_empty_image(self
):
199 self
.message('Creating disk image')
200 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
201 self
.settings
['image'],
202 str(self
.settings
['size'])])
204 def partition_image(self
):
205 self
.message('Creating partitions')
206 self
.runcmd(['parted', '-s', self
.settings
['image'],
208 if self
.settings
['bootsize'] and self
.settings
['bootsize'] is not '0%':
209 bootsize
=str(self
.settings
['bootsize']/(1024*1024))
210 self
.runcmd(['parted', '-s', self
.settings
['image'],
211 'mkpart', 'primary', 'fat16', '0', bootsize
])
214 self
.runcmd(['parted', '-s', self
.settings
['image'],
215 'mkpart', 'primary', bootsize
, '100%'])
216 self
.runcmd(['parted', '-s', self
.settings
['image'],
217 'set', '1', 'boot', 'on'])
219 def install_mbr(self
):
220 self
.message('Installing MBR')
221 self
.runcmd(['install-mbr', self
.settings
['image']])
223 def setup_kpartx(self
):
224 out
= self
.runcmd(['kpartx', '-avs', self
.settings
['image']])
225 if self
.settings
['bootsize']:
233 devices
= [line
.split()[2]
234 for line
in out
.splitlines()
235 if line
.startswith('add map ')]
236 if len(devices
) != parts
:
237 raise cliapp
.AppException('Surprising number of partitions')
238 root
= '/dev/mapper/%s' % devices
[rootindex
]
239 if self
.settings
['bootsize']:
240 boot
= '/dev/mapper/%s' % devices
[bootindex
]
243 def mkfs(self
, device
, type):
244 self
.message('Creating filesystem %s' % type)
245 self
.runcmd(['mkfs', '-t', type, device
])
247 def debootstrap(self
, rootdir
):
248 self
.message('Debootstrapping')
250 if self
.settings
['foreign']:
251 necessary_packages
= []
253 necessary_packages
= ['acpid']
255 include
= self
.settings
['package']
257 if not self
.settings
['no-kernel']:
258 if self
.settings
['arch'] == 'i386':
261 kernel_arch
= self
.settings
['arch']
262 kernel_image
= 'linux-image-%s' % kernel_arch
263 include
.append(kernel_image
)
265 if self
.settings
['sudo'] and 'sudo' not in include
:
266 include
.append('sudo')
268 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
270 '--include=%s' % ','.join(necessary_packages
+ include
))
271 if self
.settings
['foreign']:
272 args
.append('--foreign')
273 if self
.settings
['variant']:
274 args
.append('--variant')
275 args
.append(self
.settings
['variant'])
276 args
+= [self
.settings
['distribution'],
277 rootdir
, self
.settings
['mirror']]
279 if self
.settings
['foreign']:
280 # First copy the binfmt handler over
281 shutil
.copy(self
.settings
['foreign'], '%s/usr/bin/' % rootdir
)
282 # Next, run the package install scripts etc.
283 self
.runcmd(['chroot', rootdir
,
284 '/debootstrap/debootstrap', '--second-stage'])
286 def set_hostname(self
, rootdir
):
287 hostname
= self
.settings
['hostname']
288 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
289 f
.write('%s\n' % hostname
)
291 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
292 with
open(etc_hosts
, 'r') as f
:
294 with
open(etc_hosts
, 'w') as f
:
295 for line
in data
.splitlines():
296 if line
.startswith('127.0.0.1'):
297 line
+= ' %s' % hostname
298 f
.write('%s\n' % line
)
300 def create_fstab(self
, rootdir
, rootdev
, roottype
, bootdev
, boottype
):
302 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
303 '-s', 'UUID', device
])
304 return out
.splitlines()[0].strip()
307 rootdevstr
= 'UUID=%s' % fsuuid(rootdev
)
309 rootdevstr
= '/dev/sda1'
312 bootdevstr
= 'UUID=%s' % fsuuid(bootdev
)
316 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
317 with
open(fstab
, 'w') as f
:
318 f
.write('proc /proc proc defaults 0 0\n')
319 f
.write('%s / %s errors=remount-ro 0 1\n' % (rootdevstr
, roottype
))
321 f
.write('%s /boot %s errors=remount-ro 0 2\n' % (bootdevstr
, boottype
))
323 def install_debs(self
, rootdir
):
324 if not self
.settings
['custom-package']:
326 self
.message('Installing custom packages')
327 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
329 for deb
in self
.settings
['custom-package']:
330 shutil
.copy(deb
, tmp
)
331 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
332 for deb
in self
.settings
['custom-package']]
334 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
335 logging
.debug('stdout:\n%s' % out
)
336 logging
.debug('stderr:\n%s' % err
)
337 out
= self
.runcmd(['chroot', rootdir
,
338 'apt-get', '-f', '--no-remove', 'install'])
339 logging
.debug('stdout:\n%s' % out
)
342 def cleanup_apt_cache(self
, rootdir
):
343 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
344 logging
.debug('stdout:\n%s' % out
)
346 def set_root_password(self
, rootdir
):
347 if self
.settings
['root-password']:
348 self
.message('Setting root password')
349 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
350 elif self
.settings
['lock-root-password']:
351 self
.message('Locking root password')
352 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
354 self
.message('Give root an empty password')
355 self
.delete_password(rootdir
, 'root')
357 def create_users(self
, rootdir
):
358 def create_user(user
):
359 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
360 '--disabled-password', user
])
361 if self
.settings
['sudo']:
362 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
364 for userpass
in self
.settings
['user']:
366 user
, password
= userpass
.split('/', 1)
368 self
.set_password(rootdir
, user
, password
)
370 create_user(userpass
)
371 self
.delete_password(rootdir
, userpass
)
373 def set_password(self
, rootdir
, user
, password
):
374 encrypted
= crypt
.crypt(password
, '..')
375 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
377 def delete_password(self
, rootdir
, user
):
378 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
380 def remove_udev_persistent_rules(self
, rootdir
):
381 self
.message('Removing udev persistent cd and net rules')
382 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
383 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
384 if os
.path
.exists(pathname
):
385 logging
.debug('rm %s' % pathname
)
388 logging
.debug('not removing non-existent %s' % pathname
)
390 def setup_networking(self
, rootdir
):
391 self
.message('Setting up networking')
393 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
395 f
.write('iface lo inet loopback\n')
397 if self
.settings
['enable-dhcp']:
399 f
.write('auto eth0\n')
400 f
.write('iface eth0 inet dhcp\n')
404 def install_extlinux(self
, rootdev
, rootdir
):
405 self
.message('Installing extlinux')
408 dirname
= os
.path
.join(rootdir
, 'boot')
409 basenames
= os
.listdir(dirname
)
410 logging
.debug('find: %s' % basenames
)
411 for basename
in basenames
:
412 if re
.search(pattern
, basename
):
413 return os
.path
.join('boot', basename
)
414 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
416 kernel_image
= find('vmlinuz-.*')
417 initrd_image
= find('initrd.img-.*')
419 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
420 '-s', 'UUID', rootdev
])
421 uuid
= out
.splitlines()[0].strip()
423 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
424 logging
.debug('configure extlinux %s' % conf
)
432 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
435 'kernel': kernel_image
,
436 'initrd': initrd_image
,
439 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
440 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
444 if self
.settings
['serial-console']:
445 serial_command
= self
.settings
['serial-console-command']
446 logging
.debug('adding getty to serial console')
447 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
448 with
open(inittab
, 'a') as f
:
449 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
451 self
.runcmd(['extlinux', '--install', rootdir
])
452 self
.runcmd(['sync'])
453 import time
; time
.sleep(2)
455 def optimize_image(self
, rootdir
):
457 Filing up the image with zeros will increase its compression rate
459 zeros
= os
.path
.join(rootdir
, 'ZEROS')
460 self
.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros
, 'bs=1M'])
461 self
.runcmd(['rm', '-f', zeros
])
464 def cleanup_system(self
):
465 # Clean up after any errors.
467 self
.message('Cleaning up')
469 # Umount in the reverse mount order
470 if self
.settings
['image']:
471 for i
in xrange(len(self
.mount_points
) - 1, -1, -1):
472 mount_point
= self
.mount_points
[i
]
474 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
475 except cliapp
.AppException
:
476 logging
.debug("umount failed, sleeping and trying again")
478 self
.runcmd(['umount', mount_point
], ignore_fail
=False)
480 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
482 for dirname
in self
.remove_dirs
:
483 shutil
.rmtree(dirname
)
485 def customize(self
, rootdir
):
486 script
= self
.settings
['customize']
488 self
.message('Running customize script %s' % script
)
489 with
open('/dev/tty', 'w') as tty
:
490 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
492 def create_tarball(self
, rootdir
):
493 # Create a tarball of the disk's contents
494 # shell out to runcmd since it more easily handles rootdir
495 self
.message('Creating tarball of disk contents')
496 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
499 if __name__
== '__main__':
500 VmDebootstrap(version
=__version__
).run()