2 # -*- coding: utf-8 -*-
3 # pylint: disable-msg=C0302
8 This script installs a grml system (either a running system or ISO[s]) to a USB device
10 :copyright: (c) 2009, 2010, 2011 by Michael Prokop <mika@grml.org>
11 :license: GPL v2 or any later version
12 :bugreports: http://grml.org/bugs/
16 from optparse import OptionParser
17 from inspect import isroutine, isclass
32 # The line following this line is patched by debian/rules and tarball.sh.
33 PROG_VERSION = '***UNRELEASED***'
36 MOUNTED = set() # register mountpoints
37 TMPFILES = set() # register tmpfiles
38 DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
39 GRML_FLAVOURS = set() # which flavours are being installed?
42 SYSLINUX_LIBS = "/usr/lib/syslinux/"
43 GPT_HEADER = "\x55\xaa\x45\x46\x49\x20\x50\x41\x52\x54" # original GPT header
45 RE_PARTITION = re.compile(r'([a-z/]*?)(\d+)$')
46 RE_P_PARTITION = re.compile(r'(.*?\d+)p(\d+)$')
47 RE_LOOP_DEVICE = re.compile(r'/dev/loop\d+$')
50 def syslinux_warning(option, opt, value, opt_parser):
51 """A helper function for printing a warning about deprecated option
53 # pylint: disable-msg=W0613
54 sys.stderr.write("Note: the --syslinux option is deprecated as syslinux "
55 "is grml2usb's default. Continuing anyway.\n")
56 setattr(opt_parser.values, option.dest, True)
59 # if grub option is set, unset syslinux option
60 def grub_option(option, opt, value, opt_parser):
61 """A helper function adjusting other option values
63 # pylint: disable-msg=W0613
64 setattr(opt_parser.values, option.dest, True)
65 setattr(opt_parser.values, 'syslinux', False)
68 USAGE = "Usage: %prog [options] <[ISO[s] | /lib/live/mount/medium]> </dev/sdX#>\n\
70 %prog installs Grml ISO[s] to an USB device to be able to boot from it.\n\
71 Make sure you have at least one Grml ISO or a running Grml system (/lib/live/mount/medium),\n\
72 grub or syslinux and root access.\n\
74 Run %prog --help for usage hints, further information via: man grml2usb"
76 # pylint: disable-msg=C0103
77 # pylint: disable-msg=W0603
78 parser = OptionParser(usage=USAGE)
79 parser.add_option("--bootoptions", dest="bootoptions",
80 action="append", type="string",
81 help="use specified bootoptions as default")
82 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
83 help="do not copy files but just install a bootloader")
84 parser.add_option("--copy-only", dest="copyonly", action="store_true",
85 help="copy files only but do not install bootloader")
86 parser.add_option("--dry-run", dest="dryrun", action="store_true",
87 help="avoid executing commands")
88 parser.add_option("--fat16", dest="fat16", action="store_true",
89 help="format specified partition with FAT16")
90 parser.add_option("--force", dest="force", action="store_true",
91 help="force any actions requiring manual interaction")
92 parser.add_option("--grub", dest="grub", action="callback",
94 help="install grub bootloader instead of (default) syslinux")
95 parser.add_option("--grub-mbr", dest="grubmbr", action="store_true",
96 help="install grub into MBR instead of (default) PBR")
97 parser.add_option("--mbr-menu", dest="mbrmenu", action="store_true",
98 help="enable interactive boot menu in MBR")
99 parser.add_option("--quiet", dest="quiet", action="store_true",
100 help="do not output anything but just errors on console")
101 parser.add_option("--remove-bootoption", dest="removeoption", action="append",
102 help="regex for removing existing bootoptions")
103 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
104 help="do not install /boot/addons/ files")
105 parser.add_option("--skip-grub-config", dest="skipgrubconfig", action="store_true",
106 help="skip generation of grub configuration files")
107 parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
108 help="do not install a master boot record (MBR) on the device")
109 parser.add_option("--skip-syslinux-config", dest="skipsyslinuxconfig", action="store_true",
110 help="skip generation of syslinux configuration files")
111 parser.add_option("--syslinux", dest="syslinux", action="callback", default=True,
112 callback=syslinux_warning,
113 help="install syslinux bootloader (deprecated as it's the default)")
114 parser.add_option("--syslinux-mbr", dest="syslinuxmbr", action="store_true",
115 help="install syslinux master boot record (MBR) instead of default")
116 parser.add_option("--tmpdir", dest="tmpdir", default="/tmp",
117 help="directory to be used for temporary files")
118 parser.add_option("--verbose", dest="verbose", action="store_true",
119 help="enable verbose mode")
120 parser.add_option("-v", "--version", dest="version", action="store_true",
121 help="display version and exit")
122 (options, args) = parser.parse_args()
125 GRML2USB_BASE = '/usr/share/grml2usb'
126 if not os.path.isdir(GRML2USB_BASE):
127 GRML2USB_BASE = os.path.dirname(os.path.realpath(__file__))
130 class CriticalException(Exception):
131 """Throw critical exception if the exact error is not known but fatal.
133 @Exception: message"""
137 class VerifyException(Exception):
138 """Throw critical exception if there is an fatal error when verifying something.
140 @Exception: message"""
144 # The following two functions help to operate on strings as
145 # array (list) of bytes (octets). In Python 3000, the bytes
146 # datatype will need to be used. This is intended for using
147 # with manipulation of files on the octet level, like shell
148 # arrays, e.g. in MBR creation.
151 def array2string(*a):
152 """Convert a list of integers [0;255] to a string."""
153 return struct.pack("%sB" % len(a), *a)
157 """Convert a (bytes) string into a list of integers."""
158 return struct.unpack("%sB" % len(s), s)
162 """Cleanup function to make sure there aren't any mounted devices left behind.
165 logging.info("Cleaning up before exiting...")
166 proc = subprocess.Popen(["sync"])
170 for device in MOUNTED:
172 for tmpfile in TMPFILES:
174 # ignore: RuntimeError: Set changed size during iteration
176 logging.debug('caught exception RuntimeError, ignoring')
179 def register_tmpfile(path):
187 def unregister_tmpfile(path):
189 remove registered tmpfile
193 TMPFILES.remove(path)
198 def register_mountpoint(target):
199 """register specified target in a set() for handling clean exiting
201 @target: destination target of mountpoint
207 def unregister_mountpoint(target):
208 """unregister specified target in a set() for handling clean exiting
210 @target: destination target of mountpoint
213 if target in MOUNTED:
214 MOUNTED.remove(target)
217 def get_function_name(obj):
218 """Helper function for use in execute() to retrive name of a function
220 @obj: the function object
222 if not (isroutine(obj) or isclass(obj)):
224 return obj.__module__ + '.' + obj.__name__
227 def execute(f, *exec_arguments):
228 """Wrapper for executing a command. Either really executes
229 the command (default) or when using --dry-run commandline option
230 just displays what would be executed."""
231 # usage: execute(subprocess.Popen, (["ls", "-la"]))
233 # pylint: disable-msg=W0141
234 logging.debug('dry-run only: %s(%s)', get_function_name(f), ', '.join(map(repr, exec_arguments)))
236 # pylint: disable-msg=W0142
237 return f(*exec_arguments)
241 """Check whether a given file can be executed
243 @fpath: full path to file
245 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
249 """Check whether a given program is available in PATH
251 @program: name of executable"""
252 fpath = os.path.split(program)[0]
257 for path in os.environ["PATH"].split(os.pathsep):
258 exe_file = os.path.join(path, program)
265 def get_defaults_file(iso_mount, flavour, name):
266 """get the default file for syslinux
268 bootloader_dirs = ['/boot/isolinux/', '/boot/syslinux/']
269 for directory in bootloader_dirs:
271 "%s_%s" % (get_flavour_filename(flavour), name):
272 if os.path.isfile(iso_mount + directory + name):
273 return (directory, name)
277 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin', lst_return=False):
278 """Given a search path, find file
280 @filename: name of file to search for
281 @search_path: path where searching for the specified filename
282 @lst_return: return list of matching files instead one file"""
283 paths = search_path.split(os.pathsep)
284 current_dir = '' # make pylint happy :)
288 """Helper function ffor testing if specified file exists in cwd
290 @cwd: current working directory
292 return os.path.exists(os.path.join(cwd, filename))
296 if match_file(current_dir):
297 retval.append(os.path.abspath(os.path.join(current_dir, filename)))
300 # pylint: disable-msg=W0612
301 for current_dir, directories, files in os.walk(path):
302 if match_file(current_dir):
303 retval.append(os.path.abspath(os.path.join(current_dir, filename)))
314 def check_uid_root():
315 """Check for root permissions"""
316 if not os.geteuid() == 0:
317 raise CriticalException("please run this script with uid 0 (root).")
320 # for usage inside check_boot_flag
321 def get_partition_for_path(path):
324 boot_dev, x = get_device_from_partition(path)
326 d = parted.getDevice(boot_dev)
327 disk = parted.Disk(d)
328 return disk.getPartitionByPath(path)
331 def check_boot_flag(device):
332 boot_dev, x = get_device_from_partition(device)
336 part = get_partition_for_path(device)
337 if part.getFlag(parted.PARTITION_BOOT):
338 logging.debug("bootflag is enabled on %s" % device)
340 except ImportError, e:
343 with open(boot_dev, 'r') as image:
344 data = image.read(520)
345 bootcode = data[440:]
346 gpt_data = bootcode[70:80]
348 if gpt_data == GPT_HEADER:
349 logging.info("GPT detected, skipping bootflag check")
350 elif bootcode[6] == '\x80':
351 logging.debug("bootflag is enabled")
353 logging.debug("bootflag is NOT enabled")
354 raise VerifyException("Device %s does not have the bootflag set. "
355 "Please enable it to be able to boot." % device)
358 def mkfs_fat16(device):
359 """Format specified device with VFAT/FAT16 filesystem.
361 @device: partition that should be formated"""
364 logging.info("Would execute mkfs.vfat -F 16 %s now.", device)
367 logging.info("Formating partition with fat16 filesystem")
368 logging.debug("mkfs.vfat -F 16 %s", device)
369 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
371 if proc.returncode != 0:
372 raise CriticalException("error executing mkfs.vfat")
375 def generate_isolinux_splash(grml_flavour):
376 """Generate bootsplash for isolinux/syslinux
378 @grml_flavour: name of grml flavour the configuration should be generated for"""
380 grml_name = grml_flavour
383 \ f17
\f\18/boot/syslinux/logo.16
385 Some information and boot options available via keys F2 - F10. http://grml.org/
387 """ % {'grml_name': grml_name})
390 def generate_main_syslinux_config(*arg):
391 """Generate main configuration for use in syslinux.cfg
393 @*arg: just for backward compatibility"""
394 # pylint: disable-msg=W0613
395 # remove warning about unused arg
399 menu label Default boot modes:
408 menu label Additional boot entries for:
410 include additional.cfg
417 include promptname.cfg
420 Jump to old style isolinux prompt
421 featuring further information
422 regarding available boot options.
430 def generate_flavour_specific_syslinux_config(grml_flavour):
431 """Generate flavour specific configuration for use in syslinux.cfg
433 @grml_flavour: name of grml flavour the configuration should be generated for"""
436 menu begin grml %(grml_flavour)s
437 menu title %(display_name)s
439 menu label ^Back to main menu...
442 # include config for boot parameters from disk
443 include %(grml_flavour)s_grml.cfg
446 """ % {'grml_flavour': grml_flavour, 'display_name': get_flavour_filename(grml_flavour)})
449 def install_grub(device):
450 """Install grub on specified device.
452 @mntpoint: mountpoint of device where grub should install its files to
453 @device: partition where grub should be installed to"""
456 logging.info("Would execute grub-install [--root-directory=mount_point] %s now.", device)
458 device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
459 register_tmpfile(device_mountpoint)
462 mount(device, device_mountpoint, "")
464 # If using --grub-mbr then make sure we install grub in MBR instead of PBR
466 logging.debug("Using option --grub-mbr ...")
467 grub_device, x = get_device_from_partition(device)
471 logging.info("Installing grub as bootloader")
472 for opt in ["", "--force"]:
473 logging.debug("grub-install --recheck %s --no-floppy --root-directory=%s %s",
474 opt, device_mountpoint, grub_device)
475 proc = subprocess.Popen(["grub-install", "--recheck", opt, "--no-floppy",
476 "--root-directory=%s" % device_mountpoint, grub_device],
477 stdout=file(os.devnull, "r+"))
479 if proc.returncode == 0:
482 if proc.returncode != 0:
483 # raise Exception("error executing grub-install")
484 logging.critical("Fatal: error executing grub-install "
485 + "(please check the grml2usb FAQ or drop the --grub option)")
486 logging.critical("Note: if using grub2 consider using "
487 + "the --grub-mbr option as grub considers PBR problematic.")
490 except CriticalException, error:
491 logging.critical("Fatal: %s", error)
496 unmount(device_mountpoint, "")
497 os.rmdir(device_mountpoint)
498 unregister_tmpfile(device_mountpoint)
501 def install_syslinux(device):
502 """Install syslinux on specified device.
504 @device: partition where syslinux should be installed to"""
507 logging.info("Would install syslinux as bootloader on %s", device)
510 # syslinux -d boot/isolinux /dev/sdb1
511 logging.info("Installing syslinux as bootloader")
512 logging.debug("syslinux -d boot/syslinux %s", device)
513 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
515 if proc.returncode != 0:
516 raise CriticalException("Error executing syslinux (either try --fat16 or use grub?)")
519 def install_bootloader(device):
520 """Install bootloader on specified device.
522 @device: partition where bootloader should be installed to"""
524 # by default we use grub, so install syslinux only on request
528 except CriticalException, error:
529 logging.critical("Fatal: %s", error)
534 install_syslinux(device)
535 except CriticalException, error:
536 logging.critical("Fatal: %s", error)
541 def install_mbr(mbrtemplate, device, partition, ismirbsdmbr=True):
542 """install 'mbr' master boot record (MBR) on a device
544 Retrieve the partition table from "device", install an MBR from the
545 "mbrtemplate" file, set the "partition" (0..3) active, and install the
546 result back to "device".
548 @mbrtemplate: default MBR file
550 @device: name of a file assumed to be a hard disc (or USB stick) image, or
551 something like "/dev/sdb"
553 @partition: must be a number between 0 and 3, inclusive
555 @mbrtemplate: must be a valid MBR file of at least 440 (or 439 if
558 @ismirbsdmbr: if true then ignore the active flag, set the mirbsdmbr
559 specific flag to 0/1/2/3 and set the MBR's default value accordingly. If
560 false then leave the mirbsdmbr specific flag set to FFh, set all
561 active flags to 0 and set the active flag of the partition to 80h. Note:
562 behaviour of mirbsdmbr: if flag = 0/1/2/3 then use it, otherwise search for
565 logging.info("Installing default MBR")
567 if not os.path.isfile(mbrtemplate):
568 logging.error('Error installing MBR (either try --syslinux-mbr or '
569 'install missing file "%s"?)', mbrtemplate)
570 raise CriticalException("%s can not be read." % mbrtemplate)
572 if partition is not None and ((partition < 0) or (partition > 3)):
573 logging.warn("Cannot activate partition %d", partition)
581 tmpf = tempfile.NamedTemporaryFile()
583 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1", device, tmpf.name)
584 proc = subprocess.Popen(["dd", "if=%s" % device, "of=%s" % tmpf.name, "bs=512", "count=1"],
585 stderr=file(os.devnull, "r+"))
587 if proc.returncode != 0:
588 raise Exception("error executing dd (first run)")
590 logging.debug("executing: dd if=%s of=%s bs=%s count=1 conv=notrunc", mbrtemplate,
591 tmpf.name, nmbrbytes)
592 proc = subprocess.Popen(["dd", "if=%s" % mbrtemplate, "of=%s" % tmpf.name, "bs=%s" % nmbrbytes,
593 "count=1", "conv=notrunc"], stderr=file(os.devnull, "r+"))
595 if proc.returncode != 0:
596 raise Exception("error executing dd (second run)")
598 mbrcode = tmpf.file.read(512)
599 if len(mbrcode) < 512:
600 raise EOFError("MBR size (%d) < 512" % len(mbrcode))
602 if partition is not None:
604 mbrcode = mbrcode[0:439] + chr(partition) + \
605 mbrcode[440:510] + "\x55\xAA"
607 actives = ["\x00", "\x00", "\x00", "\x00"]
608 actives[partition] = "\x80"
609 mbrcode = mbrcode[0:446] + actives[0] + \
610 mbrcode[447:462] + actives[1] + \
611 mbrcode[463:478] + actives[2] + \
612 mbrcode[479:494] + actives[3] + \
613 mbrcode[495:510] + "\x55\xAA"
617 tmpf.file.write(mbrcode)
620 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1 conv=notrunc", tmpf.name, device)
621 proc = subprocess.Popen(["dd", "if=%s" % tmpf.name, "of=%s" % device, "bs=512", "count=1",
622 "conv=notrunc"], stderr=file(os.devnull, "r+"))
624 if proc.returncode != 0:
625 raise Exception("error executing dd (third run)")
629 def is_writeable(device):
630 """Check if the device is writeable for the current user
632 @device: partition where bootloader should be installed to"""
636 #raise Exception("no device for checking write permissions")
638 if not os.path.exists(device):
641 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
644 def mount(source, target, mount_options):
645 """Mount specified source on given target
647 @source: name of device/ISO that should be mounted
648 @target: directory where the ISO should be mounted to
649 @options: mount specific options"""
651 # note: options.dryrun does not work here, as we have to
652 # locate files and identify the grml flavour
654 for x in file('/proc/mounts').readlines():
655 if x.startswith(source):
656 raise CriticalException("Error executing mount: %s already mounted - " % source
657 + "please unmount before invoking grml2usb")
659 if os.path.isdir(source):
660 logging.debug("Source %s is not a device, therefore not mounting.", source)
663 logging.debug("mount %s %s %s", mount_options, source, target)
664 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
666 if proc.returncode != 0:
667 raise CriticalException("Error executing mount (no filesystem on the partition?)")
669 logging.debug("register_mountpoint(%s)", target)
670 register_mountpoint(target)
673 def unmount(target, unmount_options):
674 """Unmount specified target
676 @target: target where something is mounted on and which should be unmounted
677 @options: options for umount command"""
679 # make sure we unmount only already mounted targets
680 target_unmount = False
681 mounts = open('/proc/mounts').readlines()
682 mountstring = re.compile(".*%s.*" % re.escape(os.path.realpath(target)))
684 if re.match(mountstring, line):
685 target_unmount = True
687 if not target_unmount:
688 logging.debug("%s not mounted anymore", target)
690 logging.debug("umount %s %s", list(unmount_options), target)
691 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
693 if proc.returncode != 0:
694 raise Exception("Error executing umount")
696 logging.debug("unregister_mountpoint(%s)", target)
697 unregister_mountpoint(target)
700 def check_for_usbdevice(device):
701 """Check whether the specified device is a removable USB device
703 @device: device name, like /dev/sda1 or /dev/sda
706 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
708 usbdev = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
709 if not os.path.isfile(usbdev):
710 # Ubuntu with kernel 2.6.24 for example:
711 usbdev = os.path.realpath('/sys/block/' + usbdevice + '/removable')
713 if os.path.isfile(usbdev):
714 is_usb = open(usbdev).readline()
721 def check_for_fat(partition):
722 """Check whether specified partition is a valid VFAT/FAT16 filesystem
724 @partition: device name of partition"""
726 if not os.access(partition, os.R_OK):
727 raise CriticalException("Failed to read device %s"
728 " (wrong UID/permissions or device/directory not present?)" % partition)
731 udev_info = subprocess.Popen(["/sbin/blkid", "-s", "TYPE", "-o", "value", partition],
732 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
733 filesystem = udev_info.communicate()[0].rstrip()
735 if filesystem != "vfat":
736 raise CriticalException(
737 "Partition %s does not contain a FAT16 filesystem. "
738 "(Use --fat16 or run mkfs.vfat %s)" % (partition, partition))
741 raise CriticalException("Sorry, /sbin/blkid not available (install e2fsprogs?)")
744 def mkdir(directory):
745 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
747 # just silently pass as it's just fine it the directory exists
748 if not os.path.isdir(directory):
750 os.makedirs(directory)
751 # pylint: disable-msg=W0704
756 def exec_rsync(source, target):
757 """Simple wrapper around rsync to install files
759 @source: source file/directory
760 @target: target file/directory"""
761 logging.debug("Source: %s / Target: %s", source, target)
762 proc = subprocess.Popen(["rsync", "-rlptDH", "--inplace", source, target])
764 if proc.returncode == 12:
765 logging.critical("Fatal: No space left on device")
769 if proc.returncode != 0:
770 logging.critical("Fatal: could not install %s", source)
775 def write_uuid(target_file):
776 """Generates an returns uuid and write it to the specified file
778 @target_file: filename to write the uuid to
781 fileh = open(target_file, 'w')
782 uid = str(uuid.uuid4())
788 def get_uuid(target):
789 """Get the uuid of the specified target. Will generate an uuid if none exist.
791 @target: directory/mountpoint containing the grml layout
794 conf_target = target + "/conf/"
795 uuid_file_name = conf_target + "/bootid.txt"
796 if os.path.isdir(conf_target):
797 if os.path.isfile(uuid_file_name):
798 uuid_file = open(uuid_file_name, 'r')
799 uid = uuid_file.readline().strip()
803 return write_uuid(uuid_file_name)
805 execute(mkdir, conf_target)
806 return write_uuid(uuid_file_name)
809 def get_shortname(grml_flavour):
810 """Get shortname based from grml_flavour name. The rules applied are the same as in grml-live
811 @grml_flavour: flavour name which shold be translated to shortname"""
813 return re.sub(r'[,._-]', '', grml_flavour)
816 def copy_system_files(grml_flavour, iso_mount, target):
817 """copy grml's main files (like squashfs, kernel and initrd) to a given target
819 @grml_flavour: name of grml flavour the configuration should be generated for
820 @iso_mount: path where a grml ISO is mounted on
821 @target: path where grml's main files should be copied to"""
823 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
825 logging.error("error locating squashfs file")
826 raise CriticalException("squashfs file not found, please check that your iso is not corrupt")
828 squashfs_target = target + '/live/' + grml_flavour + '/'
829 execute(mkdir, squashfs_target)
830 exec_rsync(squashfs, squashfs_target + grml_flavour + '.squashfs')
832 for prefix in grml_flavour + "/", "":
833 filesystem_module = search_file(prefix + 'filesystem.module', iso_mount)
834 if filesystem_module:
836 if filesystem_module is None:
837 logging.error("error locating filesystem.module file")
838 raise CriticalException("filesystem.module not found")
840 exec_rsync(filesystem_module, squashfs_target + 'filesystem.module')
842 shortname = get_shortname(grml_flavour)
843 if os.path.isdir(iso_mount + '/boot/' + shortname):
844 exec_rsync(iso_mount + '/boot/' + shortname, target + '/boot')
846 kernel = search_file('vmlinuz', iso_mount)
848 # compat for releases < 2011.12
849 kernel = search_file('linux26', iso_mount)
852 logging.error("error locating kernel file")
853 raise CriticalException("Kernel not found")
855 source = os.path.dirname(kernel) + '/'
856 dest = target + '/' + os.path.dirname(kernel).replace(iso_mount, '') + '/'
858 exec_rsync(source, dest)
861 def update_grml_versions(iso_mount, target):
862 """Update the grml version file on a cd
863 Returns true if version was updated successfully,
864 False if grml-version does not exist yet on the mountpoint
866 @iso_mount: string of the iso mount point
867 @target: path of the target mount point
869 grml_target = target + '/grml/'
870 target_grml_version_file = search_file('grml-version', grml_target)
871 if target_grml_version_file:
872 iso_grml_version_file = search_file('grml-version', iso_mount)
873 if not iso_grml_version_file:
874 logging.warn("Warning: %s could not be found - can not install it", iso_grml_version_file)
877 # read the flavours from the iso image
879 iso_file = open(iso_grml_version_file, 'r')
880 for line in iso_file:
881 iso_versions[get_flavour(line)] = line.strip()
883 # update the existing flavours on the target
884 for line in fileinput.input([target_grml_version_file], inplace=1):
885 flavour = get_flavour(line)
886 if flavour in iso_versions.keys():
887 print iso_versions.pop(flavour)
892 target_file = open(target_grml_version_file, 'a')
893 # add the new flavours from the current iso
894 for flavour in iso_versions:
895 target_file.write("%s\n" % iso_versions[flavour])
897 logging.warn("Warning: Could not write file")
906 def copy_grml_files(grml_flavour, iso_mount, target):
907 """copy some minor grml files to a given target
909 @grml_flavour: the current grml_flavour
910 @iso_mount: path where a grml ISO is mounted on
911 @target: path where grml's main files should be copied to"""
913 grml_target = target + '/grml/'
914 execute(mkdir, grml_target)
916 grml_prefixe = ["GRML", "grml"]
917 for prefix in grml_prefixe:
918 filename = "{0}/{1}/{2}".format(iso_mount, prefix, grml_flavour)
919 if os.path.exists(filename):
920 exec_rsync(filename, grml_target)
923 logging.warn("Warning: could not find flavour directory for %s ", grml_flavour)
926 def handle_addon_copy(filename, dst, iso_mount, ignore_errors=False):
927 """handle copy of optional addons
929 @filename: filename of the addon
930 @dst: destination directory
931 @iso_mount: location of the iso mount
932 @ignore_errors: don't report missing files
934 file_location = search_file(filename, iso_mount)
935 if file_location is None:
936 if not ignore_errors:
937 logging.warn("Warning: %s not found (that's fine if you don't need it)", filename)
939 exec_rsync(file_location, dst)
942 def copy_addons(iso_mount, target):
943 """copy grml's addons files (like allinoneimg, bsd4grml,..) to a given target
945 @iso_mount: path where a grml ISO is mounted on
946 @target: path where grml's main files should be copied to"""
948 addons = target + '/boot/addons/'
949 execute(mkdir, addons)
951 # grub all-in-one image
952 handle_addon_copy('allinone.img', addons, iso_mount)
955 handle_addon_copy('bsd4grml', addons, iso_mount)
958 handle_addon_copy('balder10.imz', addons, iso_mount)
960 # syslinux + pci.ids for hdt
961 for expr in '*.c32', 'pci.ids':
962 glob_and_copy(iso_mount + '/boot/addons/' + expr, addons)
965 handle_addon_copy('memdisk', addons, iso_mount)
968 handle_addon_copy('memtest', addons, iso_mount)
970 # gpxe.lkrn: got replaced by ipxe
971 handle_addon_copy('gpxe.lkrn', addons, iso_mount, ignore_errors=True)
974 handle_addon_copy('ipxe.lkrn', addons, iso_mount)
977 def build_loopbackcfg(target):
978 """Generate GRUB's loopback.cfg based on existing config files.
980 @target: target directory
983 grub_dir = '/boot/grub/'
984 mkdir(os.path.join(target, grub_dir))
986 f = open(target + grub_dir + 'loopback.cfg', 'w')
988 f.write("# grml2usb generated grub2 configuration file\n")
989 f.write("source /boot/grub/header.cfg\n")
991 for defaults in glob.glob(target + os.path.sep + grub_dir + os.path.sep + "*_default.cfg"):
992 sourcefile = defaults.split(target + os.path.sep)[1]
993 logging.debug("Found source file" + sourcefile)
994 os.path.isfile(defaults) and f.write("source " + sourcefile + "\n")
996 for ops in glob.glob(target + os.path.sep + grub_dir + os.path.sep + "*_options.cfg"):
997 sourcefile = ops.split(target + os.path.sep)[1]
998 logging.debug("Found source file" + sourcefile)
999 os.path.isfile(ops) and f.write("source " + sourcefile + "\n")
1001 f.write("source /boot/grub/adddons.cfg\n")
1002 f.write("source /boot/grub/footer.cfg\n")
1006 def glob_and_copy(filepattern, dst):
1007 """Glob on specified filepattern and copy the result to dst
1009 @filepattern: globbing pattern
1010 @dst: target directory
1012 for name in glob.glob(filepattern):
1013 copy_if_exist(name, dst)
1016 def search_and_copy(filename, search_path, dst):
1017 """Search for the specified filename at searchpath and copy it to dst
1019 @filename: filename to look for
1020 @search_path: base search file
1021 @dst: destionation to copy the file to
1023 file_location = search_file(filename, search_path)
1024 copy_if_exist(file_location, dst)
1027 def copy_if_exist(filename, dst):
1028 """Copy filename to dst if filename is set.
1030 @filename: a filename
1033 if filename and (os.path.isfile(filename) or os.path.isdir(filename)):
1034 exec_rsync(filename, dst)
1037 def copy_bootloader_files(iso_mount, target, grml_flavour):
1038 """Copy grml's bootloader files to a given target
1040 @iso_mount: path where a grml ISO is mounted on
1041 @target: path where grml's main files should be copied to
1042 @grml_flavour: name of the current processed grml_flavour
1045 syslinux_target = target + '/boot/syslinux/'
1046 execute(mkdir, syslinux_target)
1048 grub_target = target + '/boot/grub/'
1049 execute(mkdir, grub_target)
1051 logo = search_file('logo.16', iso_mount)
1052 exec_rsync(logo, syslinux_target + 'logo.16')
1054 bootx64_efi = search_file('bootx64.efi', iso_mount)
1056 mkdir(target + '/efi/boot/')
1057 exec_rsync(bootx64_efi, target + '/efi/boot/bootx64.efi')
1059 efi_img = search_file('efi.img', iso_mount)
1061 mkdir(target + '/boot/')
1062 exec_rsync(efi_img, target + '/boot/efi.img')
1064 for ffile in ['f%d' % number for number in range(1, 11)]:
1065 search_and_copy(ffile, iso_mount, syslinux_target + ffile)
1067 # avoid the "file is read only, overwrite anyway (y/n) ?" question
1068 # of mtools by syslinux ("mmove -D o -D O s:/ldlinux.sys $target_file")
1069 if os.path.isfile(syslinux_target + 'ldlinux.sys'):
1070 os.unlink(syslinux_target + 'ldlinux.sys')
1072 (source_dir, name) = get_defaults_file(iso_mount, grml_flavour, "default.cfg")
1073 (source_dir, defaults_file) = get_defaults_file(iso_mount, grml_flavour, "grml.cfg")
1076 raise CriticalException(
1077 "file default.cfg could not be found.\n"
1078 "Note: this grml2usb version requires an ISO generated by grml-live >=0.9.24 ...\n"
1079 " ... either use grml releases >=2009.10 or switch to an older grml2usb version.")
1081 if not os.path.exists(iso_mount + '/boot/grub/footer.cfg'):
1082 logging.warning("Warning: Grml releases older than 2011.12 support only one flavour in grub.")
1084 for expr in name, 'distri.cfg', \
1085 defaults_file, 'grml.png', 'hd.cfg', 'isolinux.cfg', 'isolinux.bin', \
1086 'isoprompt.cfg', 'options.cfg', \
1087 'prompt.cfg', 'vesamenu.cfg', 'grml.png', '*.c32':
1088 glob_and_copy(iso_mount + source_dir + expr, syslinux_target)
1090 for filename in glob.glob1(syslinux_target, "*.c32"):
1091 copy_if_exist(os.path.join(SYSLINUX_LIBS, filename), syslinux_target)
1093 # copy the addons_*.cfg file to the new syslinux directory
1094 glob_and_copy(iso_mount + source_dir + 'addon*.cfg', syslinux_target)
1096 search_and_copy('hidden.cfg', iso_mount + source_dir, syslinux_target + "new_" + 'hidden.cfg')
1098 # copy all grub files from ISO
1099 glob_and_copy(iso_mount + '/boot/grub/*', grub_target)
1101 # finally (after all GRUB files have been been installed) build static loopback.cfg
1102 build_loopbackcfg(target)
1105 def install_iso_files(grml_flavour, iso_mount, device, target):
1106 """Copy files from ISO to given target
1108 @grml_flavour: name of grml flavour the configuration should be generated for
1109 @iso_mount: path where a grml ISO is mounted on
1110 @device: device/partition where bootloader should be installed to
1111 @target: path where grml's main files should be copied to"""
1114 GRML_DEFAULT = GRML_DEFAULT or grml_flavour
1117 elif not options.bootloaderonly:
1118 logging.info("Copying files. This might take a while....")
1120 copy_system_files(grml_flavour, iso_mount, target)
1121 copy_grml_files(grml_flavour, iso_mount, target)
1122 except CriticalException, error:
1123 logging.critical("Execution failed: %s", error)
1126 if not options.skipaddons:
1127 if not search_file('addons', iso_mount):
1128 logging.info("Could not find addons, therefore not installing.")
1130 copy_addons(iso_mount, target)
1132 if not options.copyonly:
1133 copy_bootloader_files(iso_mount, target, grml_flavour)
1135 if not options.dryrun:
1136 handle_bootloader_config(grml_flavour, device, target)
1138 # make sure we sync filesystems before returning
1139 proc = subprocess.Popen(["sync"])
1143 def get_device_from_partition(partition):
1145 partition_number = None
1146 if partition[-1].isdigit() and not RE_LOOP_DEVICE.match(partition):
1147 m = RE_P_PARTITION.match(partition)
1149 m = RE_PARTITION.match(partition)
1152 partition_number = int(m.group(2)) - 1
1153 return (device, partition_number)
1156 def get_flavour(flavour_str):
1157 """Returns the flavour of a grml version string
1159 return re.match(r'[\w-]*', flavour_str).group()
1162 def identify_grml_flavour(mountpath):
1163 """Get name of grml flavour
1165 @mountpath: path where the grml ISO is mounted to
1166 @return: name of grml-flavour"""
1168 version_files = search_file('grml-version', mountpath, lst_return=True)
1170 if not version_files:
1171 if mountpath.startswith("/lib/live/mount/medium"):
1172 logging.critical("Error: could not find grml-version file.")
1173 logging.critical("Looks like your system is running from RAM but required files are not available.")
1174 logging.critical("Please either boot without toram=... or use boot option toram instead of toram=...")
1178 logging.critical("Error: could not find grml-version file.")
1183 logging.debug("version_files = %s", version_files)
1184 for version_file in version_files:
1187 tmpfile = open(version_file, 'r')
1188 for line in tmpfile.readlines():
1189 flavours.append(get_flavour(line))
1190 except TypeError, e:
1192 except Exception, e:
1201 def get_bootoptions(grml_flavour):
1202 """Returns bootoptions for specific flavour
1204 @grml_flavour: name of the grml_flavour
1206 # do NOT write "None" in kernel cmdline
1207 if not options.bootoptions:
1210 bootopt = " ".join(options.bootoptions)
1211 bootopt = bootopt.replace("%flavour", grml_flavour)
1215 def handle_grub_config(grml_flavour, device, target):
1216 """Main handler for generating grub (v1 and v2) configuration
1218 @grml_flavour: name of grml flavour the configuration should be generated for
1219 @device: device/partition where grub should be installed to
1220 @target: path of grub's configuration files"""
1224 logging.debug("Updating grub configuration")
1226 grub_target = target + '/boot/grub/'
1228 bootid_re = re.compile("bootid=[\w_-]+")
1229 live_media_path_re = re.compile("live-media-path=[\w_/-]+")
1231 bootopt = get_bootoptions(grml_flavour)
1234 option_re = re.compile(r'(.*/boot/.*(linux26|vmlinuz).*)')
1236 if options.removeoption:
1237 for regex in options.removeoption:
1238 remove_regexes.append(re.compile(regex))
1240 shortname = get_shortname(grml_flavour)
1241 for filename in glob.glob(grub_target + '*.cfg'):
1242 for line in fileinput.input(filename, inplace=1):
1243 line = line.rstrip("\r\n")
1244 if option_re.search(line):
1245 line = bootid_re.sub('', line)
1246 if shortname in filename:
1247 line = live_media_path_re.sub('', line)
1248 line = line.rstrip() + ' live-media-path=/live/%s/ ' % (grml_flavour)
1249 line = line.rstrip() + r' bootid=%s %s ' % (UUID, bootopt)
1250 for regex in remove_regexes:
1251 line = regex.sub(' ', line)
1256 def initial_syslinux_config(target):
1257 """Generates intial syslinux configuration
1259 @target path of syslinux's configuration files"""
1261 target = target + "/"
1262 filename = target + "grmlmain.cfg"
1263 if os.path.isfile(target + "grmlmain.cfg"):
1265 data = open(filename, "w")
1266 data.write(generate_main_syslinux_config())
1269 filename = target + "hiddens.cfg"
1270 data = open(filename, "w")
1271 data.write("include hidden.cfg\n")
1275 def add_entry_if_not_present(filename, entry):
1276 """Write entry into filename if entry is not already in the file
1278 @filanme: name of the file
1279 @entry: data to write to the file
1281 data = open(filename, "a+")
1291 def get_flavour_filename(flavour):
1292 """Generate a iso9960 save filename out of the specified flavour
1294 @flavour: grml flavour
1296 return flavour.replace('-', '_')
1299 def adjust_syslinux_bootoptions(src, flavour):
1300 """Adjust existing bootoptions of specified syslinux config to
1301 grml2usb specific ones, e.g. change the location of the kernel...
1303 @src: config file to alter
1304 @flavour: grml flavour
1307 append_re = re.compile("^(\s*append.*/boot/.*)$", re.I)
1308 # flavour_re = re.compile("(label.*)(grml\w+)")
1309 default_re = re.compile("(default.cfg)")
1310 bootid_re = re.compile("bootid=[\w_-]+")
1311 live_media_path_re = re.compile("live-media-path=[\w_/-]+")
1313 bootopt = get_bootoptions(flavour)
1317 if options.removeoption:
1318 option_re = re.compile(r'/boot/.*/(initrd.gz|initrd.img)')
1320 for regex in options.removeoption:
1321 regexe.append(re.compile(r'%s' % regex))
1323 for line in fileinput.input(src, inplace=1):
1324 # line = flavour_re.sub(r'\1 %s-\2' % flavour, line)
1325 line = default_re.sub(r'%s-\1' % flavour, line)
1326 line = bootid_re.sub('', line)
1327 line = live_media_path_re.sub('', line)
1328 line = append_re.sub(r'\1 live-media-path=/live/%s/ ' % flavour, line)
1329 line = append_re.sub(r'\1 boot=live %s ' % bootopt, line)
1330 line = append_re.sub(r'\1 %s=%s ' % ("bootid", UUID), line)
1331 if option_re and option_re.search(line):
1332 for regex in regexe:
1333 line = regex.sub(' ', line)
1334 sys.stdout.write(line)
1338 def adjust_labels(src, replacement):
1339 """Adjust the specified labels in the syslinux config file src with
1340 specified replacement
1342 label_re = re.compile("^(\s*label\s*) ([a-zA-Z0-9_-]+)", re.I)
1343 for line in fileinput.input(src, inplace=1):
1344 line = label_re.sub(replacement, line)
1345 sys.stdout.write(line)
1349 def add_syslinux_entry(filename, grml_flavour):
1350 """Add includes for a specific grml_flavour to the specified filename
1352 @filename: syslinux config file
1353 @grml_flavour: grml flavour to add
1356 entry_filename = "option_%s.cfg" % grml_flavour
1357 entry = "include %s\n" % entry_filename
1359 add_entry_if_not_present(filename, entry)
1360 path = os.path.dirname(filename)
1362 data = open(path + "/" + entry_filename, "w")
1363 data.write(generate_flavour_specific_syslinux_config(grml_flavour))
1367 def modify_filenames(grml_flavour, target, filenames):
1368 """Replace the standard filenames with the new ones
1370 @grml_flavour: grml-flavour strin
1371 @target: directory where the files are located
1372 @filenames: list of filenames to alter
1374 grml_filename = get_flavour_filename(grml_flavour)
1375 for filename in filenames:
1376 old_filename = "%s/%s" % (target, filename)
1377 new_filename = "%s/%s_%s" % (target, grml_filename, filename)
1378 os.rename(old_filename, new_filename)
1381 def remove_default_entry(filename):
1382 """Remove the default entry from specified syslinux file
1384 @filename: syslinux config file
1386 default_re = re.compile("^(\s*menu\s*default\s*)$", re.I)
1387 for line in fileinput.input(filename, inplace=1):
1388 if default_re.match(line):
1390 sys.stdout.write(line)
1394 def handle_syslinux_config(grml_flavour, target):
1395 """Main handler for generating syslinux configuration
1397 @grml_flavour: name of grml flavour the configuration should be generated for
1398 @target: path of syslinux's configuration files"""
1400 logging.debug("Generating syslinux configuration")
1401 syslinux_target = target + '/boot/syslinux/'
1402 # should be present via copy_bootloader_files(), but make sure it exits:
1403 execute(mkdir, syslinux_target)
1404 syslinux_cfg = syslinux_target + 'syslinux.cfg'
1406 # install main configuration only *once*, no matter how many ISOs we have:
1407 syslinux_config_file = open(syslinux_cfg, 'w')
1408 syslinux_config_file.write("timeout 300\n")
1409 syslinux_config_file.write("include vesamenu.cfg\n")
1410 syslinux_config_file.close()
1412 prompt_name = open(syslinux_target + 'promptname.cfg', 'w')
1413 prompt_name.write('menu label S^yslinux prompt\n')
1416 initial_syslinux_config(syslinux_target)
1417 flavour_filename = get_flavour_filename(grml_flavour)
1419 if search_file('default.cfg', syslinux_target):
1420 modify_filenames(grml_flavour, syslinux_target, ['grml.cfg', 'default.cfg'])
1422 filename = search_file("new_hidden.cfg", syslinux_target)
1424 # process hidden file
1425 if not search_file("hidden.cfg", syslinux_target):
1426 new_hidden = syslinux_target + "hidden.cfg"
1427 os.rename(filename, new_hidden)
1428 adjust_syslinux_bootoptions(new_hidden, grml_flavour)
1430 new_hidden_file = "%s/%s_hidden.cfg" % (syslinux_target, flavour_filename)
1431 os.rename(filename, new_hidden_file)
1432 adjust_labels(new_hidden_file, r'\1 %s-\2' % grml_flavour)
1433 adjust_syslinux_bootoptions(new_hidden_file, grml_flavour)
1434 entry = 'include %s_hidden.cfg\n' % flavour_filename
1435 add_entry_if_not_present("%s/hiddens.cfg" % syslinux_target, entry)
1437 new_default = "%s_default.cfg" % (flavour_filename)
1438 entry = 'include %s\n' % new_default
1439 defaults_file = '%s/defaults.cfg' % syslinux_target
1440 new_default_with_path = "%s/%s" % (syslinux_target, new_default)
1441 new_grml_cfg = "%s/%s_grml.cfg" % (syslinux_target, flavour_filename)
1443 if os.path.isfile(defaults_file):
1445 # remove default menu entry in menu
1446 remove_default_entry(new_default_with_path)
1448 # adjust all labels for additional isos
1449 adjust_labels(new_default_with_path, r'\1 %s' % grml_flavour)
1450 adjust_labels(new_grml_cfg, r'\1 %s-\2' % grml_flavour)
1452 # always adjust bootoptions
1453 adjust_syslinux_bootoptions(new_default_with_path, grml_flavour)
1454 adjust_syslinux_bootoptions(new_grml_cfg, grml_flavour)
1456 add_entry_if_not_present("%s/defaults.cfg" % syslinux_target, entry)
1458 add_syslinux_entry("%s/additional.cfg" % syslinux_target, flavour_filename)
1461 def handle_bootloader_config(grml_flavour, device, target):
1462 """Main handler for generating bootloader's configuration
1464 @grml_flavour: name of grml flavour the configuration should be generated for
1465 @device: device/partition where bootloader should be installed to
1466 @target: path of bootloader's configuration files"""
1469 UUID = get_uuid(target)
1470 if options.skipsyslinuxconfig:
1471 logging.info("Skipping generation of syslinux configuration as requested.")
1474 handle_syslinux_config(grml_flavour, target)
1475 except CriticalException, error:
1476 logging.critical("Fatal: %s", error)
1479 if options.skipgrubconfig:
1480 logging.info("Skipping generation of grub configuration as requested.")
1483 handle_grub_config(grml_flavour, device, target)
1484 except CriticalException, error:
1485 logging.critical("Fatal: %s", error)
1489 def install(image, device):
1490 """Install a grml image to the specified device
1492 @image: directory or is file
1493 @device: partition or directory to install the device
1495 iso_mountpoint = image
1496 remove_image_mountpoint = False
1497 if os.path.isdir(image):
1498 logging.info("Using %s as install base", image)
1500 logging.info("Using ISO %s", image)
1501 iso_mountpoint = tempfile.mkdtemp(prefix="grml2usb", dir=os.path.abspath(options.tmpdir))
1502 register_tmpfile(iso_mountpoint)
1503 remove_image_mountpoint = True
1505 mount(image, iso_mountpoint, ["-o", "loop,ro", "-t", "iso9660"])
1506 except CriticalException, error:
1507 logging.critical("Fatal: %s", error)
1511 install_grml(iso_mountpoint, device)
1513 if remove_image_mountpoint:
1515 remove_mountpoint(iso_mountpoint)
1516 except CriticalException, error:
1521 def install_grml(mountpoint, device):
1522 """Main logic for copying files of the currently running grml system.
1524 @mountpoint: directory where currently running live system resides (usually /lib/live/mount/medium)
1525 @device: partition where the specified ISO should be installed to"""
1527 device_mountpoint = device
1528 if os.path.isdir(device):
1529 logging.info("Specified device is a directory, therefore not mounting.")
1530 remove_device_mountpoint = False
1532 device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
1533 register_tmpfile(device_mountpoint)
1534 remove_device_mountpoint = True
1536 check_for_fat(device)
1537 check_boot_flag(device)
1538 mount(device, device_mountpoint, ['-o', 'utf8,iocharset=iso8859-1'])
1539 except VerifyException, error:
1541 except CriticalException, error:
1542 mount(device, device_mountpoint, "")
1544 grml_flavours = identify_grml_flavour(mountpoint)
1545 for flavour in set(grml_flavours):
1547 logging.warning("No valid flavour found, please check your iso")
1548 logging.info("Identified grml flavour \"%s\".", flavour)
1549 install_iso_files(flavour, mountpoint, device, device_mountpoint)
1550 GRML_FLAVOURS.add(flavour)
1552 if remove_device_mountpoint:
1553 remove_mountpoint(device_mountpoint)
1556 def remove_mountpoint(mountpoint):
1557 """remove a registered mountpoint
1561 unmount(mountpoint, "")
1562 if os.path.isdir(mountpoint):
1563 os.rmdir(mountpoint)
1564 unregister_tmpfile(mountpoint)
1565 except CriticalException, error:
1570 def handle_mbr(device):
1571 """Main handler for installing master boot record (MBR)
1573 @device: device where the MBR should be installed to"""
1576 logging.info("Would install MBR")
1579 mbr_device, partition_number = get_device_from_partition(device)
1580 if partition_number is None:
1581 logging.warn("Could not detect partition number, not activating partition")
1583 # if we get e.g. /dev/loop1 as device we don't want to put the MBR
1584 # into /dev/loop of course, therefore use /dev/loop1 as mbr_device
1585 if mbr_device == "/dev/loop":
1587 logging.info("Detected loop device - using %s as MBR device therefore", mbr_device)
1589 mbrcode = GRML2USB_BASE + '/mbr/mbrldr'
1590 if options.syslinuxmbr:
1592 mbr_locations = ('/usr/lib/syslinux/mbr.bin',
1593 '/usr/share/syslinux/mbr.bin')
1594 for mbrpath in mbr_locations:
1595 if os.path.isfile(mbrpath):
1600 str_locations = " or ".join(['"%s"' % l for l in mbr_locations])
1601 logging.error('Cannot find syslinux MBR, install it at %s)',
1603 raise CriticalException("syslinux MBR can not be found at %s."
1605 elif options.mbrmenu:
1606 mbrcode = GRML2USB_BASE + '/mbr/mbrldr'
1609 install_mbr(mbrcode, mbr_device, partition_number, True)
1610 except IOError, error:
1611 logging.critical("Execution failed: %s", error)
1613 except Exception, error:
1614 logging.critical("Execution failed: %s", error)
1618 def handle_vfat(device):
1619 """Check for FAT specific settings and options
1621 @device: device that should checked / formated"""
1623 # make sure we have mkfs.vfat available
1625 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
1626 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
1627 logging.critical('Please make sure to install dosfstools.')
1631 print "Forcing mkfs.fat16 on %s as requested via option --force." % device
1633 # make sure the user is aware of what he is doing
1634 f = raw_input("Are you sure you want to format the specified partition with fat16? y/N ")
1635 if f == "y" or f == "Y":
1636 logging.info("Note: you can skip this question using the option --force")
1641 except CriticalException, error:
1642 logging.critical("Execution failed: %s", error)
1645 # check for vfat filesystem
1646 if device is not None and not os.path.isdir(device) and options.syslinux:
1648 check_for_fat(device)
1649 except CriticalException, error:
1650 logging.critical("Execution failed: %s", error)
1653 if not os.path.isdir(device) and not check_for_usbdevice(device) and not options.force:
1654 print "Warning: the specified device %s does not look like a removable usb device." % device
1655 f = raw_input("Do you really want to continue? y/N ")
1656 if f == "y" or f == "Y":
1662 def handle_compat_warning(device):
1663 """Backwards compatible checks
1665 @device: device that should be checked"""
1667 # make sure we can replace old grml2usb script and warn user when using old way of life:
1668 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1669 print "Warning: the semantics of grml2usb has changed."
1670 print "Instead of using grml2usb /path/to/iso %s you might" % device
1671 print "want to use grml2usb /path/to/iso /dev/... instead."
1672 print "Please check out the grml2usb manpage for details."
1673 f = raw_input("Do you really want to continue? y/N ")
1674 if f == "y" or f == "Y":
1680 def handle_logging():
1681 """Log handling and configuration"""
1683 if options.verbose and options.quiet:
1684 parser.error("please use either verbose (--verbose) or quiet (--quiet) option")
1686 FORMAT = "%(message)s"
1688 FORMAT = "%(asctime)-15s %(message)s"
1689 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1691 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1693 logging.basicConfig(level=logging.INFO, format=FORMAT)
1696 def handle_bootloader(device):
1697 """wrapper for installing bootloader
1699 @device: device where bootloader should be installed to"""
1701 # Install bootloader only if not using the --copy-only option
1702 if options.copyonly:
1703 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1704 elif os.path.isdir(device):
1705 logging.info("Not installing bootloader as %s is a directory.", device)
1707 install_bootloader(device)
1710 def check_options(opts):
1711 """Check compability of provided user opts
1713 @opts option dict from OptionParser
1715 if opts.grubmbr and not opts.grub:
1716 raise CriticalException("--grub-mbr requires --grub option.")
1719 def check_programs():
1720 """check if all needed programs are installed"""
1722 if not which("grub-install"):
1723 logging.critical("Fatal: grub-install not available (please install the "
1724 + "grub package or drop the --grub option)")
1727 if options.syslinux:
1728 if not which("syslinux"):
1729 logging.critical("Fatal: syslinux not available (please install the "
1730 + "syslinux package or use the --grub option)")
1733 if not which("rsync"):
1734 logging.critical("Fatal: rsync not available, can not continue - sorry.")
1739 """Runs modprobe loop and throws away it's output"""
1740 if not which("modprobe"):
1741 logging.critical("Fatal: modprobe not available, can not continue - sorry.")
1742 logging.critical("Hint: is /sbin missing in PATH?")
1745 proc = subprocess.Popen(["modprobe", "loop"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1750 """Main function [make pylint happy :)]"""
1754 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1758 parser.error("invalid usage")
1763 # make sure we have the appropriate permissions
1766 check_options(options)
1770 logging.info("Executing grml2usb version %s", PROG_VERSION)
1773 logging.info("Running in simulation mode as requested via option dry-run.")
1777 # specified arguments
1778 device = os.path.realpath(args[len(args) - 1])
1779 isos = args[0:len(args) - 1]
1781 if not os.path.isdir(device):
1782 if device[-1:].isdigit():
1783 if int(device[-1:]) > 4 or device[-2:].isdigit():
1784 logging.critical("Fatal: installation on partition number >4 not supported. (BIOS won't support it.)")
1787 # provide upgrade path
1788 handle_compat_warning(device)
1790 # check for vfat partition
1793 # main operation (like installing files)
1795 install(iso, device)
1798 is_superfloppy = not device[-1:].isdigit()
1800 logging.info("Detected superfloppy format - not installing MBR")
1802 if not options.skipmbr and not os.path.isdir(device) and not is_superfloppy:
1805 handle_bootloader(device)
1807 logging.info("Note: grml flavour %s was installed as the default booting system.", GRML_DEFAULT)
1809 for flavour in GRML_FLAVOURS:
1810 logging.info("Note: you can boot flavour %s using '%s' on the commandline.", flavour, flavour)
1812 # finally be politely :)
1813 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system.", PROG_VERSION)
1815 except Exception, error:
1816 logging.critical("Fatal: %s", str(error))
1820 if __name__ == "__main__":
1823 except KeyboardInterrupt:
1824 logging.info("Received KeyboardInterrupt")
1827 ## END OF FILE #################################################################
1828 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8