class Lock: def __init__(self, _file, shared=False): lockfile = os.path.join(os.path.dirname(_file), ".%s" % os.path.basename(_file)) try: self.lock = FileLock(_file) self.lock.lock(timeout=TIMEOUT, shared=shared) except IOError: fail(FAIL_TIMEOUT) def release(self): self.lock.unlock()
class grubParser: def __init__(self, _dir, write=False, timeout=-1): self.dir = _dir self.write = write self.grub_conf = os.path.join(_dir, "grub.conf") self.device_map = os.path.join(_dir, "device.map") self.device_remap = os.path.join(_dir, "device.remap") self.lock = FileLock("%s/.grub.lock" % _dir) try: self.lock.lock(write, timeout) except IOError: fail(FAIL_TIMEOUT) # Fail if grub is not installed if os.path.exists(self.grub_conf) and os.path.exists(self.device_map): self.config = grubConf() self.config.parseConf(self.grub_conf) else: self.fail(FAIL_NOGRUB) # Get device map mapped_devices = {} for line in file(self.device_map): try: grub_device, linux_device = line.split("\t") except ValueError: self.fail(FAIL_NOGRUB) mapped_devices[grub_device] = linux_device.strip() # Remap devices if necessary if not os.path.exists(self.device_remap): remapped_devices = {} for entry in self.config.entries: commands = entry.listCommands() if "root" in commands and "kernel" in commands: grub_device = entry.getCommand("root").value try: grub_disk, grub_part, linux_disk, linux_part = parseGrubDevice(grub_device, remapped=False) except TypeError: self.fail(FAIL_NODEVICE % grub_device) entry_version, entry_root = getKernelData(entry.getCommand("kernel")) if entry_root: if entry_root.startswith("LABEL="): entry_root = getDeviceByLabel(entry_root.split("LABEL=")[1]) try: linux_disk2, linux_part2, grub_disk2, grub_part2 = parseLinuxDevice(entry_root, remapped=False) except: self.fail(FAIL_NODEVICE % entry_root) remapped_devices["(%s)" % grub_disk] = linux_disk2 grub_devices = mapped_devices.keys() grub_devices.sort(key=lambda x: int(x[3:-1])) linux_devices = [] for device in grub_devices: linux_devices.append(mapped_devices[device]) if "(hd0)" in remapped_devices and remapped_devices["(hd0)"] != mapped_devices["(hd0)"]: # Need remapping linux_devices.remove(remapped_devices["(hd0)"]) linux_devices.insert(0, remapped_devices["(hd0)"]) list_map = [] for i in xrange(len(grub_devices)): list_map.append("%s\t%s" % (grub_devices[i], linux_devices[i])) file(self.device_remap, "w").write("\n".join(list_map)) def fail(self, msg): self.lock.unlock() fail(msg) def release(self, save=True): if save and self.write: self.config.write(self.grub_conf) self.lock.unlock()