Implement execute() logic
[grml2usb.git] / grml2usb.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """
4 grml2usb
5 ~~~~~~~~
6
7 This script installs a grml system to a USB device
8
9 :copyright: (c) 2009 by Michael Prokop <mika@grml.org>
10 :license: GPL v2 or any later version
11 :bugreports: http://grml.org/bugs/
12
13 TODO
14 ----
15
16 * implement missing options (--kernel, --initrd, --uninstall,...)
17 * improve error handling :)
18 * get rid of "if not dry_run" inside code/functions
19 * implement mount handling
20 * log wrapper (-> logging module)
21 * implement logic for storing information about copied files
22   -> register every single file?
23 * trap handling (like unmount devices when interrupting?)
24 * get rid of all TODOs in code :)
25 * graphical version
26 """
27
28 import os, re, subprocess, sys, tempfile
29 from optparse import OptionParser
30 from os.path import exists, join, abspath
31 from os import pathsep
32 # TODO string.split() is deprecated - replace?
33 #      -> http://docs.python.org/library/string.html#deprecated-string-functions
34 from string import split
35
36 PROG_VERSION = "0.0.1"
37
38 # cmdline parsing
39 # TODO
40 # * --bootloader-only?
41 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
42 \n\
43 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
44 Make sure you have at least a grml ISO or a running grml system,\n\
45 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
46 and root access."
47
48 parser = OptionParser(usage=usage)
49 parser.add_option("--bootoptions", dest="bootoptions",
50                   action="store", type="string",
51                   help="use specified bootoptions as defaut")
52 parser.add_option("--copy-only", dest="copyonly", action="store_true",
53                   help="copy files only and do not install bootloader")
54 parser.add_option("--dry-run", dest="dryrun", action="store_true",
55                   help="do not actually execute any commands")
56 parser.add_option("--fat16", dest="fat16", action="store_true",
57                   help="format specified partition with FAT16")
58 parser.add_option("--force", dest="force", action="store_true",
59                   help="force any actions requiring manual interaction")
60 parser.add_option("--grub", dest="grub", action="store_true",
61                   help="install grub bootloader instead of syslinux")
62 parser.add_option("--initrd", dest="initrd", action="store", type="string",
63                   help="install specified initrd instead of the default")
64 parser.add_option("--kernel", dest="kernel", action="store", type="string",
65                   help="install specified kernel instead of the default")
66 parser.add_option("--mbr", dest="mbr", action="store_true",
67                   help="install master boot record (MBR) on the device")
68 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
69                   help="install specified squashfs file instead of the default")
70 parser.add_option("--uninstall", dest="uninstall", action="store_true",
71                   help="remove grml ISO files")
72 parser.add_option("--verbose", dest="verbose", action="store_true",
73                   help="enable verbose mode")
74 parser.add_option("-v", "--version", dest="version", action="store_true",
75                   help="display version and exit")
76 (options, args) = parser.parse_args()
77
78
79 def execute(f, *args):
80     """Wrapper for executing a command. Either really executes
81     the command (default) or when using --dry-run commandline option
82     just displays what would be executed."""
83     # demo: execute(subprocess.Popen, (["ls", "-la"]))
84     if options.dryrun:
85         print "would execute %s(%s) now" % (f, args)
86     else:
87         return f(*args)
88
89
90 def is_exe(fpath):
91     """Check whether a given file can be executed
92
93     @fpath: full path to file
94     @return:"""
95     return os.path.exists(fpath) and os.access(fpath, os.X_OK)
96
97
98 def which(program):
99     """Check whether a given program is available in PATH
100
101     @program: name of executable"""
102     fpath, fname = os.path.split(program)
103     if fpath:
104         if is_exe(program):
105             return program
106     else:
107         for path in os.environ["PATH"].split(os.pathsep):
108             exe_file = os.path.join(path, program)
109             if is_exe(exe_file):
110                 return exe_file
111
112     return None
113
114
115 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
116     """Given a search path, find file"""
117     file_found = 0
118     paths = split(search_path, pathsep)
119     for path in paths:
120         for current_dir, directories, files in os.walk(path):
121             if exists(join(current_dir, filename)):
122                 file_found = 1
123                 break
124     if file_found:
125         return abspath(join(current_dir, filename))
126     else:
127         return None
128
129
130 def check_uid_root():
131     """Check for root permissions"""
132     if not os.geteuid()==0:
133         sys.exit("Error: please run this script with uid 0 (root).")
134
135
136 def install_syslinux(device, dry_run=False):
137     # TODO
138     """Install syslinux on specified device."""
139     print("debug: syslinux %s [TODO]") % device
140
141     # syslinux -d boot/isolinux /dev/usb-sdb1
142
143
144 def generate_grub_config(grml_flavour):
145     """Generate grub configuration for use via menu,lst"""
146
147     # TODO
148     # * install main part of configuration just *once* and append
149     #   flavour specific configuration only
150     # * what about systems using grub2 without having grub1 available?
151     # * support grub2?
152
153     grml_name = grml_flavour
154
155     return("""\
156 # misc options:
157 timeout 30
158 # color red/blue green/black
159 splashimage=/boot/grub/splash.xpm.gz
160 foreground  = 000000
161 background  = FFCC33
162
163 # define entries:
164 title %(grml_name)s  - Default boot (using 1024x768 framebuffer)
165 kernel /boot/release/%(grml_name)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_name)s
166 initrd /boot/release/%(grml_name)s/initrd.gz
167
168 # TODO: extend configuration :)
169 """ % locals())
170
171
172 def generate_isolinux_splash(grml_flavour):
173     """Generate bootsplash for isolinux/syslinux"""
174
175     # TODO
176     # * adjust last bootsplash line
177
178     grml_name = grml_flavour
179
180     return("""\
181 \ f17\f\18/boot/isolinux/logo.16
182
183 Some information and boot options available via keys F2 - F10. http://grml.org/
184 %(grml_name)s
185 """ % locals())
186
187 def generate_syslinux_config(grml_flavour):
188     """Generate configuration for use in syslinux.cfg"""
189
190     # TODO
191     # * install main part of configuration just *once* and append
192     #   flavour specific configuration only
193     # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
194     #   as far as possible
195
196     grml_name = grml_flavour
197
198     return("""\
199 # use this to control the bootup via a serial port
200 # SERIAL 0 9600
201 DEFAULT grml
202 TIMEOUT 300
203 PROMPT 1
204 DISPLAY /boot/isolinux/boot.msg
205 F1 /boot/isolinux/boot.msg
206 F2 /boot/isolinux/f2
207 F3 /boot/isolinux/f3
208 F4 /boot/isolinux/f4
209 F5 /boot/isolinux/f5
210 F6 /boot/isolinux/f6
211 F7 /boot/isolinux/f7
212 F8 /boot/isolinux/f8
213 F9 /boot/isolinux/f9
214 F10 /boot/isolinux/f10
215
216 LABEL grml
217 KERNEL /boot/release/%(grml_name)s/linux26
218 APPEND initrd=/boot/release/%(grml_name)s/initrd.gz apm=power-off lang=us boot=live nomce module=%(grml_name)s
219
220 # TODO: extend configuration :)
221 """ % locals())
222
223
224 def install_grub(device, dry_run=False):
225     """Install grub on specified device."""
226     print("grub-install %s") % device
227
228
229 def install_bootloader(partition, dry_run=False):
230     """Install bootloader on device."""
231     # Install bootloader on the device (/dev/sda),
232     # not on the partition itself (/dev/sda1)
233     if partition[-1:].isdigit():
234         device = re.match(r'(.*?)\d*$', partition).group(1)
235     else:
236         device = partition
237
238     if options.grub:
239         install_grub(device, dry_run)
240     else:
241         install_syslinux(device, dry_run)
242
243
244 def is_writeable(device):
245     """Check if the device is writeable for the current user"""
246
247     if not device:
248         return False
249         #raise Exception, "no device for checking write permissions"
250
251     if not os.path.exists(device):
252         return False
253
254     return os.access(device, os.W_OK) and os.access(device, os.R_OK)
255
256 def install_mbr(device, dry_run=False):
257     """Install a default master boot record on given device
258
259     @device: device where MBR should be installed to"""
260
261     if not is_writeable(device):
262         raise IOError, "device not writeable for user"
263
264     lilo = './lilo/lilo.static' # FIXME
265
266     if not is_exe(lilo):
267         raise Exception, "lilo executable not available."
268
269     # to support -A for extended partitions:
270     print("debug: ./lilo/lilo.static -S /dev/null -M %s ext") % device
271     proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-M", device, "ext"])
272     proc.wait()
273     if proc.returncode != 0:
274         raise Exception, "error executing lilo"
275
276     # activate partition:
277     print("debug: ./lilo/lilo.static -S /dev/null -A %s 1") % device
278     if not dry_run:
279         proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-A", device, "1"])
280         proc.wait()
281         if proc.returncode != 0:
282             raise Exception, "error executing lilo"
283
284     # lilo's mbr is broken, use the one from syslinux instead:
285     print("debug: cat /usr/lib/syslinux/mbr.bin > %s") % device
286     if not dry_run:
287         try:
288             # TODO use Popen instead?
289             retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
290             if retcode < 0:
291                 print >> sys.stderr, "Error copying MBR to device", -retcode
292         except OSError, error:
293             print >> sys.stderr, "Execution failed:", error
294
295
296 def mount(source, target, options):
297     """Mount specified source on given target
298
299     @source: name of device/ISO that should be mounted
300     @target: directory where the ISO should be mounted to
301     @options: mount specific options"""
302
303     print("debug: mount %s %s %s [TODO]") % (options, source, target)
304
305
306 def unmount(directory):
307     """Unmount specified directory
308
309     @directory: directory where something is mounted on and which should be unmounted"""
310
311     print("debug: umount %s [TODO]") % directory
312
313
314 def check_for_vat(partition):
315     """Check whether specified partition is a valid VFAT/FAT16 filesystem
316
317     @partition: device name of partition"""
318
319     try:
320         udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
321             partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
322         filesystem = udev_info.communicate()[0].rstrip()
323
324         if udev_info.returncode == 2:
325             print("failed to read device %s - wrong UID / permissions?") % partition
326             return 1
327
328         if filesystem != "vfat":
329             return(1)
330
331         # TODO
332         # * check for ID_FS_VERSION=FAT16 as well?
333
334     except OSError:
335         print("Sorry, /lib/udev/vol_id not available.")
336         return 1
337
338
339 def mkdir(directory):
340     """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
341
342     if not os.path.isdir(directory):
343         try:
344             os.makedirs(directory)
345         except OSError:
346             # just silently pass as it's just fine it the directory exists
347             pass
348
349
350 def copy_grml_files(grml_flavour, iso_mount, target, dry_run=False):
351     """Copy files from ISO on given target"""
352
353     # TODO
354     # * provide alternative search_file() if file information is stored in a config.ini file?
355     # * catch "install: .. No space left on device" & CO
356     # * abstract copy logic to make the code shorter and get rid of spaghetti ;)
357
358     print("Copying files. This might take a while....")
359
360     squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
361     squashfs_target = target + '/live/'
362     execute(mkdir, squashfs_target)
363
364     # use install(1) for now to make sure we can write the files afterwards as normal user as well
365     print("cp %s %s") % (squashfs, target + '/live/' + grml_flavour + '.squashfs')
366     execute(subprocess.Popen, ["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
367
368     filesystem_module = search_file('filesystem.module', iso_mount)
369     print("cp %s %s") % (filesystem_module, squashfs_target + grml_flavour + '.module')
370     execute(subprocess.Popen, ["install", "--mode=664", filesystem_module, squashfs_target + grml_flavour + '.module'])
371
372     release_target = target + '/boot/release/' + grml_flavour
373     execute(mkdir, release_target)
374
375     kernel = search_file('linux26', iso_mount)
376     print("cp linux26 %s") % release_target + '/linux26'
377     execute(subprocess.Popen, ["install", "--mode=664", kernel, release_target + '/linux26'])
378
379     initrd = search_file('initrd.gz', iso_mount)
380     print("debug: copy initrd to %s") % release_target + '/initrd.gz'
381     execute(subprocess.Popen, ["install", "--mode=664", initrd, release_target + '/initrd.gz'])
382
383     if not options.copyonly:
384         isolinux_target = target + '/boot/isolinux/'
385         execute(mkdir, isolinux_target)
386
387         logo = search_file('logo.16', iso_mount)
388         print("debug: copy logo.16 to %s") % isolinux_target + 'logo.16'
389         execute(subprocess.Popen, ["install", "--mode=664", logo, isolinux_target + 'logo.16'])
390
391         for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
392             bootsplash = search_file(ffile, iso_mount)
393             print("debug: copy %s to %s") % (bootsplash, isolinux_target + ffile)
394             execute(subprocess.Popen, ["install", "--mode=664", bootsplash, isolinux_target + ffile])
395
396         grub_target = target + '/boot/grub/'
397         execute(mkdir, grub_target)
398
399         print("debug: copy grub/splash.xpm.gz to %s") % grub_target + 'splash.xpm.gz'
400         execute(subprocess.Popen, ["install", "--mode=664", 'grub/splash.xpm.gz', grub_target + 'splash.xpm.gz'])
401
402         print("debug: copy grub/stage2_eltorito to %s") % grub_target + 'stage2_eltorito'
403         execute(subprocess.Popen, ["install", "--mode=664", 'grub/stage2_eltorito', grub_target + 'stage2_eltorito'])
404
405         print("debug: generating grub configuration %s") % grub_target + 'menu.lst'
406         if not dry_run:
407             grub_config_file = open(grub_target + 'menu.lst', 'w')
408             grub_config_file.write(generate_grub_config(grml_flavour))
409             grub_config_file.close( )
410
411         syslinux_target = target + '/boot/isolinux/'
412         execute(mkdir, syslinux_target)
413
414         print("debug: generating syslinux configuration %s") % syslinux_target + 'syslinux.cfg'
415         if not dry_run:
416             syslinux_config_file = open(syslinux_target + 'syslinux.cfg', 'w')
417             syslinux_config_file.write(generate_syslinux_config(grml_flavour))
418             syslinux_config_file.close( )
419
420         print("debug: generating isolinux/syslinux splash %s") % syslinux_target + 'boot.msg'
421         if not dry_run:
422             isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
423             isolinux_splash.write(generate_isolinux_splash(grml_flavour))
424             isolinux_splash.close( )
425
426
427 def uninstall_files(device):
428     """Get rid of all grml files on specified device"""
429
430     # TODO
431     print("TODO: %s") % device
432
433
434 def identify_grml_flavour(mountpath):
435     """Get name of grml flavour
436
437     @mountpath: path where the grml ISO is mounted to
438     @return: name of grml-flavour"""
439
440     version_file = search_file('grml-version', mountpath)
441
442     if version_file == "":
443         print("gucku")
444
445     try:
446         tmpfile = open(version_file, 'r')
447         grml_info = tmpfile.readline()
448         grml_flavour = re.match(r'[\w-]*', grml_info).group()
449     except TypeError:
450         raise
451     except:
452         print "Unexpected error:", sys.exc_info()[0]
453         raise
454
455     return grml_flavour
456
457
458 def main():
459     """Main function [make pylint happy :)]"""
460
461     if options.version:
462         print("%s %s")% (os.path.basename(sys.argv[0]), PROG_VERSION)
463         sys.exit(0)
464
465     if len(args) < 2:
466         parser.error("invalid usage")
467
468     if options.dryrun:
469         print("Running in simulate mode as requested via option dry-run.")
470     else:
471         check_uid_root()
472
473     device = args[len(args) - 1]
474     isos = args[0:len(args) - 1]
475
476     if not which("syslinux"):
477         print >> sys.stderr, 'Sorry, syslinux not available. Exiting.'
478         print >> sys.stderr, 'Please install syslinux or consider using the --grub option.'
479         sys.exit(1)
480
481     # TODO
482     # * check for valid blockdevice, vfat and mount functions
483     # if device is not None:
484         # check_for_vat(device)
485         # mount_target(partition)
486
487     # TODO
488     # * it doesn't need to be a ISO, could be /live/image as well
489     for iso in isos:
490         print("debug: iso = %s") % iso
491
492         if os.path.isdir(iso):
493             print("TODO: /live/image handling not yet implemented") # TODO
494         else:
495             iso_mountpoint = '/mnt/test'     # FIXME
496             # iso_mount = tempfile.mkdtemp()
497             mount(iso, iso_mountpoint, "-o loop -t iso9660")
498             # device_mountpoint = '/mnt/usb-sdb1'
499             # device_mountpoint = tempfile.mkdtemp()
500             device_mountpoint = '/dev/shm/grml2usb' # FIXME
501             mount(device, device_mountpoint, "")
502
503             try:
504                 grml_flavour = identify_grml_flavour(iso_mountpoint)
505                 print("Identified grml flavour \"%s\".") % grml_flavour
506             except TypeError:
507                 print("Fatal: could not identify grml flavour, sorry.")
508                 sys.exit(1)
509
510             # grml_flavour_short = grml_flavour.replace('-','')
511             #p rint("debug: grml_flavour_short = %s") % grml_flavour_short
512
513             copy_grml_files(grml_flavour, iso_mountpoint, device_mountpoint, dry_run=options.dryrun)
514
515             unmount(device_mountpoint)     # TODO
516             unmount(iso_mountpoint)  # TODO
517
518             #if os.path.isdir(target):
519             #    os.rmdir(target)
520             #if os.path.isdir(iso_mount):
521             #    os.rmdir(iso_mount)
522
523
524     if options.mbr:
525         # make sure we install MBR on /dev/sdX and not /dev/sdX#
526         if device[-1:].isdigit():
527             device = re.match(r'(.*?)\d*$', device).group(1)
528
529         try:
530             install_mbr(device, dry_run=options.dryrun)
531         except IOError, error:
532             print >> sys.stderr, "Execution failed:", error
533             sys.exit(1)
534         except Exception, error:
535             print >> sys.stderr, "Execution failed:", error
536             sys.exit(1)
537
538     if options.copyonly:
539         print("Not installing bootloader and its files as requested via option copyonly.")
540     else:
541         install_bootloader(device, dry_run=options.dryrun)
542
543     print("Finished execution of grml2usb (%s). Have fun with your grml system.") % PROG_VERSION
544
545 if __name__ == "__main__":
546     main()
547
548 ## END OF FILE #################################################################
549 # vim:foldmethod=marker expandtab ai ft=python tw=120 fileencoding=utf-8