]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
2ffe6634bb58303aa13241f9f9736e0bb600d149
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(['mirror'],
41 'use MIRROR as package source (%default)',
43 default
='http://cdn.debian.net/debian/')
44 self
.settings
.string(['arch'], 'architecture to use (%default)',
47 self
.settings
.string(['distribution'],
48 'release to use (%default)',
51 self
.settings
.string_list(['package'], 'install PACKAGE onto system')
52 self
.settings
.string_list(['custom-package'],
53 'install package in DEB file onto system '
56 self
.settings
.boolean(['no-kernel'], 'do not install a linux package')
57 self
.settings
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
58 self
.settings
.string(['root-password'], 'set root password',
60 self
.settings
.boolean(['lock-root-password'],
61 'lock root account so they cannot login?')
62 self
.settings
.string(['customize'],
63 'run SCRIPT after setting up system',
65 self
.settings
.string(['hostname'],
66 'set name to HOSTNAME (%default)',
69 self
.settings
.string_list(['user'],
70 'create USER with PASSWORD',
71 metavar
='USER/PASSWORD')
72 self
.settings
.boolean(['serial-console'],
73 'configure image to use a serial console')
74 self
.settings
.boolean(['sudo'],
75 'install sudo, and if user is created, add them '
78 def process_args(self
, args
):
79 if not self
.settings
['image']:
80 raise cliapp
.AppException('You must give image filename.')
81 if not self
.settings
['size']:
82 raise cliapp
.AppException('You must give image size.')
85 self
.mount_points
= []
88 self
.create_empty_image()
89 self
.partition_image()
91 rootdev
= self
.setup_kpartx()
93 rootdir
= self
.mount(rootdev
)
94 self
.debootstrap(rootdir
)
95 self
.set_hostname(rootdir
)
96 self
.create_fstab(rootdir
)
97 self
.install_debs(rootdir
)
98 self
.set_root_password(rootdir
)
99 self
.create_users(rootdir
)
100 self
.remove_udev_persistent_rules(rootdir
)
101 self
.setup_networking(rootdir
)
102 self
.customize(rootdir
)
103 self
.install_extlinux(rootdev
, rootdir
)
104 except BaseException
, e
:
105 self
.message('EEEK! Something bad happened...')
106 self
.cleanup_system()
109 self
.cleanup_system()
111 def message(self
, msg
):
113 if self
.settings
['verbose']:
116 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
117 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
118 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
119 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
121 out
, err
= p
.communicate(stdin
)
122 if p
.returncode
!= 0:
123 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
126 raise cliapp
.AppException(msg
)
130 dirname
= tempfile
.mkdtemp()
131 self
.remove_dirs
.append(dirname
)
132 logging
.debug('mkdir %s' % dirname
)
135 def mount(self
, device
):
136 self
.message('Mounting %s' % device
)
137 mount_point
= self
.mkdtemp()
138 self
.runcmd(['mount', device
, mount_point
])
139 self
.mount_points
.append(mount_point
)
140 logging
.debug('mounted %s on %s' % (device
, mount_point
))
143 def create_empty_image(self
):
144 self
.message('Creating disk image')
145 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
146 self
.settings
['image'],
147 str(self
.settings
['size'])])
149 def partition_image(self
):
150 self
.message('Creating partitions')
151 self
.runcmd(['parted', '-s', self
.settings
['image'],
153 self
.runcmd(['parted', '-s', self
.settings
['image'],
154 'mkpart', 'primary', '0%', '100%'])
155 self
.runcmd(['parted', '-s', self
.settings
['image'],
156 'set', '1', 'boot', 'on'])
158 def install_mbr(self
):
159 self
.message('Installing MBR')
160 self
.runcmd(['install-mbr', self
.settings
['image']])
162 def setup_kpartx(self
):
163 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
164 devices
= [line
.split()[2]
165 for line
in out
.splitlines()
166 if line
.startswith('add map ')]
167 if len(devices
) != 1:
168 raise cliapp
.AppException('Surprising number of partitions')
169 return '/dev/mapper/%s' % devices
[0]
171 def mkfs(self
, device
):
172 self
.message('Creating filesystem')
173 self
.runcmd(['mkfs', '-t', 'ext2', device
])
175 def debootstrap(self
, rootdir
):
176 self
.message('Debootstrapping')
178 include
= self
.settings
['package']
180 if not self
.settings
['no-kernel']:
181 if self
.settings
['arch'] == 'i386':
184 kernel_arch
= self
.settings
['arch']
185 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
186 include
.append(kernel_image
)
188 if self
.settings
['sudo'] and 'sudo' not in include
:
189 include
.append('sudo')
191 self
.runcmd(['debootstrap',
192 '--arch=%s' % self
.settings
['arch'],
193 '--include=%s' % ','.join(include
),
194 self
.settings
['distribution'],
196 self
.settings
['mirror']])
198 def set_hostname(self
, rootdir
):
199 hostname
= self
.settings
['hostname']
200 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
201 f
.write('%s\n' % hostname
)
203 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
204 with
open(etc_hosts
, 'r') as f
:
206 with
open(etc_hosts
, 'w') as f
:
207 for line
in data
.splitlines():
208 if line
.startswith('127.0.0.1'):
209 line
+= ' %s' % hostname
210 f
.write('%s\n' % line
)
212 def create_fstab(self
, rootdir
):
213 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
214 with
open(fstab
, 'w') as f
:
215 f
.write('proc /proc proc defaults 0 0\n')
216 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
218 def install_debs(self
, rootdir
):
219 if not self
.settings
['custom-package']:
221 self
.message('Installing custom packages')
222 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
224 for deb
in self
.settings
['custom-package']:
225 shutil
.copy(deb
, tmp
)
226 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
227 for deb
in self
.settings
['custom-package']]
229 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
230 logging
.debug('stdout:\n%s' % out
)
231 logging
.debug('stderr:\n%s' % err
)
232 out
= self
.runcmd(['chroot', rootdir
,
233 'apt-get', '-f', '--no-remove', 'install'])
234 logging
.debug('stdout:\n%s' % out
)
237 def set_root_password(self
, rootdir
):
238 if self
.settings
['root-password']:
239 self
.message('Setting root password')
240 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
241 elif self
.settings
['lock-root-password']:
242 self
.message('Locking root password')
243 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
245 self
.message('Give root an empty password')
246 self
.delete_password(rootdir
, 'root')
248 def create_users(self
, rootdir
):
249 def create_user(user
):
250 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
251 '--disabled-password', user
])
252 if self
.settings
['sudo']:
253 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
255 for userpass
in self
.settings
['user']:
257 user
, password
= userpass
.split('/', 1)
259 self
.set_password(rootdir
, user
, password
)
261 create_user(userpass
)
262 self
.delete_password(rootdir
, userpass
)
264 def set_password(self
, rootdir
, user
, password
):
265 encrypted
= crypt
.crypt(password
, '..')
266 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
268 def delete_password(self
, rootdir
, user
):
269 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
271 def remove_udev_persistent_rules(self
, rootdir
):
272 self
.message('Removing udev persistent cd and net rules')
273 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
274 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
275 if os
.path
.exists(pathname
):
276 logging
.debug('rm %s' % pathname
)
279 logging
.debug('not removing non-existent %s' % pathname
)
281 def setup_networking(self
, rootdir
):
282 self
.message('Setting up networking')
284 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
286 f
.write('iface lo inet loopback\n')
288 if self
.settings
['enable-dhcp']:
290 f
.write('allow-hotplug eth0\n')
291 f
.write('iface eth0 inet dhcp\n')
295 def install_extlinux(self
, rootdev
, rootdir
):
296 self
.message('Installing extlinux')
299 dirname
= os
.path
.join(rootdir
, 'boot')
300 basenames
= os
.listdir(dirname
)
301 logging
.debug('find: %s' % basenames
)
302 for basename
in basenames
:
303 if re
.search(pattern
, basename
):
304 return os
.path
.join('boot', basename
)
305 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
307 kernel_image
= find('vmlinuz-.*')
308 initrd_image
= find('initrd.img-.*')
310 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
311 '-s', 'UUID', rootdev
])
312 uuid
= out
.splitlines()[0].strip()
314 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
315 logging
.debug('configure extlinux %s' % conf
)
323 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
326 'kernel': kernel_image
,
327 'initrd': initrd_image
,
330 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
331 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
335 if self
.settings
['serial-console']:
336 logging
.debug('adding getty to serial console')
337 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
338 with
open(inittab
, 'a') as f
:
339 f
.write('\nS0:23:respawn:/sbin/getty -L ttyS0 115200 vt100\n')
341 self
.runcmd(['extlinux', '--install', rootdir
])
342 self
.runcmd(['sync'])
343 import time
; time
.sleep(2)
345 def cleanup_system(self
):
346 # Clean up after any errors.
348 self
.message('Cleaning up')
350 for mount_point
in self
.mount_points
:
351 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
353 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
355 for dirname
in self
.remove_dirs
:
356 shutil
.rmtree(dirname
)
358 def customize(self
, rootdir
):
359 script
= self
.settings
['customize']
361 self
.message('Running customize script %s' % script
)
362 with
open('/dev/tty', 'w') as tty
:
363 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
366 if __name__
== '__main__':
367 VmDebootstrap().run()