コード例 #1
0
def setSize(path, size, confirm):
    sizeMB = size / (1024 * 1024)
    cmd = [CMD_LVRESIZE, "-L", str(sizeMB), path]
    if confirm:
        util.pread3(cmd, "y\n")
    else:
        util.pread(cmd)
コード例 #2
0
    def _probe_hba(self):
        try:
            # use sysfs tree to gather FC data

            dom = xml.dom.minidom.Document()
            hbalist = dom.createElement("HBAInfoList")
            dom.appendChild(hbalist)

            hostlist = util.listdir("/sys/class/fc_host")
            for host in hostlist: 

                hbainfo = dom.createElement("HBAInfo")
                hbalist.appendChild(hbainfo)

                cmd = ["cat", "/sys/class/fc_host/%s/symbolic_name" % host]
                sname = util.pread(cmd)[:-1]
                entry = dom.createElement("model")
                hbainfo.appendChild(entry)
                textnode = dom.createTextNode(sname)
                entry.appendChild(textnode)

                cmd = ["cat", "/sys/class/fc_host/%s/node_name" % host]
                nname = util.pread(cmd)[:-1]
                nname = util.make_WWN(nname)
                entry = dom.createElement("nodeWWN")
                hbainfo.appendChild(entry)
                # adjust nodename to look like expected string
                textnode = dom.createTextNode(nname)
                entry.appendChild(textnode)

                port = dom.createElement("Port")
                hbainfo.appendChild(port)

                cmd = ["cat", "/sys/class/fc_host/%s/port_name" % host]
                pname = util.pread(cmd)[:-1]
                pname = util.make_WWN(pname)
                entry = dom.createElement("portWWN")
                port.appendChild(entry)
                # adjust nodename to look like expected string
                textnode = dom.createTextNode(pname)
                entry.appendChild(textnode)

                cmd = ["cat", "/sys/class/fc_host/%s/port_state" % host]
                state = util.pread(cmd)[:-1]
                entry = dom.createElement("state")
                port.appendChild(entry)
                # adjust nodename to look like expected string
                textnode = dom.createTextNode(state)
                entry.appendChild(textnode)

                entry = dom.createElement("deviceName")
                port.appendChild(entry)
                # adjust nodename to look like expected string
                textnode = dom.createTextNode("/sys/class/scsi_host/%s" % host)
                entry.appendChild(textnode)

            return dom.toxml()
        except:
            raise xs_errors.XenError('CSLGXMLParse', \
                                     opterr='HBA probe failed')
コード例 #3
0
ファイル: NFSSR.py プロジェクト: BobBall/sm
 def detach(self, sr_uuid):
     if not util.ioretry(lambda: self._checkmount()):
         return
     try:
         util.pread(["umount", self.path])
         os.rmdir(self.path)
     except util.CommandException, inst:
         raise xs_errors.XenError('NFSUnMount', \
               opterr='error is %d' % inst.code)
コード例 #4
0
ファイル: FileSR.py プロジェクト: falaa/sm
 def detach(self, sr_uuid):
     if self._checkmount():
         try:
             util.SMlog("Aborting GC/coalesce")
             cleanup.abort(self.uuid)
             os.chdir(SR.MOUNT_BASE)
             util.pread(["umount", self.path])
             os.rmdir(self.path)
         except Exception, e:
             raise xs_errors.XenError('SRInUse', opterr=str(e))
コード例 #5
0
ファイル: FileSR.py プロジェクト: falaa/sm
 def attach(self, sr_uuid):
     if not self._checkmount():
         try:
             util.ioretry(lambda: util.makedirs(self.path))
         except util.CommandException, inst:
             if inst.code != errno.EEXIST:
                 raise xs_errors.XenError("FileSRCreate", \
                                          opterr='fail to create mount point. Errno is %s' % inst.code)
         try:
             util.pread(["mount", "--bind", self.remotepath, self.path])
         except util.CommandException, inst:
             raise xs_errors.XenError('FileSRCreate', \
                                      opterr='fail to mount FileSR. Errno is %s' % inst.code)
コード例 #6
0
ファイル: lvutil.py プロジェクト: MarkSymsCtx/sm
def _lvmBugCleanup(path):
    # the device should not exist at this point. If it does, this was an LVM 
    # bug, and we manually clean up after LVM here
    mapperDevice = path[5:].replace("-", "--").replace("/", "-")
    mapperPath = "/dev/mapper/" + mapperDevice
            
    nodeExists = False
    cmd = [CMD_DMSETUP, "status", mapperDevice]
    try:
        util.pread(cmd, expect_rc=1)
    except util.CommandException, e:
        if e.code == 0:
            nodeExists = True
コード例 #7
0
ファイル: nfs.py プロジェクト: chandrikas/sm
def check_server_service(server):
    """Ensure NFS service is up and available on the remote server.

    Returns False if fails to detect service after 
    NFS_SERVICE_RETRY * NFS_SERVICE_WAIT
    """

    retries = 0
    errlist = [errno.EPERM, errno.EPIPE, errno.EIO]

    while True:
        try:
            services = util.pread([RPCINFO_BIN, "-s", "%s" % server])
            services = services.split("\n")
            for i in range(len(services)):
                if services[i].find("nfs") > 0:
                    return True
        except util.CommandException, inst:
            if not int(inst.code) in errlist:
                raise

        util.SMlog("NFS service not ready on server %s" % server)
        retries += 1
        if retries >= NFS_SERVICE_RETRY:
            break

        time.sleep(NFS_SERVICE_WAIT)
コード例 #8
0
ファイル: lvutil.py プロジェクト: MarkSymsCtx/sm
def removeDevMapperEntry(path, strict=True):
    try:
        # remove devmapper entry using dmsetup
        cmd = [CMD_DMSETUP, "remove", path]
        util.pread2(cmd)
        return True
    except Exception, e:
        if not strict:
            cmd = [CMD_DMSETUP, "status", path]
            try:
                util.pread(cmd, expect_rc=1)
                return True
            except:
                pass  # Continuining will fail and log the right way
        util.SMlog("removeDevMapperEntry: dmsetup remove failed for file %s " \
                   "with error %s." % (path, str(e)))
        return False
コード例 #9
0
ファイル: OCFSSR.py プロジェクト: MarkSymsCtx/sm
 def create(self, sr_uuid, size):
     if util.pathexists(self.blockdevice):
         util.zeroOut(self.blockdevice, 0, 1024 * 1024)
     cmd = ["mkfs", "-t", "ocfs2", "-b", "4K", "-C", "1M", "-N", "16", "-F", self.blockdevice]
     try:
         ret = util.pread(cmd)
     except util.CommandException, inst:
         raise xs_errors.XenError("OCFSFilesystem", opterr="mkfs failed error %d" % os.strerror(inst.code))
コード例 #10
0
ファイル: OCFSSR.py プロジェクト: Sisimon/sm
 def create(self, sr_uuid, size):
     if util.pathexists(self.blockdevice):
         util.zeroOut(self.blockdevice, 0, 1024*1024)
     cmd = ['mkfs', '-t', 'ocfs2', '-b', '4K', '-C', '1M', '-N', '16', '-F', self.blockdevice ]
     try:
         ret = util.pread(cmd)
     except util.CommandException, inst:
         raise xs_errors.XenError('OCFSFilesystem', \
               opterr='mkfs failed error %d' % os.strerror(inst.code))
コード例 #11
0
ファイル: HBASR.py プロジェクト: redivy/xe-storage-plugins
 def _probe_hba(self):
     try:
         cmd = [HBA_CLI, "xml"]
         fc_xml = util.pread(cmd)
         #strip junk until xml
         return fc_xml[fc_xml.index("<HBAInfoList>"):len(fc_xml)]
     except:
         raise xs_errors.XenError('CSLGXMLParse', \
                                  opterr='HBA probe failed')
コード例 #12
0
ファイル: FileSR.py プロジェクト: redivy/xe-storage-plugins
    def _query_info(self, path):
        diskinfo = {}
        cmd = [SR.TAPDISK_UTIL, "query", SR.DEFAULT_TAP, "-vpf", path]
        txt = util.pread(cmd).split('\n')
        diskinfo['size'] = txt[0]
	for val in filter(util.exactmatch_uuid, [txt[1].split('/')[-1].replace(".%s" % SR.DEFAULT_TAP,"")]):
            diskinfo['parent'] = val
        diskinfo['hidden'] = txt[2].split()[1]
        return diskinfo
コード例 #13
0
ファイル: FileSR.py プロジェクト: BobBall/sm
 def _query_info(self, path):
     diskinfo = {}
     cmd = [SR.TAPDISK_UTIL, "query", SR.DEFAULT_TAP, "-vpf", path]
     txt = util.pread(cmd).split('\n')
     diskinfo['size'] = txt[0]
     if txt[1].find("has no parent") == -1:
         diskinfo['parent'] = txt[1].split('/')[-1].replace(".%s" % SR.DEFAULT_TAP,"")
     diskinfo['hidden'] = txt[2].split()[1]
     return diskinfo
コード例 #14
0
ファイル: EXTSR.py プロジェクト: chandrikas/sm
    def create(self, sr_uuid, size):
        if self._checkmount():
            raise xs_errors.XenError('SRExists')

        # Check none of the devices already in use by other PBDs
        if util.test_hostPBD_devs(self.session, sr_uuid, self.root):
            raise xs_errors.XenError('SRInUse')

        # Check serial number entry in SR records
        for dev in self.root.split(','):
            if util.test_scsiserial(self.session, dev):
                raise xs_errors.XenError('SRInUse')

        if not lvutil._checkVG(self.vgname):
            lvutil.createVG(self.root, self.vgname)

        if lvutil._checkLV(self.remotepath):
            raise xs_errors.XenError('SRExists')

        try:
            numdevs = len(self.root.split(','))
            cmd = ["lvcreate", "-n", sr_uuid]
            if numdevs > 1:
                lowest = -1
                for dev in self.root.split(','):
                    stats = lvutil._getPVstats(dev)
                    if lowest < 0  or stats['freespace'] < lowest:
                        lowest = stats['freespace']
                size_mb = (lowest / (1024 * 1024)) * numdevs

                # Add stripe parameter to command
                cmd += ["-i", str(numdevs), "-I", "2048"]
            else:
                stats = lvutil._getVGstats(self.vgname)
                size_mb = stats['freespace'] / (1024 * 1024)
            assert(size_mb > 0)
            cmd += ["-L", str(size_mb), self.vgname]
            text = util.pread(cmd)

            cmd = ["lvchange", "-ay", self.remotepath]
            text = util.pread(cmd)
        except util.CommandException, inst:
            raise xs_errors.XenError('LVMCreate', \
                  opterr='lv operation, error %d' % inst.code)
コード例 #15
0
ファイル: nfs.py プロジェクト: andycjw/CloudStack
def check_server_tcp(server):
    """Make sure that NFS over TCP/IP V3 is supported on the server. 
    Returns True if everything is OK, False otherwise."""
    try:
        util.ioretry(lambda: util.pread([RPCINFO_BIN,"-t", 
                                         "%s" % server, "nfs","3"]), 
                     errlist=[errno.EPERM], maxretry=2, nofail=True)
    except util.CommandException, inst:
        raise NfsException("rpcinfo failed or timed out: return code %d" % 
                           inst.code)
コード例 #16
0
ファイル: FileSR.py プロジェクト: Sisimon/sm
 def _query_info(self, path):
     diskinfo = {}
     cmd = [SR.TAPDISK_UTIL, "query", vhdutil.VDI_TYPE_VHD, "-vpf", path]
     txt = util.pread(cmd).split('\n')
     diskinfo['size'] = txt[0]
     lst = [txt[1].split('/')[-1].replace(vhdutil.FILE_EXTN_VHD, "")]
     for val in filter(util.exactmatch_uuid, lst):
         diskinfo['parent'] = val
     diskinfo['hidden'] = txt[2].split()[1]
     return diskinfo
コード例 #17
0
ファイル: nfs.py プロジェクト: MarkSymsCtx/sm
def check_server_service(server):
    """Ensure NFS service is up and available on the remote server.

    Raises exception if fails to detect service after 
    NFS_SERVICE_RETRY * NFS_SERVICE_WAIT
    """
    util.ioretry(lambda:
                 util.pread([RPCINFO_BIN, "-t", "%s" % server, "nfs"]),
                 errlist=[errno.EPERM, errno.EPIPE, errno.EIO],
                 maxretry=NFS_SERVICE_RETRY, 
                 period=NFS_SERVICE_WAIT, nofail=True)
コード例 #18
0
def activateNoRefcount(path, refresh):
    cmd = [CMD_LVCHANGE, "-ay", path]
    if refresh:
        cmd.append("--refresh")
    text = util.pread2(cmd)
    if not _checkActive(path):
        raise util.CommandException(-1, str(cmd), "LV not activated")
    if refresh:
        mapperDevice = path[5:].replace("-", "--").replace("/", "-")
        cmd = [CMD_DMSETUP, "table", mapperDevice]
        ret = util.pread(cmd)
        util.SMlog("DM table for %s: %s" % (path, ret.strip()))
コード例 #19
0
ファイル: vhdutil.py プロジェクト: BobBall/sm
def _getVHDParentNoCheck(path):
    cmd = [VHD_UTIL, "read", "-p", "-n", "%s" % path]
    text = util.pread(cmd)
    util.SMlog(text)
    for line in text.split('\n'):
        if line.find("decoded name :") != -1:
            val = line.split(':')[1].strip()
            vdi = val.replace("--", "-")[-40:]
            if vdi[1:].startswith("LV-"):
                vdi = vdi[1:]
            return vdi
    return None
コード例 #20
0
ファイル: FileSR.py プロジェクト: falaa/sm
 def _query_info(self, path, use_bkp_footer=False):
     diskinfo = {}
     qopts = '-vpf'
     if use_bkp_footer:
         qopts += 'b'
     cmd = [SR.TAPDISK_UTIL, "query", vhdutil.VDI_TYPE_VHD, qopts, path]
     txt = util.pread(cmd).split('\n')
     diskinfo['size'] = txt[0]
     lst = [txt[1].split('/')[-1].replace(vhdutil.FILE_EXTN_VHD, "")]
     for val in filter(util.exactmatch_uuid, lst):
         diskinfo['parent'] = val
     diskinfo['hidden'] = txt[2].split()[1]
     return diskinfo
コード例 #21
0
ファイル: FileSR.py プロジェクト: MarkSymsCtx/sm
 def _query_info(self, path, use_bkp_footer=False):
     diskinfo = {}
     qopts = "-vpf"
     if use_bkp_footer:
         qopts += "b"
     cmd = [SR.TAPDISK_UTIL, "query", vhdutil.VDI_TYPE_VHD, qopts, path]
     txt = util.pread(cmd).split("\n")
     diskinfo["size"] = txt[0]
     lst = [txt[1].split("/")[-1].replace(vhdutil.FILE_EXTN_VHD, "")]
     for val in filter(util.exactmatch_uuid, lst):
         diskinfo["parent"] = val
     diskinfo["hidden"] = txt[2].split()[1]
     return diskinfo
コード例 #22
0
ファイル: EXTSR.py プロジェクト: chandrikas/sm
 def attach(self, sr_uuid):
     if not self._checkmount():
         try:
             #Activate LV
             cmd = ['lvchange','-ay',self.remotepath]
             util.pread2(cmd)
             
             # make a mountpoint:
             if not os.path.isdir(self.path):
                 os.makedirs(self.path)
         except util.CommandException, inst:
             raise xs_errors.XenError('LVMMount', \
                   opterr='Unable to activate LV. Errno is %d' % inst.code)
         
         try:
             util.pread(["fsck", "-a", self.remotepath])
         except util.CommandException, inst:
             if inst.code == 1:
                 util.SMlog("FSCK detected and corrected FS errors. Not fatal.")
             else:
                 raise xs_errors.XenError('LVMMount', \
                      opterr='FSCK failed on %s. Errno is %d' % (self.remotepath,inst.code))
コード例 #23
0
ファイル: EXTSR.py プロジェクト: GaryKirkpatrick/sm
    def detach(self, sr_uuid):
        if not self._checkmount():
            return
        cleanup.abort(self.uuid)
        try:
            # Change directory to avoid unmount conflicts
            os.chdir(SR.MOUNT_BASE)
            
            # unmount the device
            util.pread(["umount", self.path])

            # remove the mountpoint
            os.rmdir(self.path)
            self.path = None

            # deactivate SR
            try:
                cmd = ["lvchange", "-an", self.remotepath]
                util.pread2(cmd)
            except util.CommandException, inst:
                raise xs_errors.XenError('LVMUnMount', \
                      opterr='lvm -an failed errno is %d' % inst.code)

            self.attached = False
コード例 #24
0
ファイル: OCFSSR.py プロジェクト: MarkSymsCtx/sm
    def detach(self, sr_uuid):
        """Detach the SR: Unmounts and removes the mountpoint"""
        if not self._checkmount():
            return
        util.SMlog("Aborting GC/coalesce")
        cleanup.abort(self.uuid)

        # Change directory to avoid unmount conflicts
        os.chdir(SR.MOUNT_BASE)

        cmd = ["umount", self.path]
        try:
            ret = util.pread(cmd)
        except util.CommandException, inst:
            raise xs_errors.XenError("OCFSUnMount", opterr="Failed to umount FS. Errno is %d" % os.strerror(inst.code))
コード例 #25
0
ファイル: lvutil.py プロジェクト: MarkSymsCtx/sm
def activateNoRefcount(path, refresh):
    cmd = [CMD_LVCHANGE, "-ay", path]
    text = cmd_lvm(cmd)
    if not _checkActive(path):
        raise util.CommandException(-1, str(cmd), "LV not activated")
    if refresh:
        # Override slave mode lvm.conf for this command
        os.environ['LVM_SYSTEM_DIR'] = MASTER_LVM_CONF
        text = cmd_lvm([CMD_LVCHANGE, "--refresh", path])
        mapperDevice = path[5:].replace("-", "--").replace("/", "-")
        cmd = [CMD_DMSETUP, "table", mapperDevice]
        ret = util.pread(cmd)
        util.SMlog("DM table for %s: %s" % (path, ret.strip()))
        # Restore slave mode lvm.conf
        os.environ['LVM_SYSTEM_DIR'] = DEF_LVM_CONF
コード例 #26
0
ファイル: NFSSR.py プロジェクト: BobBall/sm
    def attach(self, sr_uuid):
        if not util.ioretry(lambda: self._checkmount()):
            try:
                # make sure NFS over TCP/IP V3 is supported on the server
                util.ioretry(lambda: util.pread(["/usr/sbin/rpcinfo","-t", \
                              "%s" % self.remoteserver, "nfs","3"]), \
                              errlist=[errno.EPERM], nofail=1)
            except util.CommandException, inst:
                raise xs_errors.XenError('NFSVersion', \
                      opterr='or NFS server timed out')
            try:
                # make a mountpoint:
                if not util.ioretry(lambda: util.isdir(self.path)):
                    util.ioretry(lambda: util.makedirs(self.path))

                timeout = int((SOFTMOUNT_TIMEOUT / 3.0) * 10.0)
                util.ioretry(lambda: util.pread(["mount.nfs", "%s:%s" \
                             % (self.remoteserver, self.remotepath),  \
                             self.path, "-o", \
                             "udp,soft,timeo=%d,retrans=1,noac" % \
                             timeout]), errlist=[errno.EPIPE, errno.EIO],
                             nofail=1)
            except util.CommandException, inst:
                raise xs_errors.XenError('NFSMount')
コード例 #27
0
def _getPVstats(dev):
    try:
        cmd = [CMD_PVS, "--noheadings", "--nosuffix", "--units", "b", dev]
        text = util.pread(cmd).split()
        size = long(text[4])
        freespace = long(text[5])
        utilisation = size - freespace
        stats = {}
        stats['physical_size'] = size
        stats['physical_utilisation'] = utilisation
        stats['freespace'] = freespace
        return stats
    except util.CommandException, inst:
        raise xs_errors.XenError('VDILoad', \
              opterr='pvstats failed error is %d' % inst.code)
コード例 #28
0
ファイル: lvutil.py プロジェクト: redivy/xe-storage-plugins
def _getVGstats(vgname):
    try:
        cmd = [CMD_VGS, "--noheadings", "--units", "b", vgname]
        text = util.pread(cmd).split()
        size = long(text[5].replace("B",""))
        utilisation = size - long(text[6].replace("B",""))
        freespace = size - utilisation
        stats = {}
        stats['physical_size'] = size
        stats['physical_utilisation'] = utilisation
        stats['freespace'] = freespace
        return stats
    except util.CommandException, inst:
        raise xs_errors.XenError('VDILoad', \
              opterr='rvgstats failed error is %d' % inst.code)
コード例 #29
0
ファイル: OCFSSR.py プロジェクト: Sisimon/sm
    def mount(self, mountpoint, blockdevice):
        try:
            if not util.ioretry(lambda: util.isdir(mountpoint)):
                util.ioretry(lambda: util.makedirs(mountpoint))
        except util.CommandException:
            raise xs_errors.XenError('SRUnavailable', \
                  opterr='no such directory %s' % mountpoint)

        cmd = ['mount', '-t', 'ocfs2', blockdevice, mountpoint, '-o', \
               'noatime,data=writeback,nointr,commit=60,coherency=buffered']
        try:
             ret = util.pread(cmd)
        except util.CommandException, inst:
             raise xs_errors.XenError('OCFSMount', 
                                      opterr='Failed to mount FS. Errno is %d' \
                                             % os.strerror(inst.code))
コード例 #30
0
ファイル: OCFSSR.py プロジェクト: MarkSymsCtx/sm
    def mount(self, mountpoint, blockdevice):
        try:
            if not util.ioretry(lambda: util.isdir(mountpoint)):
                util.ioretry(lambda: util.makedirs(mountpoint))
        except util.CommandException:
            raise xs_errors.XenError("SRUnavailable", opterr="no such directory %s" % mountpoint)

        cmd = [
            "mount",
            "-t",
            "ocfs2",
            blockdevice,
            mountpoint,
            "-o",
            "noatime,data=writeback,nointr,commit=60,coherency=buffered",
        ]
        try:
            ret = util.pread(cmd)
        except util.CommandException, inst:
            raise xs_errors.XenError("OCFSMount", opterr="Failed to mount FS. Errno is %d" % os.strerror(inst.code))
コード例 #31
0
def soft_mount(mountpoint, remoteserver, remotepath, transport):
    """Mount the remote NFS export at 'mountpoint'"""
    try:
        if not util.ioretry(lambda: util.isdir(mountpoint)):
            util.ioretry(lambda: util.makedirs(mountpoint))
    except util.CommandException, inst:
        raise NfsException("Failed to make directory: code is %d" % inst.code)

    options = "soft,timeo=%d,retrans=%d,%s" % (SOFTMOUNT_TIMEOUT,
                                               SOFTMOUNT_RETRANS, transport)
    options += ',noac'  # CA-27534

    try:
        util.ioretry(lambda: util.pread([
            "mount.nfs",
            "%s:%s" % (remoteserver, remotepath), mountpoint, "-o", options
        ]),
                     errlist=[errno.EPIPE, errno.EIO],
                     maxretry=2,
                     nofail=True)
    except util.CommandException, inst:
        raise NfsException("mount failed with return code %d" % inst.code)


def unmount(mountpoint, rmmountpoint):
    """Unmount the mounted mountpoint"""
    try:
        util.pread(["umount", mountpoint])
    except util.CommandException, inst:
        raise NfsException("umount failed with return code %d" % inst.code)
コード例 #32
0
 def unmount(self, mountpoint, rmmountpoint):
     """Unmount the remote SMB export at 'mountpoint'"""
     try:
         util.pread(["umount", mountpoint])
     except util.CommandException, inst:
         raise SMBException("umount failed with return code %d" % inst.code)
コード例 #33
0
ファイル: FileSR.py プロジェクト: yunleid/sm
 def _create(self, size, path):
     cmd = [SR.TAPDISK_UTIL, "create", vhdutil.VDI_TYPE_VHD, size, path]
     text = util.pread(cmd)
コード例 #34
0
 def _singlesnap(self, src, dst):
     cmd = [SR.TAPDISK_UTIL, "snapshot", SR.DEFAULT_TAP, src, dst]
     text = util.pread(cmd)
コード例 #35
0
 def _query_p_uuid(self, path):
     cmd = [SR.TAPDISK_UTIL, "query", SR.DEFAULT_TAP, "-p", path]
     parent = util.pread(cmd)
     parent = parent[:-1]
     ls = parent.split('/')
     return ls[len(ls) - 1].replace(SR.DEFAULT_TAP, '')[:-1]
コード例 #36
0
ファイル: nfs.py プロジェクト: franciozzy/sm
def unmount(mountpoint, rmmountpoint):
    """Unmount the mounted mountpoint"""
    try:
        util.pread(["umount", mountpoint])
    except util.CommandException, inst:
        raise NfsException("umount failed with return code %d" % inst.code)
コード例 #37
0
ファイル: nfs.py プロジェクト: franciozzy/sm
        raise NfsException("Failed to make directory: code is %d" % inst.code)

    mountcommand = 'mount.nfs'
    if nfsversion == '4':
        mountcommand = 'mount.nfs4'

    if timeout < 1:
        timeout = SOFTMOUNT_TIMEOUT

    options = "soft,timeo=%d,retrans=%d,proto=%s,vers=%s" % (
        timeout * 10, SOFTMOUNT_RETRANS, transport, nfsversion)
    options += ',acdirmin=0,acdirmax=0'

    try:
        util.ioretry(lambda: util.pread([
            mountcommand,
            "%s:%s" % (remoteserver, remotepath), mountpoint, "-o", options
        ]),
                     errlist=[errno.EPIPE, errno.EIO],
                     maxretry=2,
                     nofail=True)
    except util.CommandException, inst:
        raise NfsException("mount failed with return code %d" % inst.code)


def unmount(mountpoint, rmmountpoint):
    """Unmount the mounted mountpoint"""
    try:
        util.pread(["umount", mountpoint])
    except util.CommandException, inst:
        raise NfsException("umount failed with return code %d" % inst.code)
コード例 #38
0
ファイル: FileSR.py プロジェクト: MrMEEE/sm
 def _query_v(self, path):
     cmd = [SR.TAPDISK_UTIL, "query", vhdutil.VDI_TYPE_VHD, "-v", path]
     return long(util.pread(cmd)) * 1024 * 1024
コード例 #39
0
ファイル: FileSR.py プロジェクト: MrMEEE/sm
 def _query_p_uuid(self, path):
     cmd = [SR.TAPDISK_UTIL, "query", vhdutil.VDI_TYPE_VHD, "-p", path]
     parent = util.pread(cmd)
     parent = parent[:-1]
     ls = parent.split('/')
     return ls[len(ls) - 1].replace(vhdutil.FILE_EXTN_VHD, '')
コード例 #40
0
 def _mark_hidden(self, path):
     cmd = [SR.TAPDISK_UTIL, "set", SR.DEFAULT_TAP, path, "hidden", "1"]
     text = util.pread(cmd)
     self.hidden = 1
コード例 #41
0
ファイル: lvutil.py プロジェクト: thomasmck/sm
        return

    util.SMlog("_lvmBugCleanup: seeing dm file %s" % mapperPath)

    # destroy the dm device
    if nodeExists:
        util.SMlog("_lvmBugCleanup: removing dm device %s" % mapperDevice)
        for i in range(LVM_FAIL_RETRIES):
            try:
                util.pread2(cmd_rm)
                break
            except util.CommandException, e:
                if i < LVM_FAIL_RETRIES - 1:
                    util.SMlog("Failed on try %d, retrying" % i)
                    try:
                        util.pread(cmd_st, expect_rc=1)
                        util.SMlog("_lvmBugCleanup: dm device {}"
                                   " removed".format(mapperDevice))
                        break
                    except:
                        cmd_rm = cmd_rf
                        time.sleep(1)
                else:
                    # make sure the symlink is still there for consistency
                    if not os.path.lexists(path):
                        os.symlink(mapperPath, path)
                        util.SMlog("_lvmBugCleanup: restored symlink %s" %
                                   path)
                    raise e

    if util.pathexists(mapperPath):
コード例 #42
0
 def _create(self, size, path):
     cmd = [SR.TAPDISK_UTIL, "create", SR.DEFAULT_TAP, size, path]
     text = util.pread(cmd)
コード例 #43
0
            except util.CommandException, inst:
                raise xs_errors.XenError('LVMMount', \
                      opterr='Unable to activate LV. Errno is %d' % inst.code)

            try:
                util.pread(["fsck", "-a", self.remotepath])
            except util.CommandException, inst:
                if inst.code == 1:
                    util.SMlog(
                        "FSCK detected and corrected FS errors. Not fatal.")
                else:
                    raise xs_errors.XenError('LVMMount', \
                         opterr='FSCK failed on %s. Errno is %d' % (self.remotepath,inst.code))

            try:
                util.pread(["mount", self.remotepath, self.path])
            except util.CommandException, inst:
                raise xs_errors.XenError('LVMMount', \
                      opterr='Failed to mount FS. Errno is %d' % inst.code)

        self.attached = True

        #Update SCSIid string
        scsiutil.add_serial_record(self.session, self.sr_ref, \
                scsiutil.devlist_to_serialstring(self.root.split(',')))

        # Set the block scheduler
        for dev in self.root.split(','):
            self.block_setscheduler(dev)

    def detach(self, sr_uuid):
コード例 #44
0
 def _query_v(self, path):
     cmd = [SR.TAPDISK_UTIL, "query", SR.DEFAULT_TAP, "-v", path]
     return long(util.pread(cmd)) * 1024 * 1024
コード例 #45
0
ファイル: FileSR.py プロジェクト: MrMEEE/sm
 def _snap(self, child, parent):
     cmd = [
         SR.TAPDISK_UTIL, "snapshot", vhdutil.VDI_TYPE_VHD, child, parent
     ]
     text = util.pread(cmd)
コード例 #46
0
 def unmount(self, mountpoint, rmmountpoint):
     try:
         util.pread(["umount", mountpoint])
     except util.CommandException, inst:
         raise GlusterFSException("umount failed with return code %d" %
                                  inst.code)
コード例 #47
0
ファイル: lvutil.py プロジェクト: michael2012z/sm
    util.SMlog("_lvmBugCleanup: seeing dm file %s" % mapperPath)

    # destroy the dm device
    if nodeExists:
        util.SMlog("_lvmBugCleanup: removing dm device %s" % mapperDevice)
        cmd = [CMD_DMSETUP, "remove", mapperDevice]
        for i in range(LVM_FAIL_RETRIES):
            try:
                util.pread2(cmd)
                break
            except util.CommandException, e:
                if i < LVM_FAIL_RETRIES - 1:
                    util.SMlog("Failed on try %d, retrying" % i)
                    cmd = [CMD_DMSETUP, "status", mapperDevice]
                    try:
                        util.pread(cmd, expect_rc=1)
                        util.SMlog("_lvmBugCleanup: dm device {}"
                                   " removed".format(mapperDevice)
                                   )
                        break
                    except:
                        time.sleep(1)
                else:
                    # make sure the symlink is still there for consistency
                    if not os.path.lexists(path):
                        os.symlink(mapperPath, path)
                        util.SMlog("_lvmBugCleanup: restored symlink %s" % path)
                    raise e

    if util.pathexists(mapperPath):
        os.unlink(mapperPath)
コード例 #48
0
 def _dualsnap(self, src, dst, newsrc):
     cmd = [SR.TAPDISK_UTIL, "snapshot", SR.DEFAULT_TAP, src, newsrc]
     text = util.pread(cmd)
     cmd = [SR.TAPDISK_UTIL, "snapshot", SR.DEFAULT_TAP, dst, newsrc]
     text = util.pread(cmd)
コード例 #49
0
def setReadonly(path, readonly):
    val = "r"
    if not readonly:
        val += "w"
    cmd = [CMD_LVCHANGE, path, "-p", val]
    ret = util.pread(cmd)
コード例 #50
0
class SMBSR(FileSR.FileSR):
    """SMB file-based storage repository"""
    def handles(type):
        return type == 'smb'
    handles = staticmethod(handles)

    def load(self, sr_uuid):
        self.ops_exclusive = FileSR.OPS_EXCLUSIVE
        self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
        self.sr_vditype = SR.DEFAULT_TAP
        self.driver_config = DRIVER_CONFIG
        if not self.dconf.has_key('server'):
            raise xs_errors.XenError('ConfigServerMissing')
        self.remoteserver = self.dconf['server']
        if self.sr_ref and self.session is not None :
            self.sm_config = self.session.xenapi.SR.get_sm_config(self.sr_ref)
        else:
            self.sm_config = self.srcmd.params.get('sr_sm_config') or {}
        self.credentials = None
        self.mountpoint = os.path.join(SR.MOUNT_BASE, 'SMB', self.__extract_server(), sr_uuid)
        self.linkpath = os.path.join(self.mountpoint,
                                           sr_uuid or "")
        # Remotepath is the absolute path inside a share that is to be mounted
        # For a SMB SR, only the root can be mounted.
        self.remotepath = ''
        self.path = os.path.join(SR.MOUNT_BASE, sr_uuid)
        self._check_o_direct()

    def checkmount(self):
        return util.ioretry(lambda: ((util.pathexists(self.mountpoint) and \
				util.ismount(self.mountpoint)) and \
                                util.pathexists(self.linkpath)))

    def mount(self, mountpoint=None):
        """Mount the remote SMB export at 'mountpoint'"""
        if mountpoint == None:
            mountpoint = self.mountpoint
        elif not util.is_string(mountpoint) or mountpoint == "":
            raise SMBException("mountpoint not a string object")

        try:
            if not util.ioretry(lambda: util.isdir(mountpoint)):
                util.ioretry(lambda: util.makedirs(mountpoint))
        except util.CommandException, inst:
            raise SMBException("Failed to make directory: code is %d" %
                                inst.code)

        self.credentials = os.path.join("/tmp", util.gen_uuid())

        options = self.getMountOptions()
        if options:
            options = ",".join(str(x) for x in options if x)

        try:
            util.ioretry(lambda:
                util.pread(["mount.cifs", self.remoteserver,
                mountpoint, "-o", options]),
                errlist=[errno.EPIPE, errno.EIO],
                maxretry=2, nofail=True)
        except util.CommandException, inst:
            raise SMBException("mount failed with return code %d" % inst.code)
コード例 #51
0
def unblockIP(ip):
    try:
	cmd = ['iptables', '-D', 'INPUT', '-s', ip, '-j', 'DROP']
        util.pread(cmd)
    except Exception, e:
        XenCertPrint("There was an exception in unblocking ip: %s. Exception: %s" % (ip, str(e)))
コード例 #52
0
                    os.makedirs(self.path)
            except util.CommandException, inst:
                raise xs_errors.XenError('LVMMount', \
                      opterr='Unable to activate LV. Errno is %d' % inst.code)
            
            try:
                util.pread(["fsck", "-a", self.remotepath])
            except util.CommandException, inst:
                if inst.code == 1:
                    util.SMlog("FSCK detected and corrected FS errors. Not fatal.")
                else:
                    raise xs_errors.XenError('LVMMount', \
                         opterr='FSCK failed on %s. Errno is %d' % (self.remotepath,inst.code))

            try:
                util.pread(["mount", self.remotepath, self.path])

                FileSR.FileSR.attach(self, sr_uuid)

                self.attached = True
            except util.CommandException, inst:
                raise xs_errors.XenError('LVMMount', \
                      opterr='Failed to mount FS. Errno is %d' % inst.code)
        #Update SCSIid string
        scsiutil.add_serial_record(self.session, self.sr_ref, \
                scsiutil.devlist_to_serialstring(self.root.split(',')))
        
        # Set the block scheduler
        for dev in self.root.split(','): self.block_setscheduler(dev)

    def detach(self, sr_uuid):
コード例 #53
0
class GlusterFSSR(FileSR.FileSR):
    """Gluster file-based storage repository"""
    def handles(sr_type):
        # fudge, because the parent class (FileSR) checks for smb to alter its behavior
        return sr_type == 'glusterfs' or sr_type == 'smb'

    handles = staticmethod(handles)

    def load(self, sr_uuid):
        self.ops_exclusive = FileSR.OPS_EXCLUSIVE
        self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
        self.sr_vditype = SR.DEFAULT_TAP
        self.driver_config = DRIVER_CONFIG
        if 'server' not in self.dconf:
            raise xs_errors.XenError('ConfigServerMissing')
        self.remoteserver = self.dconf['server']
        if self.sr_ref and self.session is not None:
            self.sm_config = self.session.xenapi.SR.get_sm_config(self.sr_ref)
        else:
            self.sm_config = self.srcmd.params.get('sr_sm_config') or {}
        self.mountpoint = os.path.join(SR.MOUNT_BASE, 'GlusterFS',
                                       self.remoteserver.split(':')[0],
                                       sr_uuid)
        self.linkpath = os.path.join(self.mountpoint, sr_uuid or "")
        self.path = os.path.join(SR.MOUNT_BASE, sr_uuid)
        self._check_o_direct()

    def checkmount(self):
        return util.ioretry(
            lambda: ((util.pathexists(self.mountpoint) and util.ismount(
                self.mountpoint)) and util.pathexists(self.linkpath)))

    def mount(self, mountpoint=None):
        """Mount the remote gluster export at 'mountpoint'"""
        if mountpoint is None:
            mountpoint = self.mountpoint
        elif not util.is_string(mountpoint) or mountpoint == "":
            raise GlusterFSException("mountpoint not a string object")

        try:
            if not util.ioretry(lambda: util.isdir(mountpoint)):
                util.ioretry(lambda: util.makedirs(mountpoint))
        except util.CommandException, inst:
            raise GlusterFSException("Failed to make directory: code is %d" %
                                     inst.code)
        try:
            options = []
            if 'backupservers' in self.dconf:
                options.append('backup-volfile-servers=' +
                               self.dconf['backupservers'])
            if 'fetchattempts' in self.dconf:
                options.append('fetch-attempts=' + self.dconf['fetchattempts'])
            if options:
                options = ['-o', ','.join(options)]
            command = [
                "mount", '-t', 'glusterfs', self.remoteserver, mountpoint
            ] + options
            util.ioretry(lambda: util.pread(command),
                         errlist=[errno.EPIPE, errno.EIO],
                         maxretry=2,
                         nofail=True)
        except util.CommandException, inst:
            syslog(_syslog.LOG_ERR, 'GlusterFS mount failed ' + inst.__str__())
            raise GlusterFSException("mount failed with return code %d" %
                                     inst.code)
コード例 #54
0
ファイル: FileSR.py プロジェクト: MrMEEE/sm
 def _create(self, size, path):
     cmd = [SR.TAPDISK_UTIL, "create", vhdutil.VDI_TYPE_VHD, size, path]
     text = util.pread(cmd)
     if self.key_hash:
         vhdutil.setKey(path, self.key_hash)
コード例 #55
0
def rename(path, newName):
    cmd = [CMD_LVRENAME, path, newName]
    util.pread(cmd)