]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
2 # Copyright 2011, 2012, 2013 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(['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',
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',
67 self
.settings
.string(['hostname'],
68 'set name to HOSTNAME (%default)',
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
.boolean(['sudo'],
77 'install sudo, and if user is created, add them '
80 def process_args(self
, args
):
81 if not self
.settings
['image'] and not self
.settings
['tarball']:
82 raise cliapp
.AppException('You must give disk image filename, '
83 'or tarball filename')
84 if self
.settings
['image'] and not self
.settings
['size']:
85 raise cliapp
.AppException('If disk image is specified, '
86 'You must give image size.')
89 self
.mount_points
= []
92 if self
.settings
['image']:
93 self
.create_empty_image()
94 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 self
.customize(rootdir
)
109 if self
.settings
['image']:
110 self
.install_extlinux(rootdev
, 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 setup_kpartx(self
):
168 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
169 devices
= [line
.split()[2]
170 for line
in out
.splitlines()
171 if line
.startswith('add map ')]
172 if len(devices
) != 1:
173 raise cliapp
.AppException('Surprising number of partitions')
174 return '/dev/mapper/%s' % devices
[0]
176 def mkfs(self
, device
):
177 self
.message('Creating filesystem')
178 self
.runcmd(['mkfs', '-t', 'ext2', device
])
180 def debootstrap(self
, rootdir
):
181 self
.message('Debootstrapping')
183 include
= self
.settings
['package']
185 if not self
.settings
['no-kernel']:
186 if self
.settings
['arch'] == 'i386':
189 kernel_arch
= self
.settings
['arch']
190 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
191 include
.append(kernel_image
)
193 if self
.settings
['sudo'] and 'sudo' not in include
:
194 include
.append('sudo')
196 args
= ['debootstrap', '--arch=%s' % self
.settings
['arch']]
197 if include
: args
.append('--include=%s' % ','.join(include
))
198 args
+= [self
.settings
['distribution'],
199 rootdir
, self
.settings
['mirror']]
202 def set_hostname(self
, rootdir
):
203 hostname
= self
.settings
['hostname']
204 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
205 f
.write('%s\n' % hostname
)
207 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
208 with
open(etc_hosts
, 'r') as f
:
210 with
open(etc_hosts
, 'w') as f
:
211 for line
in data
.splitlines():
212 if line
.startswith('127.0.0.1'):
213 line
+= ' %s' % hostname
214 f
.write('%s\n' % line
)
216 def create_fstab(self
, rootdir
):
217 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
218 with
open(fstab
, 'w') as f
:
219 f
.write('proc /proc proc defaults 0 0\n')
220 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
222 def install_debs(self
, rootdir
):
223 if not self
.settings
['custom-package']:
225 self
.message('Installing custom packages')
226 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
228 for deb
in self
.settings
['custom-package']:
229 shutil
.copy(deb
, tmp
)
230 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
231 for deb
in self
.settings
['custom-package']]
233 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
234 logging
.debug('stdout:\n%s' % out
)
235 logging
.debug('stderr:\n%s' % err
)
236 out
= self
.runcmd(['chroot', rootdir
,
237 'apt-get', '-f', '--no-remove', 'install'])
238 logging
.debug('stdout:\n%s' % out
)
241 def set_root_password(self
, rootdir
):
242 if self
.settings
['root-password']:
243 self
.message('Setting root password')
244 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
245 elif self
.settings
['lock-root-password']:
246 self
.message('Locking root password')
247 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
249 self
.message('Give root an empty password')
250 self
.delete_password(rootdir
, 'root')
252 def create_users(self
, rootdir
):
253 def create_user(user
):
254 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
255 '--disabled-password', user
])
256 if self
.settings
['sudo']:
257 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
259 for userpass
in self
.settings
['user']:
261 user
, password
= userpass
.split('/', 1)
263 self
.set_password(rootdir
, user
, password
)
265 create_user(userpass
)
266 self
.delete_password(rootdir
, userpass
)
268 def set_password(self
, rootdir
, user
, password
):
269 encrypted
= crypt
.crypt(password
, '..')
270 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
272 def delete_password(self
, rootdir
, user
):
273 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
275 def remove_udev_persistent_rules(self
, rootdir
):
276 self
.message('Removing udev persistent cd and net rules')
277 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
278 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
279 if os
.path
.exists(pathname
):
280 logging
.debug('rm %s' % pathname
)
283 logging
.debug('not removing non-existent %s' % pathname
)
285 def setup_networking(self
, rootdir
):
286 self
.message('Setting up networking')
288 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
290 f
.write('iface lo inet loopback\n')
292 if self
.settings
['enable-dhcp']:
294 f
.write('allow-hotplug eth0\n')
295 f
.write('iface eth0 inet dhcp\n')
299 def install_extlinux(self
, rootdev
, rootdir
):
300 self
.message('Installing extlinux')
303 dirname
= os
.path
.join(rootdir
, 'boot')
304 basenames
= os
.listdir(dirname
)
305 logging
.debug('find: %s' % basenames
)
306 for basename
in basenames
:
307 if re
.search(pattern
, basename
):
308 return os
.path
.join('boot', basename
)
309 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
311 kernel_image
= find('vmlinuz-.*')
312 initrd_image
= find('initrd.img-.*')
314 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
315 '-s', 'UUID', rootdev
])
316 uuid
= out
.splitlines()[0].strip()
318 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
319 logging
.debug('configure extlinux %s' % conf
)
327 append initrd=%(initrd)s root=UUID=%(uuid)s ro %(kserial)s
330 'kernel': kernel_image
,
331 'initrd': initrd_image
,
334 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
335 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
339 if self
.settings
['serial-console']:
340 logging
.debug('adding getty to serial console')
341 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
342 with
open(inittab
, 'a') as f
:
343 f
.write('\nS0:23:respawn:/sbin/getty -L ttyS0 115200 vt100\n')
345 self
.runcmd(['extlinux', '--install', rootdir
])
346 self
.runcmd(['sync'])
347 import time
; time
.sleep(2)
349 def cleanup_system(self
):
350 # Clean up after any errors.
352 self
.message('Cleaning up')
354 if self
.settings
['image']:
355 for mount_point
in self
.mount_points
:
356 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
358 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
360 for dirname
in self
.remove_dirs
:
361 shutil
.rmtree(dirname
)
363 def customize(self
, rootdir
):
364 script
= self
.settings
['customize']
366 self
.message('Running customize script %s' % script
)
367 with
open('/dev/tty', 'w') as tty
:
368 cliapp
.runcmd([script
, rootdir
], stdout
=tty
, stderr
=tty
)
370 def create_tarball(self
, rootdir
):
371 # Create a tarball of the disk's contents
372 # shell out to runcmd since it more easily handles rootdir
373 self
.message('Creating tarball of disk contents')
374 self
.runcmd(['tar', '-cf', self
.settings
['tarball'], '-C', rootdir
, '.'])
377 if __name__
== '__main__':
378 VmDebootstrap().run()