]> git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
Allow custom command to handle the serial console
[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(['tarball'], "tar up the disk's contents in FILE",
41 metavar='FILE')
42 self.settings.string(['mirror'],
43 'use MIRROR as package source (%default)',
44 metavar='URL',
45 default='http://cdn.debian.net/debian/')
46 self.settings.string(['arch'], 'architecture to use (%default)',
47 metavar='ARCH',
48 default=default_arch)
49 self.settings.string(['distribution'],
50 'release to use (%default)',
51 metavar='NAME',
52 default='stable')
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 '
56 '(not from mirror)',
57 metavar='DEB')
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',
61 metavar='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',
66 metavar='SCRIPT')
67 self.settings.string(['hostname'],
68 'set name to HOSTNAME (%default)',
69 metavar='HOSTNAME',
70 default='debian')
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)',
79 metavar='COMMAND',
80 default='/sbin/getty -L ttyS0 115200 vt100')
81 self.settings.boolean(['sudo'],
82 'install sudo, and if user is created, add them '
83 'to sudo group')
84
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.')
92
93 self.remove_dirs = []
94 self.mount_points = []
95
96 try:
97 if self.settings['image']:
98 self.create_empty_image()
99 self.partition_image()
100 self.install_mbr()
101 rootdev = self.setup_kpartx()
102 self.mkfs(rootdev)
103 rootdir = self.mount(rootdev)
104 else:
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.set_root_password(rootdir)
111 self.create_users(rootdir)
112 self.remove_udev_persistent_rules(rootdir)
113 self.setup_networking(rootdir)
114 self.customize(rootdir)
115 if self.settings['image']:
116 self.install_extlinux(rootdev, rootdir)
117 if self.settings['tarball']:
118 self.create_tarball(rootdir)
119 except BaseException, e:
120 self.message('EEEK! Something bad happened...')
121 self.cleanup_system()
122 raise
123 else:
124 self.cleanup_system()
125
126 def message(self, msg):
127 logging.info(msg)
128 if self.settings['verbose']:
129 print msg
130
131 def runcmd(self, argv, stdin='', ignore_fail=False, **kwargs):
132 logging.debug('runcmd: %s %s' % (argv, kwargs))
133 p = subprocess.Popen(argv, stdin=subprocess.PIPE,
134 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
135 **kwargs)
136 out, err = p.communicate(stdin)
137 if p.returncode != 0:
138 msg = 'command failed: %s\n%s\n%s' % (argv, out, err)
139 logging.error(msg)
140 if not ignore_fail:
141 raise cliapp.AppException(msg)
142 return out
143
144 def mkdtemp(self):
145 dirname = tempfile.mkdtemp()
146 self.remove_dirs.append(dirname)
147 logging.debug('mkdir %s' % dirname)
148 return dirname
149
150 def mount(self, device):
151 self.message('Mounting %s' % device)
152 mount_point = self.mkdtemp()
153 self.runcmd(['mount', device, mount_point])
154 self.mount_points.append(mount_point)
155 logging.debug('mounted %s on %s' % (device, mount_point))
156 return mount_point
157
158 def create_empty_image(self):
159 self.message('Creating disk image')
160 self.runcmd(['qemu-img', 'create', '-f', 'raw',
161 self.settings['image'],
162 str(self.settings['size'])])
163
164 def partition_image(self):
165 self.message('Creating partitions')
166 self.runcmd(['parted', '-s', self.settings['image'],
167 'mklabel', 'msdos'])
168 self.runcmd(['parted', '-s', self.settings['image'],
169 'mkpart', 'primary', '0%', '100%'])
170 self.runcmd(['parted', '-s', self.settings['image'],
171 'set', '1', 'boot', 'on'])
172
173 def install_mbr(self):
174 self.message('Installing MBR')
175 self.runcmd(['install-mbr', self.settings['image']])
176
177 def setup_kpartx(self):
178 out = self.runcmd(['kpartx', '-av', self.settings['image']])
179 devices = [line.split()[2]
180 for line in out.splitlines()
181 if line.startswith('add map ')]
182 if len(devices) != 1:
183 raise cliapp.AppException('Surprising number of partitions')
184 return '/dev/mapper/%s' % devices[0]
185
186 def mkfs(self, device):
187 self.message('Creating filesystem')
188 self.runcmd(['mkfs', '-t', 'ext2', device])
189
190 def debootstrap(self, rootdir):
191 self.message('Debootstrapping')
192
193 necessary_packages = ['acpid']
194
195 include = self.settings['package']
196
197 if not self.settings['no-kernel']:
198 if self.settings['arch'] == 'i386':
199 kernel_arch = '486'
200 else:
201 kernel_arch = self.settings['arch']
202 kernel_image = 'linux-image-%s' % kernel_arch
203 include.append(kernel_image)
204
205 if self.settings['sudo'] and 'sudo' not in include:
206 include.append('sudo')
207
208 args = ['debootstrap', '--arch=%s' % self.settings['arch']]
209 args.append(
210 '--include=%s' % ','.join(necessary_packages + include))
211 args += [self.settings['distribution'],
212 rootdir, self.settings['mirror']]
213 self.runcmd(args)
214
215 def set_hostname(self, rootdir):
216 hostname = self.settings['hostname']
217 with open(os.path.join(rootdir, 'etc', 'hostname'), 'w') as f:
218 f.write('%s\n' % hostname)
219
220 etc_hosts = os.path.join(rootdir, 'etc', 'hosts')
221 with open(etc_hosts, 'r') as f:
222 data = f.read()
223 with open(etc_hosts, 'w') as f:
224 for line in data.splitlines():
225 if line.startswith('127.0.0.1'):
226 line += ' %s' % hostname
227 f.write('%s\n' % line)
228
229 def create_fstab(self, rootdir):
230 fstab = os.path.join(rootdir, 'etc', 'fstab')
231 with open(fstab, 'w') as f:
232 f.write('proc /proc proc defaults 0 0\n')
233 f.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
234
235 def install_debs(self, rootdir):
236 if not self.settings['custom-package']:
237 return
238 self.message('Installing custom packages')
239 tmp = os.path.join(rootdir, 'tmp', 'install_debs')
240 os.mkdir(tmp)
241 for deb in self.settings['custom-package']:
242 shutil.copy(deb, tmp)
243 filenames = [os.path.join('/tmp/install_debs', os.path.basename(deb))
244 for deb in self.settings['custom-package']]
245 out, err, exit = \
246 self.runcmd_unchecked(['chroot', rootdir, 'dpkg', '-i'] + filenames)
247 logging.debug('stdout:\n%s' % out)
248 logging.debug('stderr:\n%s' % err)
249 out = self.runcmd(['chroot', rootdir,
250 'apt-get', '-f', '--no-remove', 'install'])
251 logging.debug('stdout:\n%s' % out)
252 shutil.rmtree(tmp)
253
254 def set_root_password(self, rootdir):
255 if self.settings['root-password']:
256 self.message('Setting root password')
257 self.set_password(rootdir, 'root', self.settings['root-password'])
258 elif self.settings['lock-root-password']:
259 self.message('Locking root password')
260 self.runcmd(['chroot', rootdir, 'passwd', '-l', 'root'])
261 else:
262 self.message('Give root an empty password')
263 self.delete_password(rootdir, 'root')
264
265 def create_users(self, rootdir):
266 def create_user(user):
267 self.runcmd(['chroot', rootdir, 'adduser', '--gecos', user,
268 '--disabled-password', user])
269 if self.settings['sudo']:
270 self.runcmd(['chroot', rootdir, 'adduser', user, 'sudo'])
271
272 for userpass in self.settings['user']:
273 if '/' in userpass:
274 user, password = userpass.split('/', 1)
275 create_user(user)
276 self.set_password(rootdir, user, password)
277 else:
278 create_user(userpass)
279 self.delete_password(rootdir, userpass)
280
281 def set_password(self, rootdir, user, password):
282 encrypted = crypt.crypt(password, '..')
283 self.runcmd(['chroot', rootdir, 'usermod', '-p', encrypted, user])
284
285 def delete_password(self, rootdir, user):
286 self.runcmd(['chroot', rootdir, 'passwd', '-d', user])
287
288 def remove_udev_persistent_rules(self, rootdir):
289 self.message('Removing udev persistent cd and net rules')
290 for x in ['70-persistent-cd.rules', '70-persistent-net.rules']:
291 pathname = os.path.join(rootdir, 'etc', 'udev', 'rules.d', x)
292 if os.path.exists(pathname):
293 logging.debug('rm %s' % pathname)
294 os.remove(pathname)
295 else:
296 logging.debug('not removing non-existent %s' % pathname)
297
298 def setup_networking(self, rootdir):
299 self.message('Setting up networking')
300
301 f = open(os.path.join(rootdir, 'etc', 'network', 'interfaces'), 'w')
302 f.write('auto lo\n')
303 f.write('iface lo inet loopback\n')
304
305 if self.settings['enable-dhcp']:
306 f.write('\n')
307 f.write('allow-hotplug eth0\n')
308 f.write('iface eth0 inet dhcp\n')
309
310 f.close()
311
312 def install_extlinux(self, rootdev, rootdir):
313 self.message('Installing extlinux')
314
315 def find(pattern):
316 dirname = os.path.join(rootdir, 'boot')
317 basenames = os.listdir(dirname)
318 logging.debug('find: %s' % basenames)
319 for basename in basenames:
320 if re.search(pattern, basename):
321 return os.path.join('boot', basename)
322 raise cliapp.AppException('Cannot find match: %s' % pattern)
323
324 kernel_image = find('vmlinuz-.*')
325 initrd_image = find('initrd.img-.*')
326
327 out = self.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
328 '-s', 'UUID', rootdev])
329 uuid = out.splitlines()[0].strip()
330
331 conf = os.path.join(rootdir, 'extlinux.conf')
332 logging.debug('configure extlinux %s' % conf)
333 f = open(conf, 'w')
334 f.write('''
335 default linux
336 timeout 1
337
338 label linux
339 kernel %(kernel)s
340 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
341 %(extserial)s
342 ''' % {
343 'kernel': kernel_image,
344 'initrd': initrd_image,
345 'uuid': uuid,
346 'kserial':
347 'console=ttyS0,115200' if self.settings['serial-console'] else '',
348 'extserial': 'serial 0 115200' if self.settings['serial-console'] else '',
349 })
350 f.close()
351
352 if self.settings['serial-console']:
353 serial_command = self.settings['serial-console-command']
354 logging.debug('adding getty to serial console')
355 inittab = os.path.join(rootdir, 'etc/inittab')
356 with open(inittab, 'a') as f:
357 f.write('\nS0:23:respawn:%s\n' % serial_command)
358
359 self.runcmd(['extlinux', '--install', rootdir])
360 self.runcmd(['sync'])
361 import time; time.sleep(2)
362
363 def cleanup_system(self):
364 # Clean up after any errors.
365
366 self.message('Cleaning up')
367
368 if self.settings['image']:
369 for mount_point in self.mount_points:
370 self.runcmd(['umount', mount_point], ignore_fail=True)
371
372 self.runcmd(['kpartx', '-d', self.settings['image']], ignore_fail=True)
373
374 for dirname in self.remove_dirs:
375 shutil.rmtree(dirname)
376
377 def customize(self, rootdir):
378 script = self.settings['customize']
379 if script:
380 self.message('Running customize script %s' % script)
381 with open('/dev/tty', 'w') as tty:
382 cliapp.runcmd([script, rootdir], stdout=tty, stderr=tty)
383
384 def create_tarball(self, rootdir):
385 # Create a tarball of the disk's contents
386 # shell out to runcmd since it more easily handles rootdir
387 self.message('Creating tarball of disk contents')
388 self.runcmd(['tar', '-cf', self.settings['tarball'], '-C', rootdir, '.'])
389
390
391 if __name__ == '__main__':
392 VmDebootstrap().run()
393