def create(self):
        """
        Newly creates the logical volume
        """
        LinuxVolumeManager.has_lvm()
        size=""

        if self.ondisk and self.getAttribute("overwrite", "false") == "true":
            self.remove()

        try:
            self.init_from_disk()
        except:
            pass

        if self.ondisk:
            raise LinuxVolumeManager.LVMAlreadyExistsException(self.__class__.__name__+"("+str(self.getAttribute("name"))+")")
        try:
            size=self.getAttribute("size")
            if int(self.getAttribute("size")) > int(self.parentvg.getAttribute("free")):
                ComLog.getLogger(self.__logStrLevel__).warn("Requested LV size %s is too big taking free %s" % (self.getAttribute("size"), self.parentvg.getAttribute("free")))
                self.setAttribute("size", self.parentvg.getAttribute("free"))
                size=self.getAttribute("size")
        except NameError:
            if ComSystem.isSimulate():
                size="1000"
            else:
                size=self.parentvg.getAttribute("free")
        LinuxVolumeManager.lvm('lvcreate', '-L %sM' %size, '-n %s' %str(self.getAttribute("name")), '%s' %str(self.parentvg.getAttribute("name")))
        self.init_from_disk()
        if ComSystem.isSimulate():
            self.ondisk=True
    def init_from_disk(self):
        """
      Initializes this physical volume from disk and reads all attributes and sets them
      """
        LinuxVolumeManager.has_lvm()

        self.ondisk = False
        rv = LinuxVolumeManager.lvmarray(
            "pvdisplay",
            "-C",
            "--noheadings",
            "--units b",
            "--nosuffix",
            "--separator :",
            str(self.getAttribute("name")),
        )

        for line in rv:
            try:
                (pvname, vgname, format, attr, size, free) = line.strip().split(":")
                self.setAttribute("format", format)
                self.setAttribute("attr", attr)
                self.setAttribute("size", long(math.floor(long(size) / (1024 * 1024))))
                self.setAttribute("free", long(math.floor(long(free) / (1024 * 1024))))
            except:
                continue
            if not self.parentvg and vgname:
                self.parentvg = VolumeGroup(vgname, self)
                self.parentvg.init_from_disk()
        if not ComSystem.isSimulate():
            self.ondisk = True
示例#3
0
    def init_from_disk(self):
        """
        Initializes this volume group from disk and reads all attributes and sets them
        """
        LinuxVolumeManager.has_lvm()
        self.ondisk = False

        rv = LinuxVolumeManager.lvmarray('vgdisplay', '-C', '--noheadings',
                                         '--units b', '--nosuffix',
                                         '--separator : ',
                                         str(self.getAttribute("name")))

        for line in rv:
            try:
                (vgname, numpvs, numlvs, serial, attrs, size,
                 free) = line.strip().split(':')
                if vgname == self.getAttribute("name"):
                    self.setAttribute("numpvs", numpvs)
                    self.setAttribute("numlvs", numlvs)
                    self.setAttribute("serial", serial)
                    self.setAttribute("attrs", attrs)
                    self.setAttribute(
                        "size",
                        str(long(math.floor(long(size) / (1024 * 1024)))))
                    self.setAttribute(
                        "free", long(math.floor(long(free) / (1024 * 1024))))
            except:
                continue
        if not ComSystem.isSimulate():
            self.ondisk = True
    def create(self):
        """
        Creates this volumegroup
        """

        LinuxVolumeManager.has_lvm()

        if self.ondisk and self.getAttribute("overwrite", "false") == "true":
            for lv in self.lvs:
                lv.remove()
            self.remove()

        try:
            self.init_from_disk()
        except:
            pass

        if self.ondisk:
            raise LinuxVolumeManager.LVMAlreadyExistsException(self.__class__.__name__+"("+str(self.getAttribute("name"))+")")
        _cmdoptions=list()
        try:
            _cmdoptions.append("--physicalextentsize %sk" % self.getAttribute("pe_size"))
        except:
            pass

        if self.isClustered():
            _cmdoptions.append("--clustered y")
        else:
            _cmdoptions.append("--clustered n")
        LinuxVolumeManager.lvm('vgcreate', '%s %s %s' % (" ".join(_cmdoptions), str(self.getAttribute("name")), ' '.join(self.getPhysicalVolumeMap().keys())))
        self.init_from_disk()
        if ComSystem.isSimulate():
            self.ondisk=True
    def init_from_disk(self):
        """
      Initializes this volume group from disk and reads all attributes and sets them
      """
        LinuxVolumeManager.has_lvm()
        self.ondisk = False

        rv = LinuxVolumeManager.lvmarray(
            "vgdisplay",
            "-C",
            "--noheadings",
            "--units b",
            "--nosuffix",
            "--separator : ",
            str(self.getAttribute("name")),
        )

        for line in rv:
            try:
                (vgname, numpvs, numlvs, serial, attrs, size, free) = line.strip().split(":")
                if vgname == self.getAttribute("name"):
                    self.setAttribute("numpvs", numpvs)
                    self.setAttribute("numlvs", numlvs)
                    self.setAttribute("serial", serial)
                    self.setAttribute("attrs", attrs)
                    self.setAttribute("size", str(long(math.floor(long(size) / (1024 * 1024)))))
                    self.setAttribute("free", long(math.floor(long(free) / (1024 * 1024))))
            except:
                continue
        if not ComSystem.isSimulate():
            self.ondisk = True
    def init_from_disk(self):
        """
      Initializes this logical volume from disk and reads all attributes and sets them
      """
        LinuxVolumeManager.has_lvm()

        try:
            rv = LinuxVolumeManager.lvmarray(
                "lvdisplay",
                "-C",
                "--noheadings",
                "--units b",
                "--nosuffix",
                "--separator : ",
                str(self.parentvg.getAttribute("name")) + "/" + str(self.getAttribute("name")),
            )
            self.ondisk = False
            # FIXME
            # an exception should be thrown, if lvdisplay output has changed the syntax.
            # do we really need the for loop ?
            for line in rv:
                try:
                    (attrs, size, origin) = line.strip().split(":")[2:5]
                    self.setAttribute("attrs", attrs)
                    self.setAttribute("size", long(math.floor(long(size) / (1024 * 1024))))
                    self.setAttribute("origin", origin)
                except:
                    # FIXME
                    # this should be fixed to get an exception if the values cannot be parsed.
                    continue

            if not ComSystem.isSimulate():
                self.ondisk = True
        except LinuxVolumeManager.LVMCommandException:
            pass
示例#7
0
    def create(self):
        """
        Newly creates the physical volume
        """
        LinuxVolumeManager.has_lvm()
        if self.ondisk and self.getAttribute("overwrite", "false") == "true":
            for lv in self.parentvg.lvs:
                lv.delete()
            self.parentvg.remove()
            self.remove()

        try:
            self.init_from_disk()
        except:
            pass

        if self.ondisk:
            raise LinuxVolumeManager.LVMAlreadyExistsException(
                self.__class__.__name__ + "(" +
                str(self.getAttribute("name")) + ")")
        LinuxVolumeManager.lvm('pvcreate', '-f', '-v', '-y',
                               str(self.getAttribute("name")))
        self.init_from_disk()
        if ComSystem.isSimulate():
            self.ondisk = True
示例#8
0
    def doPost(self):
        """
        Does something afterwards
        """
        srcfile = self.getAttribute("name")
        destfile = self.getAttribute("dest")

        if self.check() and not ComSystem.isSimulate():
            if not os.access(srcfile, os.R_OK) or not os.access(
                    destfile, os.F_OK) or not os.access(destfile, os.W_OK):
                raise ArchiveRequirementException(
                    "Either srcfile %s is not readable or dest %s is not writeable"
                    % (srcfile, destfile))
        ComSystem.execMethod(os.chdir, destfile)
        __cmd = "cp %s %s" % (srcfile, srcfile +
                              self.getAttribute("bak_suffix", ".bak"))
        try:
            (rc, rv, stderr) = ComSystem.execLocalGetResult(__cmd, True)
            if rc >> 8 != 0:
                raise RuntimeError(
                    "running \"%s\" failed: %u, %s, errors: %s" %
                    (__cmd, rc, rv, stderr))
        except RuntimeError, re:
            ComLog.getLogger(ArchiveRequirement.__logStrLevel__).warn(
                "Cannot backup sourcefile %s=%s, %s." %
                (srcfile, srcfile + ".bak", re))
    def init_from_disk(self):
        """
        Initializes this logical volume from disk and reads all attributes and sets them
        """
        LinuxVolumeManager.has_lvm()

        try:
            rv=LinuxVolumeManager.lvmarray('lvdisplay', '-C', '--noheadings', '--units b', '--nosuffix', '--separator : ', str(self.parentvg.getAttribute("name"))+"/"+str(self.getAttribute("name")))
            self.ondisk=False
            #FIXME
            # an exception should be thrown, if lvdisplay output has changed the syntax.
            # do we really need the for loop ?
            for line in rv:
                try:
                    if line.count(":") == 8:
                        (lvname, vgname, attrs, size, origin, snap, move, log, copy) = line.strip().split(':')
                    else:
                        #This is for newer lvm implementations.
                        (lvname, vgname, attrs, size, origin, snap, move, log, copy, convert) = line.strip().split(':')
                    self.setAttribute("attrs", attrs)
                    self.setAttribute("size", long(math.floor(long(size) / (1024 * 1024))))
                    self.setAttribute("origin", origin)
                except:
                    #FIXME
                    # this should be fixed to get an exception if the values cannot be parsed.
                    continue

            if not ComSystem.isSimulate():
                self.ondisk=True
        except LinuxVolumeManager.LVMCommandException:
            pass
示例#10
0
    def init_from_disk(self):
        """
        Initializes this physical volume from disk and reads all attributes and sets them
        """
        LinuxVolumeManager.has_lvm()

        self.ondisk = False
        rv = LinuxVolumeManager.lvmarray('pvdisplay', '-C', '--noheadings',
                                         '--units b', '--nosuffix',
                                         '--separator :',
                                         str(self.getAttribute("name")))

        for line in rv:
            try:
                (pvname, vgname, format, attr, size,
                 free) = line.strip().split(':')
                self.setAttribute("format", format)
                self.setAttribute("attr", attr)
                self.setAttribute("size",
                                  long(math.floor(long(size) / (1024 * 1024))))
                self.setAttribute("free",
                                  long(math.floor(long(free) / (1024 * 1024))))
            except:
                continue
        if not ComSystem.isSimulate():
            self.ondisk = True
示例#11
0
    def doPre(self):
        """
        Unpacks the given file to dest
        """
        srcfile = self.getAttribute("name")
        destfile = self.getAttribute("dest")
        __mkdir = self.getAttributeBoolean("mkdir", default=True)

        if not ComSystem.execMethod(os.path.exists, destfile) and __mkdir:
            ComLog.getLogger(ArchiveRequirement.__logStrLevel__).debug(
                "Path %s does not exists. I'll create it." % destfile)
            os.makedirs(destfile)

        if self.check() and not ComSystem.isSimulate():
            if not os.access(srcfile, os.R_OK) or not os.access(
                    destfile, os.F_OK) or not os.access(destfile, os.W_OK):
                raise ArchiveRequirementException(
                    "Either srcfile %s is not readable or dest %s is not writeable"
                    % (srcfile, destfile))

        __cmd = "rm -rf %s/*" % destfile
        (rc, rv) = ComSystem.execLocalGetResult(__cmd)
        if rc >> 8 != 0:
            raise RuntimeError("running \"%s\" failed: %u, %s" %
                               (__cmd, rc, rv))

        self.olddir = os.curdir
        ComSystem.execMethod(os.chdir, destfile)
        __cmd = "gzip -cd %s | cpio -i" % srcfile
        (rc, rv, stderr) = ComSystem.execLocalGetResult(__cmd, True)
        if rc >> 8 != 0:
            raise RuntimeError("running \"%s\" failed: %u, %s, %s" %
                               (__cmd, rc, rv, stderr))
    def doPre(self):
        """
        Unpacks the given file to dest
        """
        srcfile=self.getAttribute("name")
        destfile=self.getAttribute("dest")
        __mkdir=self.getAttributeBoolean("mkdir", default=True)

        if not ComSystem.execMethod(os.path.exists, destfile) and __mkdir:
            ComLog.getLogger(ArchiveRequirement.__logStrLevel__).debug("Path %s does not exists. I'll create it." % destfile)
            os.makedirs(destfile)

        if self.check() and not ComSystem.isSimulate():
            if not os.access(srcfile, os.R_OK) or not os.access(destfile, os.F_OK) or not os.access(destfile, os.W_OK):
                raise ArchiveRequirementException("Either srcfile %s is not readable or dest %s is not writeable" % (srcfile, destfile))

        __cmd="rm -rf %s/*" % destfile
        (rc, rv) = ComSystem.execLocalGetResult(__cmd)
        if rc >> 8 != 0:
            raise RuntimeError("running \"%s\" failed: %u, %s" % (__cmd, rc,rv))

        self.olddir=os.curdir
        ComSystem.execMethod(os.chdir, destfile)
        __cmd="gzip -cd %s | cpio -i" % srcfile
        (rc, rv, stderr) = ComSystem.execLocalGetResult(__cmd, True)
        if rc >> 8 != 0:
            raise RuntimeError("running \"%s\" failed: %u, %s, %s" % (__cmd, rc,rv, stderr))
 def __prepare(self):
     import os
     self.origpath = self.path.getPath()
     ComSystem.execMethod(self.path.mkdir)
     ComSystem.execMethod(self.path.pushd, self.path.getPath())
     if not ComSystem.isSimulate():
         self.journal(self.path, "pushd", self.path.getPath())
     PathCopyObject.logger.debug("prepareAsSource() CWD: " + os.getcwd())
 def __prepare(self):
     import os
     self.origpath=self.path.getPath()
     ComSystem.execMethod(self.path.mkdir)
     ComSystem.execMethod(self.path.pushd, self.path.getPath())
     if not ComSystem.isSimulate():
         self.journal(self.path, "pushd")
     PathCopyObject.logger.debug("prepareAsSource() CWD: " + os.getcwd())
示例#15
0
 def __init__(self):
     if os.path.isfile(RedHatClusterHelper.defaultclusterstatus_cmd
                       ) or ComSystem.isSimulate():
         self.clusterstatus_cmd = RedHatClusterHelper.defaultclusterstatus_cmd
         self.clusterstatus_opts = RedHatClusterHelper.defaultclusterstatus_opts
     else:
         raise HelperNotSupportedError(
             "The helperclass RedHatClusterHelper is not supported in this environment."
         )
示例#16
0
    def __init__(self, *params):
        '''
        Constructor

        Valid Constructors are:
        __init__(element, doc=None)
        __init__(name, _pv=None, doc=None)
        '''

        self.pvs = dict()
        self.lvs = dict()

        if (len(params) == 1) or (len(params) == 2
                                  and isinstance(params[1], PhysicalVolume)):
            doc = doc = xml.dom.getDOMImplementation().createDocument(
                None, None, None)
        elif (len(params) == 2) and not isinstance(params[1], PhysicalVolume):
            doc = params[1]
        else:
            raise IndexError(
                "Index out of range for Volume Group constructor (%u)" %
                len(params))

        if isinstance(params[0], Node):
            self.log.debug(
                "createing volumegroup %s/%s from element" %
                (params[0].tagName, str(params[0].getAttribute("name"))))
            LinuxVolumeManager.__init__(self, params[0], params[1])
            # init all lvs
            __lvs = self.getElement().getElementsByTagName(
                LogicalVolume.TAGNAME)
            for i in range(len(__lvs)):
                self.addLogicalVolume(LogicalVolume(__lvs[i], self, doc))
            # init all pvs
            __pvs = self.getElement().getElementsByTagName(
                PhysicalVolume.TAGNAME)
            for i in range(len(__pvs)):
                self.addPhysicalVolume(PhysicalVolume(__pvs[i], self, doc))
        elif isinstance(params[0], basestring):
            self.log.debug("createing volumegroup %s from new element" %
                           params[0])
            LinuxVolumeManager.__init__(self, doc.createElement(self.TAGNAME),
                                        doc)
            self.setAttribute("name", params[0])
            if len(params) > 1 and isinstance(params[1], PhysicalVolume):
                self.addPhysicalVolume(params[1])
        else:
            raise TypeError("Unsupported type for constructor %s" %
                            type(params[0]))
        try:
            LinuxVolumeManager.lvm(
                'pvscan', ' | grep "[[:blank:]]%s[[:blank:]]"' %
                str(self.getAttribute("name")))
            if not ComSystem.isSimulate():
                self.ondisk = True
        except LinuxVolumeManager.LVMCommandException:
            pass
示例#17
0
    def has_lvm():
        '''
        Just checks if lvm functionality is available.
        Returns true or raises an exception (RuntimeException)
        '''
        if ComSystem.isSimulate():
            return 1
        CMD_LVM = "/usr/sbin/lvm"
        if not (os.access(CMD_LVM, os.X_OK)
                or os.access("/sbin/lvm", os.X_OK)):
            raise RuntimeError("LVM binaries do not seam to be available")

        if not (os.access(CMD_LVM, os.X_OK)) and (os.access(
                "/sbin/lvm", os.X_OK)):
            CMD_LVM = "/sbin/lvm"

        try:
            _cachedir = LinuxVolumeManager.lvm("dumpconfig",
                                               "devices/cache_dir")
            _cachedir.strip()
        except LinuxVolumeManager.LVMCommandException:
            if not ComSystem.isSimulate() and not os.access(
                    "/etc/lvm/.cache", os.R_OK) and not os.access(
                        "/etc/lvm/cache/.cache", os.R_OK):
                raise RuntimeError("LVM could not read lvm cache file")

        f = open("/proc/devices", "r")
        lines = f.readlines()
        f.close()

        for line in lines:
            try:
                (dev, name) = line[:-1].split(' ', 2)
            except:
                continue
            if name == "device-mapper":
                __lvmDevicePresent__ = 1
                break

        if __lvmDevicePresent__ == 0:
            raise RuntimeError(
                "LVM Functionality does not seam to be available")
        return 1
    def has_lvm():
        """
      Just checks if lvm functionality is available.
      Returns true or raises an exception (RuntimeException)
      """
        if ComSystem.isSimulate():
            return 1
        CMD_LVM = "/usr/sbin/lvm"
        if not (os.access(CMD_LVM, os.X_OK) or os.access("/sbin/lvm", os.X_OK)):
            raise RuntimeError("LVM binaries do not seam to be available")

        if not (os.access(CMD_LVM, os.X_OK)) and (os.access("/sbin/lvm", os.X_OK)):
            CMD_LVM = "/sbin/lvm"

        try:
            _cachedir = LinuxVolumeManager.lvm("dumpconfig", "devices/cache_dir")
            _cachedir.strip()
        except LinuxVolumeManager.LVMCommandException:
            if (
                not ComSystem.isSimulate()
                and not os.access("/etc/lvm/.cache", os.R_OK)
                and not os.access("/etc/lvm/cache/.cache", os.R_OK)
            ):
                raise RuntimeError("LVM could not read lvm cache file")

        f = open("/proc/devices", "r")
        lines = f.readlines()
        f.close()

        for line in lines:
            try:
                (dev, name) = line[:-1].split(" ", 2)
            except:
                continue
            if name == "device-mapper":
                __lvmDevicePresent__ = 1
                break

        if __lvmDevicePresent__ == 0:
            raise RuntimeError("LVM Functionality does not seam to be available")
        return 1
示例#19
0
    def create(self):
        """
        Newly creates the logical volume
        """
        LinuxVolumeManager.has_lvm()
        size = ""

        if self.ondisk and self.getAttribute("overwrite", "false") == "true":
            self.remove()

        try:
            self.init_from_disk()
        except:
            pass

        if self.ondisk:
            raise LinuxVolumeManager.LVMAlreadyExistsException(
                self.__class__.__name__ + "(" +
                str(self.getAttribute("name")) + ")")
        try:
            size = self.getAttribute("size")
            if int(self.getAttribute("size")) > int(
                    self.parentvg.getAttribute("free")):
                ComLog.getLogger(self.__logStrLevel__).warn(
                    "Requested LV size %s is too big taking free %s" %
                    (self.getAttribute("size"),
                     self.parentvg.getAttribute("free")))
                self.setAttribute("size", self.parentvg.getAttribute("free"))
                size = self.getAttribute("size")
        except NameError:
            if ComSystem.isSimulate():
                size = "1000"
            else:
                size = self.parentvg.getAttribute("free")
        LinuxVolumeManager.lvm('lvcreate', '-L %sM' % size,
                               '-n %s' % str(self.getAttribute("name")),
                               '%s' % str(self.parentvg.getAttribute("name")))
        self.init_from_disk()
        if ComSystem.isSimulate():
            self.ondisk = True
    def __init__(self, *params):
        """
      Constructor

      Valid Constructors are:
      __init__(element, doc=None)
      __init__(name, _pv=None, doc=None)
      """

        self.pvs = dict()
        self.lvs = dict()

        if (len(params) == 1) or (len(params) == 2 and isinstance(params[1], PhysicalVolume)):
            doc = doc = xml.dom.getDOMImplementation().createDocument(None, None, None)
        elif (len(params) == 2) and not isinstance(params[1], PhysicalVolume):
            doc = params[1]
        else:
            raise IndexError("Index out of range for Volume Group constructor (%u)" % len(params))

        if isinstance(params[0], Node):
            self.log.debug(
                "createing volumegroup %s/%s from element" % (params[0].tagName, str(params[0].getAttribute("name")))
            )
            LinuxVolumeManager.__init__(self, params[0], params[1])
            # init all lvs
            __lvs = self.getElement().getElementsByTagName(LogicalVolume.TAGNAME)
            for i in range(len(__lvs)):
                self.addLogicalVolume(LogicalVolume(__lvs[i], self, doc))
            # init all pvs
            __pvs = self.getElement().getElementsByTagName(PhysicalVolume.TAGNAME)
            for i in range(len(__pvs)):
                self.addPhysicalVolume(PhysicalVolume(__pvs[i], self, doc))
        elif isinstance(params[0], basestring):
            self.log.debug("createing volumegroup %s from new element" % params[0])
            LinuxVolumeManager.__init__(self, doc.createElement(self.TAGNAME), doc)
            self.setAttribute("name", params[0])
            if len(params) > 1 and isinstance(params[1], PhysicalVolume):
                self.addPhysicalVolume(params[1])
        else:
            raise TypeError("Unsupported type for constructor %s" % type(params[0]))
        try:
            LinuxVolumeManager.lvm("pvscan", ' | grep "[[:blank:]]%s[[:blank:]]"' % str(self.getAttribute("name")))
            if not ComSystem.isSimulate():
                self.ondisk = True
        except LinuxVolumeManager.LVMCommandException:
            pass
    def doPost(self):
        """
        Does something afterwards
        """
        srcfile=self.getAttribute("name")
        destfile=self.getAttribute("dest")

        if self.check() and not ComSystem.isSimulate():
            if not os.access(srcfile, os.R_OK) or not os.access(destfile, os.F_OK) or not os.access(destfile, os.W_OK):
                raise ArchiveRequirementException("Either srcfile %s is not readable or dest %s is not writeable" % (srcfile, destfile))
        ComSystem.execMethod(os.chdir, destfile)
        __cmd="cp %s %s" %(srcfile, srcfile+self.getAttribute("bak_suffix", ".bak"))
        try:
            (rc, rv, stderr) = ComSystem.execLocalGetResult(__cmd, True)
            if rc >> 8 != 0:
                raise RuntimeError("running \"%s\" failed: %u, %s, errors: %s" % (__cmd, rc,rv, stderr))
        except RuntimeError, re:
            ComLog.getLogger(ArchiveRequirement.__logStrLevel__).warn("Cannot backup sourcefile %s=%s, %s." %(srcfile, srcfile+".bak", re))
def test_tools(tools=[ "sg_persist" ]):
    import os
    notfoundtools=list()
    try:
        from comoonics import ComSystem
        if ComSystem.isSimulate():
            return notfoundtools
    except:
        pass
    for tool in tools:
        found=False
        for path in os.environ['PATH'].split(":"):
            cmd=os.path.join(path, tool)
            if os.path.exists(cmd) and os.access(cmd, os.X_OK):
                found=True
        if not found:
            notfoundtools.append(tool)
    return notfoundtools
def test_tools(tools=["sg_persist"]):
    import os
    notfoundtools = list()
    try:
        from comoonics import ComSystem
        if ComSystem.isSimulate():
            return notfoundtools
    except:
        pass
    for tool in tools:
        found = False
        for path in os.environ['PATH'].split(":"):
            cmd = os.path.join(path, tool)
            if os.path.exists(cmd) and os.access(cmd, os.X_OK):
                found = True
        if not found:
            notfoundtools.append(tool)
    return notfoundtools
    def init_from_disk(self):
        """
        Initializes this physical volume from disk and reads all attributes and sets them
        """
        LinuxVolumeManager.has_lvm()

        self.ondisk=False
        rv=LinuxVolumeManager.lvmarray('pvdisplay', '-C', '--noheadings', '--units b', '--nosuffix', '--separator :', str(self.getAttribute("name")))

        for line in rv:
            try:
                (pvname, vgname, format, attr, size, free) = line.strip().split(':')
                self.setAttribute("format", format)
                self.setAttribute("attr", attr)
                self.setAttribute("size", long(math.floor(long(size) / (1024 * 1024))))
                self.setAttribute("free", long(math.floor(long(free) / (1024 * 1024))))
            except:
                continue
        if not ComSystem.isSimulate():
            self.ondisk=True
    def create(self):
        """
        Newly creates the physical volume
        """
        LinuxVolumeManager.has_lvm()
        if self.ondisk and self.getAttribute("overwrite", "false") == "true":
            for lv in self.parentvg.lvs:
                lv.delete()
            self.parentvg.remove()
            self.remove()

        try:
            self.init_from_disk()
        except:
            pass

        if self.ondisk:
            raise LinuxVolumeManager.LVMAlreadyExistsException(self.__class__.__name__+"("+str(self.getAttribute("name"))+")")
        LinuxVolumeManager.lvm('pvcreate', '-f', '-v', '-y', str(self.getAttribute("name")))
        self.init_from_disk()
        if ComSystem.isSimulate():
            self.ondisk=True
示例#26
0
    def create(self):
        """
        Creates this volumegroup
        """

        LinuxVolumeManager.has_lvm()

        if self.ondisk and self.getAttribute("overwrite", "false") == "true":
            for lv in self.lvs:
                lv.remove()
            self.remove()

        try:
            self.init_from_disk()
        except:
            pass

        if self.ondisk:
            raise LinuxVolumeManager.LVMAlreadyExistsException(
                self.__class__.__name__ + "(" +
                str(self.getAttribute("name")) + ")")
        _cmdoptions = list()
        try:
            _cmdoptions.append("--physicalextentsize %sk" %
                               self.getAttribute("pe_size"))
        except:
            pass

        if self.isClustered():
            _cmdoptions.append("--clustered y")
        else:
            _cmdoptions.append("--clustered n")
        LinuxVolumeManager.lvm(
            'vgcreate', '%s %s %s' %
            (" ".join(_cmdoptions), str(self.getAttribute("name")), ' '.join(
                self.getPhysicalVolumeMap().keys())))
        self.init_from_disk()
        if ComSystem.isSimulate():
            self.ondisk = True
示例#27
0
    def init_from_disk(self):
        """
        Initializes this logical volume from disk and reads all attributes and sets them
        """
        LinuxVolumeManager.has_lvm()

        try:
            rv = LinuxVolumeManager.lvmarray(
                'lvdisplay', '-C', '--noheadings', '--units b', '--nosuffix',
                '--separator : ',
                str(self.parentvg.getAttribute("name")) + "/" +
                str(self.getAttribute("name")))
            self.ondisk = False
            #FIXME
            # an exception should be thrown, if lvdisplay output has changed the syntax.
            # do we really need the for loop ?
            for line in rv:
                try:
                    if line.count(":") == 8:
                        (lvname, vgname, attrs, size, origin, snap, move, log,
                         copy) = line.strip().split(':')
                    else:
                        #This is for newer lvm implementations.
                        (lvname, vgname, attrs, size, origin, snap, move, log,
                         copy, convert) = line.strip().split(':')
                    self.setAttribute("attrs", attrs)
                    self.setAttribute(
                        "size", long(math.floor(long(size) / (1024 * 1024))))
                    self.setAttribute("origin", origin)
                except:
                    #FIXME
                    # this should be fixed to get an exception if the values cannot be parsed.
                    continue

            if not ComSystem.isSimulate():
                self.ondisk = True
        except LinuxVolumeManager.LVMCommandException:
            pass
示例#28
0
class BaseTestFileSystem(unittest.TestCase):
    xml = None
    filesystem = None
    device = None
    mountpoint = None
    commands = None
    simmethods = None
    name = ""
    label = "mylabel"

    def setUp(self):
        from comoonics import XmlTools
        import StringIO
        from comoonics.storage.ComDevice import Device
        from comoonics.storage.ComMountpoint import MountPoint
        from comoonics.storage.ComFileSystem import getFileSystem

        xmlfp = StringIO.StringIO(self.xml)
        doc = XmlTools.parseXMLFP(xmlfp)
        __device = doc.documentElement

        self.device = Device(__device, doc)
        __fs = __device.getElementsByTagName("filesystem")[0]
        self.filesystem = getFileSystem(__fs, doc)
        __mp = __device.getElementsByTagName("mountpoint")[0]
        self.mountpoint = MountPoint(__mp, doc)

    def _testMethod(self, method, execmode, *params):
        oldmode = ComSystem.getExecMode()
        ComSystem.clearSimCommands()
        ComSystem.setExecMode(execmode)
        try:
            method(*params)
        except Exception, e:
            import traceback
            traceback.print_exc()
            self.fail(
                "Could not execute %s method on with parameters %s, Error: %s"
                % (method, params, e))
        if self.simmethods and ComSystem.isSimulate():
            errormethods = list()
            for simmethod in ComSystem.getSimCommands():
                matched = False
                for simmethod2 in self.simmethods:
                    if not matched and isinstance(simmethod2, basestring):
                        matched = simmethod == simmethod2
                    elif not matched:
                        # Must be re
                        matched = simmethod2.match(simmethod)
                if matched == False:
                    errormethods.append(simmethod)
            if len(errormethods) > 0:
                bufsimmethods = list()
                for simmethod in self.simmethods:
                    if isinstance(simmethod, basestring):
                        bufsimmethods.append(simmethod)
                    else:
                        bufsimmethods.append(simmethod.pattern)
                self.fail(
                    """The commands being executed are not to be found in the commands that must have been executed.
Commands that could not be matched are:
%s
Executed commands are: 
%s
Expected commands are:
%s
""" % ("\n".join(errormethods), "\n".join(
                        ComSystem.getSimCommands()), "\n".join(bufsimmethods)))
        ComSystem.setExecMode(oldmode)
 def __init__(self):
     if os.path.isfile(RedHatClusterHelper.defaultclusterstatus_cmd) or ComSystem.isSimulate():
         self.clusterstatus_cmd=RedHatClusterHelper.defaultclusterstatus_cmd
         self.clusterstatus_opts=RedHatClusterHelper.defaultclusterstatus_opts
     else:
         raise HelperNotSupportedError("The helperclass RedHatClusterHelper is not supported in this environment.")