]> git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
Add --no-kernel option
[forks/vmdebootstrap.git] / vmdebootstrap
1 #!/usr/bin/python
2 # Copyright 2011, 2012 Lars Wirzenius
3 # Copyright 2012 Codethink Limited
4 #
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.
9 #
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.
14 #
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/>.
17
18 import cliapp
19 import crypt
20 import logging
21 import os
22 import re
23 import shutil
24 import subprocess
25 import tempfile
26
27
28 class VmDebootstrap(cliapp.Application):
29
30 def add_settings(self):
31 default_arch = 'amd64'
32
33 self.settings.boolean(['verbose'], 'report what is going on')
34 self.settings.string(['image'], 'put created disk image in FILE',
35 metavar='FILE')
36 self.settings.bytesize(['size'],
37 'create a disk image of size SIZE (%default)',
38 metavar='SIZE',
39 default='1G')
40 self.settings.string(['mirror'],
41 'use MIRROR as package source (%default)',
42 metavar='URL',
43 default='http://cdn.debian.net/debian/')
44 self.settings.string(['arch'], 'architecture to use (%default)',
45 metavar='ARCH',
46 default=default_arch)
47 self.settings.string(['distribution'],
48 'release to use (%default)',
49 metavar='NAME',
50 default='stable')
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 '
54 '(not from mirror)',
55 metavar='DEB')
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',
59 metavar='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',
64 metavar='SCRIPT')
65 self.settings.string(['hostname'],
66 'set name to HOSTNAME (%default)',
67 metavar='HOSTNAME',
68 default='debian')
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 '
76 'to sudo group')
77
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.')
83
84 self.remove_dirs = []
85 self.mount_points = []
86
87 try:
88 self.create_empty_image()
89 self.partition_image()
90 self.install_mbr()
91 rootdev = self.setup_kpartx()
92 self.mkfs(rootdev)
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.install_extlinux(rootdev, rootdir)
103 self.customize(rootdir)
104 except BaseException, e:
105 self.message('EEEK! Something bad happened...')
106 self.cleanup_system()
107 raise
108 else:
109 self.cleanup_system()
110
111 def message(self, msg):
112 logging.info(msg)
113 if self.settings['verbose']:
114 print msg
115
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,
120 **kwargs)
121 out, err = p.communicate(stdin)
122 if p.returncode != 0:
123 msg = 'command failed: %s\n%s\n%s' % (argv, out, err)
124 logging.error(msg)
125 if not ignore_fail:
126 raise cliapp.AppException(msg)
127 return out
128
129 def mkdtemp(self):
130 dirname = tempfile.mkdtemp()
131 self.remove_dirs.append(dirname)
132 logging.debug('mkdir %s' % dirname)
133 return dirname
134
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))
141 return mount_point
142
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'])])
148
149 def partition_image(self):
150 self.message('Creating partitions')
151 self.runcmd(['parted', '-s', self.settings['image'],
152 'mklabel', 'msdos'])
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'])
157
158 def install_mbr(self):
159 self.message('Installing MBR')
160 self.runcmd(['install-mbr', self.settings['image']])
161
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]
170
171 def mkfs(self, device):
172 self.message('Creating filesystem')
173 self.runcmd(['mkfs', '-t', 'ext2', device])
174
175 def debootstrap(self, rootdir):
176 self.message('Debootstrapping')
177
178 include = self.settings['package']
179
180 if not self.settings['no-kernel']:
181 if self.settings['arch'] == 'i386':
182 kernel_arch = '686'
183 else:
184 kernel_arch = self.settings['arch']
185 kernel_image = 'linux-image-2.6-%s' % kernel_arch
186 include.append(kernel_image)
187
188 if self.settings['sudo'] and 'sudo' not in include:
189 include.append('sudo')
190
191 self.runcmd(['debootstrap',
192 '--arch=%s' % self.settings['arch'],
193 '--include=%s' % ','.join(include),
194 self.settings['distribution'],
195 rootdir,
196 self.settings['mirror']])
197
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)
202
203 etc_hosts = os.path.join(rootdir, 'etc', 'hosts')
204 with open(etc_hosts, 'r') as f:
205 data = f.read()
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)
211
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')
217
218 def install_debs(self, rootdir):
219 if not self.settings['custom-package']:
220 return
221 self.message('Installing custom packages')
222 tmp = os.path.join(rootdir, 'tmp', 'install_debs')
223 os.mkdir(tmp)
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']]
228 out, err, exit = \
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)
235 shutil.rmtree(tmp)
236
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'])
244 else:
245 self.message('Give root an empty password')
246 self.delete_password(rootdir, 'root')
247
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'])
254
255 for userpass in self.settings['user']:
256 if '/' in userpass:
257 user, password = userpass.split('/', 1)
258 create_user(user)
259 self.set_password(rootdir, user, password)
260 else:
261 create_user(userpass)
262 self.delete_password(rootdir, userpass)
263
264 def set_password(self, rootdir, user, password):
265 encrypted = crypt.crypt(password, '..')
266 self.runcmd(['chroot', rootdir, 'usermod', '-p', encrypted, user])
267
268 def delete_password(self, rootdir, user):
269 self.runcmd(['chroot', rootdir, 'passwd', '-d', user])
270
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)
277 os.remove(pathname)
278 else:
279 logging.debug('not removing non-existent %s' % pathname)
280
281 def setup_networking(self, rootdir):
282 self.message('Setting up networking')
283
284 f = open(os.path.join(rootdir, 'etc', 'network', 'interfaces'), 'w')
285 f.write('auto lo\n')
286 f.write('iface lo inet loopback\n')
287
288 if self.settings['enable-dhcp']:
289 f.write('\n')
290 f.write('allow-hotplug eth0\n')
291 f.write('iface eth0 inet dhcp\n')
292
293 f.close()
294
295 def install_extlinux(self, rootdev, rootdir):
296 self.message('Installing extlinux')
297
298 def find(pattern):
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)
306
307 kernel_image = find('vmlinuz-.*')
308 initrd_image = find('initrd.img-.*')
309
310 out = self.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
311 '-s', 'UUID', rootdev])
312 uuid = out.splitlines()[0].strip()
313
314 conf = os.path.join(rootdir, 'extlinux.conf')
315 logging.debug('configure extlinux %s' % conf)
316 f = open(conf, 'w')
317 f.write('''
318 default linux
319 timeout 1
320
321 label linux
322 kernel %(kernel)s
323 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
324 %(extserial)s
325 ''' % {
326 'kernel': kernel_image,
327 'initrd': initrd_image,
328 'uuid': uuid,
329 'kserial':
330 'console=ttyS0,115200' if self.settings['serial-console'] else '',
331 'extserial': 'serial 0 115200' if self.settings['serial-console'] else '',
332 })
333 f.close()
334
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')
340
341 self.runcmd(['extlinux', '--install', rootdir])
342 self.runcmd(['sync'])
343 import time; time.sleep(2)
344
345 def cleanup_system(self):
346 # Clean up after any errors.
347
348 self.message('Cleaning up')
349
350 for mount_point in self.mount_points:
351 self.runcmd(['umount', mount_point], ignore_fail=True)
352
353 self.runcmd(['kpartx', '-d', self.settings['image']], ignore_fail=True)
354
355 for dirname in self.remove_dirs:
356 shutil.rmtree(dirname)
357
358 def customize(self, rootdir):
359 script = self.settings['customize']
360 if script:
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)
364
365
366 if __name__ == '__main__':
367 VmDebootstrap().run()
368