]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
cef188fd0fb77317557dba29b2ae2b8b79a949d4
2 # Copyright 2011, 2012 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(['mirror'],
41 'use MIRROR as package source (%default)',
43 default
='http://cdn.debian.net/debian/')
44 self
.settings
.string(['arch'], 'architecture to use (%default)',
47 self
.settings
.string(['distribution'],
48 'release to use (%default)',
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 '
56 self
.settings
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
57 self
.settings
.string(['root-password'], 'set root 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',
64 self
.settings
.string(['hostname'],
65 'set name to HOSTNAME (%default)',
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 '
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.')
84 self
.mount_points
= []
87 self
.create_empty_image()
88 self
.partition_image()
90 rootdev
= self
.setup_kpartx()
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()
108 self
.cleanup_system()
110 def message(self
, msg
):
111 if self
.settings
['verbose']:
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
,
119 out
, err
= p
.communicate(stdin
)
120 if p
.returncode
!= 0:
121 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
124 raise cliapp
.AppException(msg
)
128 dirname
= tempfile
.mkdtemp()
129 self
.remove_dirs
.append(dirname
)
130 logging
.debug('mkdir %s' % dirname
)
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
))
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'])])
147 def partition_image(self
):
148 self
.message('Creating partitions')
149 self
.runcmd(['parted', '-s', self
.settings
['image'],
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'])
156 def install_mbr(self
):
157 self
.message('Installing MBR')
158 self
.runcmd(['install-mbr', self
.settings
['image']])
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]
169 def mkfs(self
, device
):
170 self
.message('Creating filesystem')
171 self
.runcmd(['mkfs', '-t', 'ext2', device
])
173 def debootstrap(self
, rootdir
):
174 self
.message('Debootstrapping')
176 if self
.settings
['arch'] == 'i386':
179 kernel_arch
= self
.settings
['arch']
180 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
182 include
= [kernel_image
] + self
.settings
['package']
183 if self
.settings
['sudo'] and 'sudo' not in include
:
184 include
.append('sudo')
186 self
.runcmd(['debootstrap',
187 '--arch=%s' % self
.settings
['arch'],
188 '--include=%s' % ','.join(include
),
189 self
.settings
['distribution'],
191 self
.settings
['mirror']])
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
)
198 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
199 with
open(etc_hosts
, 'r') as f
:
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
)
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')
213 def install_debs(self
, rootdir
):
214 if not self
.settings
['custom-package']:
216 self
.message('Installing custom packages')
217 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
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']]
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
)
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'])
240 self
.message('Give root an empty password')
241 self
.delete_password(rootdir
, 'root')
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'])
250 for userpass
in self
.settings
['user']:
252 user
, password
= userpass
.split('/', 1)
254 self
.set_password(rootdir
, user
, password
)
256 create_user(userpass
)
257 self
.delete_password(rootdir
, userpass
)
259 def set_password(self
, rootdir
, user
, password
):
260 encrypted
= crypt
.crypt(password
, '..')
261 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
263 def delete_password(self
, rootdir
, user
):
264 self
.runcmd(['chroot', rootdir
, 'passwd', '-d', user
])
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
)
274 logging
.debug('not removing non-existent %s' % pathname
)
276 def setup_networking(self
, rootdir
):
277 self
.message('Setting up networking')
279 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
281 f
.write('iface lo inet loopback\n')
283 if self
.settings
['enable-dhcp']:
285 f
.write('allow-hotplug eth0\n')
286 f
.write('iface eth0 inet dhcp\n')
290 def install_extlinux(self
, rootdev
, rootdir
):
291 self
.message('Installing extlinux')
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
)
302 kernel_image
= find('vmlinuz-.*')
303 initrd_image
= find('initrd.img-.*')
305 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
306 '-s', 'UUID', rootdev
])
307 uuid
= out
.splitlines()[0].strip()
309 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
310 logging
.debug('configure extlinux %s' % conf
)
318 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
321 'kernel': kernel_image
,
322 'initrd': initrd_image
,
325 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
326 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
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')
336 self
.runcmd(['extlinux', '--install', rootdir
])
337 self
.runcmd(['sync'])
338 import time
; time
.sleep(2)
340 def cleanup_system(self
):
341 # Clean up after any errors.
343 self
.message('Cleaning up')
345 for mount_point
in self
.mount_points
:
346 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
348 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
350 for dirname
in self
.remove_dirs
:
351 shutil
.rmtree(dirname
)
353 def customize(self
, rootdir
):
354 script
= self
.settings
['customize']
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
)
361 if __name__
== '__main__':
362 VmDebootstrap().run()