]>
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
= []
113 if self
.settings
['image']:
114 self
.create_empty_image()
115 self
.partition_image()
117 (rootdev
,bootdev
) = self
.setup_kpartx()
118 self
.mkfs(rootdev
, type=roottype
)
119 rootdir
= self
.mount(rootdev
)
121 if self
.settings
['boottype']:
122 boottype
= self
.settings
['boottype']
125 self
.mkfs(bootdev
, type=boottype
)
126 bootdir
= '%s/%s' % (rootdir
, 'boot/')
128 bootdir
= self
.mount(bootdev
, bootdir
)
130 rootdir
= self
.mkdtemp()
131 self
.debootstrap(rootdir
)
132 self
.set_hostname(rootdir
)
133 self
.create_fstab(rootdir
, rootdev
, roottype
, bootdev
, boottype
)
134 self
.install_debs(rootdir
)
135 self
.cleanup_apt_cache(rootdir
)
136 self
.set_root_password(rootdir
)
137 self
.create_users(rootdir
)
138 self
.remove_udev_persistent_rules(rootdir
)
139 self
.setup_networking(rootdir
)
140 self
.customize(rootdir
)
141 if self
.settings
['image']:
142 if not self
.settings
['no-extlinux']:
143 self
.install_extlinux(rootdev
, rootdir
)
144 self
.optimize_image(rootdir
)
146 if self
.settings
['foreign']:
147 os
.unlink('%s/usr/bin/%s' %
148 (rootdir
, os
.path
.basename(self
.settings
['foreign'])))
150 if self
.settings
['tarball']:
151 self
.create_tarball(rootdir
)
152 except BaseException
, e
:
153 self
.message('EEEK! Something bad happened...')
154 self
.cleanup_system()
157 self
.cleanup_system()
159 def message(self
, msg
):
161 if self
.settings
['verbose']:
164 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
165 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
166 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
167 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
169 out
, err
= p
.communicate(stdin
)
170 if p
.returncode
!= 0:
171 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
174 raise cliapp
.AppException(msg
)
178 dirname
= tempfile
.mkdtemp()
179 self
.remove_dirs
.append(dirname
)
180 logging
.debug('mkdir %s' % dirname
)
183 def mount(self
, device
, path
=None):
185 mount_point
= self
.mkdtemp()
188 self
.message('Mounting %s on %s' % (device
,mount_point
))
189 self
.runcmd(['mount', device
, mount_point
])
190 self
.mount_points
.append(mount_point
)
191 logging
.debug('mounted %s on %s' % (device
, mount_point
))
194 def create_empty_image(self
):
195 self
.message('Creating disk image')
196 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
197 self
.settings
['image'],
198 str(self
.settings
['size'])])
200 def partition_image(self
):
201 self
.message('Creating partitions')
202 self
.runcmd(['parted', '-s', self
.settings
['image'],
204 if self
.settings
['bootsize'] and self
.settings
['bootsize'] is not '0%':
205 bootsize
=str(self
.settings
['bootsize']/(1024*1024))
206 self
.runcmd(['parted', '-s', self
.settings
['image'],
207 'mkpart', 'primary', 'fat16', '0', bootsize
])
210 self
.runcmd(['parted', '-s', self
.settings
['image'],
211 'mkpart', 'primary', bootsize
, '100%'])
212 self
.runcmd(['parted', '-s', self
.settings
['image'],
213 'set', '1', 'boot', 'on'])
215 def install_mbr(self
):
216 self
.message('Installing MBR')
217 self
.runcmd(['install-mbr', self
.settings
['image']])
219 def setup_kpartx(self
):
220 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
221 if self
.settings
['bootsize']:
229 devices
= [line
.split()[2]
230 for line
in out
.splitlines()
231 if line
.startswith('add map ')]
232 if len(devices
) != parts
:
233 raise cliapp
.AppException('Surprising number of partitions')
234 root
= '/dev/mapper/%s' % devices
[rootindex
]
235 if self
.settings
['bootsize']:
236 boot
= '/dev/mapper/%s' % devices
[bootindex
]
239 def mkfs(self
, device
, type):
240 self
.message('Creating filesystem %s' % type)
241 self
.runcmd(['mkfs', '-t', type, device
])
243 def debootstrap(self
, rootdir
):
244 self
.message('Debootstrapping')
246 if self
.settings
['foreign']:
247 necessary_packages
= []
249 necessary_packages
= ['acpid']
251 include
= self
.settings
['package']
253 if not self
.settings
['no-kernel']:
254 if self
.settings
['arch'] == 'i386':
257 kernel_arch
= self
.settings
['arch']
258 kernel_image
= 'linux-image-%s' % kernel_arch
259 include
.append(kernel_image
)
261 if self
.settings
['sudo'] and 'sudo' not in include
:
262 include
.append('sudo')
264 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
266 '--include=%s' % ','.join(necessary_packages
+ include
))
267 if self
.settings
['foreign']:
268 args
.append('--foreign')
269 if self
.settings
['variant']:
270 args
.append('--variant')
271 args
.append(self
.settings
['variant'])
272 args
+= [self
.settings
['distribution'],
273 rootdir
, self
.settings
['mirror']]
275 if self
.settings
['foreign']:
276 # First copy the binfmt handler over
277 shutil
.copy(self
.settings
['foreign'], '%s/usr/bin/' % rootdir
)
278 # Next, run the package install scripts etc.
279 self
.runcmd(['chroot', rootdir
,
280 '/debootstrap/debootstrap', '--second-stage'])
282 def set_hostname(self
, rootdir
):
283 hostname
= self
.settings
['hostname']
284 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
285 f
.write('%s\n' % hostname
)
287 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
288 with
open(etc_hosts
, 'r') as f
:
290 with
open(etc_hosts
, 'w') as f
:
291 for line
in data
.splitlines():
292 if line
.startswith('127.0.0.1'):
293 line
+= ' %s' % hostname
294 f
.write('%s\n' % line
)
296 def create_fstab(self
, rootdir
, rootdev
, roottype
, bootdev
, boottype
):
298 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
299 '-s', 'UUID', device
])
300 return out
.splitlines()[0].strip()
303 rootdevstr
= 'UUID=%s' % fsuuid(rootdev
)
305 rootdevstr
= '/dev/sda1'
308 bootdevstr
= 'UUID=%s' % fsuuid(bootdev
)
312 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
313 with
open(fstab
, 'w') as f
:
314 f
.write('proc /proc proc defaults 0 0\n')
315 f
.write('%s / %s errors=remount-ro 0 1\n' % (rootdevstr
, roottype
))
317 f
.write('%s /boot %s errors=remount-ro 0 2\n' % (bootdevstr
, boottype
))
319 def install_debs(self
, rootdir
):
320 if not self
.settings
['custom-package']:
322 self
.message('Installing custom packages')
323 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
325 for deb
in self
.settings
['custom-package']:
326 shutil
.copy(deb
, tmp
)
327 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
328 for deb
in self
.settings
['custom-package']]
330 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
331 logging
.debug('stdout:\n%s' % out
)
332 logging
.debug('stderr:\n%s' % err
)
333 out
= self
.runcmd(['chroot', rootdir
,
334 'apt-get', '-f', '--no-remove', 'install'])
335 logging
.debug('stdout:\n%s' % out
)
338 def cleanup_apt_cache(self
, rootdir
):
339 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
340 logging
.debug('stdout:\n%s' % out
)
342 def set_root_password(self
, rootdir
):
343 if self
.settings
['root-password']:
344 self
.message('Setting root password')
345 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
346 elif self
.settings
['lock-root-password']:
347 self
.message('Locking root password')
348 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
350 self
.message('Give root an empty password')
351 self
.delete_password(rootdir
, 'root')
353 def create_users(self
, rootdir
):
354 def create_user(user
):
355 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
356 '--disabled-password', user
])
357 if self
.settings
['sudo']:
358 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
360 for userpass
in self
.settings
['user']:
362 user
, password
= userpass
.split('/', 1)
364 self
.set_password(rootdir
, user
, password
)
366 create_user(userpass
)
367 self
.delete_password(rootdir
, userpass
)
369 def set_password(self
, rootdir
, user
, password
):
370 encrypted
= crypt
.crypt(password
, '..')
371 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
373 def delete_password(self
, rootdir
, user
):
374 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
376 def remove_udev_persistent_rules(self
, rootdir
):
377 self
.message('Removing udev persistent cd and net rules')
378 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
379 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
380 if os
.path
.exists(pathname
):
381 logging
.debug('rm %s' % pathname
)
384 logging
.debug('not removing non-existent %s' % pathname
)
386 def setup_networking(self
, rootdir
):
387 self
.message('Setting up networking')
389 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
391 f
.write('iface lo inet loopback\n')
393 if self
.settings
['enable-dhcp']:
395 f
.write('auto eth0\n')
396 f
.write('iface eth0 inet dhcp\n')
400 def install_extlinux(self
, rootdev
, rootdir
):
401 self
.message('Installing extlinux')
404 dirname
= os
.path
.join(rootdir
, 'boot')
405 basenames
= os
.listdir(dirname
)
406 logging
.debug('find: %s' % basenames
)
407 for basename
in basenames
:
408 if re
.search(pattern
, basename
):
409 return os
.path
.join('boot', basename
)
410 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
412 kernel_image
= find('vmlinuz-.*')
413 initrd_image
= find('initrd.img-.*')
415 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
416 '-s', 'UUID', rootdev
])
417 uuid
= out
.splitlines()[0].strip()
419 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
420 logging
.debug('configure extlinux %s' % conf
)
428 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
431 'kernel': kernel_image
,
432 'initrd': initrd_image
,
435 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
436 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
440 if self
.settings
['serial-console']:
441 serial_command
= self
.settings
['serial-console-command']
442 logging
.debug('adding getty to serial console')
443 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
444 with
open(inittab
, 'a') as f
:
445 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
447 self
.runcmd(['extlinux', '--install', rootdir
])
448 self
.runcmd(['sync'])
449 import time
; time
.sleep(2)
451 def optimize_image(self
, rootdir
):
453 Filing up the image with zeros will increase its compression rate
455 zeros
= os
.path
.join(rootdir
, 'ZEROS')
456 self
.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros
, 'bs=1M'])
457 self
.runcmd(['rm', '-f', zeros
])
460 def cleanup_system(self
):
461 # Clean up after any errors.
463 self
.message('Cleaning up')
465 # Umount in the reverse mount order
466 if self
.settings
['image']:
467 for i
in xrange(len(self
.mount_points
) - 1, -1, -1):
468 mount_point
= self
.mount_points
[i
]
469 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
471 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
473 for dirname
in self
.remove_dirs
:
474 shutil
.rmtree(dirname
)
476 def customize(self
, rootdir
):
477 script
= self
.settings
['customize']
479 self
.message('Running customize script %s' % script
)
480 with
open('/dev/tty', 'w') as tty
:
481 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
483 def create_tarball(self
, rootdir
):
484 # Create a tarball of the disk's contents
485 # shell out to runcmd since it more easily handles rootdir
486 self
.message('Creating tarball of disk contents')
487 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
490 if __name__
== '__main__':
491 VmDebootstrap(version
=__version__
).run()