def mountRootPartition(anaconda, rootInfo, oldfsset, allowDirty = 0, warnDirty = 0, readOnly = 0): (root, rootFs) = rootInfo diskset = partedUtils.DiskSet(anaconda) encryptedDevices = anaconda.id.partitions.encryptedDevices diskset.openDevices() for cryptoDev in encryptedDevices.values(): cryptoDev.openDevice() diskset.startMPath() diskset.startDmRaid() diskset.startMdRaid() for cryptoDev in encryptedDevices.values(): cryptoDev.openDevice() lvm.vgscan() lvm.vgactivate() for cryptoDev in encryptedDevices.values(): if cryptoDev.openDevice(): log.warning("failed to open encrypted device %s" % (cryptoDev.getDevice(encrypted=True))) log.info("going to mount %s on %s as %s" %(root, anaconda.rootPath, rootFs)) isys.mount(root, anaconda.rootPath, rootFs) oldfsset.reset() newfsset = readFstab(anaconda) for entry in newfsset.entries: oldfsset.add(entry) isys.umount(anaconda.rootPath) dirtyDevs = oldfsset.hasDirtyFilesystems(anaconda.rootPath) if not allowDirty and dirtyDevs != []: lvm.vgdeactivate() diskset.stopMdRaid() diskset.stopDmRaid() diskset.stopMPath() anaconda.intf.messageWindow(_("Dirty File Systems"), _("The following file systems for your Linux system " "were not unmounted cleanly. Please boot your " "Linux installation, let the file systems be " "checked and shut down cleanly to upgrade.\n" "%s" %(getDirtyDevString(dirtyDevs),))) sys.exit(0) elif warnDirty and dirtyDevs != []: rc = anaconda.intf.messageWindow(_("Dirty File Systems"), _("The following file systems for your Linux " "system were not unmounted cleanly. Would " "you like to mount them anyway?\n" "%s" % (getDirtyDevString(dirtyDevs,))), type = "yesno") if rc == 0: return -1 if flags.setupFilesystems: oldfsset.mountFilesystems(anaconda, readOnly = readOnly) if (not oldfsset.getEntryByMountPoint("/") or not oldfsset.getEntryByMountPoint("/").fsystem or not oldfsset.getEntryByMountPoint("/").fsystem.isMountable()): raise RuntimeError, "/etc/fstab did not list a fstype for the root partition which we support"
def mountImage(self, cdNum): if (self.currentMedia): raise SystemError, "trying to mount already-mounted iso image!" retrymount = True while retrymount: try: isoImage = self.isoPath + '/' + self.discImages[cdNum] isys.makeDevInode("loop3", "/tmp/loop3") isys.losetup("/tmp/loop3", isoImage, readOnly = 1) isys.mount("loop3", "/tmp/isomedia", fstype = 'iso9660', readOnly = 1); self.mntPoint = "/tmp/isomedia/" self.currentMedia = [ cdNum ] retrymount = False except: ans = self.messageWindow( _("Missing ISO 9660 Image"), _("The installer has tried to mount " "image #%s, but cannot find it on " "the server.\n\n" "Please copy this image to the " "remote server's share path and " "click Retry. Click Reboot to " "abort the installation.") % (cdNum,), type="custom", custom_icon="warning", custom_buttons=[_("_Reboot"), _("Re_try")]) if ans == 0: sys.exit(0) elif ans == 1: self.discImages = findIsoImages(self.isoPath, self.messageWindow)
def mountImage(isodir, tree, messageWindow): def complain(): ans = messageWindow(_("Missing ISO 9660 Image"), _("The installer has tried to mount the " "installation image, but cannot find it on " "the hard drive.\n\n" "Please copy this image to the " "drive and click Retry. Click Exit " "to abort the installation."), type="custom", custom_icon="warning", custom_buttons=[_("_Exit"), _("_Retry")]) if ans == 0: sys.exit(0) if os.path.ismount(tree): raise SystemError, "trying to mount already-mounted iso image!" while True: image = findFirstIsoImage(isodir, messageWindow) if image is None: complain() continue try: isys.mount(image, tree, fstype = 'iso9660', readOnly = True) break except SystemError: complain()
def findExistingRootPartitions(self, intf, mountpoint, upgradeany = 0): """Return a list of all of the partitions which look like a root fs.""" rootparts = [] self.startAllRaid() for dev, devices, level, numActive in self.mdList: (errno, msg) = (None, None) found = 0 for fs in fsset.getFStoTry(dev): try: isys.mount(dev, mountpoint, fs, readOnly = 1) found = 1 break except SystemError, (errno, msg): pass if found: if os.access (mountpoint + '/etc/fstab', os.R_OK): relstr = getRedHatReleaseString(mountpoint) cmdline = open('/proc/cmdline', 'r').read() if ((cmdline.find("upgradeany") != -1) or (upgradeany == 1) or (productMatches(relstr, productName))): rootparts.append ((dev, fs, relstr)) isys.umount(mountpoint)
def mountImage(isodir, tree, discnum, messageWindow, discImages={}): if os.path.ismount(tree): raise SystemError, "trying to mount already-mounted iso image!" if discImages == {}: discImages = findIsoImages(isodir, messageWindow) while True: try: isoImage = "%s/%s" % (isodir, discImages[discnum]) isys.losetup("/dev/loop1", isoImage, readOnly = 1) isys.mount("/dev/loop1", tree, fstype = 'iso9660', readOnly = True) break except: ans = messageWindow(_("Missing ISO 9660 Image"), _("The installer has tried to mount " "image #%s, but cannot find it on " "the hard drive.\n\n" "Please copy this image to the " "drive and click Retry. Click Exit " "to abort the installation.") % (discnum,), type="custom", custom_icon="warning", custom_buttons=[_("_Exit"), _("_Retry")]) if ans == 0: sys.exit(0) elif ans == 1: discImages = findIsoImages(isodir, messageWindow) return discImages
def mountMedia(self, cdNum): if self.mediaIsMounted: raise SystemError, "trying to mount already-mounted iso image!" self.mountDirectory() retry = True while retry: try: isoImage = self.isoDir + '/' + self.path + '/' + self.discImages[cdNum] isys.makeDevInode("loop3", "/tmp/loop3") isys.losetup("/tmp/loop3", isoImage, readOnly = 1) isys.mount("loop3", self.tree, fstype = 'iso9660', readOnly = 1); self.mediaIsMounted = cdNum retry = False except: ans = self.messageWindow( _("Missing ISO 9660 Image"), _("The installer has tried to mount " "image #%s, but cannot find it on " "the hard drive.\n\n" "Please copy this image to the " "drive and click Retry. Click Reboot " " to abort the installation.") % (cdNum,), type="custom", custom_icon="warning", custom_buttons=[_("_Reboot"), _("Re_try")]) if ans == 0: sys.exit(0) elif ans == 1: self.discImages = findIsoImages(self.isoPath, self.messageWindow)
def copyExceptionToFloppy(anaconda): # in test mode have save to floppy option just copy to new name if not flags.setupFilesystems: try: shutil.copyfile("/tmp/anacdump.txt", "/tmp/test-anacdump.txt") except: log.error("Failed to copy anacdump.txt to /tmp/test-anacdump.txt") pass anaconda.intf.__del__() return 2 while 1: # Bail if they hit the cancel button. rc = anaconda.intf.dumpWindow() if rc: return 1 device = anaconda.id.floppyDevice file = "/tmp/floppy" try: isys.makeDevInode(device, file) except SystemError: pass try: fd = os.open(file, os.O_RDONLY) except: continue os.close(fd) if rhpl.getArch() != "ia64": cmd = "/usr/sbin/mkdosfs" if os.access("/sbin/mkdosfs", os.X_OK): cmd = "/sbin/mkdosfs" iutil.execWithRedirect(cmd, ["/tmp/floppy"], stdout='/dev/tty5', stderr='/dev/tty5') try: isys.mount(device, "/tmp/crash", fstype="vfat") except SystemError: continue # copy trace dump we wrote to local storage to floppy try: shutil.copyfile("/tmp/anacdump.txt", "/tmp/crash/anacdump.txt") except: log.error("Failed to copy anacdump.txt to floppy") return 2 isys.umount("/tmp/crash") return 0
def mountRootPartition(intf, rootInfo, oldfsset, instPath, allowDirty=0, raiseErrors=0, warnDirty=0, readOnly=0): (root, rootFs) = rootInfo diskset = partedUtils.DiskSet() diskset.openDevices() diskset.startAllRaid() lvm.vgscan() lvm.vgactivate() log("going to mount %s on %s as %s" % (root, instPath, rootFs)) isys.mount(root, instPath, rootFs) oldfsset.reset() newfsset = fsset.readFstab(instPath + '/etc/fstab', intf) for entry in newfsset.entries: oldfsset.add(entry) isys.umount(instPath) dirtyDevs = oldfsset.hasDirtyFilesystems(instPath) if not allowDirty and dirtyDevs != []: diskset.stopAllRaid() lvm.vgdeactivate() intf.messageWindow( _("Dirty File Systems"), _("The following file systems for your Linux system " "were not unmounted cleanly. Please boot your " "Linux installation, let the file systems be " "checked and shut down cleanly to upgrade.\n" "%s" % (getDirtyDevString(dirtyDevs), ))) sys.exit(0) elif warnDirty and dirtyDevs != []: rc = intf.messageWindow(_("Dirty File Systems"), _("The following file systems for your Linux " "system were not unmounted cleanly. Would " "you like to mount them anyway?\n" "%s" % (getDirtyDevString(dirtyDevs, ))), type="yesno") if rc == 0: return -1 if flags.setupFilesystems: oldfsset.mountFilesystems(instPath, readOnly=readOnly) # XXX we should properly support 'auto' at some point if (not oldfsset.getEntryByMountPoint("/") or not oldfsset.getEntryByMountPoint("/").fsystem or not oldfsset.getEntryByMountPoint("/").fsystem.isMountable()): raise RuntimeError, "/etc/fstab did not list a fstype for the root partition which we support"
def copyExceptionToFloppy (anaconda): # in test mode have save to floppy option just copy to new name if not flags.setupFilesystems: try: shutil.copyfile("/tmp/anacdump.txt", "/tmp/test-anacdump.txt") except: log.error("Failed to copy anacdump.txt to /tmp/test-anacdump.txt") pass anaconda.intf.__del__ () return 2 while 1: # Bail if they hit the cancel button. rc = anaconda.intf.dumpWindow() if rc: return 1 device = anaconda.id.floppyDevice file = "/tmp/floppy" try: isys.makeDevInode(device, file) except SystemError: pass try: fd = os.open(file, os.O_RDONLY) except: continue os.close(fd) if rhpl.getArch() != "ia64": cmd = "/usr/sbin/mkdosfs" if os.access("/sbin/mkdosfs", os.X_OK): cmd = "/sbin/mkdosfs" iutil.execWithRedirect (cmd, ["/tmp/floppy"], stdout = '/dev/tty5', stderr = '/dev/tty5') try: isys.mount(device, "/tmp/crash", fstype = "vfat") except SystemError: continue # copy trace dump we wrote to local storage to floppy try: shutil.copyfile("/tmp/anacdump.txt", "/tmp/crash/anacdump.txt") except: log.error("Failed to copy anacdump.txt to floppy") return 2 isys.umount("/tmp/crash") return 0
def mountImage(self, cdNum): if (self.imageMounted): raise SystemError, "trying to mount already-mounted iso image!" isoImage = self.isoPath + '/' + self.discImages[cdNum] isys.makeDevInode("loop3", "/tmp/loop3") isys.losetup("/tmp/loop3", isoImage, readOnly = 1) isys.mount("loop3", "/tmp/isomedia", fstype = 'iso9660', readOnly = 1); self.mntPoint = "/tmp/isomedia/" self.imageMounted = cdNum
def mountMedia(self, cdNum): if (self.mediaIsMounted): raise SystemError, "trying to mount already-mounted iso image!" self.mountDirectory() isoImage = self.isoDir + '/' + self.path + '/' + self.discImages[cdNum] isys.makeDevInode("loop3", "/tmp/loop3") isys.losetup("/tmp/loop3", isoImage, readOnly=1) isys.mount("loop3", "/tmp/isomedia", fstype='iso9660', readOnly=1) self.tree = "/tmp/isomedia/" self.mediaIsMounted = cdNum
def mountDirectory(self): if (self.isoDirIsMounted): raise SystemError, "trying to mount already-mounted image!" f = open("/proc/mounts", "r") l = f.readlines() f.close() for line in l: s = string.split(line) if s[0] == "/dev/" + self.device: self.isoDir = s[1] + "/" return isys.mount(self.device, "/tmp/isodir", fstype=self.fstype, readOnly=1) self.isoDir = "/tmp/isodir/" self.isoDirIsMounted = 1
def mountDirectory(methodstr, messageWindow): # No need to mount it again. if os.path.ismount("/mnt/install/isodir"): return if methodstr.startswith("hd:"): method = methodstr[3:] options = '' if method.count(":") == 1: (device, path) = method.split(":") fstype = "auto" else: (device, fstype, path) = method.split(":") if not device.startswith("/dev/") and not device.startswith("UUID=") \ and not device.startswith("LABEL="): device = "/dev/%s" % device elif methodstr.startswith("nfsiso:"): (options, host, path) = iutil.parseNfsUrl(methodstr) if path.endswith(".iso"): path = os.path.dirname(path) device = "%s:%s" % (host, path) fstype = "nfs" else: return while True: try: isys.mount(device, "/mnt/install/isodir", fstype=fstype, options=options) break except SystemError as msg: log.error("couldn't mount ISO source directory: %s" % msg) ans = messageWindow(_("Couldn't Mount ISO Source"), _("An error occurred mounting the source " "device %s. This may happen if your ISO " "images are located on an advanced storage " "device like LVM or RAID, or if there was a " "problem mounting a partition. Click exit " "to abort the installation.") % (device,), type="custom", custom_icon="error", custom_buttons=[_("_Exit"), _("_Retry")]) if ans == 0: sys.exit(0) else: continue
def mountDirectory(methodstr, messageWindow): if methodstr.startswith("hd:"): method = methodstr[3:] options = '' if method.count(":") == 1: (device, path) = method.split(":") fstype = "auto" else: (device, fstype, path) = method.split(":") if not device.startswith("/dev/") and not device.startswith("UUID=") \ and not device.startswith("LABEL="): device = "/dev/%s" % device elif methodstr.startswith("nfsiso:"): (options, host, path) = iutil.parseNfsUrl(methodstr) device = "%s:%s" % (host, path) fstype = "nfs" else: return # No need to mount it again. if os.path.ismount("/mnt/isodir"): return while True: try: isys.mount(device, "/mnt/isodir", fstype=fstype, options=options) break except SystemError, msg: log.error("couldn't mount ISO source directory: %s" % msg) ans = messageWindow(_("Couldn't Mount ISO Source"), _("An error occurred mounting the source " "device %s. This may happen if your ISO " "images are located on an advanced storage " "device like LVM or RAID, or if there was a " "problem mounting a partition. Click exit " "to abort the installation.") % (device, ), type="custom", custom_icon="error", custom_buttons=[_("_Exit"), _("_Retry")]) if ans == 0: sys.exit(0) else: continue
def mountDirectory(self): if (self.isoDirIsMounted): raise SystemError, "trying to mount already-mounted image!" f = open("/proc/mounts", "r") l = f.readlines() f.close() for line in l: s = string.split(line) if s[0] == "/dev/" + self.device: self.isoDir = s[1] + "/" return isys.mount(self.device, "/tmp/isodir", fstype = self.fstype, readOnly = 1); self.isoDir = "/tmp/isodir/" self.isoDirIsMounted = 1
def _applyNfs(self, repo): server = self.nfsServerEntry.get_text() server.strip() path = self.nfsPathEntry.get_text() path.strip() options = self.nfsOptionsEntry.get_text() options.strip() repo.name = self.nameEntry.get_text() if not server or not path: self.intf.messageWindow(_("Error"), _("Please enter an NFS server and path.")) return False if not network.hasActiveNetDev(): if not self.anaconda.intf.enableNetwork(): self.intf.messageWindow( _("No Network Available"), _("Some of your software repositories require " "networking, but there was an error enabling the " "network on your system.")) return False urlgrabber.grabber.reset_curl_obj() import tempfile dest = tempfile.mkdtemp("", repo.name.replace(" ", ""), "/mnt") try: isys.mount("%s:%s" % (server, path), dest, "nfs", options=options) except Exception as e: self.intf.messageWindow( _("Error Setting Up Repository"), _("The following error occurred while setting up the " "repository:\n\n%s") % e) return False repo.baseurl = "file://%s" % dest repo.anacondaBaseURLs = ["nfs:%s:%s:%s" % (options, server, path)] return True
def _applyNfs(self, repo): server = self.nfsServerEntry.get_text() server.strip() path = self.nfsPathEntry.get_text() path.strip() options = self.nfsOptionsEntry.get_text() options.strip() repo.name = self.nameEntry.get_text() if not server or not path: self.intf.messageWindow(_("Error"), _("Please enter an NFS server and path.")) return False if not network.hasActiveNetDev(): if not self.anaconda.intf.enableNetwork(): self.intf.messageWindow(_("No Network Available"), _("Some of your software repositories require " "networking, but there was an error enabling the " "network on your system.")) return False urlgrabber.grabber.reset_curl_obj() import tempfile dest = tempfile.mkdtemp("", repo.name.replace(" ", ""), "/mnt") try: isys.mount("%s:%s" % (server, path), dest, "nfs", options=options) except Exception as e: self.intf.messageWindow(_("Error Setting Up Repository"), _("The following error occurred while setting up the " "repository:\n\n%s") % e) return False repo.baseurl = "file://%s" % dest repo.anacondaBaseURLs = ["nfs:%s:%s:%s" % (options,server,path)] return True
def remount(self, *args, **kwargs): """ Remount the filesystem with new options """ options = kwargs.get("options", "") log.info("remounting %s on %s", self.device, self._mountpoint) if not self.exists: raise FSError("filesystem has not been created") if not self._mountpoint: # not mounted return if not os.path.exists(self._mountpoint): raise FSError("mountpoint does not exist") # passed in options override default options if not options or not isinstance(options, str): options = self.options try: rc = isys.mount(self.device, self._mountpoint, fstype=self.mountType, options=options, remount=True, bindMount=isinstance(self, BindFS)) except Exception as e: raise FSError("mount failed: %s" % e) if rc: raise FSError("mount failed: %s" % rc) if flags.selinux: ret = isys.resetFileContext(self._mountpoint, "") log.info("set SELinux context for newly mounted filesystem " "root at %s to %s" % (self._mountpoint, ret)) isys.setFileContext("%s/lost+found" % self._mountpoint, lost_and_found_context, "")
def remount(self, *args, **kwargs): """ Remount the filesystem with new options """ options = kwargs.get("options", "") log.info("remounting %s on %s", self.device, self._mountpoint) if not self.exists: raise FSError("filesystem has not been created") if not self._mountpoint: # not mounted return if not os.path.exists(self._mountpoint): raise FSError("mountpoint does not exist") # passed in options override default options if not options or not isinstance(options, str): options = self.options try: rc = isys.mount(self.device, self._mountpoint, fstype=self.mountType, options=options, remount=True, bindMount=isinstance(self, BindFS)) except Exception as e: raise FSError("mount failed: %s" % e) if rc: raise FSError("mount failed: %s" % rc) if flags.selinux: ret = isys.resetFileContext(self._mountpoint, "") log.info("set SELinux context for newly mounted filesystem " "root at %s to %s" %(self._mountpoint, ret)) isys.setFileContext("%s/lost+found" % self._mountpoint, lost_and_found_context, "")
def mount(self, *args, **kwargs): """ Mount this filesystem. Arguments: None Keyword Arguments: options -- mount options (overrides all other option strings) chroot -- prefix to apply to mountpoint mountpoint -- mountpoint (overrides self.mountpoint) """ options = kwargs.get("options", "") chroot = kwargs.get("chroot", "/") mountpoint = kwargs.get("mountpoint") if not self.exists: raise FSError("filesystem has not been created") if not mountpoint: mountpoint = self.mountpoint if not mountpoint: raise FSError("no mountpoint given") if self.status: return if not isinstance(self, NoDevFS) and not os.path.exists(self.device): raise FSError("device %s does not exist" % self.device) # XXX os.path.join is FUBAR: # # os.path.join("/mnt/foo", "/") -> "/" # #mountpoint = os.path.join(chroot, mountpoint) chrootedMountpoint = os.path.normpath("%s/%s" % (chroot, mountpoint)) iutil.mkdirChain(chrootedMountpoint) if flags.selinux: ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for mountpoint %s to %s" \ % (mountpoint, ret)) # passed in options override default options if not options or not isinstance(options, str): options = self.options try: rc = isys.mount(self.device, chrootedMountpoint, fstype=self.mountType, options=options, bindMount=isinstance(self, BindFS)) except Exception as e: raise FSError("mount failed: %s" % e) if rc: raise FSError("mount failed: %s" % rc) if flags.selinux and "ro" not in options.split(","): ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for newly mounted filesystem " "root at %s to %s" % (mountpoint, ret)) isys.setFileContext("%s/lost+found" % mountpoint, lost_and_found_context, chroot) self._mountpoint = chrootedMountpoint
def postAction(self, anaconda): silvereye.InstallClass.postAction(self, anaconda) # XXX: use proper constants for path names def copy_script(src, dest, mode=0770): shutil.copyfile('/tmp/updates/scripts/%s' % src, '%s%s' % (anaconda.rootPath, dest)) os.chmod('%s%s' % (anaconda.rootPath, dest), mode) def copy_file(src, dest): copy_script(src, dest, mode=0644) copy_script('eucalyptus-frontend-config.sh', '/usr/local/sbin/eucalyptus-frontend-config') copy_script('eucalyptus-teardown', '/usr/local/sbin/eucalyptus-teardown') copy_script('install-unpacked-image.py', '/usr/local/sbin/install-unpacked-image.py') copy_script('eucalyptus-setup.init', '/etc/init.d/eucalyptus-setup') copy_script('register_cloud_start', '/usr/local/sbin/register_cloud_start', mode=0755) os.mkdir('%s/tmp/img' % anaconda.rootPath) # EKI shutil.copyfile('/tmp/updates/scripts/vmlinuz-kexec', '%s/tmp/img/vmlinuz-kexec' % anaconda.rootPath) # ERI shutil.copyfile('/tmp/updates/scripts/initramfs-kexec', '%s/tmp/img/initramfs-kexec' % anaconda.rootPath) # Image kickstart newks = open('%s/tmp/ks-centos6.cfg' % anaconda.rootPath, 'w') ayum = anaconda.backend.ayum for repo in ayum.repos.listEnabled(): newks.write('repo --name=%s --baseurl=%s\n' % (repo.name, repo.baseurl[0])) for line in open('/tmp/updates/ks-centos6.cfg', 'r').readlines(): if line.startswith('repo '): continue newks.write(line) newks.close() # Image creation script copy_script('ami_creator.py', '/tmp/ami_creator.py') # XXX clean this up bindmount = False if ayum._baseRepoURL and ayum._baseRepoURL.startswith("file://"): os.mkdir('/mnt/sysimage/mnt/source') isys.mount('/mnt/source', '/mnt/sysimage/mnt/source', bindMount=True) bindmount = True # eucalyptus.conf fragment from config screen w = anaconda.intf.progressWindow(_("Creating EMI"), _("Creating an initial CentOS 6 EMI."), 100) shutil.copyfile('/tmp/eucalyptus.conf', '%s/etc/eucalyptus/eucalyptus.conf.anaconda' % anaconda.rootPath) copy_script('eucalyptus-firstboot-final.py', '/usr/share/firstboot/modules/eucalyptus-firstboot-final.py') postscriptlines =""" /usr/sbin/euca_conf --upgrade-conf /etc/eucalyptus/eucalyptus.conf.anaconda chkconfig dnsmasq off chkconfig eucalyptus-cloud off chkconfig eucalyptus-setup on """ postscript = AnacondaKSScript(postscriptlines, inChroot=True, logfile='/root/frontend-ks-post.log', type=KS_SCRIPT_POST) postscript.run(anaconda.rootPath, flags.serial, anaconda.intf) # TODO: Add status line for text mode pkgstatus = None if anaconda.id.displayMode == 'g': import gtk pkgstatus = gtk.Label("Preparing to install...") w.window.child.add(pkgstatus) pkgstatus.show() messages = '/root/ami-creation.log' rc = iutil.execWithCallback('/bin/sh' , ['-c', 'cd /tmp/img; /tmp/ami_creator.py -c /tmp/ks-centos6.cfg'], stdin = messages, stdout = messages, stderr = messages, root = '/mnt/sysimage', callback=imageProgress, callback_data=ImageProgress(w, pkgstatus)) if bindmount: isys.umount('/mnt/sysimage/mnt/source') w.pop()
if case == '6': isys.sync() if case == '7': my_swap = "/dev/sda7" isys.swapon(my_swap) if case == '8': my_swap = "/dev/sda7" isys.swapoff(my_swap) procpath = 'tgtsys/proc' syspath = 'tgtsys/sys' if case == '9': if not os.path.exists(procpath): os.makedirs(procpath) if not os.path.exists(syspath): os.makedirs(syspath) isys.mount('proc', 'proc', procpath) isys.mount('sysfs', 'sys', syspath) if case == '10': isys.umount(procpath) isys.umount(syspath) try: os.rmdir(procpath) except: pass try: os.rmdir(syspath) except: pass #fstype_map[]
def mount(self, *args, **kwargs): """ Mount this filesystem. Arguments: None Keyword Arguments: options -- mount options (overrides all other option strings) chroot -- prefix to apply to mountpoint mountpoint -- mountpoint (overrides self.mountpoint) """ options = kwargs.get("options", "") chroot = kwargs.get("chroot", "/") mountpoint = kwargs.get("mountpoint") if not self.exists: raise FSError("filesystem has not been created") if not mountpoint: mountpoint = self.mountpoint if not mountpoint: raise FSError("no mountpoint given") if self.status: return if not isinstance(self, NoDevFS) and not os.path.exists(self.device): raise FSError("device %s does not exist" % self.device) # XXX os.path.join is FUBAR: # # os.path.join("/mnt/foo", "/") -> "/" # #mountpoint = os.path.join(chroot, mountpoint) chrootedMountpoint = os.path.normpath("%s/%s" % (chroot, mountpoint)) iutil.mkdirChain(chrootedMountpoint) if flags.selinux: ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for mountpoint %s to %s" \ % (mountpoint, ret)) # passed in options override default options if not options or not isinstance(options, str): options = self.options try: rc = isys.mount(self.device, chrootedMountpoint, fstype=self.mountType, options=options, bindMount=isinstance(self, BindFS)) except Exception as e: raise FSError("mount failed: %s" % e) if rc: raise FSError("mount failed: %s" % rc) if flags.selinux: ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for newly mounted filesystem " "root at %s to %s" %(mountpoint, ret)) isys.setFileContext("%s/lost+found" % mountpoint, lost_and_found_context, chroot) self._mountpoint = chrootedMountpoint
def findIsoImages(path, messageWindow): flush = os.stat(path) files = os.listdir(path) arch = _arch discImages = {} for file in files: what = path + '/' + file if not isys.isIsoImage(what): continue try: isys.losetup("/dev/loop2", what, readOnly = 1) except SystemError: continue try: isys.mount("/dev/loop2", "/mnt/cdimage", fstype = "iso9660", readOnly = True) for num in range(1, 10): if os.access("/mnt/cdimage/.discinfo", os.R_OK): f = open("/mnt/cdimage/.discinfo") try: f.readline() # skip timestamp f.readline() # skip release description discArch = string.strip(f.readline()) # read architecture discNum = getDiscNums(f.readline().strip()) except: discArch = None discNum = [ 0 ] f.close() if num not in discNum or discArch != arch: continue # if it's disc1, it needs to have images/install.img if (num == 1 and not os.access("/mnt/cdimage/images/install.img", os.R_OK)): log.warning("%s doesn't have a install.img, skipping" %(what,)) continue # we only install binary packages, so let's look for a # product/ dir and hope that this avoids getting # discs from the src.rpm set if not os.path.isdir("/mnt/cdimage/%s" %(productPath,)): log.warning("%s doesn't have binary RPMS, skipping" %(what,)) continue # warn user if images appears to be wrong size if os.stat(what)[stat.ST_SIZE] % 2048: rc = messageWindow(_("Warning"), _("The ISO image %s has a size which is not " "a multiple of 2048 bytes. This may mean " "it was corrupted on transfer to this computer." "\n\n" "It is recommended that you exit and abort your " "installation, but you can choose to continue if " "you think this is in error.") % (file,), type="custom", custom_icon="warning", custom_buttons= [_("_Exit installer"), _("_Continue")]) if rc == 0: sys.exit(0) discImages[num] = file isys.umount("/mnt/cdimage", removeDir=False) except SystemError: pass isys.unlosetup("/dev/loop2") return discImages
def switchMedia(self, mediano, filename=""): log.info("switching from CD %s to %s for %s" %(self.currentMedia, mediano, filename)) if mediano in self.currentMedia: return if os.access("/mnt/source/.discinfo", os.R_OK): f = open("/mnt/source/.discinfo") timestamp = f.readline().strip() f.close() else: timestamp = self.timestamp if self.timestamp is None: self.timestamp = timestamp needed = mediano # if self.currentMedia is empty, then we shouldn't have anything # mounted. double-check by trying to unmount, but we don't want # to get into a loop of trying to unmount forever. if # self.currentMedia is set, then it should still be mounted and # we want to loop until it unmounts successfully if not self.currentMedia: try: isys.umount("/mnt/source") except: pass else: self.unmountCD() done = 0 cdlist = [] for (dev, something, descript) in \ kudzu.probe(kudzu.CLASS_CDROM, kudzu.BUS_UNSPEC, 0): cdlist.append(dev) for dev in cdlist: try: if not isys.mount(dev, "/mnt/source", fstype = "iso9660", readOnly = 1): if os.access("/mnt/source/.discinfo", os.R_OK): f = open("/mnt/source/.discinfo") newStamp = f.readline().strip() try: descr = f.readline().strip() except: descr = None try: arch = f.readline().strip() except: arch = None try: discNum = getDiscNums(f.readline().strip()) except: discNum = [ 0 ] f.close() if (newStamp == timestamp and arch == _arch and needed in discNum): done = 1 self.currentMedia = discNum if not done: isys.umount("/mnt/source") except: pass if done: break if not done: if self.noeject: log.info("noeject in effect, not ejecting cdrom") else: isys.ejectCdrom(self.device) while not done: if self.intf is not None: self.intf.beep() self.messageWindow(_("Change CDROM"), _("Please insert %s disc %d to continue.") % (productName, needed)) try: if isys.mount(self.device, "/mnt/source", fstype = "iso9660", readOnly = 1): time.sleep(3) isys.mount(self.device, "/mnt/source", fstype = "iso9660", readOnly = 1) if os.access("/mnt/source/.discinfo", os.R_OK): f = open("/mnt/source/.discinfo") newStamp = f.readline().strip() try: descr = f.readline().strip() except: descr = None try: arch = f.readline().strip() except: arch = None try: discNum = getDiscNums(f.readline().strip()) except: discNum = [ 0 ] f.close() if (newStamp == timestamp and arch == _arch and needed in discNum): done = 1 self.currentMedia = discNum # make /tmp/cdrom again so cd gets ejected isys.makeDevInode(self.device, "/tmp/cdrom") if not done: self.messageWindow(_("Wrong CDROM"), _("That's not the correct %s CDROM.") % (productName,)) isys.umount("/mnt/source") if self.noeject: log.info("noeject in effect, not ejecting cdrom") else: isys.ejectCdrom(self.device) except: self.messageWindow(_("Error"), _("Unable to access the CDROM."))
class DiskSet: """The disks in the system.""" skippedDisks = [] mdList = [] def __init__ (self): self.disks = {} self.onlyPrimary = None def onlyPrimaryParts(self): for disk in self.disks.values(): if disk.type.check_feature(parted.DISK_TYPE_EXTENDED): return 0 return 1 def startAllRaid(self): """Start all of the raid devices associated with the DiskSet.""" driveList = [] origDriveList = self.driveList() for drive in origDriveList: if not drive in DiskSet.skippedDisks: driveList.append(drive) DiskSet.mdList.extend(raid.startAllRaid(driveList)) def stopAllRaid(self): """Stop all of the raid devices associated with the DiskSet.""" raid.stopAllRaid(DiskSet.mdList) while DiskSet.mdList: DiskSet.mdList.pop() def getLabels(self): """Return a list of all of the labels used on partitions.""" labels = {} drives = self.disks.keys() drives.sort() for drive in drives: disk = self.disks[drive] func = lambda part: (part.is_active() and not (part.get_flag(parted.PARTITION_RAID) or part.get_flag(parted.PARTITION_LVM)) and part.fs_type and (part.fs_type.name in ("ext2", "ext3", "xfs"))) parts = filter_partitions(disk, func) for part in parts: node = get_partition_name(part) label = isys.readFSLabel(node) if label: labels[node] = label for dev, devices, level, numActive in DiskSet.mdList: label = isys.readFSLabel(dev) if label: labels[dev] = label return labels def findExistingRootPartitions(self, intf, mountpoint, upgradeany = 0): """Return a list of all of the partitions which look like a root fs.""" rootparts = [] self.startAllRaid() for dev, devices, level, numActive in self.mdList: (errno, msg) = (None, None) found = 0 for fs in fsset.getFStoTry(dev): try: isys.mount(dev, mountpoint, fs, readOnly = 1) found = 1 break except SystemError, (errno, msg): pass if found: if os.access (mountpoint + '/etc/fstab', os.R_OK): relstr = getRedHatReleaseString(mountpoint) cmdline = open('/proc/cmdline', 'r').read() if ((cmdline.find("upgradeany") != -1) or (upgradeany == 1) or (productMatches(relstr, productName))): rootparts.append ((dev, fs, relstr)) isys.umount(mountpoint) # now, look for candidate lvm roots lvm.vgscan() lvm.vgactivate() for (vg, lv, size) in lvm.lvlist(): dev = "/dev/%s/%s" %(vg, lv) found = 0 for fs in fsset.getFStoTry(dev): try: isys.mount(dev, mountpoint, fs, readOnly = 1) found = 1 break except SystemError: pass if found: if os.access (mountpoint + '/etc/fstab', os.R_OK): relstr = getRedHatReleaseString(mountpoint) cmdline = open('/proc/cmdline', 'r').read() if ((cmdline.find("upgradeany") != -1) or (upgradeany == 1) or (productMatches(relstr, productName))): rootparts.append ((dev, fs, relstr)) isys.umount(mountpoint) lvm.vgdeactivate() # don't stop raid until after we've looked for lvm on top of it self.stopAllRaid() drives = self.disks.keys() drives.sort() for drive in drives: disk = self.disks[drive] part = disk.next_partition () while part: if (part.is_active() and (part.get_flag(parted.PARTITION_RAID) or part.get_flag(parted.PARTITION_LVM))): pass elif (part.fs_type and part.fs_type.name in fsset.getUsableLinuxFs()): node = get_partition_name(part) try: isys.mount(node, mountpoint, part.fs_type.name) except SystemError, (errno, msg): intf.messageWindow(_("Error"), _("Error mounting file system on " "%s: %s") % (node, msg)) part = disk.next_partition(part) continue if os.access (mountpoint + '/etc/fstab', os.R_OK): relstr = getRedHatReleaseString(mountpoint) cmdline = open('/proc/cmdline', 'r').read() if ((cmdline.find("upgradeany") != -1) or (upgradeany == 1) or (productMatches(relstr, productName))): rootparts.append ((node, part.fs_type.name, relstr)) isys.umount(mountpoint) part = disk.next_partition(part)
#ret, msg = remove_empty_dir(mntdir) #if not ret: # return False, msg if not os.path.exists(mntdir): try: os.makedirs(mntdir) except OSError, e: return False, str(e) logger.i("mount_dev: Device = %s Mount = %s Fstype = %s\n" % \ (devfn, mntdir, fstype)) if not os.path.exists(mntdir): os.makedirs(mntdir) if USE_ISYS: try: isys.mount(fstype, devfn, mntdir, flags) except SystemError, e: errmsg = "mount_dev: mount failed: %s\n" % str(e) logger.e(errmsg) return False, errmsg else: return True, mntdir else: f_loop = False if flags: flag_list = flags.split(',') else: flag_list = [] new_flag_list = [] for f in flag_list: if f.strip().startswith('loop'):
def runRescue(anaconda): for file in [ "services", "protocols", "group", "joe", "man.config", "nsswitch.conf", "selinux", "mke2fs.conf" ]: try: os.symlink('/mnt/runtime/etc/' + file, '/etc/' + file) except: pass # see if they would like networking enabled if not network.hasActiveNetDev(): screen = SnackScreen() while True: rc = ButtonChoiceWindow(screen, _("Setup Networking"), _("Do you want to start the network interfaces on " "this system?"), [_("Yes"), _("No")]) if rc != string.lower(_("No")): anaconda.intf = RescueInterface(screen) if not anaconda.intf.enableNetwork(anaconda): anaconda.intf.messageWindow(_("No Network Available"), _("Unable to activate a networking device. Networking " "will not be available in rescue mode.")) break startNetworking(anaconda.network, anaconda.intf) break else: break anaconda.intf = None screen.finish() # Early shell access with no disk access attempts if not anaconda.rescue_mount: # the %post should be responsible for mounting all needed file systems # NOTE: 1st script must be bash or simple python as nothing else might be available in the rescue image if anaconda.ksdata and anaconda.ksdata.scripts: from kickstart import runPostScripts runPostScripts(anaconda) else: runShell() sys.exit(0) screen = SnackScreen() anaconda.intf = RescueInterface(screen) if anaconda.ksdata: if anaconda.ksdata.rescue and anaconda.ksdata.rescue.romount: readOnly = 1 else: readOnly = 0 else: # prompt to see if we should try and find root filesystem and mount # everything in /etc/fstab on that root while True: rc = ButtonChoiceWindow(screen, _("Rescue"), _("The rescue environment will now attempt to find your " "Linux installation and mount it under the directory " "%s. You can then make any changes required to your " "system. If you want to proceed with this step choose " "'Continue'. You can also choose to mount your file systems " "read-only instead of read-write by choosing 'Read-Only'. " "If you need to activate SAN devices choose 'Advanced'." "\n\n" "If for some reason this process fails you can choose 'Skip' " "and this step will be skipped and you will go directly to a " "command shell.\n\n") % (anaconda.rootPath,), [_("Continue"), _("Read-Only"), _("Skip"), _("Advanced")] ) if rc == string.lower(_("Skip")): runShell(screen) sys.exit(0) elif rc == string.lower(_("Advanced")): addDialog = addDriveDialog(anaconda) addDialog.addDriveDialog(screen) continue elif rc == string.lower(_("Read-Only")): readOnly = 1 else: readOnly = 0 break import storage storage.storageInitialize(anaconda) (disks, notUpgradable) = upgrade.findExistingRoots(anaconda, upgradeany=True) if not disks: root = None elif (len(disks) == 1) or anaconda.ksdata: root = disks[0] else: height = min (len (disks), 12) if height == 12: scroll = 1 else: scroll = 0 devList = [] for (device, relstr) in disks: if getattr(device.format, "label", None): devList.append("%s (%s) - %s" % (device.name, device.format.label, relstr)) else: devList.append("%s - %s" % (device.name, relstr)) (button, choice) = \ ListboxChoiceWindow(screen, _("System to Rescue"), _("Which device holds the root partition " "of your installation?"), devList, [ _("OK"), _("Exit") ], width = 30, scroll = scroll, height = height, help = "multipleroot") if button == string.lower (_("Exit")): root = None else: root = disks[choice] rootmounted = 0 if root: try: rc = mountExistingSystem(anaconda, root, allowDirty = 1, warnDirty = 1, readOnly = readOnly) if rc == -1: if anaconda.ksdata: log.error("System had dirty file systems which you chose not to mount") else: ButtonChoiceWindow(screen, _("Rescue"), _("Your system had dirty file systems which you chose not " "to mount. Press return to get a shell from which " "you can fsck and mount your partitions. The system " "will reboot automatically when you exit from the " "shell."), [_("OK")], width = 50) rootmounted = 0 else: if anaconda.ksdata: log.info("System has been mounted under: %s" % anaconda.rootPath) else: ButtonChoiceWindow(screen, _("Rescue"), _("Your system has been mounted under %(rootPath)s.\n\n" "Press <return> to get a shell. If you would like to " "make your system the root environment, run the command:\n\n" "\tchroot %(rootPath)s\n\nThe system will reboot " "automatically when you exit from the shell.") % {'rootPath': anaconda.rootPath}, [_("OK")] ) rootmounted = 1 # now turn on swap if not readOnly: try: anaconda.storage.turnOnSwap() except: log.error("Error enabling swap") # and /sys/fs/selinux too if flags.selinux and os.path.isdir("%s/sys/fs/selinux" %(anaconda.rootPath,)): try: isys.mount("/sys/fs/selinux", "%s/sys/fs/selinux" %(anaconda.rootPath,), "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" %(e,)) # we have to catch the possible exception # because we support read-only mounting try: fd = open("%s/.autorelabel" % anaconda.rootPath, "w+") fd.close() except Exception, e: log.warning("cannot touch /.autorelabel") # set a library path to use mounted fs libdirs = os.environ["LD_LIBRARY_PATH"].split(":") mounted = map(lambda dir: "/mnt/sysimage%s" % dir, libdirs) os.environ["LD_LIBRARY_PATH"] = ":".join(libdirs + mounted) # find groff data dir try: glst = os.listdir("/mnt/sysimage/usr/share/groff") # find a directory which is a numeral, its where # data files are gversion = None for gdir in glst: try: isone = 1 for idx in range(0, len(gdir)): if string.find(string.digits + '.', gdir[idx]) == -1: isone = 0 break if isone: gversion = gdir break except: gversion = None continue except: gversion = None if gversion is not None: gpath = "/mnt/sysimage/usr/share/groff/"+gversion os.environ["GROFF_FONT_PATH"] = gpath + '/font' os.environ["GROFF_TMAC_PATH"] = "%s:/mnt/sysimage/usr/share/groff/site-tmac" % (gpath + '/tmac',) # do we have bash? try: if os.access("/usr/bin/bash", os.R_OK): os.symlink ("/usr/bin/bash", "/bin/bash") except: pass
def mountRootPartition(anaconda, rootInfo, oldfsset, allowDirty=0, warnDirty=0, readOnly=0): (root, rootFs) = rootInfo diskset = partedUtils.DiskSet(anaconda) encryptedDevices = anaconda.id.partitions.encryptedDevices diskset.openDevices() for cryptoDev in encryptedDevices.values(): cryptoDev.openDevice() diskset.startMPath() diskset.startDmRaid() diskset.startMdRaid() for cryptoDev in encryptedDevices.values(): cryptoDev.openDevice() lvm.vgscan() lvm.vgactivate() for cryptoDev in encryptedDevices.values(): if cryptoDev.openDevice(): log.warning("failed to open encrypted device %s" % (cryptoDev.getDevice(encrypted=True))) log.info("going to mount %s on %s as %s" % (root, anaconda.rootPath, rootFs)) isys.mount(root, anaconda.rootPath, rootFs) oldfsset.reset() newfsset = readFstab(anaconda) for entry in newfsset.entries: oldfsset.add(entry) isys.umount(anaconda.rootPath) dirtyDevs = oldfsset.hasDirtyFilesystems(anaconda.rootPath) if not allowDirty and dirtyDevs != []: lvm.vgdeactivate() diskset.stopMdRaid() diskset.stopDmRaid() diskset.stopMPath() anaconda.intf.messageWindow( _("Dirty File Systems"), _("The following file systems for your Linux system " "were not unmounted cleanly. Please boot your " "Linux installation, let the file systems be " "checked and shut down cleanly to upgrade.\n" "%s" % (getDirtyDevString(dirtyDevs), ))) sys.exit(0) elif warnDirty and dirtyDevs != []: rc = anaconda.intf.messageWindow( _("Dirty File Systems"), _("The following file systems for your Linux " "system were not unmounted cleanly. Would " "you like to mount them anyway?\n" "%s" % (getDirtyDevString(dirtyDevs, ))), type="yesno") if rc == 0: return -1 if flags.setupFilesystems: oldfsset.mountFilesystems(anaconda, readOnly=readOnly) if (not oldfsset.getEntryByMountPoint("/") or not oldfsset.getEntryByMountPoint("/").fsystem or not oldfsset.getEntryByMountPoint("/").fsystem.isMountable()): raise RuntimeError, "/etc/fstab did not list a fstype for the root partition which we support"
if case == "6": isys.sync() if case == "7": my_swap = "/dev/sda7" isys.swapon(my_swap) if case == "8": my_swap = "/dev/sda7" isys.swapoff(my_swap) procpath = "tgtsys/proc" syspath = "tgtsys/sys" if case == "9": if not os.path.exists(procpath): os.makedirs(procpath) if not os.path.exists(syspath): os.makedirs(syspath) isys.mount("proc", "proc", procpath) isys.mount("sysfs", "sys", syspath) if case == "10": isys.umount(procpath) isys.umount(syspath) try: os.rmdir(procpath) except: pass try: os.rmdir(syspath) except: pass # fstype_map[]
def runRescue(anaconda): for file in [ "services", "protocols", "group", "joe", "man.config", "nsswitch.conf", "selinux", "mke2fs.conf" ]: try: os.symlink('/mnt/runtime/etc/' + file, '/etc/' + file) except: pass # see if they would like networking enabled if not methodUsesNetworking(anaconda.id.methodstr): screen = SnackScreen() while 1: rc = ButtonChoiceWindow( screen, _("Setup Networking"), _("Do you want to start the network interfaces on " "this system?"), [_("Yes"), _("No")]) if rc != string.lower(_("No")): anaconda.intf = RescueInterface(screen) # need to call sequence of screens, have to look in text.py # # this code is based on main loop in text.py, and if it # or the network step in dispatch.py change significantly # then this will certainly break # pyfile = "network_text" classNames = ("NetworkDeviceWindow", "NetworkGlobalWindow") lastrc = INSTALL_OK step = 0 anaconda.dir = 1 while 1: s = "from %s import %s; nextWindow = %s" % \ (pyfile, classNames[step], classNames[step]) exec s win = nextWindow() rc = win(screen, anaconda, showonboot=0) if rc == INSTALL_NOOP: rc = lastrc if rc == INSTALL_BACK: step = step - 1 anaconda.dir = -1 elif rc == INSTALL_OK: step = step + 1 anaconda.dir = 1 lastrc = rc if step == -1: ButtonChoiceWindow(screen, _("Cancelled"), _("I can't go to the previous step " "from here. You will have to try " "again."), buttons=[_("OK")]) anaconda.dir = 1 step = 0 elif step >= len(classNames): break startNetworking(anaconda.id.network, anaconda.intf, anaconda) break else: break screen.finish() # Early shell access with no disk access attempts if not anaconda.rescue_mount: runShell() sys.exit(0) # need loopback devices too for lpminor in range(8): dev = "loop%s" % (lpminor, ) isys.makeDevInode(dev, "/dev/" + dev) screen = SnackScreen() anaconda.intf = RescueInterface(screen) anaconda.setMethod() # prompt to see if we should try and find root filesystem and mount # everything in /etc/fstab on that root rc = ButtonChoiceWindow( screen, _("Rescue"), _("The rescue environment will now attempt to find your " "Linux installation and mount it under the directory " "%s. You can then make any changes required to your " "system. If you want to proceed with this step choose " "'Continue'. You can also choose to mount your file systems " "read-only instead of read-write by choosing 'Read-Only'." "\n\n" "If for some reason this process fails you can choose 'Skip' " "and this step will be skipped and you will go directly to a " "command shell.\n\n") % (anaconda.rootPath, ), [_("Continue"), _("Read-Only"), _("Skip")]) if rc == string.lower(_("Skip")): runShell(screen) sys.exit(0) elif rc == string.lower(_("Read-Only")): readOnly = 1 else: readOnly = 0 disks = upgrade.findExistingRoots(anaconda, upgradeany=1) if not disks: root = None elif len(disks) == 1: root = disks[0] else: height = min(len(disks), 12) if height == 12: scroll = 1 else: scroll = 0 partList = [] for (drive, fs, relstr, label) in disks: if label: partList.append("%s (%s)" % (drive, label)) else: partList.append(drive) (button, choice) = \ ListboxChoiceWindow(screen, _("System to Rescue"), _("What partition holds the root partition " "of your installation?"), partList, [ _("OK"), _("Exit") ], width = 30, scroll = scroll, height = height, help = "multipleroot") if button == string.lower(_("Exit")): root = None else: root = disks[choice] rootmounted = 0 if root: try: fs = fsset.FileSystemSet(anaconda) # only pass first two parts of tuple for root, since third # element is a comment we dont want rc = upgrade.mountRootPartition(anaconda, root[:2], fs, allowDirty=1, warnDirty=1, readOnly=readOnly) if rc == -1: ButtonChoiceWindow( screen, _("Rescue"), _("Your system had dirty file systems which you chose not " "to mount. Press return to get a shell from which " "you can fsck and mount your partitions. The system " "will reboot automatically when you exit from the " "shell."), [_("OK")], width=50) rootmounted = 0 else: ButtonChoiceWindow( screen, _("Rescue"), _("Your system has been mounted under %s.\n\n" "Press <return> to get a shell. If you would like to " "make your system the root environment, run the command:\n\n" "\tchroot %s\n\nThe system will reboot " "automatically when you exit from the shell.") % (anaconda.rootPath, anaconda.rootPath), [_("OK")]) rootmounted = 1 # now turn on swap if not readOnly: try: fs.turnOnSwap("/") except: log.error("Error enabling swap") # now that dev is udev, bind mount the installer dev there isys.mount("/dev", "%s/dev" % (anaconda.rootPath, ), bindMount=1) # and /dev/pts isys.mount("/dev/pts", "%s/dev/pts" % (anaconda.rootPath, ), bindMount=1) # and /selinux too if flags.selinux and os.path.isdir("%s/selinux" % (anaconda.rootPath, )): try: isys.mount("/selinux", "%s/selinux" % (anaconda.rootPath, ), "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" % (e, )) # set a library path to use mounted fs os.environ[ "LD_LIBRARY_PATH"] = "/lib:/usr/lib:/usr/X11R6/lib:/lib:/mnt/usr/lib:/mnt/sysimage/lib:/mnt/sysimage/usr/lib:/mnt/sysimage/usr/X11R6/lib" # get man pages to work os.environ[ "MANPATH"] = "/mnt/sysimage/usr/share/man:/mnt/sysimage/usr/local/share/man:/usr/share/man:/usr/local/share/man" # find groff data dir try: glst = os.listdir("/mnt/sysimage/usr/share/groff") # find a directory which is a numeral, its where # data files are gversion = None for gdir in glst: try: isone = 1 for idx in range(0, len(gdir)): if string.find(string.digits + '.', gdir[idx]) == -1: isone = 0 break if isone: gversion = gdir break except: gversion = None continue except: gversion = None if gversion is not None: gpath = "/mnt/sysimage/usr/share/groff/" + gversion os.environ["GROFF_FONT_PATH"] = gpath + '/font' os.environ[ "GROFF_TMAC_PATH"] = "%s:/mnt/sysimage/usr/share/groff/site-tmac" % ( gpath + '/tmac', ) # do we have bash? try: if os.access("/usr/bin/bash", os.R_OK): os.symlink("/usr/bin/bash", "/bin/bash") except: pass except: # This looks horrible, but all it does is catch every exception, # and reraise those in the tuple check. This lets programming # errors raise exceptions, while any runtime error will # still result in a shell. (exc, val) = sys.exc_info()[0:2] log.error(val) if exc in (IndexError, ValueError, SyntaxError): raise exc, val, sys.exc_info()[2] ButtonChoiceWindow( screen, _("Rescue"), _("An error occurred trying to mount some or all of your " "system. Some of it may be mounted under %s.\n\n" "Press <return> to get a shell. The system will reboot " "automatically when you exit from the shell.") % (anaconda.rootPath, ), [_("OK")]) else: ButtonChoiceWindow(screen, _("Rescue Mode"), _("You don't have any Linux partitions. Press " "return to get a shell. The system will reboot " "automatically when you exit from the shell."), [_("OK")], width=50) msgStr = "" if rootmounted and not readOnly: makeMtab(anaconda.rootPath, fs) try: makeResolvConf(anaconda.rootPath) except Exception, e: log.error("error making a resolv.conf: %s" % (e, )) msgStr = _("Your system is mounted under the %s directory.") % ( anaconda.rootPath, )
def _doFilesystemMangling(self, anaconda): log.info("doing post-install fs mangling") wait = anaconda.intf.waitWindow( _("Post-Installation"), _("Performing post-installation filesystem changes. This may take several minutes." )) # resize rootfs first, since it is 100% full due to genMinInstDelta self._resizeRootfs(anaconda, wait) # remount filesystems anaconda.id.storage.mountFilesystems() # restore the label of / to what we think it is rootDevice = anaconda.id.storage.rootDevice rootDevice.setup() # ensure we have a random UUID on the rootfs # FIXME: this should be abstracted per filesystem type iutil.execWithRedirect("tune2fs", ["-U", "random", rootDevice.path], stdout="/dev/tty5", stderr="/dev/tty5") # and now set the uuid in the storage layer rootDevice.updateSysfsPath() iutil.notify_kernel("/sys%s" % rootDevice.sysfsPath) storage.udev.udev_settle() rootDevice.updateSysfsPath() info = storage.udev.udev_get_block_device(rootDevice.sysfsPath) rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info) log.info("reset the rootdev (%s) to have a uuid of %s" % (rootDevice.sysfsPath, rootDevice.format.uuid)) # for any filesystem that's _not_ on the root, we need to handle # moving the bits from the livecd -> the real filesystems. # this is pretty distasteful, but should work with things like # having a separate /usr/local def _setupFilesystems(mounts, chroot="", teardown=False): """ Setup or teardown all filesystems except for "/" """ mountpoints = sorted(mounts.keys(), reverse=teardown is True) if teardown: method = "teardown" kwargs = {} else: method = "setup" kwargs = {"chroot": chroot} mountpoints.remove("/") for mountpoint in mountpoints: device = mounts[mountpoint] getattr(device.format, method)(**kwargs) # Start by sorting the mountpoints in decreasing-depth order. mountpoints = sorted(anaconda.id.storage.mountpoints.keys(), reverse=True) # We don't want to copy the root filesystem. mountpoints.remove("/") stats = {} # mountpoint: posix.stat_result # unmount the filesystems, except for / _setupFilesystems(anaconda.id.storage.mountpoints, teardown=True) # mount all of the filesystems under /mnt so we can copy in content _setupFilesystems(anaconda.id.storage.mountpoints, chroot=anaconda.rootPath + "/mnt") # And now let's do the real copies for tocopy in mountpoints: device = anaconda.id.storage.mountpoints[tocopy] # FIXME: all calls to wait.refresh() are kind of a hack... we # should do better about not doing blocking things in the # main thread. but threading anaconda is a job for another # time. wait.refresh() if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)): # the directory does not exist in the live image, so there's # nothing to move continue iutil.copytree("%s/%s" % (anaconda.rootPath, tocopy), "%s/mnt/%s" % (anaconda.rootPath, tocopy), True, True, flags.selinux) wait.refresh() shutil.rmtree("%s/%s" % (anaconda.rootPath, tocopy)) wait.refresh() # now unmount each fs, collect stat info for the mountpoint, then # remove the entire tree containing the mountpoint for tocopy in mountpoints: device = anaconda.id.storage.mountpoints[tocopy] device.format.teardown() if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)): continue try: stats[tocopy] = os.stat("%s/mnt/%s" % (anaconda.rootPath, tocopy)) except Exception as e: log.info("failed to get stat info for mountpoint %s: %s" % (tocopy, e)) shutil.rmtree("%s/mnt/%s" % (anaconda.rootPath, tocopy.split("/")[1])) wait.refresh() # now mount all of the filesystems so that post-install writes end # up where they're supposed to end up _setupFilesystems(anaconda.id.storage.mountpoints, chroot=anaconda.rootPath) # restore stat info for each mountpoint for mountpoint in reversed(mountpoints): if mountpoint not in stats: # there's no info to restore since the mountpoint did not # exist in the live image continue dest = "%s/%s" % (anaconda.rootPath, mountpoint) st = stats[mountpoint] # restore the correct stat info for this mountpoint os.utime(dest, (st.st_atime, st.st_mtime)) os.chown(dest, st.st_uid, st.st_gid) os.chmod(dest, stat.S_IMODE(st.st_mode)) # ensure that non-fstab filesystems are mounted in the chroot if flags.selinux: try: isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" % (e, ))
def postAction(self, anaconda): silvereye.InstallClass.postAction(self, anaconda) # XXX: use proper constants for path names def copy_script(src, dest, mode=0770): shutil.copyfile('/tmp/updates/scripts/%s' % src, '%s%s' % (anaconda.rootPath, dest)) os.chmod('%s%s' % (anaconda.rootPath, dest), mode) def copy_file(src, dest): copy_script(src, dest, mode=0644) copy_script('eucalyptus-frontend-config.sh', '/usr/local/sbin/eucalyptus-frontend-config') copy_script('eucalyptus-teardown', '/usr/local/sbin/eucalyptus-teardown') copy_script('install-unpacked-image.py', '/usr/local/sbin/install-unpacked-image.py') copy_script('eucalyptus-setup.init', '/etc/init.d/eucalyptus-setup') copy_script('register_cloud_start', '/usr/local/sbin/register_cloud_start', mode=0755) os.mkdir('%s/tmp/img' % anaconda.rootPath) # EKI shutil.copyfile('/tmp/updates/scripts/vmlinuz-kexec', '%s/tmp/img/vmlinuz-kexec' % anaconda.rootPath) # ERI shutil.copyfile('/tmp/updates/scripts/initramfs-kexec', '%s/tmp/img/initramfs-kexec' % anaconda.rootPath) # Image kickstart newks = open('%s/tmp/ks-centos6.cfg' % anaconda.rootPath, 'w') ayum = anaconda.backend.ayum for repo in ayum.repos.listEnabled(): newks.write('repo --name=%s --baseurl=%s\n' % (repo.name, repo.baseurl[0])) for line in open('/tmp/updates/ks-centos6.cfg', 'r').readlines(): if line.startswith('repo '): continue newks.write(line) newks.close() # Image creation script copy_script('ami_creator.py', '/tmp/ami_creator.py') # XXX clean this up bindmount = False if ayum._baseRepoURL and ayum._baseRepoURL.startswith("file://"): os.mkdir('/mnt/sysimage/mnt/source') isys.mount('/mnt/source', '/mnt/sysimage/mnt/source', bindMount=True) bindmount = True # eucalyptus.conf fragment from config screen w = anaconda.intf.progressWindow( _("Creating EMI"), _("Creating an initial CentOS 6 EMI."), 100) shutil.copyfile( '/tmp/eucalyptus.conf', '%s/etc/eucalyptus/eucalyptus.conf.anaconda' % anaconda.rootPath) copy_script( 'eucalyptus-firstboot-final.py', '/usr/share/firstboot/modules/eucalyptus-firstboot-final.py') postscriptlines = """ /usr/sbin/euca_conf --upgrade-conf /etc/eucalyptus/eucalyptus.conf.anaconda chkconfig dnsmasq off chkconfig eucalyptus-cloud off chkconfig eucalyptus-setup on """ postscript = AnacondaKSScript(postscriptlines, inChroot=True, logfile='/root/frontend-ks-post.log', type=KS_SCRIPT_POST) postscript.run(anaconda.rootPath, flags.serial, anaconda.intf) # TODO: Add status line for text mode pkgstatus = None if anaconda.id.displayMode == 'g': import gtk pkgstatus = gtk.Label("Preparing to install...") w.window.child.add(pkgstatus) pkgstatus.show() messages = '/root/ami-creation.log' rc = iutil.execWithCallback( '/bin/sh', ['-c', 'cd /tmp/img; /tmp/ami_creator.py -c /tmp/ks-centos6.cfg'], stdin=messages, stdout=messages, stderr=messages, root='/mnt/sysimage', callback=imageProgress, callback_data=ImageProgress(w, pkgstatus)) if bindmount: isys.umount('/mnt/sysimage/mnt/source') w.pop()
def getRPMFilename(self, h, timer, callback=None): if h[1000002] == None or 1000002 not in h.keys(): log ("header for %s has no disc location tag, assuming it's" "on the current CD" %(h[1000000],)) elif h[1000002] not in self.currentDisc: timer.stop() log("switching from iso %s to %s for %s-%s-%s.%s" %(self.currentDisc, h[1000002], h['name'], h['version'], h['release'], h['arch'])) if os.access("/mnt/source/.discinfo", os.R_OK): f = open("/mnt/source/.discinfo") timestamp = f.readline().strip() f.close() else: timestamp = self.timestamp if self.timestamp is None: self.timestamp = timestamp needed = h[1000002] # if self.currentDisc is empty, then we shouldn't have anything # mounted. double-check by trying to unmount, but we don't want # to get into a loop of trying to unmount forever. if # self.currentDisc is set, then it should still be mounted and # we want to loop until it unmounts successfully if not self.currentDisc: try: isys.umount("/mnt/source") except: pass else: self.unmountCD() done = 0 cdlist = [] for (dev, something, descript) in \ kudzu.probe(kudzu.CLASS_CDROM, kudzu.BUS_UNSPEC, 0): cdlist.append(dev) for dev in cdlist: try: if not isys.mount(dev, "/mnt/source", fstype = "iso9660", readOnly = 1): if os.access("/mnt/source/.discinfo", os.R_OK): f = open("/mnt/source/.discinfo") newStamp = f.readline().strip() try: descr = f.readline().strip() except: descr = None try: arch = f.readline().strip() except: arch = None try: discNum = getDiscNums(f.readline().strip()) except: discNum = [ 0 ] f.close() if (newStamp == timestamp and arch == _arch and needed in discNum): done = 1 self.currentDisc = discNum if not done: isys.umount("/mnt/source") except: pass if done: break if not done: isys.ejectCdrom(self.device) while not done: self.messageWindow(_("Change CDROM"), _("Please insert disc %d to continue.") % needed) try: if isys.mount(self.device, "/mnt/source", fstype = "iso9660", readOnly = 1): time.sleep(3) isys.mount(self.device, "/mnt/source", fstype = "iso9660", readOnly = 1) if os.access("/mnt/source/.discinfo", os.R_OK): f = open("/mnt/source/.discinfo") newStamp = f.readline().strip() try: descr = f.readline().strip() except: descr = None try: arch = f.readline().strip() except: arch = None try: discNum = getDiscNums(f.readline().strip()) except: discNum = [ 0 ] f.close() if (newStamp == timestamp and arch == _arch and needed in discNum): done = 1 self.currentDisc = discNum # make /tmp/cdrom again so cd gets ejected isys.makeDevInode(self.device, "/tmp/cdrom") if not done: self.messageWindow(_("Wrong CDROM"), _("That's not the correct %s CDROM.") % (productName,)) isys.umount("/mnt/source") isys.ejectCdrom(self.device) except: self.messageWindow(_("Error"), _("The CDROM could not be mounted.")) timer.start() # if we haven't read a timestamp yet, let's try to get one if (self.timestamp is None and os.access("/mnt/source/.discinfo", os.R_OK)): try: f = open("/mnt/source/.discinfo") self.timestamp = f.readline().strip() f.close() except: pass tmppath = self.getTempPath() tries = 0 # FIXME: should retry a few times then prompt for new cd while tries < 5: try: shutil.copy("%s/%s/RPMS/%s" % (self.tree, productPath, h[1000000]), tmppath + h[1000000]) except IOError, (errnum, msg): log("IOError %s occurred copying %s: %s", errnum, h[1000000], str(msg)) time.sleep(5) else: break tries = tries + 1
def findIsoImages(path, messageWindow): files = os.listdir(path) arch = _arch discImages = {} for file in files: what = path + '/' + file if not isys.isIsoImage(what): continue isys.makeDevInode("loop2", "/tmp/loop2") try: isys.losetup("/tmp/loop2", what, readOnly = 1) except SystemError: continue try: isys.mount("loop2", "/mnt/cdimage", fstype = "iso9660", readOnly = 1) for num in range(1, 10): if os.access("/mnt/cdimage/.discinfo", os.R_OK): f = open("/mnt/cdimage/.discinfo") try: f.readline() # skip timestamp f.readline() # skip release description discArch = string.strip(f.readline()) # read architecture discNum = getDiscNums(f.readline().strip()) except: discArch = None discNum = [ 0 ] f.close() if num not in discNum or discArch != arch: continue # if it's disc1, it needs to have RedHat/base/stage2.img if (num == 1 and not os.access("/mnt/cdimage/%s/base/stage2.img" % (productPath,), os.R_OK)): continue # warn user if images appears to be wrong size if os.stat(what)[stat.ST_SIZE] % 2048: rc = messageWindow(_("Warning"), "The ISO image %s has a size which is not " "a multiple of 2048 bytes. This may mean " "it was corrupted on transfer to this computer." "\n\n" "It is recommended that you reboot and abort your " "installation, but you can choose to continue if " "you think this is in error." % (file,), type="custom", custom_icon="warning", custom_buttons= [_("_Reboot"), _("_Continue")]) if rc == 0: sys.exit(0) discImages[num] = file isys.umount("/mnt/cdimage") except SystemError: pass isys.makeDevInode("loop2", '/tmp/' + "loop2") isys.unlosetup("/tmp/loop2") return discImages
def runRescue(anaconda, instClass): for file in [ "services", "protocols", "group", "joe", "man.config", "nsswitch.conf", "selinux", "mke2fs.conf" ]: try: os.symlink('/mnt/runtime/etc/' + file, '/etc/' + file) except: pass # see if they would like networking enabled if not network.hasActiveNetDev(): screen = SnackScreen() while True: rc = ButtonChoiceWindow(screen, _("Setup Networking"), _("Do you want to start the network interfaces on " "this system?"), [_("Yes"), _("No")]) if rc != string.lower(_("No")): anaconda.intf = RescueInterface(screen) if not anaconda.intf.enableNetwork(anaconda): anaconda.intf.messageWindow(_("No Network Available"), _("Unable to activate a networking device. Networking " "will not be available in rescue mode.")) break startNetworking(anaconda.id.network, anaconda.intf) break else: break anaconda.intf = None screen.finish() # Early shell access with no disk access attempts if not anaconda.rescue_mount: # the %post should be responsible for mounting all needed file systems # NOTE: 1st script must be bash or simple python as nothing else might be available in the rescue image if anaconda.isKickstart and anaconda.id.ksdata.scripts: from kickstart import runPostScripts runPostScripts(anaconda) else: runShell() sys.exit(0) screen = SnackScreen() anaconda.intf = RescueInterface(screen) if anaconda.isKickstart: if anaconda.id.ksdata.rescue and anaconda.id.ksdata.rescue.romount: readOnly = 1 else: readOnly = 0 else: # prompt to see if we should try and find root filesystem and mount # everything in /etc/fstab on that root while True: rc = ButtonChoiceWindow(screen, _("Rescue"), _("The rescue environment will now attempt to find your " "Linux installation and mount it under the directory " "%s. You can then make any changes required to your " "system. If you want to proceed with this step choose " "'Continue'. You can also choose to mount your file systems " "read-only instead of read-write by choosing 'Read-Only'. " "If you need to activate SAN devices choose 'Advanced'." "\n\n" "If for some reason this process fails you can choose 'Skip' " "and this step will be skipped and you will go directly to a " "command shell.\n\n") % (anaconda.rootPath,), [_("Continue"), _("Read-Only"), _("Skip"), _("Advanced")] ) if rc == string.lower(_("Skip")): runShell(screen) sys.exit(0) elif rc == string.lower(_("Advanced")): addDialog = addDriveDialog(anaconda) addDialog.addDriveDialog(screen) continue elif rc == string.lower(_("Read-Only")): readOnly = 1 else: readOnly = 0 break import storage storage.storageInitialize(anaconda) disks = upgrade.findExistingRoots(anaconda, upgradeany=True) if not disks: root = None elif (len(disks) == 1) or anaconda.isKickstart: root = disks[0] else: height = min (len (disks), 12) if height == 12: scroll = 1 else: scroll = 0 devList = [] for (device, relstr) in disks: if getattr(device.format, "label", None): devList.append("%s (%s) - %s" % (device.name, device.format.label, relstr)) else: devList.append("%s - %s" % (device.name, relstr)) (button, choice) = \ ListboxChoiceWindow(screen, _("System to Rescue"), _("Which device holds the root partition " "of your installation?"), devList, [ _("OK"), _("Exit") ], width = 30, scroll = scroll, height = height, help = "multipleroot") if button == string.lower (_("Exit")): root = None else: root = disks[choice] rootmounted = 0 if root: try: rc = mountExistingSystem(anaconda, root, allowDirty = 1, warnDirty = 1, readOnly = readOnly) if rc == -1: if anaconda.isKickstart: log.error("System had dirty file systems which you chose not to mount") else: ButtonChoiceWindow(screen, _("Rescue"), _("Your system had dirty file systems which you chose not " "to mount. Press return to get a shell from which " "you can fsck and mount your partitions. The system " "will reboot automatically when you exit from the " "shell."), [_("OK")], width = 50) rootmounted = 0 else: if anaconda.isKickstart: log.info("System has been mounted under: %s" % anaconda.rootPath) else: ButtonChoiceWindow(screen, _("Rescue"), _("Your system has been mounted under %(rootPath)s.\n\n" "Press <return> to get a shell. If you would like to " "make your system the root environment, run the command:\n\n" "\tchroot %(rootPath)s\n\nThe system will reboot " "automatically when you exit from the shell.") % {'rootPath': anaconda.rootPath}, [_("OK")] ) rootmounted = 1 # now turn on swap if not readOnly: try: anaconda.id.storage.turnOnSwap() except: log.error("Error enabling swap") # and /selinux too if flags.selinux and os.path.isdir("%s/selinux" %(anaconda.rootPath,)): try: isys.mount("/selinux", "%s/selinux" %(anaconda.rootPath,), "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" %(e,)) fd = open("%s/.autorelabel" % anaconda.rootPath, "w+") fd.close() # set a library path to use mounted fs libdirs = os.environ["LD_LIBRARY_PATH"].split(":") mounted = map(lambda dir: "/mnt/sysimage%s" % dir, libdirs) os.environ["LD_LIBRARY_PATH"] = ":".join(libdirs + mounted) # find groff data dir try: glst = os.listdir("/mnt/sysimage/usr/share/groff") # find a directory which is a numeral, its where # data files are gversion = None for gdir in glst: try: isone = 1 for idx in range(0, len(gdir)): if string.find(string.digits + '.', gdir[idx]) == -1: isone = 0 break if isone: gversion = gdir break except: gversion = None continue except: gversion = None if gversion is not None: gpath = "/mnt/sysimage/usr/share/groff/"+gversion os.environ["GROFF_FONT_PATH"] = gpath + '/font' os.environ["GROFF_TMAC_PATH"] = "%s:/mnt/sysimage/usr/share/groff/site-tmac" % (gpath + '/tmac',) # do we have bash? try: if os.access("/usr/bin/bash", os.R_OK): os.symlink ("/usr/bin/bash", "/bin/bash") except: pass except: # This looks horrible, but all it does is catch every exception, # and reraise those in the tuple check. This lets programming # errors raise exceptions, while any runtime error will # still result in a shell (exc, val) = sys.exc_info()[0:2] log.error(str(exc)+": "+str(val)) if exc in (IndexError, ValueError, SyntaxError): raise exc, val, sys.exc_info()[2] if anaconda.isKickstart: log.error("An error occurred trying to mount some or all of your system") else: ButtonChoiceWindow(screen, _("Rescue"), _("An error occurred trying to mount some or all of your " "system. Some of it may be mounted under %s.\n\n" "Press <return> to get a shell. The system will reboot " "automatically when you exit from the shell.") % (anaconda.rootPath,), [_("OK")] ) else: if anaconda.isKickstart and \ anaconda.id.ksdata.reboot.action in [KS_REBOOT, KS_SHUTDOWN]: log.info("No Linux partitions found") screen.finish() print(_("You don't have any Linux partitions. Rebooting.\n")) sys.exit(0) else: ButtonChoiceWindow(screen, _("Rescue Mode"), _("You don't have any Linux partitions. Press " "return to get a shell. The system will reboot " "automatically when you exit from the shell."), [ _("OK") ], width = 50) msgStr = "" if rootmounted and not readOnly: makeMtab(anaconda.rootPath, anaconda.id.storage) try: makeResolvConf(anaconda.rootPath) except Exception, e: log.error("error making a resolv.conf: %s" %(e,)) msgStr = _("Your system is mounted under the %s directory.") % (anaconda.rootPath,) ButtonChoiceWindow(screen, _("Rescue"), msgStr, [_("OK")] )
def _doFilesystemMangling(self, anaconda): log.info("doing post-install fs mangling") wait = anaconda.intf.waitWindow(_("Post-Installation"), _("Performing post-installation filesystem changes. This may take several minutes.")) # resize rootfs first, since it is 100% full due to genMinInstDelta self._resizeRootfs(anaconda, wait) # remount filesystems anaconda.id.storage.mountFilesystems() # restore the label of / to what we think it is rootDevice = anaconda.id.storage.rootDevice rootDevice.setup() # ensure we have a random UUID on the rootfs # FIXME: this should be abstracted per filesystem type iutil.execWithRedirect("tune2fs", ["-U", "random", rootDevice.path], stdout="/dev/tty5", stderr="/dev/tty5") # and now set the uuid in the storage layer rootDevice.updateSysfsPath() iutil.notify_kernel("/sys%s" %rootDevice.sysfsPath) storage.udev.udev_settle() rootDevice.updateSysfsPath() info = storage.udev.udev_get_block_device(rootDevice.sysfsPath) rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info) log.info("reset the rootdev (%s) to have a uuid of %s" %(rootDevice.sysfsPath, rootDevice.format.uuid)) # for any filesystem that's _not_ on the root, we need to handle # moving the bits from the livecd -> the real filesystems. # this is pretty distasteful, but should work with things like # having a separate /usr/local def _setupFilesystems(mounts, chroot="", teardown=False): """ Setup or teardown all filesystems except for "/" """ mountpoints = sorted(mounts.keys(), reverse=teardown is True) if teardown: method = "teardown" kwargs = {} else: method = "setup" kwargs = {"chroot": chroot} mountpoints.remove("/") for mountpoint in mountpoints: device = mounts[mountpoint] getattr(device.format, method)(**kwargs) # Start by sorting the mountpoints in decreasing-depth order. mountpoints = sorted(anaconda.id.storage.mountpoints.keys(), reverse=True) # We don't want to copy the root filesystem. mountpoints.remove("/") stats = {} # mountpoint: posix.stat_result # unmount the filesystems, except for / _setupFilesystems(anaconda.id.storage.mountpoints, teardown=True) # mount all of the filesystems under /mnt so we can copy in content _setupFilesystems(anaconda.id.storage.mountpoints, chroot=anaconda.rootPath + "/mnt") # And now let's do the real copies for tocopy in mountpoints: device = anaconda.id.storage.mountpoints[tocopy] # FIXME: all calls to wait.refresh() are kind of a hack... we # should do better about not doing blocking things in the # main thread. but threading anaconda is a job for another # time. wait.refresh() if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)): # the directory does not exist in the live image, so there's # nothing to move continue copytree("%s/%s" % (anaconda.rootPath, tocopy), "%s/mnt/%s" % (anaconda.rootPath, tocopy), True, True, flags.selinux) wait.refresh() shutil.rmtree("%s/%s" % (anaconda.rootPath, tocopy)) wait.refresh() # now unmount each fs, collect stat info for the mountpoint, then # remove the entire tree containing the mountpoint for tocopy in mountpoints: device = anaconda.id.storage.mountpoints[tocopy] device.format.teardown() if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)): continue try: stats[tocopy]= os.stat("%s/mnt/%s" % (anaconda.rootPath, tocopy)) except Exception as e: log.info("failed to get stat info for mountpoint %s: %s" % (tocopy, e)) shutil.rmtree("%s/mnt/%s" % (anaconda.rootPath, tocopy.split("/")[1])) wait.refresh() # now mount all of the filesystems so that post-install writes end # up where they're supposed to end up _setupFilesystems(anaconda.id.storage.mountpoints, chroot=anaconda.rootPath) # restore stat info for each mountpoint for mountpoint in reversed(mountpoints): if mountpoint not in stats: # there's no info to restore since the mountpoint did not # exist in the live image continue dest = "%s/%s" % (anaconda.rootPath, mountpoint) st = stats[mountpoint] # restore the correct stat info for this mountpoint os.utime(dest, (st.st_atime, st.st_mtime)) os.chown(dest, st.st_uid, st.st_gid) os.chmod(dest, stat.S_IMODE(st.st_mode)) # ensure that non-fstab filesystems are mounted in the chroot if flags.selinux: try: isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" %(e,))
def _doFilesystemMangling(self, anaconda): # FIXME: this whole method is a big f*****g mess log.info("doing post-install fs mangling") wait = anaconda.intf.waitWindow(_("Post-Installation"), _("Performing post-installation filesystem changes. This may take several minutes.")) # resize rootfs first, since it is 100% full due to genMinInstDelta self._resizeRootfs(anaconda, wait) # remount filesystems anaconda.storage.mountFilesystems() # restore the label of / to what we think it is rootDevice = anaconda.storage.rootDevice rootDevice.setup() # ensure we have a random UUID on the rootfs # FIXME: this should be abstracted per filesystem type iutil.execWithRedirect("tune2fs", ["-U", "random", rootDevice.path], stdout="/dev/tty5", stderr="/dev/tty5") # and now set the uuid in the storage layer rootDevice.updateSysfsPath() iutil.notify_kernel("/sys%s" %rootDevice.sysfsPath) storage.udev.udev_settle() rootDevice.updateSysfsPath() info = storage.udev.udev_get_block_device(rootDevice.sysfsPath) rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info) log.info("reset the rootdev (%s) to have a uuid of %s" %(rootDevice.sysfsPath, rootDevice.format.uuid)) # for any filesystem that's _not_ on the root, we need to handle # moving the bits from the livecd -> the real filesystems. # this is pretty distasteful, but should work with things like # having a separate /usr/local # now create a tree so that we know what's mounted under where fsdict = {"/": []} for mount in sorted(anaconda.storage.mountpoints.keys()): entry = anaconda.storage.mountpoints[mount] tocopy = entry.format.mountpoint if tocopy.startswith("/mnt") or tocopy == "swap": continue keys = sorted(fsdict.keys(), reverse = True) for key in keys: if tocopy.startswith(key): fsdict[key].append(entry) break fsdict[tocopy] = [] log.debug("mangling dict looks like %s" %(fsdict,)) # and now let's do the real copies; and we don't want to copy /! copied = ["/"] for tocopy in sorted(fsdict.keys()): if tocopy in copied: continue copied.append(tocopy) copied.extend(map(lambda x: x.format.mountpoint, fsdict[tocopy])) entry = anaconda.storage.mountpoints[tocopy] # FIXME: all calls to wait.refresh() are kind of a hack... we # should do better about not doing blocking things in the # main thread. but threading anaconda is a job for another # time. wait.refresh() # unmount subdirs + this one and then remount under /mnt for e in fsdict[tocopy] + [entry]: e.format.teardown() for e in [entry] + fsdict[tocopy]: e.format.setup(chroot=anaconda.rootPath + "/mnt") copytree("%s/%s" %(anaconda.rootPath, tocopy), "%s/mnt/%s" %(anaconda.rootPath, tocopy), True, True, flags.selinux) shutil.rmtree("%s/%s" %(anaconda.rootPath, tocopy)) wait.refresh() # mount it back in the correct place for e in fsdict[tocopy] + [entry]: e.format.teardown() try: os.rmdir("%s/mnt/%s" %(anaconda.rootPath, e.format.mountpoint)) except OSError as e: log.debug("error removing %s" %(tocopy,)) for e in [entry] + fsdict[tocopy]: e.format.setup(chroot=anaconda.rootPath) wait.refresh() # ensure that non-fstab filesystems are mounted in the chroot if flags.selinux: try: isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" %(e,))
def runRescue(anaconda): for file in [ "services", "protocols", "group", "joe", "man.config", "nsswitch.conf", "selinux", "mke2fs.conf" ]: try: os.symlink('/mnt/runtime/etc/' + file, '/etc/' + file) except: pass # see if they would like networking enabled if not methodUsesNetworking(anaconda.id.methodstr): screen = SnackScreen() while 1: rc = ButtonChoiceWindow(screen, _("Setup Networking"), _("Do you want to start the network interfaces on " "this system?"), [_("Yes"), _("No")]) if rc != string.lower(_("No")): anaconda.intf = RescueInterface(screen) # need to call sequence of screens, have to look in text.py # # this code is based on main loop in text.py, and if it # or the network step in dispatch.py change significantly # then this will certainly break # pyfile = "network_text" classNames = ("NetworkDeviceWindow", "NetworkGlobalWindow") lastrc = INSTALL_OK step = 0 anaconda.dir = 1 while 1: s = "from %s import %s; nextWindow = %s" % \ (pyfile, classNames[step], classNames[step]) exec s win = nextWindow() rc = win(screen, anaconda, showonboot = 0) if rc == INSTALL_NOOP: rc = lastrc if rc == INSTALL_BACK: step = step - 1 anaconda.dir = - 1 elif rc == INSTALL_OK: step = step + 1 anaconda.dir = 1 lastrc = rc if step == -1: ButtonChoiceWindow(screen, _("Cancelled"), _("I can't go to the previous step " "from here. You will have to try " "again."), buttons=[_("OK")]) anaconda.dir = 1 step = 0 elif step >= len(classNames): break startNetworking(anaconda.id.network, anaconda.intf, anaconda) break else: break screen.finish() # Early shell access with no disk access attempts if not anaconda.rescue_mount: runShell() sys.exit(0) # need loopback devices too for lpminor in range(8): dev = "loop%s" % (lpminor,) isys.makeDevInode(dev, "/dev/" + dev) screen = SnackScreen() anaconda.intf = RescueInterface(screen) anaconda.setMethod() # prompt to see if we should try and find root filesystem and mount # everything in /etc/fstab on that root rc = ButtonChoiceWindow(screen, _("Rescue"), _("The rescue environment will now attempt to find your " "Linux installation and mount it under the directory " "%s. You can then make any changes required to your " "system. If you want to proceed with this step choose " "'Continue'. You can also choose to mount your file systems " "read-only instead of read-write by choosing 'Read-Only'." "\n\n" "If for some reason this process fails you can choose 'Skip' " "and this step will be skipped and you will go directly to a " "command shell.\n\n") % (anaconda.rootPath,), [_("Continue"), _("Read-Only"), _("Skip")] ) if rc == string.lower(_("Skip")): runShell(screen) sys.exit(0) elif rc == string.lower(_("Read-Only")): readOnly = 1 else: readOnly = 0 disks = upgrade.findExistingRoots(anaconda, upgradeany = 1) if not disks: root = None elif len(disks) == 1: root = disks[0] else: height = min (len (disks), 12) if height == 12: scroll = 1 else: scroll = 0 partList = [] for (drive, fs, relstr, label) in disks: if label: partList.append("%s (%s)" % (drive, label)) else: partList.append(drive) (button, choice) = \ ListboxChoiceWindow(screen, _("System to Rescue"), _("What partition holds the root partition " "of your installation?"), partList, [ _("OK"), _("Exit") ], width = 30, scroll = scroll, height = height, help = "multipleroot") if button == string.lower (_("Exit")): root = None else: root = disks[choice] rootmounted = 0 if root: try: fs = fsset.FileSystemSet(anaconda) # only pass first two parts of tuple for root, since third # element is a comment we dont want rc = upgrade.mountRootPartition(anaconda, root[:2], fs, allowDirty = 1, warnDirty = 1, readOnly = readOnly) if rc == -1: ButtonChoiceWindow(screen, _("Rescue"), _("Your system had dirty file systems which you chose not " "to mount. Press return to get a shell from which " "you can fsck and mount your partitions. The system " "will reboot automatically when you exit from the " "shell."), [_("OK")], width = 50) rootmounted = 0 else: ButtonChoiceWindow(screen, _("Rescue"), _("Your system has been mounted under %s.\n\n" "Press <return> to get a shell. If you would like to " "make your system the root environment, run the command:\n\n" "\tchroot %s\n\nThe system will reboot " "automatically when you exit from the shell.") % (anaconda.rootPath, anaconda.rootPath), [_("OK")] ) rootmounted = 1 # now turn on swap if not readOnly: try: fs.turnOnSwap("/") except: log.error("Error enabling swap") # now that dev is udev, bind mount the installer dev there isys.mount("/dev", "%s/dev" %(anaconda.rootPath,), bindMount = 1) # and /dev/pts isys.mount("/dev/pts", "%s/dev/pts" %(anaconda.rootPath,), bindMount = 1) # and /selinux too if flags.selinux and os.path.isdir("%s/selinux" %(anaconda.rootPath,)): try: isys.mount("/selinux", "%s/selinux" %(anaconda.rootPath,), "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" %(e,)) # set a library path to use mounted fs os.environ["LD_LIBRARY_PATH"] = "/lib:/usr/lib:/usr/X11R6/lib:/lib:/mnt/usr/lib:/mnt/sysimage/lib:/mnt/sysimage/usr/lib:/mnt/sysimage/usr/X11R6/lib" # get man pages to work os.environ["MANPATH"] = "/mnt/sysimage/usr/share/man:/mnt/sysimage/usr/local/share/man:/usr/share/man:/usr/local/share/man" # find groff data dir try: glst = os.listdir("/mnt/sysimage/usr/share/groff") # find a directory which is a numeral, its where # data files are gversion = None for gdir in glst: try: isone = 1 for idx in range(0, len(gdir)): if string.find(string.digits + '.', gdir[idx]) == -1: isone = 0 break if isone: gversion = gdir break except: gversion = None continue except: gversion = None if gversion is not None: gpath = "/mnt/sysimage/usr/share/groff/"+gversion os.environ["GROFF_FONT_PATH"] = gpath + '/font' os.environ["GROFF_TMAC_PATH"] = "%s:/mnt/sysimage/usr/share/groff/site-tmac" % (gpath + '/tmac',) # do we have bash? try: if os.access("/usr/bin/bash", os.R_OK): os.symlink ("/usr/bin/bash", "/bin/bash") except: pass except: # This looks horrible, but all it does is catch every exception, # and reraise those in the tuple check. This lets programming # errors raise exceptions, while any runtime error will # still result in a shell. (exc, val) = sys.exc_info()[0:2] log.error(val) if exc in (IndexError, ValueError, SyntaxError): raise exc, val, sys.exc_info()[2] ButtonChoiceWindow(screen, _("Rescue"), _("An error occurred trying to mount some or all of your " "system. Some of it may be mounted under %s.\n\n" "Press <return> to get a shell. The system will reboot " "automatically when you exit from the shell.") % (anaconda.rootPath,), [_("OK")] ) else: ButtonChoiceWindow(screen, _("Rescue Mode"), _("You don't have any Linux partitions. Press " "return to get a shell. The system will reboot " "automatically when you exit from the shell."), [ _("OK") ], width = 50) msgStr = "" if rootmounted and not readOnly: makeMtab(anaconda.rootPath, fs) try: makeResolvConf(anaconda.rootPath) except Exception, e: log.error("error making a resolv.conf: %s" %(e,)) msgStr = _("Your system is mounted under the %s directory.") % (anaconda.rootPath,)
def setup(self, command=None, argv=None): iutil.mkdirChain(self.smart_dir) iutil.mkdirChain(self.anaconda.backend.instPath + "/install/tmp") buf = """#!/bin/bash export PATH="${PATH}" export D="%s" export OFFLINE_ROOT="$D" export IPKG_OFFLINE_ROOT="$D" export OPKG_OFFLINE_ROOT="$D" export INTERCEPT_DIR="/" export NATIVE_ROOT="/" exec 1>>/tmp/scriptlet.log 2>&1 echo $2 $1/$3 $4 if [ $2 = "/bin/sh" ]; then $2 -x $1/$3 $4 else $2 $1/$3 $4 fi if [ $? -ne 0 ]; then if [ $4 -eq 1 ]; then mkdir -p $1/etc/rpm-postinsts num=100 while [ -e $1/etc/rpm-postinsts/${num}-* ]; do num=$((num + 1)); done name=`head -1 $1/$3 | cut -d' ' -f 2` echo "#!$2" > $1/etc/rpm-postinsts/${num}-${name} echo "# Arg: $4" >> $1/etc/rpm-postinsts/${num}-${name} cat $1/$3 >> $1/etc/rpm-postinsts/${num}-${name} chmod +x $1/etc/rpm-postinsts/${num}-${name} else echo "Error: pre/post remove scriptlet failed" fi fi """ % (self.anaconda.backend.instPath) fd = open( self.anaconda.backend.instPath + "/install/scriptlet_wrapper", "w") fd.write(buf) fd.close() os.chmod(self.anaconda.backend.instPath + "/install/scriptlet_wrapper", 0755) self.smart_ctrl = init(command, argv=argv, datadir=self.smart_dir, configfile=None, gui=False, shell=False, quiet=True, interface=None, forcelocks=False, loglevel=None) # Override the dummy interface with the locally defined one iface.object = AnacondaInterface(self.smart_ctrl, self.anaconda) initDistro(self.smart_ctrl) initPlugins() initPycurl() initPsyco() sysconf.set("rpm-root", self.anaconda.backend.instPath, soft=True) sysconf.set("rpm-extra-macros._tmppath", "/install/tmp", soft=True) sysconf.set("rpm-extra-macros._cross_scriptlet_wrapper", self.anaconda.backend.instPath + "/install/scriptlet_wrapper", soft=True) sysconf.set("rpm-nolinktos", "1") sysconf.set("rpm-noparentdirs", "1") if self.anaconda.upgrade: # Note: # This is a fix, we didn't remove the channels that we added in # previous installs, so remove them here. #FIXME: Do we need disable user's channels ? self.removeWrlLoclRepo() # Enable the installed RPM DB channels = sysconf.get("channels") or {} if 'rpmsys' not in channels: self.runSmart('channel', ['--add', 'rpmsys', 'type=rpm-sys', '-y']) iface.object.hideStatus() else: # Ensure we start with a blank channel set... sysconf.remove("channels") self.repos = AnacondaSmartRepo("anaconda-config", self.anaconda) # Setup repository for localpath in [ "/mnt/install/source", "/mnt/install/cdimage", "/mnt/install/isodir", "" ]: if os.path.isdir("%s/Packages" % localpath) and os.access( "%s/Packages/.feedpriority" % localpath, os.R_OK): f = open("%s/Packages/.feedpriority" % localpath) for line in f: (priority, feed) = line.split() if os.path.isdir("%s/Packages/%s/repodata" % (localpath, feed)): repo = SmartRepo("media_%s" % feed) repo.name = "Install Media feed for %s" % feed repo.cost = priority repo.baseurl = [ "file://%s/Packages/%s" % (localpath, feed) ] self.repos.add(repo) f.close() if self.anaconda.ksdata: for ksrepo in self.anaconda.ksdata.repo.repoList: # If no location was given, this must be a repo pre-configured # repo that we just want to enable. if not ksrepo.baseurl and not ksrepo.mirrorlist: self.repos.enable(ksrepo.name) continue anacondaBaseURLs = [ksrepo.baseurl] # smart doesn't understand nfs:// and doesn't want to. We need # to first do the mount, then translate it into a file:// that # smart does understand. # "nfs:" and "nfs://" prefixes are accepted in ks_repo --baseurl if ksrepo.baseurl and ksrepo.baseurl.startswith("nfs:"): #if not network.hasActiveNetDev() and not self.anaconda.intf.enableNetwork(): # self.anaconda.intf.messageWindow(_("No Network Available"), # _("Some of your software repositories require " # "networking, but there was an error enabling the " # "network on your system."), # type="custom", custom_icon="error", # custom_buttons=[_("_Exit installer")]) # sys.exit(1) dest = tempfile.mkdtemp("", ksrepo.name.replace(" ", ""), "/mnt") # handle "nfs://" prefix if ksrepo.baseurl[4:6] == '//': ksrepo.baseurl = ksrepo.baseurl.replace('//', '', 1) anacondaBaseURLs = [ksrepo.baseurl] try: isys.mount(ksrepo.baseurl[4:], dest, "nfs") except Exception as e: log.error("error mounting NFS repo: %s" % e) ksrepo.baseurl = "file://%s" % dest repo = SmartRepo(ksrepo.name) repo.mirrorlist = ksrepo.mirrorlist repo.name = ksrepo.name if not ksrepo.baseurl: repo.baseurl = [] else: repo.baseurl = [ksrepo.baseurl] repo.anacondaBaseURLs = anacondaBaseURLs if ksrepo.cost: repo.cost = ksrepo.cost if ksrepo.excludepkgs: repo.exclude = ksrepo.excludepkgs if ksrepo.includepkgs: repo.includepkgs = ksrepo.includepkgs if ksrepo.noverifyssl: repo.sslverify = False if ksrepo.proxy: self.setProxy(ksrepo, repo) self.repos.add(repo) self.smart_ctrl.saveSysConf() self.smart_ctrl.restoreMediaState() self.doRepoSetup(self.anaconda)
def findFirstIsoImage(path, messageWindow): """ Find the first iso image in path This also supports specifying a specific .iso image Returns the full path to the image """ flush = os.stat(path) arch = _arch if os.path.isfile(path) and path.endswith(".iso"): files = [os.path.basename(path)] path = os.path.dirname(path) else: files = os.listdir(path) for fn in files: what = path + '/' + fn log.debug("Checking %s" % (what)) if not isys.isIsoImage(what): continue log.debug("mounting %s on /mnt/install/cdimage", what) try: isys.mount(what, "/mnt/install/cdimage", fstype="iso9660", readOnly=True) except SystemError: continue if not os.access("/mnt/install/cdimage/.discinfo", os.R_OK): isys.umount("/mnt/install/cdimage", removeDir=False) continue log.debug("Reading .discinfo") f = open("/mnt/install/cdimage/.discinfo") f.readline() # skip timestamp f.readline() # skip release description discArch = f.readline().strip() # read architecture f.close() log.debug("discArch = %s" % discArch) if discArch != arch: log.warning("findFirstIsoImage: architectures mismatch: %s, %s" % (discArch, arch)) isys.umount("/mnt/install/cdimage", removeDir=False) continue # If there's no repodata, there's no point in trying to # install from it. if not os.access("/mnt/install/cdimage/repodata", os.R_OK): log.warning("%s doesn't have repodata, skipping" %(what,)) isys.umount("/mnt/install/cdimage", removeDir=False) continue # warn user if images appears to be wrong size if os.stat(what)[stat.ST_SIZE] % 2048: rc = messageWindow(_("Warning"), _("The ISO image %s has a size which is not " "a multiple of 2048 bytes. This may mean " "it was corrupted on transfer to this computer." "\n\n" "It is recommended that you exit and abort your " "installation, but you can choose to continue if " "you think this is in error.") % (fn,), type="custom", custom_icon="warning", custom_buttons= [_("_Exit installer"), _("_Continue")]) if rc == 0: sys.exit(0) log.info("Found disc at %s" % fn) isys.umount("/mnt/install/cdimage", removeDir=False) return what return None
def findFirstIsoImage(path, messageWindow): flush = os.stat(path) files = os.listdir(path) arch = _arch for file in files: what = path + '/' + file log.debug("Checking %s" % (what)) if not isys.isIsoImage(what): continue try: log.debug("mounting %s on /mnt/cdimage", what) isys.mount(what, "/mnt/cdimage", fstype = "iso9660", readOnly = True) if os.access("/mnt/cdimage/.discinfo", os.R_OK): log.debug("Reading .discinfo") f = open("/mnt/cdimage/.discinfo") try: f.readline() # skip timestamp f.readline() # skip release description discArch = string.strip(f.readline()) # read architecture except: discArch = None f.close() log.debug("discArch = %s" % discArch) if discArch != arch: isys.umount("/mnt/cdimage", removeDir=False) continue # If there's no repodata, there's no point in trying to # install from it. if not os.access("/mnt/cdimage/repodata", os.R_OK): log.warning("%s doesn't have repodata, skipping" %(what,)) isys.umount("/mnt/cdimage", removeDir=False) continue # warn user if images appears to be wrong size if os.stat(what)[stat.ST_SIZE] % 2048: rc = messageWindow(_("Warning"), _("The ISO image %s has a size which is not " "a multiple of 2048 bytes. This may mean " "it was corrupted on transfer to this computer." "\n\n" "It is recommended that you exit and abort your " "installation, but you can choose to continue if " "you think this is in error.") % (file,), type="custom", custom_icon="warning", custom_buttons= [_("_Exit installer"), _("_Continue")]) if rc == 0: sys.exit(0) log.info("Found disc at %s" % file) isys.umount("/mnt/cdimage", removeDir=False) return file except SystemError: pass return None
if iutil.getArch() != "ia64": args = ['mkdosfs', '/tmp/floppy'] cmd = "/usr/sbin/mkdosfs" if os.access("/sbin/mkdosfs", os.X_OK): cmd = "/sbin/mkdosfs" iutil.execWithRedirect(cmd, args, stdout='/dev/tty5', stderr='/dev/tty5') try: isys.mount(device, "/tmp/crash", fstype="vfat") except SystemError: continue # copy trace dump we wrote to local storage to floppy try: iutil.copyFile("/tmp/anacdump.txt", "/tmp/crash/anacdump.txt") except: log("Failed to copy anacdump.txt to floppy") pass isys.umount("/tmp/crash") intf.messageWindow( _("Dump Written"), _("Your system's state has been successfully written to the "
my_fs = {"sda9": "ext4", "sda5": "ntfs", "sda10": "ext2", "sda11": "reiserfs", "sda8": "ext3", } if case == '1': # Test mount function. for key in my_fs.keys(): fstype = fstype_map[my_fs[key]][0] #print fs mntpoint = "/media/%s" % key if not os.path.exists(mntpoint): os.mkdir(mntpoint) dev_path = "/dev/%s" % key isys.mount(fstype, dev_path, mntpoint, 'ro') if case == '2': # Test iso9660 mount. fstype = fstype_map["iso9660"][0] dev_path = "/mnt/sda12/MagicLinux-2.5-1.iso" mntpoint = "/media/loop1" if not os.path.exists(mntpoint): os.mkdir(mntpoint) ext_flags = "loop" # ext_flags can be remount,ro,user,noauto,unhide... and other optlist in -o # option. isys.mount(fstype, dev_path, mntpoint, ext_flags) if case == '3': # Test umount function. for key in my_fs.keys():