]>
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)',
62 def process_args(self
, args
):
63 if not self
.settings
['image']:
64 raise cliapp
.AppException('You must give image filename.')
65 if not self
.settings
['size']:
66 raise cliapp
.AppException('You must give image size.')
69 self
.mount_points
= []
72 self
.create_empty_image()
73 self
.partition_image()
75 rootdev
= self
.setup_kpartx()
77 rootdir
= self
.mount(rootdev
)
78 self
.debootstrap(rootdir
)
79 self
.set_hostname(rootdir
)
80 self
.set_root_password(rootdir
)
81 self
.remove_udev_persistent_rules(rootdir
)
82 self
.setup_networking(rootdir
)
83 self
.install_extlinux(rootdev
, rootdir
)
84 self
.customize(rootdir
)
85 except BaseException
, e
:
86 self
.message('EEEK! Something bad happened...')
92 def message(self
, msg
):
93 if self
.settings
['verbose']:
96 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
97 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
98 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
99 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
101 out
, err
= p
.communicate(stdin
)
102 if p
.returncode
!= 0:
103 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
106 raise cliapp
.AppException(msg
)
110 dirname
= tempfile
.mkdtemp()
111 self
.remove_dirs
.append(dirname
)
112 logging
.debug('mkdir %s' % dirname
)
115 def mount(self
, device
):
116 self
.message('Mounting %s' % device
)
117 mount_point
= self
.mkdtemp()
118 self
.runcmd(['mount', device
, mount_point
])
119 self
.mount_points
.append(mount_point
)
120 logging
.debug('mounted %s on %s' % (device
, mount_point
))
123 def create_empty_image(self
):
124 self
.message('Creating disk image')
125 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
126 self
.settings
['image'],
127 str(self
.settings
['size'])])
129 def partition_image(self
):
130 self
.message('Creating partitions')
131 self
.runcmd(['parted', '-s', self
.settings
['image'],
133 self
.runcmd(['parted', '-s', self
.settings
['image'],
134 'mkpart', 'primary', '0%', '100%'])
135 self
.runcmd(['parted', '-s', self
.settings
['image'],
136 'set', '1', 'boot', 'on'])
138 def install_mbr(self
):
139 self
.message('Installing MBR')
140 self
.runcmd(['install-mbr', self
.settings
['image']])
142 def setup_kpartx(self
):
143 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
144 devices
= [line
.split()[2]
145 for line
in out
.splitlines()
146 if line
.startswith('add map ')]
147 if len(devices
) != 1:
148 raise cliapp
.AppException('Surprising number of partitions')
149 return '/dev/mapper/%s' % devices
[0]
151 def mkfs(self
, device
):
152 self
.message('Creating filesystem')
153 self
.runcmd(['mkfs', '-t', 'ext2', device
])
155 def debootstrap(self
, rootdir
):
156 self
.message('Debootstrapping')
158 if self
.settings
['arch'] == 'i386':
161 kernel_arch
= self
.settings
['arch']
162 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
164 include
= [kernel_image
] + self
.settings
['package']
166 self
.runcmd(['debootstrap',
167 '--arch=%s' % self
.settings
['arch'],
168 '--include=%s' % ','.join(include
),
169 self
.settings
['distribution'],
171 self
.settings
['mirror']])
173 def set_hostname(self
, rootdir
):
174 hostname
= self
.settings
['hostname']
175 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
178 def set_root_password(self
, rootdir
):
179 if self
.settings
['root-password']:
180 self
.message('Setting root password')
181 encrypted
= crypt
.crypt(self
.settings
['root-password'], '..')
182 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
,
185 self
.message('Locking root password')
186 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
188 def remove_udev_persistent_rules(self
, rootdir
):
189 self
.message('Removing udev persistent cd and net rules')
190 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
191 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
192 if os
.path
.exists(pathname
):
193 logging
.debug('rm %s' % pathname
)
196 logging
.debug('not removing non-existent %s' % pathname
)
198 def setup_networking(self
, rootdir
):
199 self
.message('Setting up networking')
201 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
203 f
.write('iface lo inet loopback\n')
205 if self
.settings
['enable-dhcp']:
207 f
.write('allow-hotplug eth0\n')
208 f
.write('iface eth0 inet dhcp\n')
212 def install_extlinux(self
, rootdev
, rootdir
):
213 self
.message('Installing extlinux')
216 dirname
= os
.path
.join(rootdir
, 'boot')
217 basenames
= os
.listdir(dirname
)
218 logging
.debug('find: %s' % basenames
)
219 for basename
in basenames
:
220 if re
.search(pattern
, basename
):
221 return os
.path
.join('boot', basename
)
222 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
224 kernel_image
= find('vmlinuz-.*')
225 initrd_image
= find('initrd.img-.*')
227 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
228 '-s', 'UUID', rootdev
])
229 uuid
= out
.splitlines()[0].strip()
231 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
232 logging
.debug('configure extlinux %s' % conf
)
240 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet
242 'kernel': kernel_image
,
243 'initrd': initrd_image
,
248 self
.runcmd(['extlinux', '--install', rootdir
])
249 self
.runcmd(['sync'])
250 import time
; time
.sleep(2)
253 # Clean up after any errors.
255 self
.message('Cleaning up')
257 for mount_point
in self
.mount_points
:
258 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
260 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
262 for dirname
in self
.remove_dirs
:
263 shutil
.rmtree(dirname
)
265 def customize(self
, rootdir
):
266 script
= self
.settings
['customize']
268 self
.message('Running customize script %s' % script
)
269 self
.runcmd([script
, rootdir
])
272 if __name__
== '__main__':
273 VmDebootstrap().run()