]>
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'],
63 self
.settings
.add_string_setting(['customize'],
64 'run SCRIPT after setting up system',
66 self
.settings
.add_string_setting(['hostname'],
67 'set name to HOSTNAME (%default)',
71 def process_args(self
, args
):
72 if not self
.settings
['image']:
73 raise cliapp
.AppException('You must give image filename.')
74 if not self
.settings
['size']:
75 raise cliapp
.AppException('You must give image size.')
78 self
.mount_points
= []
81 self
.create_empty_image()
82 self
.partition_image()
84 rootdev
= self
.setup_kpartx()
86 rootdir
= self
.mount(rootdev
)
87 self
.debootstrap(rootdir
)
88 self
.set_hostname(rootdir
)
89 self
.set_root_password(rootdir
)
90 self
.remove_udev_persistent_rules(rootdir
)
91 self
.setup_networking(rootdir
)
92 self
.install_extlinux(rootdev
, rootdir
)
93 self
.customize(rootdir
)
100 def message(self
, msg
):
101 if self
.settings
['verbose']:
104 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
105 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
106 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
107 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
109 out
, err
= p
.communicate(stdin
)
110 if p
.returncode
!= 0:
111 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
114 raise cliapp
.AppException(msg
)
118 dirname
= tempfile
.mkdtemp()
119 self
.remove_dirs
.append(dirname
)
120 logging
.debug('mkdir %s' % dirname
)
123 def mount(self
, device
):
124 self
.message('Mounting %s' % device
)
125 mount_point
= self
.mkdtemp()
126 self
.runcmd(['mount', device
, mount_point
])
127 self
.mount_points
.append(mount_point
)
128 logging
.debug('mounted %s on %s' % (device
, mount_point
))
131 def create_empty_image(self
):
132 self
.message('Creating disk image')
133 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
134 self
.settings
['image'],
135 str(self
.settings
['size'])])
137 def partition_image(self
):
138 self
.message('Creating partitions')
139 self
.runcmd(['parted', '-s', self
.settings
['image'],
141 self
.runcmd(['parted', '-s', self
.settings
['image'],
142 'mkpart', 'primary', '0%', '100%'])
143 self
.runcmd(['parted', '-s', self
.settings
['image'],
144 'set', '1', 'boot', 'on'])
146 def install_mbr(self
):
147 self
.message('Installing MBR')
148 self
.runcmd(['install-mbr', self
.settings
['image']])
150 def setup_kpartx(self
):
151 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
152 devices
= [line
.split()[2]
153 for line
in out
.splitlines()
154 if line
.startswith('add map ')]
155 if len(devices
) != 1:
156 raise cliapp
.AppException('Surprising number of partitions')
157 return '/dev/mapper/%s' % devices
[0]
159 def mkfs(self
, device
):
160 self
.message('Creating filesystem')
161 self
.runcmd(['mkfs', '-t', 'ext2', device
])
163 def debootstrap(self
, rootdir
):
164 self
.message('Debootstrapping')
166 if self
.settings
['arch'] == 'i386':
169 kernel_arch
= self
.settings
['arch']
170 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
172 include
= [kernel_image
] + self
.settings
['package']
174 self
.runcmd(['debootstrap',
175 '--arch=%s' % self
.settings
['arch'],
176 '--include=%s' % ','.join(include
),
177 self
.settings
['distribution'],
179 self
.settings
['mirror']])
181 def set_hostname(self
, rootdir
):
182 hostname
= self
.settings
['hostname']
183 f
= open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w')
187 def set_root_password(self
, rootdir
):
188 if self
.settings
['root-password']:
189 self
.message('Setting root password')
190 encrypted
= crypt
.crypt(self
.settings
['root-password'], '..')
191 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
,
194 self
.message('Locking root password')
195 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
197 def remove_udev_persistent_rules(self
, rootdir
):
198 self
.message('Removing udev persistent cd and net rules')
199 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
200 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
201 if os
.path
.exists(pathname
):
202 logging
.debug('rm %s' % pathname
)
205 logging
.debug('not removing non-existent %s' % pathname
)
207 def setup_networking(self
, rootdir
):
208 self
.message('Setting up networking')
210 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
212 f
.write('iface lo inet loopback\n')
214 if self
.settings
['enable-dhcp']:
216 f
.write('allow-hotplug eth0\n')
217 f
.write('iface eth0 inet dhcp\n')
221 def install_extlinux(self
, rootdev
, rootdir
):
222 self
.message('Installing extlinux')
225 dirname
= os
.path
.join(rootdir
, 'boot')
226 basenames
= os
.listdir(dirname
)
227 logging
.debug('find: %s' % basenames
)
228 for basename
in basenames
:
229 if re
.search(pattern
, basename
):
230 return os
.path
.join('boot', basename
)
231 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
233 kernel_image
= find('vmlinuz-.*')
234 initrd_image
= find('initrd.img-.*')
236 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
237 '-s', 'UUID', rootdev
])
238 uuid
= out
.splitlines()[0].strip()
240 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
241 logging
.debug('configure extlinux %s' % conf
)
249 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet
251 'kernel': kernel_image
,
252 'initrd': initrd_image
,
257 self
.runcmd(['extlinux', '--install', rootdir
])
258 self
.runcmd(['sync'])
259 import time
; time
.sleep(2)
262 # Clean up after any errors.
264 self
.message('Cleaning up')
266 for mount_point
in self
.mount_points
:
267 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
269 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
271 for dirname
in self
.remove_dirs
:
272 shutil
.rmtree(dirname
)
274 def customize(self
, rootdir
):
275 script
= self
.settings
['customize']
277 self
.message('Running customize script %s' % script
)
278 self
.runcmd([script
, rootdir
])
281 if __name__
== '__main__':
282 VmDebootstrap().run()