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