]>
git.siccegge.de Git - forks/vmdebootstrap.git/blob - vmdebootstrap
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
.boolean(['enable-dhcp'], 'enable DHCP on eth0')
52 self
.settings
.string(['root-password'], 'set root password',
54 self
.settings
.string(['customize'],
55 'run SCRIPT after setting up system',
57 self
.settings
.string(['hostname'],
58 'set name to HOSTNAME (%default)',
61 self
.settings
.string_list(['user'],
62 'create USER with PASSWORD',
63 metavar
='USER/PASSWORD')
64 self
.settings
.boolean(['serial-console'],
65 'configure image to use a serial console')
67 def process_args(self
, args
):
68 if not self
.settings
['image']:
69 raise cliapp
.AppException('You must give image filename.')
70 if not self
.settings
['size']:
71 raise cliapp
.AppException('You must give image size.')
74 self
.mount_points
= []
77 self
.create_empty_image()
78 self
.partition_image()
80 rootdev
= self
.setup_kpartx()
82 rootdir
= self
.mount(rootdev
)
83 self
.debootstrap(rootdir
)
84 self
.set_hostname(rootdir
)
85 self
.create_fstab(rootdir
)
86 self
.set_root_password(rootdir
)
87 self
.create_users(rootdir
)
88 self
.remove_udev_persistent_rules(rootdir
)
89 self
.setup_networking(rootdir
)
90 self
.install_extlinux(rootdev
, rootdir
)
91 self
.customize(rootdir
)
92 except BaseException
, e
:
93 self
.message('EEEK! Something bad happened...')
99 def message(self
, msg
):
100 if self
.settings
['verbose']:
103 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
104 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
105 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
106 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
108 out
, err
= p
.communicate(stdin
)
109 if p
.returncode
!= 0:
110 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
113 raise cliapp
.AppException(msg
)
117 dirname
= tempfile
.mkdtemp()
118 self
.remove_dirs
.append(dirname
)
119 logging
.debug('mkdir %s' % dirname
)
122 def mount(self
, device
):
123 self
.message('Mounting %s' % device
)
124 mount_point
= self
.mkdtemp()
125 self
.runcmd(['mount', device
, mount_point
])
126 self
.mount_points
.append(mount_point
)
127 logging
.debug('mounted %s on %s' % (device
, mount_point
))
130 def create_empty_image(self
):
131 self
.message('Creating disk image')
132 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
133 self
.settings
['image'],
134 str(self
.settings
['size'])])
136 def partition_image(self
):
137 self
.message('Creating partitions')
138 self
.runcmd(['parted', '-s', self
.settings
['image'],
140 self
.runcmd(['parted', '-s', self
.settings
['image'],
141 'mkpart', 'primary', '0%', '100%'])
142 self
.runcmd(['parted', '-s', self
.settings
['image'],
143 'set', '1', 'boot', 'on'])
145 def install_mbr(self
):
146 self
.message('Installing MBR')
147 self
.runcmd(['install-mbr', self
.settings
['image']])
149 def setup_kpartx(self
):
150 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
151 devices
= [line
.split()[2]
152 for line
in out
.splitlines()
153 if line
.startswith('add map ')]
154 if len(devices
) != 1:
155 raise cliapp
.AppException('Surprising number of partitions')
156 return '/dev/mapper/%s' % devices
[0]
158 def mkfs(self
, device
):
159 self
.message('Creating filesystem')
160 self
.runcmd(['mkfs', '-t', 'ext2', device
])
162 def debootstrap(self
, rootdir
):
163 self
.message('Debootstrapping')
165 if self
.settings
['arch'] == 'i386':
168 kernel_arch
= self
.settings
['arch']
169 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
171 include
= [kernel_image
] + self
.settings
['package']
173 self
.runcmd(['debootstrap',
174 '--arch=%s' % self
.settings
['arch'],
175 '--include=%s' % ','.join(include
),
176 self
.settings
['distribution'],
178 self
.settings
['mirror']])
180 def set_hostname(self
, rootdir
):
181 hostname
= self
.settings
['hostname']
182 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
183 f
.write('%s\n' % hostname
)
185 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
186 with
open(etc_hosts
, 'r') as f
:
188 with
open(etc_hosts
, 'w') as f
:
189 for line
in data
.splitlines():
190 if line
.startswith('127.0.0.1'):
191 line
+= ' %s' % hostname
192 f
.write('%s\n' % line
)
194 def create_fstab(self
, rootdir
):
195 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
196 with
open(fstab
, 'w') as f
:
197 f
.write('proc /proc proc defaults 0 0\n')
198 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
200 def set_root_password(self
, rootdir
):
201 if self
.settings
['root-password']:
202 self
.message('Setting root password')
203 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
205 self
.message('Locking root password')
206 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
208 def create_users(self
, rootdir
):
209 def create_user(user
):
210 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
211 '--disabled-password', user
])
213 for userpass
in self
.settings
['user']:
215 user
, password
= userpass
.split('/', 1)
217 self
.set_password(rootdir
, user
, password
)
219 create_user(userpass
)
221 def set_password(self
, rootdir
, user
, password
):
222 encrypted
= crypt
.crypt(password
, '..')
223 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
225 def remove_udev_persistent_rules(self
, rootdir
):
226 self
.message('Removing udev persistent cd and net rules')
227 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
228 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
229 if os
.path
.exists(pathname
):
230 logging
.debug('rm %s' % pathname
)
233 logging
.debug('not removing non-existent %s' % pathname
)
235 def setup_networking(self
, rootdir
):
236 self
.message('Setting up networking')
238 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
240 f
.write('iface lo inet loopback\n')
242 if self
.settings
['enable-dhcp']:
244 f
.write('allow-hotplug eth0\n')
245 f
.write('iface eth0 inet dhcp\n')
249 def install_extlinux(self
, rootdev
, rootdir
):
250 self
.message('Installing extlinux')
253 dirname
= os
.path
.join(rootdir
, 'boot')
254 basenames
= os
.listdir(dirname
)
255 logging
.debug('find: %s' % basenames
)
256 for basename
in basenames
:
257 if re
.search(pattern
, basename
):
258 return os
.path
.join('boot', basename
)
259 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
261 kernel_image
= find('vmlinuz-.*')
262 initrd_image
= find('initrd.img-.*')
264 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
265 '-s', 'UUID', rootdev
])
266 uuid
= out
.splitlines()[0].strip()
268 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
269 logging
.debug('configure extlinux %s' % conf
)
277 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
280 'kernel': kernel_image
,
281 'initrd': initrd_image
,
284 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
285 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
289 if self
.settings
['serial-console']:
290 logging
.debug('adding getty to serial console')
291 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
292 with
open(inittab
, 'a') as f
:
293 f
.write('\nS0:23:respawn:/sbin/getty -L ttyS0 115200 vt100\n')
295 self
.runcmd(['extlinux', '--install', rootdir
])
296 self
.runcmd(['sync'])
297 import time
; time
.sleep(2)
300 # Clean up after any errors.
302 self
.message('Cleaning up')
304 for mount_point
in self
.mount_points
:
305 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
307 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
309 for dirname
in self
.remove_dirs
:
310 shutil
.rmtree(dirname
)
312 def customize(self
, rootdir
):
313 script
= self
.settings
['customize']
315 self
.message('Running customize script %s' % script
)
316 self
.runcmd([script
, rootdir
])
319 if __name__
== '__main__':
320 VmDebootstrap().run()