]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
93bb2c6bce46b44760450e181cb79d84c16296da
2 # Copyright 2011 Lars Wirzenius
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
27 class VmDebootstrap(cliapp
.Application
):
29 def add_settings(self
):
30 default_arch
= 'amd64'
32 self
.settings
.boolean(['verbose'], 'report what is going on')
33 self
.settings
.string(['image'], 'put created disk image in FILE',
35 self
.settings
.bytesize(['size'],
36 'create a disk image of size SIZE (%default)',
39 self
.settings
.string(['mirror'],
40 'use MIRROR as package source (%default)',
42 default
='http://cdn.debian.net/debian/')
43 self
.settings
.string(['arch'], 'architecture to use (%default)',
46 self
.settings
.string(['distribution'],
47 'release to use (%default)',
50 self
.settings
.string_list(['package'], 'install PACKAGE onto system')
51 self
.settings
.string_list(['custom-package'],
52 'install package in DEB file onto system '
55 self
.settings
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
56 self
.settings
.string(['root-password'], 'set root password',
58 self
.settings
.boolean(['lock-root-password'],
59 'lock root account so they cannot login?')
60 self
.settings
.string(['customize'],
61 'run SCRIPT after setting up system',
63 self
.settings
.string(['hostname'],
64 'set name to HOSTNAME (%default)',
67 self
.settings
.string_list(['user'],
68 'create USER with PASSWORD',
69 metavar
='USER/PASSWORD')
70 self
.settings
.boolean(['serial-console'],
71 'configure image to use a serial console')
72 self
.settings
.boolean(['sudo'],
73 'install sudo, and if user is created, add them '
76 def process_args(self
, args
):
77 if not self
.settings
['image']:
78 raise cliapp
.AppException('You must give image filename.')
79 if not self
.settings
['size']:
80 raise cliapp
.AppException('You must give image size.')
83 self
.mount_points
= []
86 self
.create_empty_image()
87 self
.partition_image()
89 rootdev
= self
.setup_kpartx()
91 rootdir
= self
.mount(rootdev
)
92 self
.debootstrap(rootdir
)
93 self
.set_hostname(rootdir
)
94 self
.create_fstab(rootdir
)
95 self
.install_debs(rootdir
)
96 self
.set_root_password(rootdir
)
97 self
.create_users(rootdir
)
98 self
.remove_udev_persistent_rules(rootdir
)
99 self
.setup_networking(rootdir
)
100 self
.install_extlinux(rootdev
, rootdir
)
101 self
.customize(rootdir
)
102 except BaseException
, e
:
103 self
.message('EEEK! Something bad happened...')
104 self
.cleanup_system()
107 self
.cleanup_system()
109 def message(self
, msg
):
110 if self
.settings
['verbose']:
113 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
114 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
115 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
116 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
118 out
, err
= p
.communicate(stdin
)
119 if p
.returncode
!= 0:
120 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
123 raise cliapp
.AppException(msg
)
127 dirname
= tempfile
.mkdtemp()
128 self
.remove_dirs
.append(dirname
)
129 logging
.debug('mkdir %s' % dirname
)
132 def mount(self
, device
):
133 self
.message('Mounting %s' % device
)
134 mount_point
= self
.mkdtemp()
135 self
.runcmd(['mount', device
, mount_point
])
136 self
.mount_points
.append(mount_point
)
137 logging
.debug('mounted %s on %s' % (device
, mount_point
))
140 def create_empty_image(self
):
141 self
.message('Creating disk image')
142 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
143 self
.settings
['image'],
144 str(self
.settings
['size'])])
146 def partition_image(self
):
147 self
.message('Creating partitions')
148 self
.runcmd(['parted', '-s', self
.settings
['image'],
150 self
.runcmd(['parted', '-s', self
.settings
['image'],
151 'mkpart', 'primary', '0%', '100%'])
152 self
.runcmd(['parted', '-s', self
.settings
['image'],
153 'set', '1', 'boot', 'on'])
155 def install_mbr(self
):
156 self
.message('Installing MBR')
157 self
.runcmd(['install-mbr', self
.settings
['image']])
159 def setup_kpartx(self
):
160 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
161 devices
= [line
.split()[2]
162 for line
in out
.splitlines()
163 if line
.startswith('add map ')]
164 if len(devices
) != 1:
165 raise cliapp
.AppException('Surprising number of partitions')
166 return '/dev/mapper/%s' % devices
[0]
168 def mkfs(self
, device
):
169 self
.message('Creating filesystem')
170 self
.runcmd(['mkfs', '-t', 'ext2', device
])
172 def debootstrap(self
, rootdir
):
173 self
.message('Debootstrapping')
175 if self
.settings
['arch'] == 'i386':
178 kernel_arch
= self
.settings
['arch']
179 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
181 include
= [kernel_image
] + self
.settings
['package']
182 if self
.settings
['sudo'] and 'sudo' not in include
:
183 include
.append('sudo')
185 self
.runcmd(['debootstrap',
186 '--arch=%s' % self
.settings
['arch'],
187 '--include=%s' % ','.join(include
),
188 self
.settings
['distribution'],
190 self
.settings
['mirror']])
192 def set_hostname(self
, rootdir
):
193 hostname
= self
.settings
['hostname']
194 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
195 f
.write('%s\n' % hostname
)
197 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
198 with
open(etc_hosts
, 'r') as f
:
200 with
open(etc_hosts
, 'w') as f
:
201 for line
in data
.splitlines():
202 if line
.startswith('127.0.0.1'):
203 line
+= ' %s' % hostname
204 f
.write('%s\n' % line
)
206 def create_fstab(self
, rootdir
):
207 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
208 with
open(fstab
, 'w') as f
:
209 f
.write('proc /proc proc defaults 0 0\n')
210 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
212 def install_debs(self
, rootdir
):
213 if not self
.settings
['custom-package']:
215 self
.message('Installing custom packages')
216 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
218 for deb
in self
.settings
['custom-package']:
219 shutil
.copy(deb
, tmp
)
220 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
221 for deb
in self
.settings
['custom-package']]
223 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
224 logging
.debug('stdout:\n%s' % out
)
225 logging
.debug('stderr:\n%s' % err
)
226 out
= self
.runcmd(['chroot', rootdir
,
227 'apt-get', '-f', '--no-remove', 'install'])
228 logging
.debug('stdout:\n%s' % out
)
231 def set_root_password(self
, rootdir
):
232 if self
.settings
['root-password']:
233 self
.message('Setting root password')
234 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
235 elif self
.settings
['lock-root-password']:
236 self
.message('Locking root password')
237 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
239 self
.message('Give root an empty password')
240 self
.delete_password(rootdir
, 'root')
242 def create_users(self
, rootdir
):
243 def create_user(user
):
244 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
245 '--disabled-password', user
])
246 if self
.settings
['sudo']:
247 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
249 for userpass
in self
.settings
['user']:
251 user
, password
= userpass
.split('/', 1)
253 self
.set_password(rootdir
, user
, password
)
255 create_user(userpass
)
256 self
.delete_password(rootdir
, userpass
)
258 def set_password(self
, rootdir
, user
, password
):
259 encrypted
= crypt
.crypt(password
, '..')
260 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
262 def delete_password(self
, rootdir
, user
):
263 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
265 def remove_udev_persistent_rules(self
, rootdir
):
266 self
.message('Removing udev persistent cd and net rules')
267 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
268 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
269 if os
.path
.exists(pathname
):
270 logging
.debug('rm %s' % pathname
)
273 logging
.debug('not removing non-existent %s' % pathname
)
275 def setup_networking(self
, rootdir
):
276 self
.message('Setting up networking')
278 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
280 f
.write('iface lo inet loopback\n')
282 if self
.settings
['enable-dhcp']:
284 f
.write('allow-hotplug eth0\n')
285 f
.write('iface eth0 inet dhcp\n')
289 def install_extlinux(self
, rootdev
, rootdir
):
290 self
.message('Installing extlinux')
293 dirname
= os
.path
.join(rootdir
, 'boot')
294 basenames
= os
.listdir(dirname
)
295 logging
.debug('find: %s' % basenames
)
296 for basename
in basenames
:
297 if re
.search(pattern
, basename
):
298 return os
.path
.join('boot', basename
)
299 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
301 kernel_image
= find('vmlinuz-.*')
302 initrd_image
= find('initrd.img-.*')
304 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
305 '-s', 'UUID', rootdev
])
306 uuid
= out
.splitlines()[0].strip()
308 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
309 logging
.debug('configure extlinux %s' % conf
)
317 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
320 'kernel': kernel_image
,
321 'initrd': initrd_image
,
324 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
325 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
329 if self
.settings
['serial-console']:
330 logging
.debug('adding getty to serial console')
331 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
332 with
open(inittab
, 'a') as f
:
333 f
.write('\nS0:23:respawn:/sbin/getty -L ttyS0 115200 vt100\n')
335 self
.runcmd(['extlinux', '--install', rootdir
])
336 self
.runcmd(['sync'])
337 import time
; time
.sleep(2)
339 def cleanup_system(self
):
340 # Clean up after any errors.
342 self
.message('Cleaning up')
344 for mount_point
in self
.mount_points
:
345 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
347 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
349 for dirname
in self
.remove_dirs
:
350 shutil
.rmtree(dirname
)
352 def customize(self
, rootdir
):
353 script
= self
.settings
['customize']
355 self
.message('Running customize script %s' % script
)
356 self
.runcmd([script
, rootdir
])
359 if __name__
== '__main__':
360 VmDebootstrap().run()