]>
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')
66 self
.settings
.boolean(['sudo'],
67 'install sudo, and if user is created, add them '
70 def process_args(self
, args
):
71 if not self
.settings
['image']:
72 raise cliapp
.AppException('You must give image filename.')
73 if not self
.settings
['size']:
74 raise cliapp
.AppException('You must give image size.')
77 self
.mount_points
= []
80 self
.create_empty_image()
81 self
.partition_image()
83 rootdev
= self
.setup_kpartx()
85 rootdir
= self
.mount(rootdev
)
86 self
.debootstrap(rootdir
)
87 self
.set_hostname(rootdir
)
88 self
.create_fstab(rootdir
)
89 self
.set_root_password(rootdir
)
90 self
.create_users(rootdir
)
91 self
.remove_udev_persistent_rules(rootdir
)
92 self
.setup_networking(rootdir
)
93 self
.install_extlinux(rootdev
, rootdir
)
94 self
.customize(rootdir
)
95 except BaseException
, e
:
96 self
.message('EEEK! Something bad happened...')
102 def message(self
, msg
):
103 if self
.settings
['verbose']:
106 def runcmd(self
, argv
, stdin
='', ignore_fail
=False, **kwargs
):
107 logging
.debug('runcmd: %s %s' % (argv
, kwargs
))
108 p
= subprocess
.Popen(argv
, stdin
=subprocess
.PIPE
,
109 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
111 out
, err
= p
.communicate(stdin
)
112 if p
.returncode
!= 0:
113 msg
= 'command failed: %s\n%s\n%s' % (argv
, out
, err
)
116 raise cliapp
.AppException(msg
)
120 dirname
= tempfile
.mkdtemp()
121 self
.remove_dirs
.append(dirname
)
122 logging
.debug('mkdir %s' % dirname
)
125 def mount(self
, device
):
126 self
.message('Mounting %s' % device
)
127 mount_point
= self
.mkdtemp()
128 self
.runcmd(['mount', device
, mount_point
])
129 self
.mount_points
.append(mount_point
)
130 logging
.debug('mounted %s on %s' % (device
, mount_point
))
133 def create_empty_image(self
):
134 self
.message('Creating disk image')
135 self
.runcmd(['qemu-img', 'create', '-f', 'raw',
136 self
.settings
['image'],
137 str(self
.settings
['size'])])
139 def partition_image(self
):
140 self
.message('Creating partitions')
141 self
.runcmd(['parted', '-s', self
.settings
['image'],
143 self
.runcmd(['parted', '-s', self
.settings
['image'],
144 'mkpart', 'primary', '0%', '100%'])
145 self
.runcmd(['parted', '-s', self
.settings
['image'],
146 'set', '1', 'boot', 'on'])
148 def install_mbr(self
):
149 self
.message('Installing MBR')
150 self
.runcmd(['install-mbr', self
.settings
['image']])
152 def setup_kpartx(self
):
153 out
= self
.runcmd(['kpartx', '-av', self
.settings
['image']])
154 devices
= [line
.split()[2]
155 for line
in out
.splitlines()
156 if line
.startswith('add map ')]
157 if len(devices
) != 1:
158 raise cliapp
.AppException('Surprising number of partitions')
159 return '/dev/mapper/%s' % devices
[0]
161 def mkfs(self
, device
):
162 self
.message('Creating filesystem')
163 self
.runcmd(['mkfs', '-t', 'ext2', device
])
165 def debootstrap(self
, rootdir
):
166 self
.message('Debootstrapping')
168 if self
.settings
['arch'] == 'i386':
171 kernel_arch
= self
.settings
['arch']
172 kernel_image
= 'linux-image-2.6-%s' % kernel_arch
174 include
= [kernel_image
] + self
.settings
['package']
175 if self
.settings
['sudo'] and 'sudo' not in include
:
176 include
.append('sudo')
178 self
.runcmd(['debootstrap',
179 '--arch=%s' % self
.settings
['arch'],
180 '--include=%s' % ','.join(include
),
181 self
.settings
['distribution'],
183 self
.settings
['mirror']])
185 def set_hostname(self
, rootdir
):
186 hostname
= self
.settings
['hostname']
187 with
open(os
.path
.join(rootdir
, 'etc', 'hostname'), 'w') as f
:
188 f
.write('%s\n' % hostname
)
190 etc_hosts
= os
.path
.join(rootdir
, 'etc', 'hosts')
191 with
open(etc_hosts
, 'r') as f
:
193 with
open(etc_hosts
, 'w') as f
:
194 for line
in data
.splitlines():
195 if line
.startswith('127.0.0.1'):
196 line
+= ' %s' % hostname
197 f
.write('%s\n' % line
)
199 def create_fstab(self
, rootdir
):
200 fstab
= os
.path
.join(rootdir
, 'etc', 'fstab')
201 with
open(fstab
, 'w') as f
:
202 f
.write('proc /proc proc defaults 0 0\n')
203 f
.write('/dev/sda1 / ext4 errors=remount-ro 0 1\n')
205 def set_root_password(self
, rootdir
):
206 if self
.settings
['root-password']:
207 self
.message('Setting root password')
208 self
.set_password(rootdir
, 'root', self
.settings
['root-password'])
210 self
.message('Locking root password')
211 self
.runcmd(['chroot', rootdir
, 'passwd', '-l', 'root'])
213 def create_users(self
, rootdir
):
214 def create_user(user
):
215 self
.runcmd(['chroot', rootdir
, 'adduser', '--gecos', user
,
216 '--disabled-password', user
])
217 if self
.settings
['sudo']:
218 self
.runcmd(['chroot', rootdir
, 'adduser', user
, 'sudo'])
220 for userpass
in self
.settings
['user']:
222 user
, password
= userpass
.split('/', 1)
224 self
.set_password(rootdir
, user
, password
)
226 create_user(userpass
)
228 def set_password(self
, rootdir
, user
, password
):
229 encrypted
= crypt
.crypt(password
, '..')
230 self
.runcmd(['chroot', rootdir
, 'usermod', '-p', encrypted
, user
])
232 def remove_udev_persistent_rules(self
, rootdir
):
233 self
.message('Removing udev persistent cd and net rules')
234 for x
in ['70-persistent-cd.rules', '70-persistent-net.rules']:
235 pathname
= os
.path
.join(rootdir
, 'etc', 'udev', 'rules.d', x
)
236 if os
.path
.exists(pathname
):
237 logging
.debug('rm %s' % pathname
)
240 logging
.debug('not removing non-existent %s' % pathname
)
242 def setup_networking(self
, rootdir
):
243 self
.message('Setting up networking')
245 f
= open(os
.path
.join(rootdir
, 'etc', 'network', 'interfaces'), 'w')
247 f
.write('iface lo inet loopback\n')
249 if self
.settings
['enable-dhcp']:
251 f
.write('allow-hotplug eth0\n')
252 f
.write('iface eth0 inet dhcp\n')
256 def install_extlinux(self
, rootdev
, rootdir
):
257 self
.message('Installing extlinux')
260 dirname
= os
.path
.join(rootdir
, 'boot')
261 basenames
= os
.listdir(dirname
)
262 logging
.debug('find: %s' % basenames
)
263 for basename
in basenames
:
264 if re
.search(pattern
, basename
):
265 return os
.path
.join('boot', basename
)
266 raise cliapp
.AppException('Cannot find match: %s' % pattern
)
268 kernel_image
= find('vmlinuz-.*')
269 initrd_image
= find('initrd.img-.*')
271 out
= self
.runcmd(['blkid', '-c', '/dev/null', '-o', 'value',
272 '-s', 'UUID', rootdev
])
273 uuid
= out
.splitlines()[0].strip()
275 conf
= os
.path
.join(rootdir
, 'extlinux.conf')
276 logging
.debug('configure extlinux %s' % conf
)
284 append initrd=%(initrd)s root=UUID=%(uuid)s ro quiet %(kserial)s
287 'kernel': kernel_image
,
288 'initrd': initrd_image
,
291 'console=ttyS0,115200' if self
.settings
['serial-console'] else '',
292 'extserial': 'serial 0 115200' if self
.settings
['serial-console'] else '',
296 if self
.settings
['serial-console']:
297 logging
.debug('adding getty to serial console')
298 inittab
= os
.path
.join(rootdir
, 'etc/inittab')
299 with
open(inittab
, 'a') as f
:
300 f
.write('\nS0:23:respawn:/sbin/getty -L ttyS0 115200 vt100\n')
302 self
.runcmd(['extlinux', '--install', rootdir
])
303 self
.runcmd(['sync'])
304 import time
; time
.sleep(2)
307 # Clean up after any errors.
309 self
.message('Cleaning up')
311 for mount_point
in self
.mount_points
:
312 self
.runcmd(['umount', mount_point
], ignore_fail
=True)
314 self
.runcmd(['kpartx', '-d', self
.settings
['image']], ignore_fail
=True)
316 for dirname
in self
.remove_dirs
:
317 shutil
.rmtree(dirname
)
319 def customize(self
, rootdir
):
320 script
= self
.settings
['customize']
322 self
.message('Running customize script %s' % script
)
323 self
.runcmd([script
, rootdir
])
326 if __name__
== '__main__':
327 VmDebootstrap().run()