]>
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
.add_boolean_setting(['verbose'],
33 'report what is going on')
34 self
.settings
.add_string_setting(['image'],
35 'put created disk image in FILE',
37 self
.settings
.add_bytesize_setting(['size'],
38 'create a disk image of size SIZE '
42 self
.settings
.add_string_setting(['mirror'],
43 'use MIRROR as package source '
46 default
='http://cdn.debian.net/debian/')
47 self
.settings
.add_string_setting(['arch'],
48 'architecture to use '
52 self
.settings
.add_string_setting(['distribution'],
53 'release to use (%default)',
56 self
.settings
.add_string_list_setting(['package'],
57 'install PACKAGE onto system')
58 self
.settings
.add_boolean_setting(['enable-dhcp'],
59 'enable DHCP on eth0')
60 self
.settings
.add_string_setting(['root-password'],
64 def process_args(self
, args
):
65 if not self
.settings
['image']:
66 raise cliapp
.AppException('You must give image filename.')
67 if not self
.settings
['size']:
68 raise cliapp
.AppException('You must give image size.')
71 self
.mount_points
= []
74 self
.create_empty_image()
75 self
.partition_image()
77 rootdev
= self
.setup_kpartx()
79 rootdir
= self
.mount(rootdev
)
80 self
.debootstrap(rootdir
)
81 self
.set_root_password(rootdir
)
82 self
.remove_udev_persistent_rules(rootdir
)
83 self
.setup_networking(rootdir
)
84 self
.install_extlinux(rootdev
, rootdir
)
91 def message(self
, msg
):
92 if self
.settings
['verbose']:
95 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
96 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
97 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
98 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
100 out
, err
= p
.communicate(stdin
)
101 if p
.returncode
!= 0:
102 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
105 raise cliapp
.AppException(msg
)
109 dirname
= tempfile
.mkdtemp()
110 self
.remove_dirs
.append(dirname
)
111 logging
.debug('mkdir %s' % dirname
)
114 def mount(self
, device
):
115 self
.message('Mounting %s' % device
)
116 mount_point
= self
.mkdtemp()
117 self
.runcmd(['mount', device
, mount_point
])
118 self
.mount_points
.append(mount_point
)
119 logging
.debug('mounted %s on %s' % (device
, mount_point
))
122 def create_empty_image(self
):
123 self
.message('Creating disk image')
124 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
125 self
.settings
['image'],
126 str(self
.settings
['size'])])
128 def partition_image(self
):
129 self
.message('Creating partitions')
130 self
.runcmd(['parted', '-s', self
.settings
['image'],
132 self
.runcmd(['parted', '-s', self
.settings
['image'],
133 'mkpart', 'primary', '0%', '100%'])
134 self
.runcmd(['parted', '-s', self
.settings
['image'],
135 'set', '1', 'boot', 'on'])
137 def install_mbr(self
):
138 self
.message('Installing MBR')
139 self
.runcmd(['install-mbr', self
.settings
['image']])
141 def setup_kpartx(self
):
142 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
143 devices
= [line
.split()[2]
144 for line
in out
.splitlines()
145 if line
.startswith('add map ')]
146 if len(devices
) != 1:
147 raise cliapp
.AppException('Surprising number of partitions')
148 return '/dev/mapper/%s' % devices
[0]
150 def mkfs(self
, device
):
151 self
.message('Creating filesystem')
152 self
.runcmd(['mkfs', '-t', 'ext2', device
])
154 def debootstrap(self
, rootdir
):
155 self
.message('Debootstrapping')
157 if self
.settings
['arch'] == 'i386':
160 kernel_arch
= self
.settings
['arch']
161 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
163 include
= [kernel_image
] + self
.settings
['package']
165 self
.runcmd(['debootstrap',
166 '--arch=%s' % self
.settings
['arch'],
167 '--include=%s' % ','.join(include
),
168 self
.settings
['distribution'],
170 self
.settings
['mirror']])
172 def set_root_password(self
, rootdir
):
173 if self
.settings
['root-password']:
174 self
.message('Setting root password')
175 encrypted
= crypt
.crypt(self
.settings
['root-password'], '..')
176 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
,
179 self
.message('Locking root password')
180 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
182 def remove_udev_persistent_rules(self
, rootdir
):
183 self
.message('Removing udev persistent cd and net rules')
184 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
185 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
186 if os
.path
.exists(pathname
):
187 logging
.debug('rm %s' % pathname
)
190 logging
.debug('not removing non-existent %s' % pathname
)
192 def setup_networking(self
, rootdir
):
193 self
.message('Setting up networking')
195 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
197 f
.write('iface lo inet loopback\n')
199 if self
.settings
['enable-dhcp']:
201 f
.write('allow-hotplug eth0\n')
202 f
.write('iface eth0 inet dhcp\n')
206 def install_extlinux(self
, rootdev
, rootdir
):
207 self
.message('Installing extlinux')
210 dirname
= os
.path
.join(rootdir
, 'boot')
211 basenames
= os
.listdir(dirname
)
212 logging
.debug('find: %s' % basenames
)
213 for basename
in basenames
:
214 if re
.search(pattern
, basename
):
215 return os
.path
.join('boot', basename
)
216 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
218 kernel_image
= find('vmlinuz-.*')
219 initrd_image
= find('initrd.img-.*')
221 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
222 '-s', 'UUID', rootdev
])
223 uuid
= out
.splitlines()[0].strip()
225 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
226 logging
.debug('configure extlinux %s' % conf
)
234 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet
236 'kernel': kernel_image
,
237 'initrd': initrd_image
,
242 self
.runcmd(['extlinux', '--install', rootdir
])
243 self
.runcmd(['sync'])
244 import time
; time
.sleep(2)
247 # Clean up after any errors.
249 self
.message('Cleaning up')
251 for mount_point
in self
.mount_points
:
252 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
254 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
256 for dirname
in self
.remove_dirs
:
257 shutil
.rmtree(dirname
)
260 if __name__
== '__main__':
261 VmDebootstrap().run()