2 # -*- coding: utf-8 -*-
7 This script installs a grml system (either a running system or ISO[s]) to a USB device
9 :copyright: (c) 2009 by Michael Prokop <mika@grml.org>
10 :license: GPL v2 or any later version
11 :bugreports: http://grml.org/bugs/
16 * implement missing options (--grub, --kernel, --initrd, --squashfs, --uninstall)
17 * validate partition schema/layout: is the partition schema ok and the bootable flag set? (--validate?)
18 * provide --create-partition option?
19 * implement logic for storing information about copied files -> register every file in a set()
20 * the last line in bootsplash (boot.msg) should mention all installed grml flavours
22 - improve error handling wherever possible :)
23 - use 'with open("...", "w") as f: ... f.write("...")'
24 - simplify functions/code as much as possible, especially:
25 Too many local variables
28 * graphical version? any volunteers? :)
31 from __future__ import with_statement
32 from optparse import OptionParser
33 from inspect import isroutine, isclass
34 import datetime, logging, os, re, subprocess, sys, tempfile, time
37 PROG_VERSION = "0.9.2(pre1)"
38 MOUNTED = set() # register mountpoints
39 TMPFILES = set() # register tmpfiles
40 DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
43 USAGE = "Usage: %prog [options] <[ISO[s] | /live/image]> </dev/sdX#>\n\
45 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
46 Make sure you have at least one grml ISO or a running grml system (/live/image),\n\
47 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
48 and root access. Further information can be found in: man grml2usb"
50 # pylint: disable-msg=C0103
51 parser = OptionParser(usage=USAGE)
52 parser.add_option("--bootoptions", dest="bootoptions",
53 action="store", type="string",
54 help="use specified bootoptions as default")
55 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
56 help="do not copy files but just install a bootloader")
57 parser.add_option("--copy-only", dest="copyonly", action="store_true",
58 help="copy files only but do not install bootloader")
59 parser.add_option("--dry-run", dest="dryrun", action="store_true",
60 help="avoid executing commands")
61 parser.add_option("--fat16", dest="fat16", action="store_true",
62 help="format specified partition with FAT16")
63 parser.add_option("--force", dest="force", action="store_true",
64 help="force any actions requiring manual interaction")
65 parser.add_option("--grub", dest="grub", action="store_true",
66 help="install grub bootloader instead of syslinux [TODO]")
67 parser.add_option("--initrd", dest="initrd", action="store", type="string",
68 help="install specified initrd instead of the default [TODO]")
69 parser.add_option("--kernel", dest="kernel", action="store", type="string",
70 help="install specified kernel instead of the default [TODO]")
71 parser.add_option("--lilo", dest="lilo", action="store", type="string",
72 help="lilo executable to be used for installing MBR")
73 parser.add_option("--quiet", dest="quiet", action="store_true",
74 help="do not output anything but just errors on console")
75 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
76 help="do not install /boot/addons/ files")
77 parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
78 help="do not install a master boot record (MBR) on the device")
79 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
80 help="install specified squashfs file instead of the default [TODO]")
81 parser.add_option("--uninstall", dest="uninstall", action="store_true",
82 help="remove grml ISO files from specified device [TODO]")
83 parser.add_option("--verbose", dest="verbose", action="store_true",
84 help="enable verbose mode")
85 parser.add_option("-v", "--version", dest="version", action="store_true",
86 help="display version and exit")
87 (options, args) = parser.parse_args()
90 class CriticalException(Exception):
91 """Throw critical exception if the exact error is not known but fatal."
93 @Exception: message"""
98 """Cleanup function to make sure there aren't any mounted devices left behind.
101 logging.info("Cleaning up before exiting...")
102 proc = subprocess.Popen(["sync"])
106 for device in MOUNTED:
108 # ignore: RuntimeError: Set changed size during iteration
110 logging.debug('caught expection RuntimeError, ignoring')
113 def register_tmpfile(path):
120 def unregister_tmpfile(path):
125 TMPFILES.remove(path)
128 def register_mountpoint(target):
135 def unregister_mountpoint(target):
139 if target in MOUNTED:
140 MOUNTED.remove(target)
143 def get_function_name(obj):
144 """Helper function for use in execute() to retrive name of a function
146 @obj: the function object
148 if not (isroutine(obj) or isclass(obj)):
150 return obj.__module__ + '.' + obj.__name__
153 def execute(f, *exec_arguments):
154 """Wrapper for executing a command. Either really executes
155 the command (default) or when using --dry-run commandline option
156 just displays what would be executed."""
157 # usage: execute(subprocess.Popen, (["ls", "-la"]))
158 # TODO: doesn't work for proc = execute(subprocess.Popen...() -> any ideas?
160 # pylint: disable-msg=W0141
161 logging.debug('dry-run only: %s(%s)' % (get_function_name(f), ', '.join(map(repr, exec_arguments))))
163 # pylint: disable-msg=W0142
164 return f(*exec_arguments)
168 """Check whether a given file can be executed
170 @fpath: full path to file
172 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
176 """Check whether a given program is available in PATH
178 @program: name of executable"""
179 fpath = os.path.split(program)[0]
184 for path in os.environ["PATH"].split(os.pathsep):
185 exe_file = os.path.join(path, program)
192 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
193 """Given a search path, find file
195 @filename: name of file to search for
196 @search_path: path where searching for the specified filename"""
198 paths = search_path.split(os.pathsep)
199 current_dir = '' # make pylint happy :)
201 # pylint: disable-msg=W0612
202 for current_dir, directories, files in os.walk(path):
203 if os.path.exists(os.path.join(current_dir, filename)):
207 return os.path.abspath(os.path.join(current_dir, filename))
212 def check_uid_root():
213 """Check for root permissions"""
214 if not os.geteuid()==0:
215 sys.exit("Error: please run this script with uid 0 (root).")
218 def mkfs_fat16(device):
219 """Format specified device with VFAT/FAT16 filesystem.
221 @device: partition that should be formated"""
223 # syslinux -d boot/isolinux /dev/sdb1
224 logging.info("Formating partition with fat16 filesystem")
225 logging.debug("mkfs.vfat -F 16 %s" % device)
226 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
228 if proc.returncode != 0:
229 raise Exception("error executing mkfs.vfat")
232 def generate_grub_config(grml_flavour):
233 """Generate grub configuration for use via menu.lst
235 @grml_flavour: name of grml flavour the configuration should be generated for"""
237 # * what about systems using grub2 without having grub1 available?
243 # color red/blue green/black
244 splashimage=/boot/grub/splash.xpm.gz
249 title %(grml_flavour)s - Default boot (using 1024x768 framebuffer)
250 kernel /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s
251 initrd /boot/release/%(grml_flavour)s/initrd.gz
253 # TODO: extend configuration :)
254 """ % {'grml_flavour': grml_flavour} )
257 def generate_isolinux_splash(grml_flavour):
258 """Generate bootsplash for isolinux/syslinux
260 @grml_flavour: name of grml flavour the configuration should be generated for"""
262 # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
264 grml_name = grml_flavour
267 \ f17
\f\18/boot/syslinux/logo.16
269 Some information and boot options available via keys F2 - F10. http://grml.org/
271 """ % {'grml_name': grml_name} )
274 def generate_main_syslinux_config(grml_flavour, bootoptions):
275 """Generate main configuration for use in syslinux.cfg
277 @grml_flavour: name of grml flavour the configuration should be generated for
278 @bootoptions: bootoptions that should be used as a default"""
280 local_datestamp = DATESTAMP
283 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
284 # use this to control the bootup via a serial port
289 DISPLAY /boot/syslinux/boot.msg
290 F1 /boot/syslinux/boot.msg
299 F10 /boot/syslinux/f10
300 ## end of main configuration
302 ## global configuration
303 # the default option (using %(grml_flavour)s)
305 KERNEL /boot/release/%(grml_flavour)s/linux26
306 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s %(bootoptions)s
310 KERNEL /boot/addons/memtest
311 #APPEND BOOT_IMAGE=memtest
316 KERNEL /boot/addons/memdisk
317 APPEND initrd=/boot/addons/allinone.img
322 KERNEL /boot/addons/memdisk
323 APPEND initrd=/boot/addons/balder10.imz
325 ## end of global configuration
326 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
329 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
330 """Generate flavour specific configuration for use in syslinux.cfg
332 @grml_flavour: name of grml flavour the configuration should be generated for
333 @bootoptions: bootoptions that should be used as a default"""
335 local_datestamp = DATESTAMP
339 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
340 LABEL %(grml_flavour)s
341 KERNEL /boot/release/%(grml_flavour)s/linux26
342 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s %(bootoptions)s
344 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
345 LABEL %(grml_flavour)s2ram
346 KERNEL /boot/release/%(grml_flavour)s/linux26
347 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s toram=%(grml_flavour)s %(bootoptions)s
349 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
350 LABEL %(grml_flavour)s-debug
351 KERNEL /boot/release/%(grml_flavour)s/linux26
352 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s debug boot=live initcall_debug%(bootoptions)s
354 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
355 LABEL %(grml_flavour)s-x
356 KERNEL /boot/release/%(grml_flavour)s/linux26
357 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s startx=wm-ng %(bootoptions)s
359 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
360 LABEL %(grml_flavour)s-nofb
361 KERNEL /boot/release/%(grml_flavour)s/linux26
362 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=ofonly %(bootoptions)s
364 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
365 LABEL %(grml_flavour)s-failsafe
366 KERNEL /boot/release/%(grml_flavour)s/linux26
367 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal lang=us boot=live noautoconfig atapicd noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia maxcpus=1 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm %(bootoptions)s
369 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
370 LABEL %(grml_flavour)s-forensic
371 KERNEL /boot/release/%(grml_flavour)s/linux26
372 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s nofstab noraid nolvm noautoconfig noswap raid=noautodetect %(bootoptions)s
374 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
375 LABEL %(grml_flavour)s-serial
376 KERNEL /boot/release/%(grml_flavour)s/linux26
377 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
378 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
381 def install_grub(device):
382 """Install grub on specified device.
384 @device: partition where grub should be installed to"""
387 logging.info("Would execute grub-install %s now.", device)
389 logging.critical("TODO: sorry - grub-install %s not implemented yet" % device)
392 def install_syslinux(device):
393 """Install syslinux on specified device.
395 @device: partition where syslinux should be installed to"""
398 logging.info("Would install syslinux as bootloader on %s", device)
401 # syslinux -d boot/isolinux /dev/sdb1
402 logging.info("Installing syslinux as bootloader")
403 logging.debug("syslinux -d boot/syslinux %s" % device)
404 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
406 if proc.returncode != 0:
407 raise Exception("error executing syslinux")
410 def install_bootloader(device):
411 """Install bootloader on specified device.
413 @device: partition where bootloader should be installed to"""
415 # Install bootloader on the device (/dev/sda),
416 # not on the partition itself (/dev/sda1)?
417 #if partition[-1:].isdigit():
418 # device = re.match(r'(.*?)\d*$', partition).group(1)
425 install_syslinux(device)
428 def install_lilo_mbr(lilo, device):
431 # to support -A for extended partitions:
432 logging.info("Installing MBR")
433 logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
434 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
436 if proc.returncode != 0:
437 raise Exception("error executing lilo")
439 # activate partition:
440 logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
441 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
443 if proc.returncode != 0:
444 raise Exception("error executing lilo")
447 def install_syslinux_mbr(device):
450 # lilo's mbr is broken, use the one from syslinux instead:
451 if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
452 raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
454 logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
456 # TODO -> use Popen instead?
457 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
459 logging.critical("Error copying MBR to device (%s)" % retcode)
460 except OSError, error:
461 logging.critical("Execution failed:", error)
464 def install_mbr(device):
465 """Install a default master boot record on given device
467 @device: device where MBR should be installed to"""
469 if not is_writeable(device):
470 raise IOError("device not writeable for user")
472 # try to use system's lilo
476 # otherwise fall back to our static version
477 from platform import architecture
478 if architecture()[0] == '64bit':
479 lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
481 lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
482 # finally prefer a specified lilo executable
487 raise Exception("lilo executable can not be execute")
490 logging.info("Would install MBR running lilo and using syslinux.")
493 install_lilo_mbr(lilo, device)
494 install_syslinux_mbr(device)
497 def is_writeable(device):
498 """Check if the device is writeable for the current user
500 @device: partition where bootloader should be installed to"""
504 #raise Exception("no device for checking write permissions")
506 if not os.path.exists(device):
509 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
512 def mount(source, target, mount_options):
513 """Mount specified source on given target
515 @source: name of device/ISO that should be mounted
516 @target: directory where the ISO should be mounted to
517 @options: mount specific options"""
519 # notice: options.dryrun does not work here, as we have to
520 # locate files and identify the grml flavour
521 logging.debug("mount %s %s %s" % (mount_options, source, target))
522 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
524 if proc.returncode != 0:
525 raise CriticalException("Error executing mount")
527 logging.debug("register_mountpoint(%s)" % target)
528 register_mountpoint(target)
531 def unmount(target, unmount_options):
532 """Unmount specified target
534 @target: target where something is mounted on and which should be unmounted
535 @options: options for umount command"""
537 # make sure we unmount only already mounted targets
538 target_unmount = False
539 mounts = open('/proc/mounts').readlines()
540 mountstring = re.compile(".*%s.*" % re.escape(target))
542 if re.match(mountstring, line):
543 target_unmount = True
545 if not target_unmount:
546 logging.debug("%s not mounted anymore" % target)
548 logging.debug("umount %s %s" % (list(unmount_options), target))
549 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
551 if proc.returncode != 0:
552 raise Exception("Error executing umount")
554 logging.debug("unregister_mountpoint(%s)" % target)
555 unregister_mountpoint(target)
558 def check_for_usbdevice(device):
559 """Check whether the specified device is a removable USB device
561 @device: device name, like /dev/sda1 or /dev/sda
564 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
565 usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
566 if os.path.isfile(usbdevice):
567 is_usb = open(usbdevice).readline()
574 def check_for_fat(partition):
575 """Check whether specified partition is a valid VFAT/FAT16 filesystem
577 @partition: device name of partition"""
580 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition],
581 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
582 filesystem = udev_info.communicate()[0].rstrip()
584 if udev_info.returncode == 2:
585 raise CriticalException("Failed to read device %s"
586 "(wrong UID/permissions or device not present?)" % partition)
588 if filesystem != "vfat":
589 raise CriticalException("Device %s does not contain a FAT16 partition." % partition)
592 raise CriticalException("Sorry, /lib/udev/vol_id not available.")
595 def mkdir(directory):
596 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
598 # just silently pass as it's just fine it the directory exists
599 if not os.path.isdir(directory):
601 os.makedirs(directory)
602 # pylint: disable-msg=W0704
607 def copy_system_files(grml_flavour, iso_mount, target):
610 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
612 logging.critical("Fatal: squashfs file not found")
614 squashfs_target = target + '/live/'
615 execute(mkdir, squashfs_target)
616 # use install(1) for now to make sure we can write the files afterwards as normal user as well
617 logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
618 proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
621 filesystem_module = search_file('filesystem.module', iso_mount)
622 if filesystem_module is None:
623 logging.critical("Fatal: filesystem.module not found")
625 logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
626 proc = subprocess.Popen(["install", "--mode=664", filesystem_module,
627 squashfs_target + grml_flavour + '.module'])
630 release_target = target + '/boot/release/' + grml_flavour
631 execute(mkdir, release_target)
633 kernel = search_file('linux26', iso_mount)
635 logging.critical("Fatal kernel not found")
637 logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
638 proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
641 initrd = search_file('initrd.gz', iso_mount)
643 logging.critical("Fatal: initrd not found")
645 logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
646 proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
650 def copy_grml_files(iso_mount, target):
653 grml_target = target + '/grml/'
654 execute(mkdir, grml_target)
656 for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
657 grml_file = search_file(myfile, iso_mount)
658 if grml_file is None:
659 logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
661 logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
662 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
665 grml_web_target = grml_target + '/web/'
666 execute(mkdir, grml_web_target)
668 for myfile in 'index.html', 'style.css':
669 grml_file = search_file(myfile, iso_mount)
670 if grml_file is None:
671 logging.warn("Warning: myfile %s could not be found - can not install it")
673 logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
674 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
677 grml_webimg_target = grml_web_target + '/images/'
678 execute(mkdir, grml_webimg_target)
680 for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
681 grml_file = search_file(myfile, iso_mount)
682 if grml_file is None:
683 logging.warn("Warning: myfile %s could not be found - can not install it")
685 logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
686 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
690 def copy_addons(iso_mount, target):
692 addons = target + '/boot/addons/'
693 execute(mkdir, addons)
695 # grub all-in-one image
696 allinoneimg = search_file('allinone.img', iso_mount)
697 if allinoneimg is None:
698 logging.warn("Warning: allinone.img not found - can not install it")
700 logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
701 proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
705 balderimg = search_file('balder10.imz', iso_mount)
706 if balderimg is None:
707 logging.warn("Warning: balder10.imz not found - can not install it")
709 logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
710 proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
714 memdiskimg = search_file('memdisk', iso_mount)
715 if memdiskimg is None:
716 logging.warn("Warning: memdisk not found - can not install it")
718 logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
719 proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
723 def copy_bootloader_files(iso_mount, target):
726 syslinux_target = target + '/boot/syslinux/'
727 execute(mkdir, syslinux_target)
729 logo = search_file('logo.16', iso_mount)
730 logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
731 proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
734 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
735 bootsplash = search_file(ffile, iso_mount)
736 logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
737 proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
740 grub_target = target + '/boot/grub/'
741 execute(mkdir, grub_target)
743 if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
744 logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
747 logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
748 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz',
749 grub_target + 'splash.xpm.gz'])
752 if not os.path.isfile("/usr/share/grml2usb/grub/stage2_eltorito"):
753 logging.critical("Error: /usr/share/grml2usb/grub/stage2_eltorito can not be read.")
756 logging.debug("cp /usr/share/grml2usb/grub/stage2_eltorito to %s" % grub_target + 'stage2_eltorito')
757 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/stage2_eltorito',
758 grub_target + 'stage2_eltorito'])
762 def install_iso_files(grml_flavour, iso_mount, target):
763 """Copy files from ISO on given target"""
766 # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
767 # * provide alternative search_file() if file information is stored in a config.ini file?
768 # * catch "install: .. No space left on device" & CO
769 # * abstract copy logic to make the code shorter and get rid of spaghettis ;)
772 logging.info("Would copy files to %s", iso_mount)
774 elif not options.bootloaderonly:
775 logging.info("Copying files. This might take a while....")
776 copy_system_files(grml_flavour, iso_mount, target)
777 copy_grml_files(iso_mount, target)
779 if not options.skipaddons:
780 copy_addons(iso_mount, target)
782 if not options.copyonly:
783 copy_bootloader_files(iso_mount, target)
785 if not options.dryrun:
786 handle_bootloader_config(grml_flavour, target) # FIXME
788 # make sure we sync filesystems before returning
789 proc = subprocess.Popen(["sync"])
793 def uninstall_files(device):
794 """Get rid of all grml files on specified device
796 @device: partition where grml2usb files should be removed from"""
799 logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
802 def identify_grml_flavour(mountpath):
803 """Get name of grml flavour
805 @mountpath: path where the grml ISO is mounted to
806 @return: name of grml-flavour"""
808 version_file = search_file('grml-version', mountpath)
810 if version_file == "":
811 logging.critical("Error: could not find grml-version file.")
815 tmpfile = open(version_file, 'r')
816 grml_info = tmpfile.readline()
817 grml_flavour = re.match(r'[\w-]*', grml_info).group()
821 logging.critical("Unexpected error:", sys.exc_info()[0])
827 def handle_bootloader_config(grml_flavour, target):
830 logging.debug("Generating grub configuration")
831 #with open("...", "w") as f:
832 #f.write("bla bla bal")
834 grub_target = target + '/boot/grub/'
835 # should be present via copy_bootloader_files(), but make sure it exists:
836 execute(mkdir, grub_target)
837 grub_config_file = open(grub_target + 'menu.lst', 'w')
838 grub_config_file.write(generate_grub_config(grml_flavour))
839 grub_config_file.close()
841 logging.info("Generating syslinux configuration")
842 syslinux_target = target + '/boot/syslinux/'
843 # should be present via copy_bootloader_files(), but make sure it exits:
844 execute(mkdir, syslinux_target)
845 syslinux_cfg = syslinux_target + 'syslinux.cfg'
847 # install main configuration only *once*, no matter how many ISOs we have:
848 if os.path.isfile(syslinux_cfg):
849 string = open(syslinux_cfg).readline()
850 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
851 if not re.match(main_identifier, string):
852 syslinux_config_file = open(syslinux_cfg, 'w')
853 logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
854 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
855 syslinux_config_file.close()
857 syslinux_config_file = open(syslinux_cfg, 'w')
858 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
859 syslinux_config_file.close()
861 # install flavour specific configuration only *once* as well
862 # kind of ugly - I'm pretty sure this could be smoother...
863 flavour_config = True
864 if os.path.isfile(syslinux_cfg):
865 string = open(syslinux_cfg).readlines()
866 logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
867 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
869 if flavour.match(line):
870 flavour_config = False
873 syslinux_config_file = open(syslinux_cfg, 'a')
874 syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, options.bootoptions))
875 syslinux_config_file.close( )
877 logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
878 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
879 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
880 isolinux_splash.close( )
883 def handle_iso(iso, device):
884 """Main logic for mounting ISOs and copying files.
886 @iso: full path to the ISO that should be installed to the specified device
887 @device: partition where the specified ISO should be installed to"""
889 logging.info("Using ISO %s" % iso)
891 if os.path.isdir(iso):
892 logging.critical("TODO: /live/image handling not yet implemented - sorry") # TODO
895 iso_mountpoint = tempfile.mkdtemp()
896 register_tmpfile(iso_mountpoint)
897 remove_iso_mountpoint = True
899 if not os.path.isfile(iso):
900 logging.critical("Fatal: specified ISO %s could not be read" % iso)
905 mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
906 except CriticalException, error:
907 logging.critical("Fatal: %s" % error)
910 if os.path.isdir(device):
911 logging.info("Specified target is a directory, not mounting therefor.")
912 device_mountpoint = device
913 remove_device_mountpoint = False
916 device_mountpoint = tempfile.mkdtemp()
917 register_tmpfile(device_mountpoint)
918 remove_device_mountpoint = True
920 mount(device, device_mountpoint, "")
921 except CriticalException, error:
922 logging.critical("Fatal: %s" % error)
926 grml_flavour = identify_grml_flavour(iso_mountpoint)
927 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
928 install_iso_files(grml_flavour, iso_mountpoint, device_mountpoint)
930 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
933 if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
934 unmount(iso_mountpoint, "")
935 os.rmdir(iso_mountpoint)
936 unregister_tmpfile(iso_mountpoint)
937 if remove_device_mountpoint:
938 unmount(device_mountpoint, "")
939 if os.path.isdir(device_mountpoint):
940 os.rmdir(device_mountpoint)
941 unregister_tmpfile(device_mountpoint)
944 def handle_mbr(device):
948 # if not options.mbr:
949 # logging.info("You are NOT using the --mbr option. Consider using it if your device does not boot.")
951 # make sure we install MBR on /dev/sdX and not /dev/sdX#
953 # make sure we have syslinux available
955 if not options.skipmbr:
956 if not which("syslinux") and not options.copyonly and not options.dryrun:
957 logging.critical('Sorry, syslinux not available. Exiting.')
958 logging.critical('Please install syslinux or consider using the --grub option.')
961 if not options.skipmbr:
962 if device[-1:].isdigit():
963 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
966 install_mbr(mbr_device)
967 except IOError, error:
968 logging.critical("Execution failed: %s", error)
970 except Exception, error:
971 logging.critical("Execution failed: %s", error)
975 def handle_vfat(device):
978 # make sure we have mkfs.vfat available
979 if options.fat16 and not options.force:
980 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
981 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
982 logging.critical('Please make sure to install dosfstools.')
985 # make sure the user is aware of what he is doing
986 f = raw_input("Are you sure you want to format the device with a fat16 filesystem? y/N ")
987 if f == "y" or f == "Y":
988 logging.info("Note: you can skip this question using the option --force")
993 # check for vfat filesystem
994 if device is not None and not os.path.isdir(device):
996 check_for_fat(device)
997 except CriticalException, error:
998 logging.critical("Execution failed: %s", error)
1001 if not check_for_usbdevice(device):
1002 print "Warning: the specified device %s does not look like a removable usb device." % device
1003 f = raw_input("Do you really want to continue? y/N ")
1004 if f == "y" or f == "Y":
1014 def handle_compat_warning(device):
1017 # make sure we can replace old grml2usb script and warn user when using old way of life:
1018 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1019 print "Warning: the semantics of grml2usb has changed."
1020 print "Instead of using grml2usb /path/to/iso %s you might" % device
1021 print "want to use grml2usb /path/to/iso /dev/... instead."
1022 print "Please check out the grml2usb manpage for details."
1023 f = raw_input("Do you really want to continue? y/N ")
1024 if f == "y" or f == "Y":
1030 def handle_logging():
1034 FORMAT = "%(asctime)-15s %(message)s"
1035 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1037 FORMAT = "Critial: %(message)s"
1038 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1040 FORMAT = "Info: %(message)s"
1041 logging.basicConfig(level=logging.INFO, format=FORMAT)
1044 def handle_bootloader(device):
1046 # Install bootloader only if not using the --copy-only option
1047 if options.copyonly:
1048 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1050 install_bootloader(device)
1054 """Main function [make pylint happy :)]"""
1057 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1061 parser.error("invalid usage")
1066 # make sure we have the appropriate permissions
1070 logging.info("Running in simulate mode as requested via option dry-run.")
1072 # specified arguments
1073 device = args[len(args) - 1]
1074 isos = args[0:len(args) - 1]
1076 # provide upgrade path
1077 handle_compat_warning(device)
1079 # check for vfat partition
1082 # main operation (like installing files)
1084 handle_iso(iso, device)
1089 handle_bootloader(device)
1091 # finally be politely :)
1092 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1095 if __name__ == "__main__":
1098 except KeyboardInterrupt:
1099 logging.info("Received KeyboardInterrupt")
1102 ## END OF FILE #################################################################
1103 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8