]>
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(['enable-dhcp'], 'enable DHCP on eth0')
59 self
.settings
.string(['root-password'], 'set root password',
61 self
.settings
.boolean(['lock-root-password'],
62 'lock root account so they cannot login?')
63 self
.settings
.string(['customize'],
64 'run SCRIPT after setting up system',
66 self
.settings
.string(['hostname'],
67 'set name to HOSTNAME (%default)',
70 self
.settings
.string_list(['user'],
71 'create USER with PASSWORD',
72 metavar
='USER/PASSWORD')
73 self
.settings
.boolean(['serial-console'],
74 'configure image to use a serial console')
75 self
.settings
.boolean(['sudo'],
76 'install sudo, and if user is created, add them '
79 def process_args(self
, args
):
80 if not self
.settings
['image'] and not self
.settings
['tarball']:
81 raise cliapp
.AppException('You must give disk image filename, '
82 'or tarball filename')
83 if self
.settings
['image'] and not self
.settings
['size']:
84 raise cliapp
.AppException('If disk image is specified, '
85 'You must give image size.')
88 self
.mount_points
= []
91 if self
.settings
['image']:
92 self
.create_empty_image()
93 self
.partition_image()
95 rootdev
= self
.setup_kpartx()
97 rootdir
= self
.mount(rootdev
)
99 rootdir
= self
.mkdtemp()
100 self
.debootstrap(rootdir
)
101 self
.set_hostname(rootdir
)
102 self
.create_fstab(rootdir
)
103 self
.install_debs(rootdir
)
104 self
.set_root_password(rootdir
)
105 self
.create_users(rootdir
)
106 self
.remove_udev_persistent_rules(rootdir
)
107 self
.setup_networking(rootdir
)
108 if self
.settings
['image']:
109 self
.install_extlinux(rootdev
, rootdir
)
110 self
.customize(rootdir
)
111 if self
.settings
['tarball']:
112 self
.create_tarball(rootdir
)
113 except BaseException
, e
:
114 self
.message('EEEK! Something bad happened...')
115 self
.cleanup_system()
118 self
.cleanup_system()
120 def message(self
, msg
):
122 if self
.settings
['verbose']:
125 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
126 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
127 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
128 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
130 out
, err
= p
.communicate(stdin
)
131 if p
.returncode
!= 0:
132 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
135 raise cliapp
.AppException(msg
)
139 dirname
= tempfile
.mkdtemp()
140 self
.remove_dirs
.append(dirname
)
141 logging
.debug('mkdir %s' % dirname
)
144 def mount(self
, device
):
145 self
.message('Mounting %s' % device
)
146 mount_point
= self
.mkdtemp()
147 self
.runcmd(['mount', device
, mount_point
])
148 self
.mount_points
.append(mount_point
)
149 logging
.debug('mounted %s on %s' % (device
, mount_point
))
152 def create_empty_image(self
):
153 self
.message('Creating disk image')
154 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
155 self
.settings
['image'],
156 str(self
.settings
['size'])])
158 def partition_image(self
):
159 self
.message('Creating partitions')
160 self
.runcmd(['parted', '-s', self
.settings
['image'],
162 self
.runcmd(['parted', '-s', self
.settings
['image'],
163 'mkpart', 'primary', '0%', '100%'])
164 self
.runcmd(['parted', '-s', self
.settings
['image'],
165 'set', '1', 'boot', 'on'])
167 def install_mbr(self
):
168 self
.message('Installing MBR')
169 self
.runcmd(['install-mbr', self
.settings
['image']])
171 def setup_kpartx(self
):
172 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
173 devices
= [line
.split()[2]
174 for line
in out
.splitlines()
175 if line
.startswith('add map ')]
176 if len(devices
) != 1:
177 raise cliapp
.AppException('Surprising number of partitions')
178 return '/dev/mapper/%s' % devices
[0]
180 def mkfs(self
, device
):
181 self
.message('Creating filesystem')
182 self
.runcmd(['mkfs', '-t', 'ext2', device
])
184 def debootstrap(self
, rootdir
):
185 self
.message('Debootstrapping')
187 if self
.settings
['arch'] == 'i386':
190 kernel_arch
= self
.settings
['arch']
191 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
193 include
= [kernel_image
] + self
.settings
['package']
194 if self
.settings
['sudo'] and 'sudo' not in include
:
195 include
.append('sudo')
197 self
.runcmd(['debootstrap',
198 '--arch=%s' % self
.settings
['arch'],
199 '--include=%s' % ','.join(include
),
200 self
.settings
['distribution'],
202 self
.settings
['mirror']])
204 def set_hostname(self
, rootdir
):
205 hostname
= self
.settings
['hostname']
206 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
207 f
.write('%s\n' % hostname
)
209 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
210 with
open(etc_hosts
, 'r') as f
:
212 with
open(etc_hosts
, 'w') as f
:
213 for line
in data
.splitlines():
214 if line
.startswith('127.0.0.1'):
215 line
+= ' %s' % hostname
216 f
.write('%s\n' % line
)
218 def create_fstab(self
, rootdir
):
219 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
220 with
open(fstab
, 'w') as f
:
221 f
.write('proc /proc proc defaults 0 0\n')
222 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
224 def install_debs(self
, rootdir
):
225 if not self
.settings
['custom-package']:
227 self
.message('Installing custom packages')
228 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
230 for deb
in self
.settings
['custom-package']:
231 shutil
.copy(deb
, tmp
)
232 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
233 for deb
in self
.settings
['custom-package']]
235 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
236 logging
.debug('stdout:\n%s' % out
)
237 logging
.debug('stderr:\n%s' % err
)
238 out
= self
.runcmd(['chroot', rootdir
,
239 'apt-get', '-f', '--no-remove', 'install'])
240 logging
.debug('stdout:\n%s' % out
)
243 def set_root_password(self
, rootdir
):
244 if self
.settings
['root-password']:
245 self
.message('Setting root password')
246 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
247 elif self
.settings
['lock-root-password']:
248 self
.message('Locking root password')
249 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
251 self
.message('Give root an empty password')
252 self
.delete_password(rootdir
, 'root')
254 def create_users(self
, rootdir
):
255 def create_user(user
):
256 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
257 '--disabled-password', user
])
258 if self
.settings
['sudo']:
259 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
261 for userpass
in self
.settings
['user']:
263 user
, password
= userpass
.split('/', 1)
265 self
.set_password(rootdir
, user
, password
)
267 create_user(userpass
)
268 self
.delete_password(rootdir
, userpass
)
270 def set_password(self
, rootdir
, user
, password
):
271 encrypted
= crypt
.crypt(password
, '..')
272 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
274 def delete_password(self
, rootdir
, user
):
275 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
277 def remove_udev_persistent_rules(self
, rootdir
):
278 self
.message('Removing udev persistent cd and net rules')
279 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
280 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
281 if os
.path
.exists(pathname
):
282 logging
.debug('rm %s' % pathname
)
285 logging
.debug('not removing non-existent %s' % pathname
)
287 def setup_networking(self
, rootdir
):
288 self
.message('Setting up networking')
290 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
292 f
.write('iface lo inet loopback\n')
294 if self
.settings
['enable-dhcp']:
296 f
.write('allow-hotplug eth0\n')
297 f
.write('iface eth0 inet dhcp\n')
301 def install_extlinux(self
, rootdev
, rootdir
):
302 self
.message('Installing extlinux')
305 dirname
= os
.path
.join(rootdir
, 'boot')
306 basenames
= os
.listdir(dirname
)
307 logging
.debug('find: %s' % basenames
)
308 for basename
in basenames
:
309 if re
.search(pattern
, basename
):
310 return os
.path
.join('boot', basename
)
311 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
313 kernel_image
= find('vmlinuz-.*')
314 initrd_image
= find('initrd.img-.*')
316 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
317 '-s', 'UUID', rootdev
])
318 uuid
= out
.splitlines()[0].strip()
320 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
321 logging
.debug('configure extlinux %s' % conf
)
329 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
332 'kernel': kernel_image
,
333 'initrd': initrd_image
,
336 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
337 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
341 if self
.settings
['serial-console']:
342 logging
.debug('adding getty to serial console')
343 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
344 with
open(inittab
, 'a') as f
:
345 f
.write('\nS0:23:respawn:/sbin/getty -L ttyS0 115200 vt100\n')
347 self
.runcmd(['extlinux', '--install', rootdir
])
348 self
.runcmd(['sync'])
349 import time
; time
.sleep(2)
351 def cleanup_system(self
):
352 # Clean up after any errors.
354 self
.message('Cleaning up')
356 if self
.settings
['image']:
357 for mount_point
in self
.mount_points
:
358 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
360 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
362 for dirname
in self
.remove_dirs
:
363 shutil
.rmtree(dirname
)
365 def customize(self
, rootdir
):
366 script
= self
.settings
['customize']
368 self
.message('Running customize script %s' % script
)
369 with
open('/dev/tty', 'w') as tty
:
370 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
372 def create_tarball(self
, rootdir
):
373 # Create a tarball of the disk's contents
374 # shell out to runcmd since it more easily handles rootdir
375 self
.message('Creating tarball of disk contents')
376 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
379 if __name__
== '__main__':
380 VmDebootstrap().run()