]>
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 if self
.settings
['tarball']:
119 self
.create_tarball(rootdir
)
120 except BaseException
, e
:
121 self
.message('EEEK! Something bad happened...')
122 self
.cleanup_system()
125 self
.cleanup_system()
127 def message(self
, msg
):
129 if self
.settings
['verbose']:
132 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
133 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
134 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
135 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
137 out
, err
= p
.communicate(stdin
)
138 if p
.returncode
!= 0:
139 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
142 raise cliapp
.AppException(msg
)
146 dirname
= tempfile
.mkdtemp()
147 self
.remove_dirs
.append(dirname
)
148 logging
.debug('mkdir %s' % dirname
)
151 def mount(self
, device
):
152 self
.message('Mounting %s' % device
)
153 mount_point
= self
.mkdtemp()
154 self
.runcmd(['mount', device
, mount_point
])
155 self
.mount_points
.append(mount_point
)
156 logging
.debug('mounted %s on %s' % (device
, mount_point
))
159 def create_empty_image(self
):
160 self
.message('Creating disk image')
161 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
162 self
.settings
['image'],
163 str(self
.settings
['size'])])
165 def partition_image(self
):
166 self
.message('Creating partitions')
167 self
.runcmd(['parted', '-s', self
.settings
['image'],
169 self
.runcmd(['parted', '-s', self
.settings
['image'],
170 'mkpart', 'primary', '0%', '100%'])
171 self
.runcmd(['parted', '-s', self
.settings
['image'],
172 'set', '1', 'boot', 'on'])
174 def install_mbr(self
):
175 self
.message('Installing MBR')
176 self
.runcmd(['install-mbr', self
.settings
['image']])
178 def setup_kpartx(self
):
179 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
180 devices
= [line
.split()[2]
181 for line
in out
.splitlines()
182 if line
.startswith('add map ')]
183 if len(devices
) != 1:
184 raise cliapp
.AppException('Surprising number of partitions')
185 return '/dev/mapper/%s' % devices
[0]
187 def mkfs(self
, device
):
188 self
.message('Creating filesystem')
189 self
.runcmd(['mkfs', '-t', 'ext2', device
])
191 def debootstrap(self
, rootdir
):
192 self
.message('Debootstrapping')
194 necessary_packages
= ['acpid']
196 include
= self
.settings
['package']
198 if not self
.settings
['no-kernel']:
199 if self
.settings
['arch'] == 'i386':
202 kernel_arch
= self
.settings
['arch']
203 kernel_image
= 'linux-image-%s' % kernel_arch
204 include
.append(kernel_image
)
206 if self
.settings
['sudo'] and 'sudo' not in include
:
207 include
.append('sudo')
209 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
211 '--include=%s' % ','.join(necessary_packages
+ include
))
212 args
+= [self
.settings
['distribution'],
213 rootdir
, self
.settings
['mirror']]
216 def set_hostname(self
, rootdir
):
217 hostname
= self
.settings
['hostname']
218 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
219 f
.write('%s\n' % hostname
)
221 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
222 with
open(etc_hosts
, 'r') as f
:
224 with
open(etc_hosts
, 'w') as f
:
225 for line
in data
.splitlines():
226 if line
.startswith('127.0.0.1'):
227 line
+= ' %s' % hostname
228 f
.write('%s\n' % line
)
230 def create_fstab(self
, rootdir
):
231 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
232 with
open(fstab
, 'w') as f
:
233 f
.write('proc /proc proc defaults 0 0\n')
234 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
236 def install_debs(self
, rootdir
):
237 if not self
.settings
['custom-package']:
239 self
.message('Installing custom packages')
240 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
242 for deb
in self
.settings
['custom-package']:
243 shutil
.copy(deb
, tmp
)
244 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
245 for deb
in self
.settings
['custom-package']]
247 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
248 logging
.debug('stdout:\n%s' % out
)
249 logging
.debug('stderr:\n%s' % err
)
250 out
= self
.runcmd(['chroot', rootdir
,
251 'apt-get', '-f', '--no-remove', 'install'])
252 logging
.debug('stdout:\n%s' % out
)
255 def cleanup_apt_cache(self
, rootdir
):
256 out
= self
.runcmd(['chroot', rootdir
, 'apt-get', 'clean'])
257 logging
.debug('stdout:\n%s' % out
)
259 def set_root_password(self
, rootdir
):
260 if self
.settings
['root-password']:
261 self
.message('Setting root password')
262 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
263 elif self
.settings
['lock-root-password']:
264 self
.message('Locking root password')
265 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
267 self
.message('Give root an empty password')
268 self
.delete_password(rootdir
, 'root')
270 def create_users(self
, rootdir
):
271 def create_user(user
):
272 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
273 '--disabled-password', user
])
274 if self
.settings
['sudo']:
275 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
277 for userpass
in self
.settings
['user']:
279 user
, password
= userpass
.split('/', 1)
281 self
.set_password(rootdir
, user
, password
)
283 create_user(userpass
)
284 self
.delete_password(rootdir
, userpass
)
286 def set_password(self
, rootdir
, user
, password
):
287 encrypted
= crypt
.crypt(password
, '..')
288 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
290 def delete_password(self
, rootdir
, user
):
291 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
293 def remove_udev_persistent_rules(self
, rootdir
):
294 self
.message('Removing udev persistent cd and net rules')
295 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
296 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
297 if os
.path
.exists(pathname
):
298 logging
.debug('rm %s' % pathname
)
301 logging
.debug('not removing non-existent %s' % pathname
)
303 def setup_networking(self
, rootdir
):
304 self
.message('Setting up networking')
306 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
308 f
.write('iface lo inet loopback\n')
310 if self
.settings
['enable-dhcp']:
312 f
.write('allow-hotplug eth0\n')
313 f
.write('iface eth0 inet dhcp\n')
317 def install_extlinux(self
, rootdev
, rootdir
):
318 self
.message('Installing extlinux')
321 dirname
= os
.path
.join(rootdir
, 'boot')
322 basenames
= os
.listdir(dirname
)
323 logging
.debug('find: %s' % basenames
)
324 for basename
in basenames
:
325 if re
.search(pattern
, basename
):
326 return os
.path
.join('boot', basename
)
327 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
329 kernel_image
= find('vmlinuz-.*')
330 initrd_image
= find('initrd.img-.*')
332 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
333 '-s', 'UUID', rootdev
])
334 uuid
= out
.splitlines()[0].strip()
336 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
337 logging
.debug('configure extlinux %s' % conf
)
345 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
348 'kernel': kernel_image
,
349 'initrd': initrd_image
,
352 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
353 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
357 if self
.settings
['serial-console']:
358 serial_command
= self
.settings
['serial-console-command']
359 logging
.debug('adding getty to serial console')
360 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
361 with
open(inittab
, 'a') as f
:
362 f
.write('\nS0:23:respawn:%s\n' % serial_command
)
364 self
.runcmd(['extlinux', '--install', rootdir
])
365 self
.runcmd(['sync'])
366 import time
; time
.sleep(2)
368 def cleanup_system(self
):
369 # Clean up after any errors.
371 self
.message('Cleaning up')
373 if self
.settings
['image']:
374 for mount_point
in self
.mount_points
:
375 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
377 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
379 for dirname
in self
.remove_dirs
:
380 shutil
.rmtree(dirname
)
382 def customize(self
, rootdir
):
383 script
= self
.settings
['customize']
385 self
.message('Running customize script %s' % script
)
386 with
open('/dev/tty', 'w') as tty
:
387 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
389 def create_tarball(self
, rootdir
):
390 # Create a tarball of the disk's contents
391 # shell out to runcmd since it more easily handles rootdir
392 self
.message('Creating tarball of disk contents')
393 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
396 if __name__
== '__main__':
397 VmDebootstrap().run()