X-Git-Url: https://git.grml.org/?p=grml2usb.git;a=blobdiff_plain;f=grml2usb;h=80c51603b52b3be362663f7d58c9838a07ef2563;hp=24207b632603697e2bb1310fe5409fff9daea75b;hb=607fd410c2c8261498f4f9169fc74f7811a043f7;hpb=6b93ccd0cbbbae5ac1f86762d89a681a3243d7fa diff --git a/grml2usb b/grml2usb index 24207b6..80c5160 100755 --- a/grml2usb +++ b/grml2usb @@ -15,24 +15,33 @@ This script installs a grml system (either a running system or ISO[s]) to a USB from optparse import OptionParser from inspect import isroutine, isclass -import datetime, logging, os, re, subprocess, sys, tempfile, time, os.path +import datetime import fileinput import glob -import uuid +import logging +import os +import os.path +import re import struct +import subprocess +import sys +import tempfile +import time +import uuid # The line following this line is patched by debian/rules and tarball.sh. -PROG_VERSION='***UNRELEASED***' +PROG_VERSION = '***UNRELEASED***' # global variables -MOUNTED = set() # register mountpoints -TMPFILES = set() # register tmpfiles -DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg -GRML_FLAVOURS = set() # which flavours are being installed? +MOUNTED = set() # register mountpoints +TMPFILES = set() # register tmpfiles +DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg +GRML_FLAVOURS = set() # which flavours are being installed? GRML_DEFAULT = None UUID = None SYSLINUX_LIBS = "/usr/lib/syslinux/" + def syslinux_warning(option, opt, value, opt_parser): """A helper function for printing a warning about deprecated option """ @@ -41,6 +50,7 @@ def syslinux_warning(option, opt, value, opt_parser): "is grml2usb's default. Continuing anyway.\n") setattr(opt_parser.values, option.dest, True) + # if grub option is set, unset syslinux option def grub_option(option, opt, value, opt_parser): """A helper function adjusting other option values @@ -247,7 +257,8 @@ def get_defaults_file(iso_mount, flavour, name): "%s_%s" % (get_flavour_filename(flavour), name): if os.path.isfile(iso_mount + directory + name): return (directory, name) - return ('','') + return ('', '') + def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'): """Given a search path, find file @@ -256,7 +267,7 @@ def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'): @search_path: path where searching for the specified filename""" file_found = 0 paths = search_path.split(os.pathsep) - current_dir = '' # make pylint happy :) + current_dir = '' # make pylint happy :) def match_file(cwd): """Helper function ffor testing if specified file exists in cwd @@ -283,7 +294,7 @@ def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'): def check_uid_root(): """Check for root permissions""" - if not os.geteuid()==0: + if not os.geteuid() == 0: sys.exit("Error: please run this script with uid 0 (root).") @@ -316,7 +327,7 @@ def generate_isolinux_splash(grml_flavour): Some information and boot options available via keys F2 - F10. http://grml.org/ %(grml_name)s -""" % {'grml_name': grml_name} ) +""" % {'grml_name': grml_name}) def generate_main_syslinux_config(*arg): @@ -364,7 +375,6 @@ def generate_flavour_specific_syslinux_config(grml_flavour): @grml_flavour: name of grml flavour the configuration should be generated for""" - return("""\ menu begin grml %(grml_flavour)s menu title %(display_name)s @@ -376,7 +386,7 @@ menu begin grml %(grml_flavour)s include %(grml_flavour)s_grml.cfg menu hide menu end -""" % {'grml_flavour': grml_flavour, 'display_name' : grml_flavour.replace('_', '-') } ) +""" % {'grml_flavour': grml_flavour, 'display_name': get_flavour_filename(grml_flavour)}) def install_grub(device): @@ -405,7 +415,7 @@ def install_grub(device): grub_device = device logging.info("Installing grub as bootloader") - for opt in ["", "--force" ]: + for opt in ["", "--force"]: logging.debug("grub-install --recheck %s --no-floppy --root-directory=%s %s", opt, device_mountpoint, grub_device) proc = subprocess.Popen(["grub-install", "--recheck", opt, "--no-floppy", @@ -546,7 +556,7 @@ def install_mbr(mbrtemplate, device, partition, ismirbsdmbr=True): mbrcode[463:478] + actives[2] + \ mbrcode[479:494] + actives[3] + \ mbrcode[495:510] + "\x55\xAA" - + tmpf.file.seek(0) tmpf.file.truncate() tmpf.file.write(mbrcode) @@ -741,6 +751,13 @@ def get_uuid(target): return write_uuid(uuid_file_name) +def get_shortname(grml_flavour): + """Get shortname based from grml_flavour name. The rules applied are the same as in grml-live + @grml_flavour: flavour name which shold be translated to shortname""" + + return re.sub(r'[,._-]', '', grml_flavour) + + def copy_system_files(grml_flavour, iso_mount, target): """copy grml's main files (like squashfs, kernel and initrd) to a given target @@ -768,19 +785,23 @@ def copy_system_files(grml_flavour, iso_mount, target): else: exec_rsync(filesystem_module, squashfs_target + 'filesystem.module') - kernel = search_file('vmlinuz', iso_mount) - if kernel is None: - # compat for releases < 2011.12 - kernel = search_file('linux26', iso_mount) + shortname = get_shortname(grml_flavour) + if os.path.isdir(iso_mount + '/boot/' + shortname): + exec_rsync(iso_mount + '/boot/' + shortname, target + '/boot') + else: + kernel = search_file('vmlinuz', iso_mount) + if kernel is None: + # compat for releases < 2011.12 + kernel = search_file('linux26', iso_mount) - if kernel is None: - logging.critical("Fatal: kernel not found") - raise CriticalException("error locating kernel file") + if kernel is None: + logging.critical("Fatal: kernel not found") + raise CriticalException("error locating kernel file") - source = os.path.dirname(kernel) + '/' - dest = target + '/' + os.path.dirname(kernel).replace(iso_mount,'') + '/' - execute(mkdir, dest) - exec_rsync(source, dest) + source = os.path.dirname(kernel) + '/' + dest = target + '/' + os.path.dirname(kernel).replace(iso_mount, '') + '/' + execute(mkdir, dest) + exec_rsync(source, dest) def update_grml_versions(iso_mount, target): @@ -827,46 +848,25 @@ def update_grml_versions(iso_mount, target): else: return False -def copy_grml_files(iso_mount, target): + +def copy_grml_files(grml_flavour, iso_mount, target): """copy some minor grml files to a given target + @grml_flavour: the current grml_flavour @iso_mount: path where a grml ISO is mounted on @target: path where grml's main files should be copied to""" grml_target = target + '/grml/' execute(mkdir, grml_target) - copy_files = [ 'grml-cheatcodes.txt', 'LICENSE.txt', 'md5sums', 'README.txt' ] - # handle grml-version - if not update_grml_versions(iso_mount, target): - copy_files.append('grml-version') - - for myfile in copy_files: - grml_file = search_file(myfile, iso_mount) - if grml_file is None: - logging.warn("Warning: file %s could not be found - can not install it", myfile) - else: - exec_rsync(grml_file, grml_target + myfile) - - grml_web_target = grml_target + '/web/' - execute(mkdir, grml_web_target) - - for myfile in 'index.html', 'style.css': - grml_file = search_file(myfile, iso_mount) - if grml_file is None: - logging.warn("Warning: file %s could not be found - can not install it", myfile) - else: - exec_rsync(grml_file, grml_web_target + myfile) - - grml_webimg_target = grml_web_target + '/images/' - execute(mkdir, grml_webimg_target) - - for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png': - grml_file = search_file(myfile, iso_mount) - if grml_file is None: - logging.warn("Warning: file %s could not be found - can not install it", myfile) - else: - exec_rsync(grml_file, grml_webimg_target + myfile) + grml_prefixe = ["GRML", "grml"] + for prefix in grml_prefixe: + filename = "{0}/{1}/{2}".format(iso_mount, prefix, grml_flavour) + if os.path.exists(filename): + exec_rsync(filename, grml_target) + break + else: + logging.warn("Warning: could not find flavour directory for %s ", grml_flavour) def handle_addon_copy(filename, dst, iso_mount, ignore_errors=False): @@ -880,7 +880,7 @@ def handle_addon_copy(filename, dst, iso_mount, ignore_errors=False): file_location = search_file(filename, iso_mount) if file_location is None: if not ignore_errors: - logging.warn("Warning: %s not found (that's fine if you don't need it)", filename) + logging.warn("Warning: %s not found (that's fine if you don't need it)", filename) else: exec_rsync(file_location, dst) @@ -926,6 +926,36 @@ def copy_addons(iso_mount, target): # ipxe.lkrn handle_addon_copy('ipxe.lkrn', addons, iso_mount) + +def build_loopbackcfg(target): + """Generate GRUB's loopback.cfg based on existing config files. + + @target: target directory + """ + + grub_dir = '/boot/grub/' + mkdir(os.path.join(target, grub_dir)) + + f = open(target + grub_dir + 'loopback.cfg', 'w') + + f.write("# grml2usb generated grub2 configuration file\n") + f.write("source /boot/grub/header.cfg\n") + + for defaults in glob.glob(target + os.path.sep + grub_dir + os.path.sep + "*_default.cfg"): + sourcefile = defaults.split(target + os.path.sep)[1] + logging.debug("Found source file" + sourcefile) + os.path.isfile(defaults) and f.write("source " + sourcefile + "\n") + + for ops in glob.glob(target + os.path.sep + grub_dir + os.path.sep + "*_options.cfg"): + sourcefile = ops.split(target + os.path.sep)[1] + logging.debug("Found source file" + sourcefile) + os.path.isfile(ops) and f.write("source " + sourcefile + "\n") + + f.write("source /boot/grub/adddons.cfg\n") + f.write("source /boot/grub/footer.cfg\n") + f.close() + + def glob_and_copy(filepattern, dst): """Glob on specified filepattern and copy the result to dst @@ -935,6 +965,7 @@ def glob_and_copy(filepattern, dst): for name in glob.glob(filepattern): copy_if_exist(name, dst) + def search_and_copy(filename, search_path, dst): """Search for the specified filename at searchpath and copy it to dst @@ -945,6 +976,7 @@ def search_and_copy(filename, search_path, dst): file_location = search_file(filename, search_path) copy_if_exist(file_location, dst) + def copy_if_exist(filename, dst): """Copy filename to dst if filename is set. @@ -954,6 +986,7 @@ def copy_if_exist(filename, dst): if filename and (os.path.isfile(filename) or os.path.isdir(filename)): exec_rsync(filename, dst) + def copy_bootloader_files(iso_mount, target, grml_flavour): """Copy grml's bootloader files to a given target @@ -981,16 +1014,9 @@ def copy_bootloader_files(iso_mount, target, grml_flavour): mkdir(target + '/boot/') exec_rsync(efi_img, target + '/boot/efi.img') - for ffile in ['f%d' % number for number in range(1, 11) ]: + for ffile in ['f%d' % number for number in range(1, 11)]: search_and_copy(ffile, iso_mount, syslinux_target + ffile) - loopback_cfg = search_file("loopback.cfg", iso_mount) - if loopback_cfg: - directory = os.path.dirname(loopback_cfg) - directory = directory.replace(iso_mount, "") - mkdir(os.path.join(target, directory)) - exec_rsync(loopback_cfg, target + os.path.sep + directory) - # avoid the "file is read only, overwrite anyway (y/n) ?" question # of mtools by syslinux ("mmove -D o -D O s:/ldlinux.sys $target_file") if os.path.isfile(syslinux_target + 'ldlinux.sys'): @@ -1017,7 +1043,6 @@ def copy_bootloader_files(iso_mount, target, grml_flavour): for filename in glob.glob1(syslinux_target, "*.c32"): copy_if_exist(os.path.join(SYSLINUX_LIBS, filename), syslinux_target) - # copy the addons_*.cfg file to the new syslinux directory glob_and_copy(iso_mount + source_dir + 'addon*.cfg', syslinux_target) @@ -1026,6 +1051,10 @@ def copy_bootloader_files(iso_mount, target, grml_flavour): # copy all grub files from ISO glob_and_copy(iso_mount + '/boot/grub/*', grub_target) + # finally (after all GRUB files have been been installed) build static loopback.cfg + build_loopbackcfg(target) + + def install_iso_files(grml_flavour, iso_mount, device, target): """Copy files from ISO to given target @@ -1042,7 +1071,7 @@ def install_iso_files(grml_flavour, iso_mount, device, target): logging.info("Copying files. This might take a while....") try: copy_system_files(grml_flavour, iso_mount, target) - copy_grml_files(iso_mount, target) + copy_grml_files(grml_flavour, iso_mount, target) except CriticalException, error: logging.critical("Execution failed: %s", error) sys.exit(1) @@ -1069,6 +1098,7 @@ def get_flavour(flavour_str): """ return re.match(r'[\w-]*', flavour_str).group() + def identify_grml_flavour(mountpath): """Get name of grml flavour @@ -1138,13 +1168,16 @@ def handle_grub_config(grml_flavour, device, target): for regex in options.removeoption: remove_regexes.append(re.compile(regex)) + shortname = get_shortname(grml_flavour) for filename in glob.glob(grub_target + '*.cfg'): for line in fileinput.input(filename, inplace=1): line = line.rstrip("\r\n") if option_re.search(line): line = bootid_re.sub('', line) - line = live_media_path_re.sub('', line) - line = line.rstrip() + r' live-media-path=/live/%s/ bootid=%s %s ' % (grml_flavour, UUID, bootopt) + if shortname in filename: + line = live_media_path_re.sub('', line) + line = line.rstrip() + ' live-media-path=/live/%s/ ' % (grml_flavour) + line = line.rstrip() + r' bootid=%s %s ' % (UUID, bootopt) for regex in remove_regexes: line = regex.sub(' ', line) print line @@ -1169,6 +1202,7 @@ def initial_syslinux_config(target): data.write("include hidden.cfg\n") data.close() + def add_entry_if_not_present(filename, entry): """Write entry into filename if entry is not already in the file @@ -1184,6 +1218,7 @@ def add_entry_if_not_present(filename, entry): data.close() + def get_flavour_filename(flavour): """Generate a iso9960 save filename out of the specified flavour @@ -1191,6 +1226,7 @@ def get_flavour_filename(flavour): """ return flavour.replace('-', '_') + def adjust_syslinux_bootoptions(src, flavour): """Adjust existing bootoptions of specified syslinux config to grml2usb specific ones, e.g. change the location of the kernel... @@ -1229,6 +1265,7 @@ def adjust_syslinux_bootoptions(src, flavour): sys.stdout.write(line) fileinput.close() + def adjust_labels(src, replacement): """Adjust the specified labels in the syslinux config file src with specified replacement @@ -1257,6 +1294,7 @@ def add_syslinux_entry(filename, grml_flavour): data.write(generate_flavour_specific_syslinux_config(grml_flavour)) data.close() + def modify_filenames(grml_flavour, target, filenames): """Replace the standard filenames with the new ones @@ -1264,7 +1302,7 @@ def modify_filenames(grml_flavour, target, filenames): @target: directory where the files are located @filenames: list of filenames to alter """ - grml_filename = grml_flavour.replace('-', '_') + grml_filename = get_flavour_filename(grml_flavour) for filename in filenames: old_filename = "%s/%s" % (target, filename) new_filename = "%s/%s_%s" % (target, grml_filename, filename) @@ -1296,7 +1334,6 @@ def handle_syslinux_config(grml_flavour, target): execute(mkdir, syslinux_target) syslinux_cfg = syslinux_target + 'syslinux.cfg' - # install main configuration only *once*, no matter how many ISOs we have: syslinux_config_file = open(syslinux_cfg, 'w') syslinux_config_file.write("TIMEOUT 300\n") @@ -1308,29 +1345,26 @@ def handle_syslinux_config(grml_flavour, target): prompt_name.close() initial_syslinux_config(syslinux_target) - flavour_filename = grml_flavour.replace('-', '_') + flavour_filename = get_flavour_filename(grml_flavour) if search_file('default.cfg', syslinux_target): modify_filenames(grml_flavour, syslinux_target, ['grml.cfg', 'default.cfg']) filename = search_file("new_hidden.cfg", syslinux_target) - # process hidden file if not search_file("hidden.cfg", syslinux_target): new_hidden = syslinux_target + "hidden.cfg" os.rename(filename, new_hidden) adjust_syslinux_bootoptions(new_hidden, grml_flavour) else: - new_hidden_file = "%s/%s_hidden.cfg" % (syslinux_target, flavour_filename) + new_hidden_file = "%s/%s_hidden.cfg" % (syslinux_target, flavour_filename) os.rename(filename, new_hidden_file) adjust_labels(new_hidden_file, r'\1 %s-\2' % grml_flavour) adjust_syslinux_bootoptions(new_hidden_file, grml_flavour) entry = 'include %s_hidden.cfg\n' % flavour_filename add_entry_if_not_present("%s/hiddens.cfg" % syslinux_target, entry) - - new_default = "%s_default.cfg" % (flavour_filename) entry = 'include %s\n' % new_default defaults_file = '%s/defaults.cfg' % syslinux_target @@ -1383,7 +1417,6 @@ def handle_bootloader_config(grml_flavour, device, target): sys.exit(1) - def install(image, device): """Install a grml image to the specified device @@ -1416,7 +1449,6 @@ def install(image, device): cleanup() - def install_grml(mountpoint, device): """Main logic for copying files of the currently running grml system. @@ -1452,6 +1484,7 @@ def install_grml(mountpoint, device): if remove_device_mountpoint: remove_mountpoint(device_mountpoint) + def remove_mountpoint(mountpoint): """remove a registred mountpoint """ @@ -1465,6 +1498,7 @@ def remove_mountpoint(mountpoint): logging.critical("Fatal: %s", error) cleanup() + def handle_mbr(device): """Main handler for installing master boot record (MBR) @@ -1624,11 +1658,13 @@ def check_programs(): logging.critical("Fatal: rsync not available, can not continue - sorry.") sys.exit(1) + def load_loop(): """Runs modprobe loop and throws away it's output""" proc = subprocess.Popen(["modprobe", "loop"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.wait() + def main(): """Main function [make pylint happy :)]""" @@ -1657,7 +1693,7 @@ def main(): check_programs() # specified arguments - device = args[len(args) - 1] + device = os.path.realpath(args[len(args) - 1]) isos = args[0:len(args) - 1] if not os.path.isdir(device):