]>
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
.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
.string(['customize'],
59 'run SCRIPT after setting up system',
61 self
.settings
.string(['hostname'],
62 'set name to HOSTNAME (%default)',
65 self
.settings
.string_list(['user'],
66 'create USER with PASSWORD',
67 metavar
='USER/PASSWORD')
68 self
.settings
.boolean(['serial-console'],
69 'configure image to use a serial console')
70 self
.settings
.boolean(['sudo'],
71 'install sudo, and if user is created, add them '
74 def process_args(self
, args
):
75 if not self
.settings
['image']:
76 raise cliapp
.AppException('You must give image filename.')
77 if not self
.settings
['size']:
78 raise cliapp
.AppException('You must give image size.')
81 self
.mount_points
= []
84 self
.create_empty_image()
85 self
.partition_image()
87 rootdev
= self
.setup_kpartx()
89 rootdir
= self
.mount(rootdev
)
90 self
.debootstrap(rootdir
)
91 self
.set_hostname(rootdir
)
92 self
.create_fstab(rootdir
)
93 self
.install_debs(rootdir
)
94 self
.set_root_password(rootdir
)
95 self
.create_users(rootdir
)
96 self
.remove_udev_persistent_rules(rootdir
)
97 self
.setup_networking(rootdir
)
98 self
.install_extlinux(rootdev
, rootdir
)
99 self
.customize(rootdir
)
100 except BaseException
, e
:
101 self
.message('EEEK! Something bad happened...')
107 def message(self
, msg
):
108 if self
.settings
['verbose']:
111 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
112 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
113 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
114 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
116 out
, err
= p
.communicate(stdin
)
117 if p
.returncode
!= 0:
118 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
121 raise cliapp
.AppException(msg
)
125 dirname
= tempfile
.mkdtemp()
126 self
.remove_dirs
.append(dirname
)
127 logging
.debug('mkdir %s' % dirname
)
130 def mount(self
, device
):
131 self
.message('Mounting %s' % device
)
132 mount_point
= self
.mkdtemp()
133 self
.runcmd(['mount', device
, mount_point
])
134 self
.mount_points
.append(mount_point
)
135 logging
.debug('mounted %s on %s' % (device
, mount_point
))
138 def create_empty_image(self
):
139 self
.message('Creating disk image')
140 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
141 self
.settings
['image'],
142 str(self
.settings
['size'])])
144 def partition_image(self
):
145 self
.message('Creating partitions')
146 self
.runcmd(['parted', '-s', self
.settings
['image'],
148 self
.runcmd(['parted', '-s', self
.settings
['image'],
149 'mkpart', 'primary', '0%', '100%'])
150 self
.runcmd(['parted', '-s', self
.settings
['image'],
151 'set', '1', 'boot', 'on'])
153 def install_mbr(self
):
154 self
.message('Installing MBR')
155 self
.runcmd(['install-mbr', self
.settings
['image']])
157 def setup_kpartx(self
):
158 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
159 devices
= [line
.split()[2]
160 for line
in out
.splitlines()
161 if line
.startswith('add map ')]
162 if len(devices
) != 1:
163 raise cliapp
.AppException('Surprising number of partitions')
164 return '/dev/mapper/%s' % devices
[0]
166 def mkfs(self
, device
):
167 self
.message('Creating filesystem')
168 self
.runcmd(['mkfs', '-t', 'ext2', device
])
170 def debootstrap(self
, rootdir
):
171 self
.message('Debootstrapping')
173 if self
.settings
['arch'] == 'i386':
176 kernel_arch
= self
.settings
['arch']
177 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
179 include
= [kernel_image
] + self
.settings
['package']
180 if self
.settings
['sudo'] and 'sudo' not in include
:
181 include
.append('sudo')
183 self
.runcmd(['debootstrap',
184 '--arch=%s' % self
.settings
['arch'],
185 '--include=%s' % ','.join(include
),
186 self
.settings
['distribution'],
188 self
.settings
['mirror']])
190 def set_hostname(self
, rootdir
):
191 hostname
= self
.settings
['hostname']
192 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
193 f
.write('%s\n' % hostname
)
195 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
196 with
open(etc_hosts
, 'r') as f
:
198 with
open(etc_hosts
, 'w') as f
:
199 for line
in data
.splitlines():
200 if line
.startswith('127.0.0.1'):
201 line
+= ' %s' % hostname
202 f
.write('%s\n' % line
)
204 def create_fstab(self
, rootdir
):
205 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
206 with
open(fstab
, 'w') as f
:
207 f
.write('proc /proc proc defaults 0 0\n')
208 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
210 def install_debs(self
, rootdir
):
211 if not self
.settings
['custom-package']:
213 self
.message('Installing custom packages')
214 tmp
= os
.path
.join(rootdir
, 'tmp', 'install_debs')
216 for deb
in self
.settings
['custom-package']:
217 shutil
.copy(deb
, tmp
)
218 filenames
= [os
.path
.join('/tmp/install_debs', os
.path
.basename(deb
))
219 for deb
in self
.settings
['custom-package']]
221 self
.runcmd_unchecked(['chroot', rootdir
, 'dpkg', '-i'] + filenames
)
222 logging
.debug('stdout:\n%s' % out
)
223 logging
.debug('stderr:\n%s' % err
)
224 out
= self
.runcmd(['chroot', rootdir
,
225 'apt-get', '-f', '--no-remove', 'install'])
226 logging
.debug('stdout:\n%s' % out
)
229 def set_root_password(self
, rootdir
):
230 if self
.settings
['root-password']:
231 self
.message('Setting root password')
232 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
234 self
.message('Locking root password')
235 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
237 def create_users(self
, rootdir
):
238 def create_user(user
):
239 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
240 '--disabled-password', user
])
241 if self
.settings
['sudo']:
242 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
244 for userpass
in self
.settings
['user']:
246 user
, password
= userpass
.split('/', 1)
248 self
.set_password(rootdir
, user
, password
)
250 create_user(userpass
)
252 def set_password(self
, rootdir
, user
, password
):
253 encrypted
= crypt
.crypt(password
, '..')
254 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
256 def remove_udev_persistent_rules(self
, rootdir
):
257 self
.message('Removing udev persistent cd and net rules')
258 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
259 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
260 if os
.path
.exists(pathname
):
261 logging
.debug('rm %s' % pathname
)
264 logging
.debug('not removing non-existent %s' % pathname
)
266 def setup_networking(self
, rootdir
):
267 self
.message('Setting up networking')
269 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
271 f
.write('iface lo inet loopback\n')
273 if self
.settings
['enable-dhcp']:
275 f
.write('allow-hotplug eth0\n')
276 f
.write('iface eth0 inet dhcp\n')
280 def install_extlinux(self
, rootdev
, rootdir
):
281 self
.message('Installing extlinux')
284 dirname
= os
.path
.join(rootdir
, 'boot')
285 basenames
= os
.listdir(dirname
)
286 logging
.debug('find: %s' % basenames
)
287 for basename
in basenames
:
288 if re
.search(pattern
, basename
):
289 return os
.path
.join('boot', basename
)
290 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
292 kernel_image
= find('vmlinuz-.*')
293 initrd_image
= find('initrd.img-.*')
295 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
296 '-s', 'UUID', rootdev
])
297 uuid
= out
.splitlines()[0].strip()
299 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
300 logging
.debug('configure extlinux %s' % conf
)
308 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
311 'kernel': kernel_image
,
312 'initrd': initrd_image
,
315 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
316 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
320 if self
.settings
['serial-console']:
321 logging
.debug('adding getty to serial console')
322 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
323 with
open(inittab
, 'a') as f
:
324 f
.write('\nS0:23:respawn:/sbin/getty -L ttyS0 115200 vt100\n')
326 self
.runcmd(['extlinux', '--install', rootdir
])
327 self
.runcmd(['sync'])
328 import time
; time
.sleep(2)
331 # Clean up after any errors.
333 self
.message('Cleaning up')
335 for mount_point
in self
.mount_points
:
336 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
338 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
340 for dirname
in self
.remove_dirs
:
341 shutil
.rmtree(dirname
)
343 def customize(self
, rootdir
):
344 script
= self
.settings
['customize']
346 self
.message('Running customize script %s' % script
)
347 self
.runcmd([script
, rootdir
])
350 if __name__
== '__main__':
351 VmDebootstrap().run()