]>
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/>.
28 class VmDebootstrap(cliapp
.Application
):
30 def add_settings(self
):
31 default_arch
= 'amd64'
33 self
.settings
.boolean(['verbose'], 'report what is going on')
34 self
.settings
.string(['image'], 'put created disk image in FILE',
36 self
.settings
.bytesize(['size'],
37 'create a disk image of size SIZE (%default)',
40 self
.settings
.string(['tarball'], "tar up the disk's contents in FILE",
42 self
.settings
.string(['mirror'],
43 'use MIRROR as package source (%default)',
45 default
='http://cdn.debian.net/debian/')
46 self
.settings
.string(['arch'], 'architecture to use (%default)',
49 self
.settings
.string(['distribution'],
50 'release to use (%default)',
53 self
.settings
.string_list(['package'], 'install PACKAGE onto system')
54 self
.settings
.string_list(['custom-package'],
55 'install package in DEB file onto system '
58 self
.settings
.boolean(['no-kernel'], 'do not install a linux package')
59 self
.settings
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
60 self
.settings
.string(['root-password'], 'set root password',
62 self
.settings
.boolean(['lock-root-password'],
63 'lock root account so they cannot login?')
64 self
.settings
.string(['customize'],
65 'run SCRIPT after setting up system',
67 self
.settings
.string(['hostname'],
68 'set name to HOSTNAME (%default)',
71 self
.settings
.string_list(['user'],
72 'create USER with PASSWORD',
73 metavar
='USER/PASSWORD')
74 self
.settings
.boolean(['serial-console'],
75 'configure image to use a serial console')
76 self
.settings
.string(['serial-console-command'],
77 'command to manage the serial console, appended '
78 'to /etc/inittab (%default)',
80 default
='/sbin/getty -L ttyS0 115200 vt100')
81 self
.settings
.boolean(['sudo'],
82 'install sudo, and if user is created, add them '
85 def process_args(self
, args
):
86 if not self
.settings
['image'] and not self
.settings
['tarball']:
87 raise cliapp
.AppException('You must give disk image filename, '
88 'or tarball filename')
89 if self
.settings
['image'] and not self
.settings
['size']:
90 raise cliapp
.AppException('If disk image is specified, '
91 'You must give image size.')
94 self
.mount_points
= []
97 if self
.settings
['image']:
98 self
.create_empty_image()
99 self
.partition_image()
101 rootdev
= self
.setup_kpartx()
103 rootdir
= self
.mount(rootdev
)
105 rootdir
= self
.mkdtemp()
106 self
.debootstrap(rootdir
)
107 self
.set_hostname(rootdir
)
108 self
.create_fstab(rootdir
)
109 self
.install_debs(rootdir
)
110 self
.cleanup_apt_cache(rootdir
)
111 self
.set_root_password(rootdir
)
112 self
.create_users(rootdir
)
113 self
.remove_udev_persistent_rules(rootdir
)
114 self
.setup_networking(rootdir
)
115 self
.customize(rootdir
)
116 if self
.settings
['image']:
117 self
.install_extlinux(rootdev
, rootdir
)
118 self
.optimize_image(rootdir
)
119 if self
.settings
['tarball']:
120 self
.create_tarball(rootdir
)
121 except BaseException
, e
:
122 self
.message('EEEK! Something bad happened...')
123 self
.cleanup_system()
126 self
.cleanup_system()
128 def message(self
, msg
):
130 if self
.settings
['verbose']:
133 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
134 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
135 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
136 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
138 out
, err
= p
.communicate(stdin
)
139 if p
.returncode
!= 0:
140 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
143 raise cliapp
.AppException(msg
)
147 dirname
= tempfile
.mkdtemp()
148 self
.remove_dirs
.append(dirname
)
149 logging
.debug('mkdir %s' % dirname
)
152 def mount(self
, device
):
153 self
.message('Mounting %s' % device
)
154 mount_point
= self
.mkdtemp()
155 self
.runcmd(['mount', device
, mount_point
])
156 self
.mount_points
.append(mount_point
)
157 logging
.debug('mounted %s on %s' % (device
, mount_point
))
160 def create_empty_image(self
):
161 self
.message('Creating disk image')
162 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
163 self
.settings
['image'],
164 str(self
.settings
['size'])])
166 def partition_image(self
):
167 self
.message('Creating partitions')
168 self
.runcmd(['parted', '-s', self
.settings
['image'],
170 self
.runcmd(['parted', '-s', self
.settings
['image'],
171 'mkpart', 'primary', '0%', '100%'])
172 self
.runcmd(['parted', '-s', self
.settings
['image'],
173 'set', '1', 'boot', 'on'])
175 def install_mbr(self
):
176 self
.message('Installing MBR')
177 self
.runcmd(['install-mbr', self
.settings
['image']])
179 def setup_kpartx(self
):
180 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
181 devices
= [line
.split()[2]
182 for line
in out
.splitlines()
183 if line
.startswith('add map ')]
184 if len(devices
) != 1:
185 raise cliapp
.AppException('Surprising number of partitions')
186 return '/dev/mapper/%s' % devices
[0]
188 def mkfs(self
, device
):
189 self
.message('Creating filesystem')
190 self
.runcmd(['mkfs', '-t', 'ext2', device
])
192 def debootstrap(self
, rootdir
):
193 self
.message('Debootstrapping')
195 necessary_packages
= ['acpid']
197 include
= self
.settings
['package']
199 if not self
.settings
['no-kernel']:
200 if self
.settings
['arch'] == 'i386':
203 kernel_arch
= self
.settings
['arch']
204 kernel_image
= 'linux-image-%s' % kernel_arch
205 include
.append(kernel_image
)
207 if self
.settings
['sudo'] and 'sudo' not in include
:
208 include
.append('sudo')
210 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
212 '--include=%s' % ','.join(necessary_packages
+ include
))
213 args
+= [self
.settings
['distribution'],
214 rootdir
, self
.settings
['mirror']]
217 def set_hostname(self
, rootdir
):
218 hostname
= self
.settings
['hostname']
219 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
220 f
.write('%s\n' % hostname
)
222 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
223 with
open(etc_hosts
, 'r') as f
:
225 with
open(etc_hosts
, 'w') as f
:
226 for line
in data
.splitlines():
227 if line
.startswith('127.0.0.1'):
228 line
+= ' %s' % hostname
229 f
.write('%s\n' % line
)
231 def create_fstab(self
, rootdir
):
232 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
233 with
open(fstab
, 'w') as f
:
234 f
.write('proc /proc proc defaults 0 0\n')
235 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
237 def install_debs(self
, rootdir
):
238 if not self
.settings
['custom-package']:
240 self
.message('Installing custom packages')
241 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
243 for deb
in self
.settings
['custom-package']:
244 shutil
.copy(deb
, tmp
)
245 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
246 for deb
in self
.settings
['custom-package']]
248 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
249 logging
.debug('stdout:\n%s' % out
)
250 logging
.debug('stderr:\n%s' % err
)
251 out
= self
.runcmd(['chroot', rootdir
,
252 'apt-get', '-f', '--no-remove', 'install'])
253 logging
.debug('stdout:\n%s' % out
)
256 def cleanup_apt_cache(self
, rootdir
):
257 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
258 logging
.debug('stdout:\n%s' % out
)
260 def set_root_password(self
, rootdir
):
261 if self
.settings
['root-password']:
262 self
.message('Setting root password')
263 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
264 elif self
.settings
['lock-root-password']:
265 self
.message('Locking root password')
266 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
268 self
.message('Give root an empty password')
269 self
.delete_password(rootdir
, 'root')
271 def create_users(self
, rootdir
):
272 def create_user(user
):
273 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
274 '--disabled-password', user
])
275 if self
.settings
['sudo']:
276 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
278 for userpass
in self
.settings
['user']:
280 user
, password
= userpass
.split('/', 1)
282 self
.set_password(rootdir
, user
, password
)
284 create_user(userpass
)
285 self
.delete_password(rootdir
, userpass
)
287 def set_password(self
, rootdir
, user
, password
):
288 encrypted
= crypt
.crypt(password
, '..')
289 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
291 def delete_password(self
, rootdir
, user
):
292 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
294 def remove_udev_persistent_rules(self
, rootdir
):
295 self
.message('Removing udev persistent cd and net rules')
296 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
297 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
298 if os
.path
.exists(pathname
):
299 logging
.debug('rm %s' % pathname
)
302 logging
.debug('not removing non-existent %s' % pathname
)
304 def setup_networking(self
, rootdir
):
305 self
.message('Setting up networking')
307 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
309 f
.write('iface lo inet loopback\n')
311 if self
.settings
['enable-dhcp']:
313 f
.write('auto eth0\n')
314 f
.write('iface eth0 inet dhcp\n')
318 def install_extlinux(self
, rootdev
, rootdir
):
319 self
.message('Installing extlinux')
322 dirname
= os
.path
.join(rootdir
, 'boot')
323 basenames
= os
.listdir(dirname
)
324 logging
.debug('find: %s' % basenames
)
325 for basename
in basenames
:
326 if re
.search(pattern
, basename
):
327 return os
.path
.join('boot', basename
)
328 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
330 kernel_image
= find('vmlinuz-.*')
331 initrd_image
= find('initrd.img-.*')
333 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
334 '-s', 'UUID', rootdev
])
335 uuid
= out
.splitlines()[0].strip()
337 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
338 logging
.debug('configure extlinux %s' % conf
)
346 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
349 'kernel': kernel_image
,
350 'initrd': initrd_image
,
353 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
354 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
358 if self
.settings
['serial-console']:
359 serial_command
= self
.settings
['serial-console-command']
360 logging
.debug('adding getty to serial console')
361 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
362 with
open(inittab
, 'a') as f
:
363 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
365 self
.runcmd(['extlinux', '--install', rootdir
])
366 self
.runcmd(['sync'])
367 import time
; time
.sleep(2)
369 def optimize_image(self
, rootdir
):
371 Filing up the image with zeros will increase its compression rate
373 zeros
= os
.path
.join(rootdir
, 'ZEROS')
374 self
.runcmd_unchecked(['dd', 'if=/dev/zero', 'of=' + zeros
, 'bs=1M'])
375 self
.runcmd(['rm', '-f', zeros
])
378 def cleanup_system(self
):
379 # Clean up after any errors.
381 self
.message('Cleaning up')
383 if self
.settings
['image']:
384 for mount_point
in self
.mount_points
:
385 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
387 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
389 for dirname
in self
.remove_dirs
:
390 shutil
.rmtree(dirname
)
392 def customize(self
, rootdir
):
393 script
= self
.settings
['customize']
395 self
.message('Running customize script %s' % script
)
396 with
open('/dev/tty', 'w') as tty
:
397 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
399 def create_tarball(self
, rootdir
):
400 # Create a tarball of the disk's contents
401 # shell out to runcmd since it more easily handles rootdir
402 self
.message('Creating tarball of disk contents')
403 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
406 if __name__
== '__main__':
407 VmDebootstrap().run()