예제 #1
0
def _find_LUN(svid):
    basepath = "/dev/disk/by-csldev/"
    if svid.startswith("NETAPP_"):
        # special attention for NETAPP SVIDs
        svid_parts = svid.split("__")
        globstr = basepath + "NETAPP__LUN__" + "*" + svid_parts[2] + "*" + svid_parts[-1] + "*"
    else:
        globstr = basepath + svid + "*"

    path = util.wait_for_path_multi(globstr, MAX_TIMEOUT)
    if not len(path):
        return []

    #Find CSLDEV paths
    svid_to_use = re.sub("-[0-9]*:[0-9]*:[0-9]*:[0-9]*$","",os.path.basename(path))
    devs = scsiutil._genReverseSCSIidmap(svid_to_use, pathname="csldev")

    #Find scsiID
    for dev in devs:
        try:
            SCSIid = scsiutil.getSCSIid(dev)
        except:
            pass

    #Find root device and return
    if not SCSIid:
        return []
    else:
        device=mpath_dmp.path(SCSIid)
        XenCertPrint("DEBUG: device path : %s"%(device))
        return [device]
예제 #2
0
def _find_LUN(svid):
    basepath = "/dev/disk/by-csldev/"
    if svid.startswith("NETAPP_"):
        # special attention for NETAPP SVIDs
        svid_parts = svid.split("__")
        globstr = basepath + "NETAPP__LUN__" + "*" + svid_parts[2] + "*" + svid_parts[-1] + "*"
    else:
        globstr = basepath + svid + "*"

    path = util.wait_for_path_multi(globstr, MAX_TIMEOUT)
    if not len(path):
        return []

    #Find CSLDEV paths
    svid_to_use = re.sub("-[0-9]*:[0-9]*:[0-9]*:[0-9]*$","",os.path.basename(path))
    devs = scsiutil._genReverseSCSIidmap(svid_to_use, pathname="csldev")

    #Find scsiID
    for dev in devs:
        try:
            SCSIid = scsiutil.getSCSIid(dev)
        except:
            pass

    #Find root device and return
    if not SCSIid:
        return []
    else:
        device=mpath_dmp.path(SCSIid)
        XenCertPrint("DEBUG: device path : %s"%(device))
        return [device]
예제 #3
0
    def create(self, sr_uuid, size):
        # Check SCSIid not already in use by other PBDs
        if util.test_SCSIid(self.session, sr_uuid, self.SCSIid):
            raise xs_errors.XenError('SRInUse')

        self.iscsi.attach(sr_uuid)
        try:
            if not self.iscsi._attach_LUN_bySCSIid(self.SCSIid):
                # UPGRADE FROM GEORGE: take care of ill-formed SCSIid
                upgraded = False
                matchSCSIid = False
                for file in filter(self.iscsi.match_lun,
                                   util.listdir(self.iscsi.path)):
                    path = os.path.join(self.iscsi.path, file)
                    if not util.wait_for_path(path, ISCSISR.MAX_TIMEOUT):
                        util.SMlog(
                            "Unable to detect LUN attached to host [%s]" %
                            path)
                        continue
                    try:
                        SCSIid = scsiutil.getSCSIid(path)
                    except:
                        continue
                    try:
                        matchSCSIid = scsiutil.compareSCSIid_2_6_18(
                            self.SCSIid, path)
                    except:
                        continue
                    if (matchSCSIid):
                        util.SMlog("Performing upgrade from George")
                        try:
                            pbd = util.find_my_pbd(self.session, self.host_ref,
                                                   self.sr_ref)
                            device_config = self.session.xenapi.PBD.get_device_config(
                                pbd)
                            device_config['SCSIid'] = SCSIid
                            self.session.xenapi.PBD.set_device_config(
                                pbd, device_config)

                            self.dconf['SCSIid'] = SCSIid
                            self.SCSIid = self.dconf['SCSIid']
                        except:
                            continue
                        if not self.iscsi._attach_LUN_bySCSIid(self.SCSIid):
                            raise xs_errors.XenError('InvalidDev')
                        else:
                            upgraded = True
                            break
                    else:
                        util.SMlog(
                            "Not a matching LUN, skip ... scsi_id is: %s" %
                            SCSIid)
                        continue
                if not upgraded:
                    raise xs_errors.XenError('InvalidDev')
            self._pathrefresh(OCFSoISCSISR)
            OCFSSR.OCFSSR.create(self, sr_uuid, size)
        except Exception, inst:
            self.iscsi.detach(sr_uuid)
            raise xs_errors.XenError("SRUnavailable", opterr=inst)
예제 #4
0
    def _LUNprint(self, sr_uuid):
        if self.iscsi.attached:
            # Force a rescan on the bus.
            self.iscsi.refresh()


#            time.sleep(5)
# Now call attach (handles the refcounting + session activa)
        self.iscsi.attach(sr_uuid)

        util.SMlog("LUNprint: waiting for path: %s" % self.iscsi.path)
        if util.wait_for_path("%s/LUN*" % self.iscsi.path,
                              ISCSISR.MAX_TIMEOUT):
            try:
                adapter = self.iscsi.adapter[self.iscsi.address]
                util.SMlog("adapter=%s" % adapter)

                # find a scsi device on which to issue a report luns command:
                devs = glob.glob("%s/LUN*" % self.iscsi.path)
                sgdevs = []
                for i in devs:
                    sgdevs.append(int(i.split("LUN")[1]))
                sgdevs.sort()
                sgdev = "%s/LUN%d" % (self.iscsi.path, sgdevs[0])

                # issue a report luns:
                luns = util.pread2(["/usr/bin/sg_luns", "-q",
                                    sgdev]).split('\n')
                nluns = len(
                    luns) - 1  # remove the line relating to the final \n
                # check if the LUNs are MPP-RDAC Luns
                scsi_id = scsiutil.getSCSIid(sgdev)
                mpp_lun = False
                if (mpp_luncheck.is_RdacLun(scsi_id)):
                    mpp_lun = True
                    link = glob.glob('/dev/disk/by-scsibus/%s-*' % scsi_id)
                    mpp_adapter = link[0].split('/')[-1].split('-')[-1].split(
                        ':')[0]

                # make sure we've got that many sg devices present
                for i in range(0, 30):
                    luns = scsiutil._dosgscan()
                    sgdevs = filter(lambda r: r[1] == adapter, luns)
                    if mpp_lun:
                        sgdevs.extend(
                            filter(lambda r: r[1] == mpp_adapter, luns))
                    if len(sgdevs) >= nluns:
                        util.SMlog("Got all %d sg devices" % nluns)
                        break
                    else:
                        util.SMlog("Got %d sg devices - expecting %d" %
                                   (len(sgdevs), nluns))
                        time.sleep(1)

                util.pread2(["/sbin/udevsettle"])
            except:
                pass  # Make sure we don't break the probe...

        self.iscsi.print_LUNs()
        self.iscsi.detach(sr_uuid)
예제 #5
0
 def _attach_LUN_bylunid(self, lunid):
     if not self.attached:
         raise xs_errors.XenError('SRUnavailable')
     connected = []
     for val in self.adapter:
         if not self.pathdict.has_key(val):
             continue
         rec = self.pathdict[val]
         path = os.path.join(rec['path'],"LUN%s" % lunid)
         util.SMlog("path: %s" % path)
         realpath = os.path.realpath(path)
         util.SMlog("realpath: %s" % realpath)
         host = self.adapter[val]
         if not self.devs.has_key(realpath):
             l = [realpath, host, 0, 0, lunid]
             scsiutil.scsi_dev_ctrl(l,"add")
             if not util.wait_for_path(path, MAX_LUNID_TIMEOUT):
                 util.SMlog("Unable to detect LUN attached to host on path [%s]" % path)
                 continue
         else:
             # Verify that we are not seeing a stale LUN map
             try:
                 real_SCSIid = scsiutil.getSCSIid(realpath)
                 cur_scsibuspath = glob.glob('/dev/disk/by-scsibus/*-%s:0:0:%s' % (host,lunid))
                 cur_SCSIid = os.path.basename(cur_scsibuspath[0]).split("-")[0]
                 assert(cur_SCSIid == real_SCSIid)
             except:
                 scsiutil.rescan([host])
                 if not os.path.exists('/dev/disk/by-scsibus/%s-%s:0:0:%s' % \
                                       (real_SCSIid,host,lunid)):
                     util.SMlog("Unable to detect LUN attached to host after bus re-probe")
                     continue
         connected.append(path)
     return connected
예제 #6
0
    def _LUNprint(self, sr_uuid):
        if self.iscsi.attached:
            # Force a rescan on the bus.
            self.iscsi.refresh()
#            time.sleep(5)
        # Now call attach (handles the refcounting + session activa)
        self.iscsi.attach(sr_uuid)

        util.SMlog("LUNprint: waiting for path: %s" % self.iscsi.path)
        if util.wait_for_path("%s/LUN*" % self.iscsi.path, ISCSISR.MAX_TIMEOUT):
            try:
                adapter=self.iscsi.adapter[self.iscsi.address]
                util.SMlog("adapter=%s" % adapter)

                # find a scsi device on which to issue a report luns command:
                devs=glob.glob("%s/LUN*" % self.iscsi.path)
                sgdevs = []
                for i in devs:
                    sgdevs.append(int(i.split("LUN")[1]))
                sgdevs.sort()
                sgdev = "%s/LUN%d" % (self.iscsi.path,sgdevs[0])                

                # issue a report luns:
                luns=util.pread2(["/usr/bin/sg_luns","-q",sgdev]).split('\n')
                nluns=len(luns)-1 # remove the line relating to the final \n
                # check if the LUNs are MPP-RDAC Luns
                scsi_id = scsiutil.getSCSIid(sgdev)
                mpp_lun = False
                if (mpp_luncheck.is_RdacLun(scsi_id)):
                    mpp_lun = True
                    link=glob.glob('/dev/disk/by-scsibus/%s-*' % scsi_id)
                    mpp_adapter = link[0].split('/')[-1].split('-')[-1].split(':')[0]

                # make sure we've got that many sg devices present
                for i in range(0,30): 
                    luns=scsiutil._dosgscan()
                    sgdevs=filter(lambda r: r[1]==adapter, luns)
                    if mpp_lun:
                        sgdevs.extend(filter(lambda r: r[1]==mpp_adapter, luns))
                    if len(sgdevs)>=nluns:
                        util.SMlog("Got all %d sg devices" % nluns)
                        break
                    else:
                        util.SMlog("Got %d sg devices - expecting %d" % (len(sgdevs),nluns))
                        time.sleep(1)

                if os.path.exists("/sbin/udevsettle"):
                    util.pread2(["/sbin/udevsettle"])
                else:
                    util.pread2(["/sbin/udevadm","settle"])
            except:
                util.SMlog("Generic exception caught. Pass")
                pass # Make sure we don't break the probe...

        self.iscsi.print_LUNs()
        self.iscsi.detach(sr_uuid)        
예제 #7
0
파일: vhdd_helper.py 프로젝트: djs55/vhdd
def get_probe_possibility(path,lunid):
    scsiid=scsiutil.getSCSIid(path)
    size=scsiutil.getsize(path)
    serial=scsiutil.getserial(path)
    vendor=scsiutil.getmanufacturer(path)
    return { 'info' : {'vendor' : vendor,
                       'serial' : serial,
                       'LUNid' : lunid,
                       'size' : "%d" % size,
                       'SCSIid' : scsiid},
             'new_device_config' : {'SCSIid' : scsiid} }
예제 #8
0
 def _query(self, path, id):
     self.uuid = scsiutil.gen_uuid_from_string(scsiutil.getuniqueserial(path))
     self.location = self.uuid
     self.vendor = scsiutil.getmanufacturer(path)
     self.serial = scsiutil.getserial(path)
     self.LUNid = id
     self.size = scsiutil.getsize(path)
     self.SCSIid = scsiutil.getSCSIid(path)
     self.path = path
     sm_config = util.default(self, "sm_config", lambda: {})
     sm_config['LUNid'] = str(self.LUNid)
     sm_config['SCSIid'] = self.SCSIid
     self.sm_config = sm_config
예제 #9
0
    def create(self, sr_uuid, size):
        # Check SCSIid not already in use by other PBDs
        if util.test_SCSIid(self.session, sr_uuid, self.SCSIid):
            raise xs_errors.XenError('SRInUse')

        self.iscsi.attach(sr_uuid)
        try:
            if not self.iscsi._attach_LUN_bySCSIid(self.SCSIid):
                # UPGRADE FROM GEORGE: take care of ill-formed SCSIid
                upgraded = False
                matchSCSIid = False
                for file in filter(self.iscsi.match_lun, util.listdir(self.iscsi.path)):
                    path = os.path.join(self.iscsi.path,file)
                    if not util.wait_for_path(path, ISCSISR.MAX_TIMEOUT):
                        util.SMlog("Unable to detect LUN attached to host [%s]" % path)
                        continue
                    try:
                        SCSIid = scsiutil.getSCSIid(path)
                    except:
                        continue
                    try:
                        matchSCSIid = scsiutil.compareSCSIid_2_6_18(self.SCSIid, path)
                    except:
                        continue
                    if (matchSCSIid):
                        util.SMlog("Performing upgrade from George")
                        try:
                            pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref)
                            device_config = self.session.xenapi.PBD.get_device_config(pbd)
                            device_config['SCSIid'] = SCSIid
                            self.session.xenapi.PBD.set_device_config(pbd, device_config)

                            self.dconf['SCSIid'] = SCSIid            
                            self.SCSIid = self.dconf['SCSIid']
                        except:
                            continue
                        if not self.iscsi._attach_LUN_bySCSIid(self.SCSIid):
                            raise xs_errors.XenError('InvalidDev')
                        else:
                            upgraded = True
                            break
                    else:
                        util.SMlog("Not a matching LUN, skip ... scsi_id is: %s" % SCSIid)
                        continue
                if not upgraded:
                    raise xs_errors.XenError('InvalidDev')
            self._pathrefresh(LVHDoISCSISR)
            LVHDSR.LVHDSR.create(self, sr_uuid, size)
        except Exception, inst:
            self.iscsi.detach(sr_uuid)
            raise xs_errors.XenError("SRUnavailable", opterr=inst)
예제 #10
0
def getrootdevID():
    rootdev = getrootdev()
    try:
        rootdevID = scsiutil.getSCSIid(rootdev)
    except:
        SMlog("Unable to verify serial or SCSIid of device: %s" \
                   % rootdev)
        return ''

    if not len(rootdevID):
        SMlog("Unable to identify scsi device [%s] via scsiID" \
                   % rootdev)

    return rootdevID
예제 #11
0
파일: BaseISCSI.py 프로젝트: stormi/sm
    def _attach_LUN_bylunid(self, lunid):
        if not self.attached:
            raise xs_errors.XenError('SRUnavailable')
        connected = []
        for val in self.adapter:
            if val not in self.pathdict:
                continue
            rec = self.pathdict[val]
            path = os.path.join(rec['path'], "LUN%s" % lunid)
            realpath = os.path.realpath(path)
            host = self.adapter[val]
            l = [realpath, host, 0, 0, lunid]

            addDevice = True
            if realpath in self.devs:
                # if the device is stale remove it before adding again
                real_SCSIid = None
                try:
                    real_SCSIid = scsiutil.getSCSIid(realpath)
                except:
                    pass

                if real_SCSIid != None:
                    # make sure this is the same scsiid, if not remove the device
                    cur_scsibuspath = glob.glob(
                        '/dev/disk/by-scsibus/*-%s:0:0:%s' % (host, lunid))
                    cur_SCSIid = os.path.basename(
                        cur_scsibuspath[0]).split("-")[0]
                    if cur_SCSIid != real_SCSIid:
                        # looks stale, remove it
                        scsiutil.scsi_dev_ctrl(l, "remove")
                    else:
                        util.SMlog("Not attaching LUNID %s for adapter %s"\
                            " since the device exists and the scsi id %s seems"\
                            " to be valid. " % (lunid, val, real_SCSIid))
                        addDevice = False
                else:
                    # looks stale, remove it
                    scsiutil.scsi_dev_ctrl(l, "remove")

            if addDevice:
                # add the device
                scsiutil.scsi_dev_ctrl(l, "add")
                if not util.wait_for_path(path, MAX_LUNID_TIMEOUT):
                    util.SMlog(
                        "Unable to detect LUN attached to host on path [%s]" %
                        path)
                    continue
            connected.append(path)
        return connected
예제 #12
0
def getrootdevID():
    rootdev = getrootdev()
    try:
        rootdevID = scsiutil.getSCSIid(rootdev)
    except:
        SMlog("Unable to verify serial or SCSIid of device: %s" \
                   % rootdev)
        return ''

    if not len(rootdevID):
        SMlog("Unable to identify scsi device [%s] via scsiID" \
                   % rootdev)

    return rootdevID
예제 #13
0
 def _query(self, path, id):
     self.uuid = scsiutil.gen_uuid_from_string(
         scsiutil.getuniqueserial(path))
     self.location = self.uuid
     self.vendor = scsiutil.getmanufacturer(path)
     self.serial = scsiutil.getserial(path)
     self.LUNid = id
     self.size = scsiutil.getsize(path)
     self.SCSIid = scsiutil.getSCSIid(path)
     self.path = path
     sm_config = util.default(self, "sm_config", lambda: {})
     sm_config['LUNid'] = str(self.LUNid)
     sm_config['SCSIid'] = self.SCSIid
     self.sm_config = sm_config
예제 #14
0
 def _getSCSIid_from_LUN(self, sr_uuid):
     was_attached = True
     self.iscsi.attach(sr_uuid)
     dev = self.dconf['LUNid'].split(',')
     if len(dev) > 1:
         raise xs_errors.XenError('OCFSOneLUN')
     path = os.path.join(self.iscsi.path, "LUN%s" % dev[0])
     if not util.wait_for_path(path, ISCSISR.MAX_TIMEOUT):
         util.SMlog("Unable to detect LUN attached to host [%s]" % path)
     try:
         SCSIid = scsiutil.getSCSIid(path)
     except:
         raise xs_errors.XenError('InvalidDev')
     self.iscsi.detach(sr_uuid)
     return SCSIid
예제 #15
0
 def _getSCSIid_from_LUN(self, sr_uuid):
     was_attached = True
     self.iscsi.attach(sr_uuid)
     dev = self.dconf['LUNid'].split(',')
     if len(dev) > 1:
         raise xs_errors.XenError('LVMOneLUN')
     path = os.path.join(self.iscsi.path,"LUN%s" % dev[0])
     if not util.wait_for_path(path, ISCSISR.MAX_TIMEOUT):
         util.SMlog("Unable to detect LUN attached to host [%s]" % path)
     try:
         SCSIid = scsiutil.getSCSIid(path)
     except:
         raise xs_errors.XenError('InvalidDev')
     self.iscsi.detach(sr_uuid)
     return SCSIid
예제 #16
0
파일: ISCSISR.py 프로젝트: heiden-deng/sm
    def _attach_LUN_bylunid(self, lunid):
        if not self.attached:
            raise xs_errors.XenError("SRUnavailable")
        connected = []
        for val in self.adapter:
            if not self.pathdict.has_key(val):
                continue
            rec = self.pathdict[val]
            path = os.path.join(rec["path"], "LUN%s" % lunid)
            realpath = os.path.realpath(path)
            host = self.adapter[val]
            l = [realpath, host, 0, 0, lunid]

            addDevice = True
            if self.devs.has_key(realpath):
                # if the device is stale remove it before adding again
                real_SCSIid = None
                try:
                    real_SCSIid = scsiutil.getSCSIid(realpath)
                except:
                    pass

                if real_SCSIid != None:
                    # make sure this is the same scsiid, if not remove the device
                    cur_scsibuspath = glob.glob("/dev/disk/by-scsibus/*-%s:0:0:%s" % (host, lunid))
                    cur_SCSIid = os.path.basename(cur_scsibuspath[0]).split("-")[0]
                    if cur_SCSIid != real_SCSIid:
                        # looks stale, remove it
                        scsiutil.scsi_dev_ctrl(l, "remove")
                    else:
                        util.SMlog(
                            "Not attaching LUNID %s for adapter %s"
                            " since the device exists and the scsi id %s seems"
                            " to be valid. " % (lunid, val, real_SCSIid)
                        )
                        addDevice = False
                else:
                    # looks stale, remove it
                    scsiutil.scsi_dev_ctrl(l, "remove")

            if addDevice:
                # add the device
                scsiutil.scsi_dev_ctrl(l, "add")
                if not util.wait_for_path(path, MAX_LUNID_TIMEOUT):
                    util.SMlog("Unable to detect LUN attached to host on path [%s]" % path)
                    continue
            connected.append(path)
        return connected
예제 #17
0
def get_lun_scsiid_devicename_mapping(targetIQN, portal):
    iscsilib.refresh_luns(targetIQN, portal)
    lunToScsiId={}
    path = os.path.join("/dev/iscsi",targetIQN,portal)
    try:
        for file in util.listdir(path):
            realPath = os.path.realpath(os.path.join(path, file))
            if file.find("LUN") == 0 and file.find("_") == -1:		
                lun=file.replace("LUN","")
                scsi_id = scsiutil.getSCSIid(os.path.join(path, file))
                lunToScsiId[lun] = (scsi_id, realPath)

        return lunToScsiId
    except util.CommandException, inst:
        XenCertPrint("Failed to find any LUNs for IQN: %s and portal: %s" % (targetIQN, portal))
        return {}
예제 #18
0
    def _query(self, path, id, uuid=None, scsi_id=None):
        """Overloaded function with mostly duplicated code"""
        if uuid:
            self.uuid = uuid
        else:
            util.SMlog("RawHBA: uuid should not be generated..")
            self.uuid = scsiutil.gen_uuid_from_string(
                scsiutil.getuniqueserial(path)
                )
        if scsi_id:
            self.SCSIid = scsi_id
        else:
            # It is usually unnecessary to calculate it again but scsi_id
            # is used as a flag in this function and we cannot guarantee
            # this info is already available at call time
            self.SCSIid = scsiutil.getSCSIid(path)
        self.location = self.uuid
        self.vendor = scsiutil.getmanufacturer(path)
        self.serial = scsiutil.getserial(path)
        self.LUNid = id

        # Handle resize done at the array size. The resize gets reflected
        # only when the vdi is not in detached state. Do this if we the vdi
        # is known to xapi
        try:
            vdi_ref = self.sr.session.xenapi.VDI.get_by_uuid(self.uuid)
            # Check if the vbd is not in attached state, do a LUN rescan
            # to reflect the array LUN
            dev = [path]
            if scsi_id:
                # We want all the devices with this scsi_id
                dev = scsiutil._genReverseSCSIidmap(scsi_id)
            if self.sr.srcmd.cmd == "vdi_attach":
                scsiutil.refreshdev(dev)
            elif not B_util.is_vdi_attached(self.sr.session, vdi_ref):
                scsiutil.refreshdev(dev)
        except:
            pass

        self.size = scsiutil.getsize(path)
        self.path = path
        sm_config = util.default(self, "sm_config", lambda: {})
        sm_config['LUNid'] = str(self.LUNid)
        sm_config['SCSIid'] = self.SCSIid
        # Make sure to use kernel blkback (not blktap3) for raw LUNs
        sm_config['backend-kind'] = 'vbd'
        self.sm_config = sm_config
예제 #19
0
파일: RawHBASR.py 프로젝트: BobBall/sm
    def _query(self, path, id, uuid=None, scsi_id=None):
        """Overloaded function with mostly duplicated code"""
        if uuid:
            self.uuid = uuid
        else:
            util.SMlog("RawHBA: uuid should not be generated..")
            self.uuid = scsiutil.gen_uuid_from_string(
                scsiutil.getuniqueserial(path)
                )
        if scsi_id:
            self.SCSIid = scsi_id
        else:
            # It is usually unnecessary to calculate it again but scsi_id
            # is used as a flag in this function and we cannot guarantee
            # this info is already available at call time
            self.SCSIid = scsiutil.getSCSIid(path)
        self.location = self.uuid
        self.vendor = scsiutil.getmanufacturer(path)
        self.serial = scsiutil.getserial(path)
        self.LUNid = id

        # Handle resize done at the array size. The resize gets reflected
        # only when the vdi is not in detached state. Do this if we the vdi
        # is known to xapi
        try:
            vdi_ref = self.sr.session.xenapi.VDI.get_by_uuid(self.uuid)
            # Check if the vbd is not in attached state, do a LUN rescan
            # to reflect the array LUN
            dev = [path]
            if scsi_id:
                # We want all the devices with this scsi_id
                dev = scsiutil._genReverseSCSIidmap(scsi_id)
            if self.sr.srcmd.cmd == "vdi_attach":
                scsiutil.refreshdev(dev)
            elif not B_util.is_vdi_attached(self.sr.session, vdi_ref):
                scsiutil.refreshdev(dev)
        except:
            pass

        self.size = scsiutil.getsize(path)
        self.path = path
        sm_config = util.default(self, "sm_config", lambda: {})
        sm_config['LUNid'] = str(self.LUNid)
        sm_config['SCSIid'] = self.SCSIid
        # Make sure to use kernel blkback (not blktap3) for raw LUNs
        sm_config['backend-kind'] = 'vbd'
        self.sm_config = sm_config
예제 #20
0
def get_probe_possibility(path, lunid):
    scsiid = scsiutil.getSCSIid(path)
    size = scsiutil.getsize(path)
    serial = scsiutil.getserial(path)
    vendor = scsiutil.getmanufacturer(path)
    return {
        'info': {
            'vendor': vendor,
            'serial': serial,
            'LUNid': lunid,
            'size': "%d" % size,
            'SCSIid': scsiid
        },
        'new_device_config': {
            'SCSIid': scsiid
        }
    }
예제 #21
0
    def _LUNprint(self, sr_uuid):
        if self.iscsi.attached:
            # Force a rescan on the bus.
            self.iscsi.refresh()
#            time.sleep(5)
        # Now call attach (handles the refcounting + session activa)
        self.iscsi.attach(sr_uuid)

        util.SMlog("LUNprint: waiting for path: %s" % self.iscsi.path)
        if util.wait_for_path("%s/LUN*" % self.iscsi.path, BaseISCSI.MAX_TIMEOUT):
            try:
                adapter=self.iscsi.adapter[self.iscsi.address]
                util.SMlog("adapter=%s" % adapter)

                # find a scsi device on which to issue a report luns command:
                devs=glob.glob("%s/LUN*" % self.iscsi.path)
                sgdevs = []
                for i in devs:
                    sgdevs.append(int(i.split("LUN")[1]))
                sgdevs.sort()
                sgdev = "%s/LUN%d" % (self.iscsi.path,sgdevs[0])                

                # issue a report luns:
                luns=util.pread2(["/usr/bin/sg_luns","-q",sgdev]).split('\n')
                nluns=len(luns)-1 # remove the line relating to the final \n
                # check if the LUNs are MPP-RDAC Luns
                scsi_id = scsiutil.getSCSIid(sgdev)

                # make sure we've got that many sg devices present
                for i in range(0,30): 
                    luns=scsiutil._dosgscan()
                    sgdevs=filter(lambda r: r[1]==adapter, luns)
                    if len(sgdevs)>=nluns:
                        util.SMlog("Got all %d sg devices" % nluns)
                        break
                    else:
                        util.SMlog("Got %d sg devices - expecting %d" % (len(sgdevs),nluns))
                        time.sleep(1)

                util.pread2(["/sbin/udevsettle"])
            except:
                pass # Make sure we don't break the probe...

        self.iscsi.print_LUNs()
        self.iscsi.detach(sr_uuid)        
예제 #22
0
    def _loadvdis(self):
        if self.vdis:
            return

        self._init_hbadict()
        count = 0
        for key in self.hbadict.iterkeys():
            vdi_path = os.path.join("/dev",key)
	    if vdi_path not in self.devs:
		continue
            uuid = scsiutil.gen_uuid_from_string(scsiutil.getuniqueserial(vdi_path))
            obj = self.vdi(uuid)
            path = self.mpathmodule.path(scsiutil.getSCSIid(vdi_path))
	    ids = self.devs[vdi_path]
            obj._query(vdi_path, ids[4])
            self.vdis[uuid] = obj
            self.physical_size += obj.size
            count += 1
        return count
예제 #23
0
    def _loadvdis(self):
        if self.vdis:
            return

        self._init_hbadict()
        count = 0
        for key in self.hbadict.iterkeys():
            vdi_path = os.path.join("/dev",key)
	    if not self.devs.has_key(vdi_path):
		continue
            uuid = scsiutil.gen_uuid_from_string(scsiutil.getuniqueserial(vdi_path))
            obj = self.vdi(uuid)
            path = self.mpathmodule.path(scsiutil.getSCSIid(vdi_path))
	    ids = self.devs[vdi_path]
            obj._query(vdi_path, ids[4])
            self.vdis[uuid] = obj
            self.physical_size += obj.size
            count += 1
        return count
예제 #24
0
    def load(self, sr_uuid):
        driver = SR.driver('hba')
        self.hbasr = driver(self.original_srcmd, sr_uuid)

        # If this is a vdi command, don't initialise SR
        if not (util.isVDICommand(self.original_srcmd.cmd)):
            pbd = None
            try:
                pbd = util.find_my_pbd(self.session, self.host_ref,
                                       self.sr_ref)
            except:
                pass

            try:
                if not self.dconf.has_key('SCSIid') and self.dconf.has_key(
                        'device'):
                    # UPGRADE FROM MIAMI: add SCSIid key to device_config
                    util.SMlog("Performing upgrade from Miami")
                    if not os.path.exists(self.dconf['device']):
                        raise xs_errors.XenError('InvalidDev')
                    SCSIid = scsiutil.getSCSIid(self.dconf['device'])
                    self.dconf['SCSIid'] = SCSIid
                    del self.dconf['device']

                    if pbd <> None:
                        device_config = self.session.xenapi.PBD.get_device_config(
                            pbd)
                        device_config['SCSIid'] = SCSIid
                        device_config['upgraded_from_miami'] = 'true'
                        del device_config['device']
                        self.session.xenapi.PBD.set_device_config(
                            pbd, device_config)
            except:
                pass

            if not self.dconf.has_key('SCSIid') or not self.dconf['SCSIid']:
                print >> sys.stderr, self.hbasr.print_devs()
                raise xs_errors.XenError('ConfigSCSIid')

        self.SCSIid = self.dconf['SCSIid']
        self._pathrefresh(LVHDoHBASR, load=False)
        LVHDSR.LVHDSR.load(self, sr_uuid)
예제 #25
0
파일: LVHDoHBASR.py 프로젝트: chandrikas/sm
    def load(self, sr_uuid):
        driver = SR.driver('hba')
        self.hbasr = driver(self.original_srcmd, sr_uuid)

        # If this is a vdi command, don't initialise SR
        if not (util.isVDICommand(self.original_srcmd.cmd)):
            pbd = None
            try:
                pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref)
            except:
                pass

            try:
                if not self.dconf.has_key('SCSIid') and self.dconf.has_key('device'):
                    # UPGRADE FROM MIAMI: add SCSIid key to device_config
                    util.SMlog("Performing upgrade from Miami")
                    if not os.path.exists(self.dconf['device']):
                        raise xs_errors.XenError('InvalidDev')
                    SCSIid = scsiutil.getSCSIid(self.dconf['device'])
                    self.dconf['SCSIid'] = SCSIid
                    del self.dconf['device']

                    if pbd <> None:
                        device_config = self.session.xenapi.PBD.get_device_config(pbd)
                        device_config['SCSIid'] = SCSIid
                        device_config['upgraded_from_miami'] = 'true'
                        del device_config['device']
                        self.session.xenapi.PBD.set_device_config(pbd, device_config)
            except:
                pass

            if not self.dconf.has_key('SCSIid') or not self.dconf['SCSIid']:
                print >>sys.stderr,self.hbasr.print_devs()
                raise xs_errors.XenError('ConfigSCSIid')

        self.SCSIid = self.dconf['SCSIid']
        self._pathrefresh(LVHDoHBASR, load = False)
        LVHDSR.LVHDSR.load(self, sr_uuid)
예제 #26
0
def test_scsiserial(session, device):
    device = os.path.realpath(device)
    if not scsiutil._isSCSIdev(device):
        SMlog("Not a serial device: %s" % device)
        return False
    serial = ""
    try:
        serial += scsiutil.getserial(device)
    except:
        # Error allowed, SCSIid is the important one
        pass
    
    try:
        scsiID = scsiutil.getSCSIid(device)
    except:
        SMlog("Unable to verify serial or SCSIid of device: %s" \
                   % device)
        return False
    if not len(scsiID):
        SMlog("Unable to identify scsi device [%s] via scsiID" \
                   % device)
        return False
    
    try:
        SRs = session.xenapi.SR.get_all_records()
    except:
        raise xs_errors.XenError('APIFailure')
    for SR in SRs:
        record = SRs[SR]
        conf = record["sm_config"]
        if conf.has_key('devserial'):
            for dev in conf['devserial'].split(','):
                if _isSCSIid(dev):
                    if match_scsiID(dev, scsiID):
                        return True
                elif len(serial) and dev == serial:
                    return True
    return False
예제 #27
0
def test_scsiserial(session, device):
    device = os.path.realpath(device)
    if not scsiutil._isSCSIdev(device):
        SMlog("Not a serial device: %s" % device)
        return False
    serial = ""
    try:
        serial += scsiutil.getserial(device)
    except:
        # Error allowed, SCSIid is the important one
        pass

    try:
        scsiID = scsiutil.getSCSIid(device)
    except:
        SMlog("Unable to verify serial or SCSIid of device: %s" \
                   % device)
        return False
    if not len(scsiID):
        SMlog("Unable to identify scsi device [%s] via scsiID" \
                   % device)
        return False

    try:
        SRs = session.xenapi.SR.get_all_records()
    except:
        raise xs_errors.XenError('APIFailure')
    for SR in SRs:
        record = SRs[SR]
        conf = record["sm_config"]
        if conf.has_key('devserial'):
            for dev in conf['devserial'].split(','):
                if _isSCSIid(dev):
                    if match_scsiID(dev, scsiID):
                        return True
                elif len(serial) and dev == serial:
                    return True
    return False
예제 #28
0
    def load(self, sr_uuid):
        driver = SR.driver("hba")
        self.hbasr = driver(self.original_srcmd, sr_uuid)

        pbd = None
        try:
            pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref)
        except:
            pass

        try:
            if not self.dconf.has_key("SCSIid") and self.dconf.has_key("device"):
                # UPGRADE FROM MIAMI: add SCSIid key to device_config
                util.SMlog("Performing upgrade from Miami")
                if not os.path.exists(self.dconf["device"]):
                    raise
                SCSIid = scsiutil.getSCSIid(self.dconf["device"])
                self.dconf["SCSIid"] = SCSIid
                del self.dconf["device"]

                if pbd <> None:
                    device_config = self.session.xenapi.PBD.get_device_config(pbd)
                    device_config["SCSIid"] = SCSIid
                    device_config["upgraded_from_miami"] = "true"
                    del device_config["device"]
                    self.session.xenapi.PBD.set_device_config(pbd, device_config)
        except:
            pass

        if not self.dconf.has_key("SCSIid") or not self.dconf["SCSIid"]:
            print >>sys.stderr, self.hbasr.print_devs()
            raise xs_errors.XenError("ConfigSCSIid")

        self.SCSIid = self.dconf["SCSIid"]
        self._pathrefresh(LVMoHBASR)
        super(LVMoHBASR, self).load(sr_uuid)
예제 #29
0
def cmd_lvm(cmd, sr_alloc=None, pread_func=util.pread2, *args):
    """ Construct and run the appropriate lvm command

        depending on the SR's allocation type; 'thick' or 'xlvhd'. For
        PV commands, the full path to the device is required.

        Input:
            cmd -- (list) lvm command
                cmd[0]  -- (str) lvm command name
                cmd[1:] -- (str) lvm command parameters

            sr_alloc -- (str) SR's allocation type; 'thick' or 'xlvhd'
                              if it's not supplied, the function will
                              figure it out
                Default: None

            pread_func -- (function) the flavor of util.pread to use
                                     to execute the lvm command
                Default: util.pread2()

            *args -- extra arguments passed to cmd_lvm will be passed
                     to 'pread_func'

        Return:
            stdout -- (str) stdout after running the lvm command.

        Raise:
            util.CommandException
    """

    if type(cmd) is not list:
        util.SMlog("CMD_LVM: Argument 'cmd' not of type 'list'")
        return None
    if not len(cmd):
        util.SMlog("CMD_LVM: 'cmd' list is empty")
        return None

    lvm_cmd, lvm_args = cmd[0], cmd[1:]

    if lvm_cmd not in LVM_COMMANDS:
        util.SMlog("CMD_LVM: '{}' is not a valid lvm command".format(lvm_cmd))
        return None

    for arg in lvm_args:
        if not util.is_string(arg):
            util.SMlog("CMD_LVM: Not all lvm arguments are of type 'str'")
            return None

    if sr_alloc is None:
        if lvm_cmd not in PV_COMMANDS:
            for arg in lvm_args:
                try:
                    filename = extract_vgname(arg)
                except:
                    util.logException('CMD_LVM')
                    return None
                if filename:
                    break
            else:  # if for loop doesn't break
                util.SMlog("CMD_LVM: Could not find VG "
                           "name in lvm argument list")
                util.SMlog([lvm_cmd] + lvm_args)
                return None
        else:
            for arg in lvm_args:
                if os.path.exists(arg):
                    try:
                        filename = getSCSIid(arg)
                    except:
                        util.logException('CMD_LVM')
                        return None
                    break
            else:  # if for loop doesn't break
                util.SMlog("CMD_LVM: Could not find PV "
                           "name in lvm argument list")
                util.SMlog([lvm_cmd] + lvm_args)
                return None

        sr_alloc = get_sr_alloc(filename)

    if sr_alloc == 'xlvhd':
        stdout = pread_func(['/bin/xenvm', lvm_cmd] + lvm_args, *args)
    elif sr_alloc == 'thick':
        stdout = pread_func([os.path.join(LVM_BIN, lvm_cmd)] + lvm_args, *args)
    else:
        util.SMlog("CMD_LVM: ERROR: 'sr_alloc' neither 'xlvhd' nor 'thick'")
        return None

    return stdout
예제 #30
0
파일: RawHBASR.py 프로젝트: BobBall/sm
    def _loadvdis(self):
        if self.cmd not in NEEDS_LOADVDIS:
            return 0
        if self.vdis:
            return

        self._init_hbadict()
        count = 0
        self.physical_size = 0
        root_dev_id = util.getrootdevID()

        xapi_session = self.session.xenapi
        known_scsid = {} # dict of ids processed within the following loop

        for key in self.hbadict.iterkeys():

            # We need a fresh sm_config everytime because it is modified
            # inside this loop
            sm_config = xapi_session.SR.get_sm_config(self.sr_ref)

            # The way we create vdi_path and the following check are
            # not clear at all
            vdi_path = os.path.join("/dev",key)
            if not self.devs.has_key(vdi_path):
                continue

            scsi_id = scsiutil.getSCSIid(vdi_path)
            if scsi_id == root_dev_id:
                util.SMlog("Skipping root device %s" %scsi_id)
                continue

            # Avoid false positives: this SR can already contain this
            # SCSIid during scan.
            scsi_key = "scsi-" + scsi_id
            if sm_config.has_key(scsi_key):
                # if we know about this scsid we can skip this specific dev
                if known_scsid.has_key(scsi_key):
                    util.SMlog("This SCSI id (%s) is already added" %scsi_id)
                    continue
                else:
                    # marked as known to avoid adding it again to sm_config
                    known_scsid[scsi_key] = ""
            elif util.test_SCSIid(self.session, None, scsi_id):
                util.SMlog("This SCSI id (%s) is used by another SR" %scsi_id)
                continue

            # getuniqueserial invokes again getSCSIid -> Fix!
            uuid = scsiutil.gen_uuid_from_string(
                scsiutil.getuniqueserial(vdi_path)
                )
            # We could have checked the SCSIid but the dictionary has
            # uuid as key.
            # We have already checked known_scsid, though. This block is
            # supposed to be always False
            if self.vdis.has_key(uuid):
                util.SMlog("Warning: unexpected code block reached with"
                           " uuid = %s" %scsi_id)
                continue

            obj = self.vdi(uuid)
            path = self.mpathmodule.path(scsi_id)
            ids = self.devs[vdi_path]
            obj._query(vdi_path, ids[4], uuid, scsi_id)
            self.vdis[uuid] = obj
            self.physical_size += obj.size

            count += 1

            # If we know about it no need to add to sm_config
            if known_scsid.has_key(scsi_key):
                continue

            # Prepare multipathing and make the other SRs know this SCSIid
            # is reserved.
            # Its counterpart is vdi_delete
            try:
                xapi_session.SR.add_to_sm_config(self.sr_ref, scsi_key, uuid)
                known_scsid[scsi_key] = ""
            except:
                util.SMlog("Warning: add_to_sm_config failed unexpectedly")

        return count
예제 #31
0
파일: lvutil.py 프로젝트: letsboogey/sm
def cmd_lvm(cmd, sr_alloc=None, pread_func=util.pread2, *args):
    """ Construct and run the appropriate lvm command

        depending on the SR's allocation type; 'thick' or 'xlvhd'. For
        PV commands, the full path to the device is required.

        Input:
            cmd -- (list) lvm command
                cmd[0]  -- (str) lvm command name
                cmd[1:] -- (str) lvm command parameters

            sr_alloc -- (str) SR's allocation type; 'thick' or 'xlvhd'
                              if it's not supplied, the function will
                              figure it out
                Default: None

            pread_func -- (function) the flavor of util.pread to use
                                     to execute the lvm command
                Default: util.pread2()

            *args -- extra arguments passed to cmd_lvm will be passed
                     to 'pread_func'

        Return:
            stdout -- (str) stdout after running the lvm command.

        Raise:
            util.CommandException
    """

    if type(cmd) is not list:
        util.SMlog("CMD_LVM: Argument 'cmd' not of type 'list'")
        return None
    if not len(cmd):
        util.SMlog("CMD_LVM: 'cmd' list is empty")
        return None

    lvm_cmd, lvm_args = cmd[0], cmd[1:]

    if lvm_cmd not in LVM_COMMANDS:
        util.SMlog("CMD_LVM: '{}' is not a valid lvm command".format(lvm_cmd))
        return None

    for arg in lvm_args:
        if not util.is_string(arg):
            util.SMlog("CMD_LVM: Not all lvm arguments are of type 'str'")
            return None

    if sr_alloc is None:
        if lvm_cmd not in PV_COMMANDS:
            for arg in lvm_args:
                try:
                    filename = extract_vgname(arg)
                except:
                    util.logException('CMD_LVM')
                    return None
                if filename:
                    break
            else: # if for loop doesn't break
                util.SMlog("CMD_LVM: Could not find VG "
                           "name in lvm argument list")
                util.SMlog([lvm_cmd] + lvm_args)
                return None
        else:
            for arg in lvm_args:
                if os.path.exists(arg):
                    try:
                        filename = getSCSIid(arg)
                    except:
                        util.logException('CMD_LVM')
                        return None
                    break
            else: # if for loop doesn't break
                util.SMlog("CMD_LVM: Could not find PV "
                           "name in lvm argument list")
                util.SMlog([lvm_cmd] + lvm_args)
                return None

        sr_alloc = get_sr_alloc(filename)

    if sr_alloc == 'xlvhd':
        stdout = pread_func(['/bin/xenvm', lvm_cmd] + lvm_args, *args)
    elif sr_alloc == 'thick':
        stdout = pread_func([os.path.join(LVM_BIN, lvm_cmd)] + lvm_args, *args)
    else:
        util.SMlog("CMD_LVM: ERROR: 'sr_alloc' neither 'xlvhd' nor 'thick'")
        return None

    return stdout
예제 #32
0
    def _loadvdis(self):
        if self.cmd not in NEEDS_LOADVDIS:
            return 0
        if self.vdis:
            return

        self._init_hbadict()
        count = 0
        self.physical_size = 0
        root_dev_id = util.getrootdevID()

        xapi_session = self.session.xenapi
        known_scsid = {}  # dict of ids processed within the following loop

        for key in self.hbadict.iterkeys():

            # We need a fresh sm_config everytime because it is modified
            # inside this loop
            sm_config = xapi_session.SR.get_sm_config(self.sr_ref)

            # The way we create vdi_path and the following check are
            # not clear at all
            vdi_path = os.path.join("/dev", key)
            if vdi_path not in self.devs:
                continue

            scsi_id = scsiutil.getSCSIid(vdi_path)
            if scsi_id == root_dev_id:
                util.SMlog("Skipping root device %s" % scsi_id)
                continue

            # Avoid false positives: this SR can already contain this
            # SCSIid during scan.
            scsi_key = "scsi-" + scsi_id
            if scsi_key in sm_config:
                # if we know about this scsid we can skip this specific dev
                if scsi_key in known_scsid:
                    util.SMlog("This SCSI id (%s) is already added" % scsi_id)
                    continue
                else:
                    # marked as known to avoid adding it again to sm_config
                    known_scsid[scsi_key] = ""
            elif util.test_SCSIid(self.session, None, scsi_id):
                util.SMlog("This SCSI id (%s) is used by another SR" % scsi_id)
                continue

            # getuniqueserial invokes again getSCSIid -> Fix!
            uuid = scsiutil.gen_uuid_from_string(
                scsiutil.getuniqueserial(vdi_path))
            # We could have checked the SCSIid but the dictionary has
            # uuid as key.
            # We have already checked known_scsid, though. This block is
            # supposed to be always False
            if uuid in self.vdis:
                util.SMlog("Warning: unexpected code block reached with"
                           " uuid = %s" % scsi_id)
                continue

            obj = self.vdi(uuid)
            path = self.mpathmodule.path(scsi_id)
            ids = self.devs[vdi_path]
            obj._query(vdi_path, ids[4], uuid, scsi_id)
            self.vdis[uuid] = obj
            self.physical_size += obj.size

            count += 1

            # If we know about it no need to add to sm_config
            if scsi_key in known_scsid:
                continue

            # Prepare multipathing and make the other SRs know this SCSIid
            # is reserved.
            # Its counterpart is vdi_delete
            try:
                xapi_session.SR.add_to_sm_config(self.sr_ref, scsi_key, uuid)
                known_scsid[scsi_key] = ""
            except:
                util.SMlog("Warning: add_to_sm_config failed unexpectedly")

        return count
예제 #33
0
    def load(self, sr_uuid):
        if not sr_uuid:
            # This is a probe call, generate a temp sr_uuid
            sr_uuid = util.gen_uuid()

        driver = SR.driver('iscsi')
        if self.original_srcmd.dconf.has_key('target'):
            self.original_srcmd.dconf['targetlist'] = self.original_srcmd.dconf['target']
        iscsi = driver(self.original_srcmd, sr_uuid)
        self.iscsiSRs = []
        self.iscsiSRs.append(iscsi)
        
        if self.dconf['target'].find(',') == 0 or self.dconf['targetIQN'] == "*":
            # Instantiate multiple sessions
            self.iscsiSRs = []
            if self.dconf['targetIQN'] == "*":
                IQN = "any"
            else:
                IQN = self.dconf['targetIQN']
            dict = {}
            IQNstring = ""
            IQNs = []
            try:
                if self.dconf.has_key('multiSession'):
                    IQNs = self.dconf['multiSession'].split("|")
                    for IQN in IQNs:
                        if IQN:
                            dict[IQN] = ""
                        else:
                            try:
                                IQNs.remove(IQN)
                            except:
                                # Exceptions are not expected but just in case
                                pass
                    # Order in multiSession must be preserved. It is important for dual-controllers.
                    # IQNstring cannot be built with a dictionary iteration because of this
                    IQNstring = self.dconf['multiSession']
                else:
                    for tgt in self.dconf['target'].split(','):
                        try:
                            tgt_ip = util._convertDNS(tgt)
                        except:
                            raise xs_errors.XenError('DNSError')
                        iscsilib.ensure_daemon_running_ok(iscsi.localIQN)
                        map = iscsilib.discovery(tgt_ip,iscsi.port,iscsi.chapuser,iscsi.chappassword,targetIQN=IQN)
                        util.SMlog("Discovery for IP %s returned %s" % (tgt,map))
                        for i in range(0,len(map)):
                            (portal,tpgt,iqn) = map[i]
                            (ipaddr, port) = iscsilib.parse_IP_port(portal)
                            try:
                                util._testHost(ipaddr, long(port), 'ISCSITarget')
                            except:
                                util.SMlog("Target Not reachable: (%s:%s)" % (ipaddr, port))
                                continue
                            key = "%s,%s,%s" % (ipaddr,port,iqn)
                            dict[key] = ""
                # Again, do not mess up with IQNs order. Dual controllers will benefit from that
                if IQNstring == "":
                    # Compose the IQNstring first
                    for key in dict.iterkeys(): IQNstring += "%s|" % key
                    # Reinitialize and store iterator
                    key_iterator = dict.iterkeys()
                else:
                    key_iterator = IQNs

                # Now load the individual iSCSI base classes
                for key in key_iterator:
                    (ipaddr,port,iqn) = key.split(',')
                    srcmd_copy = copy.deepcopy(self.original_srcmd)
                    srcmd_copy.dconf['target'] = ipaddr
                    srcmd_copy.dconf['targetIQN'] = iqn
                    srcmd_copy.dconf['multiSession'] = IQNstring
                    util.SMlog("Setting targetlist: %s" % srcmd_copy.dconf['targetlist'])
                    self.iscsiSRs.append(driver(srcmd_copy, sr_uuid))
                pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref)
                if pbd <> None and not self.dconf.has_key('multiSession'):
                    dconf = self.session.xenapi.PBD.get_device_config(pbd)
                    dconf['multiSession'] = IQNstring
                    self.session.xenapi.PBD.set_device_config(pbd, dconf)
            except:
                util.logException("LVHDoISCSISR.load")
        self.iscsi = self.iscsiSRs[0]

        # Be extremely careful not to throw exceptions here since this function
        # is the main one used by all operations including probing and creating
        pbd = None
        try:
            pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref)
        except:
            pass

        # Apart from the upgrade case, user must specify a SCSIid
        if not self.dconf.has_key('SCSIid'):
            # Dual controller issue
            self.LUNs = {}  # Dict for LUNs from all the iscsi objects
            for ii in range(0, len(self.iscsiSRs)):
                self.iscsi = self.iscsiSRs[ii]
                self._LUNprint(sr_uuid)
                for key in self.iscsi.LUNs:
                    self.LUNs[key] = self.iscsi.LUNs[key]
            self.print_LUNs_XML()
            self.iscsi = self.iscsiSRs[0] # back to original value
            raise xs_errors.XenError('ConfigSCSIid')

        self.SCSIid = self.dconf['SCSIid']

        # This block checks if the first iscsi target contains the right SCSIid.
        # If not it scans the other iscsi targets because chances are that more
        # than one controller is present
        dev_match = False
        forced_login = False
        # No need to check if only one iscsi target is present
        if len(self.iscsiSRs) == 1:
            pass
        else:
            target_success = False
            attempt_discovery = False
            for iii in range(0, len(self.iscsiSRs)):
                # Check we didn't leave any iscsi session open
                # If exceptions happened before, the cleanup function has worked on the right target.
                if forced_login == True:
                    try:
                        iscsilib.ensure_daemon_running_ok(self.iscsi.localIQN)
                        iscsilib.logout(self.iscsi.target, self.iscsi.targetIQN)
                        forced_login = False
                    except:
                        raise xs_errors.XenError('ISCSILogout')
                self.iscsi = self.iscsiSRs[iii]
                util.SMlog("path %s" %self.iscsi.path)
                util.SMlog("iscsci data: targetIQN %s, portal %s" % (self.iscsi.targetIQN, self.iscsi.target))
                iscsilib.ensure_daemon_running_ok(self.iscsi.localIQN)
                if not iscsilib._checkTGT(self.iscsi.targetIQN):
                    attempt_discovery = True
                    try:
                        # Ensure iscsi db has been populated
                        map = iscsilib.discovery(
                                  self.iscsi.target,
                                  self.iscsi.port,
                                  self.iscsi.chapuser,
                                  self.iscsi.chappassword,
                                  targetIQN=self.iscsi.targetIQN)
                        if len(map) == 0:
                            util.SMlog("Discovery for iscsi data targetIQN %s,"
                                       " portal %s returned empty list"
                                       " Trying another path if available" %
                                       (self.iscsi.targetIQN,
                                        self.iscsi.target))
                            continue
                    except:
                        util.SMlog("Discovery failed for iscsi data targetIQN"
                                   " %s, portal %s. Trying another path if"
                                   " available" %
                                   (self.iscsi.targetIQN, self.iscsi.target))
                        continue
                    try:
                        iscsilib.login(self.iscsi.target,
                                       self.iscsi.targetIQN,
                                       self.iscsi.chapuser,
                                       self.iscsi.chappassword,
                                       self.iscsi.incoming_chapuser,
                                       self.iscsi.incoming_chappassword,
                                       self.mpath == "true")
                    except:
                        util.SMlog("Login failed for iscsi data targetIQN %s,"
                                   " portal %s. Trying another path"
                                   " if available" %
                                   (self.iscsi.targetIQN, self.iscsi.target))
                        continue
                    target_success = True;
                    forced_login = True
                # A session should be active.
                if not util.wait_for_path(self.iscsi.path, ISCSISR.MAX_TIMEOUT):
                    util.SMlog("%s has no associated LUNs" % self.iscsi.targetIQN)
                    continue
                scsiid_path = "/dev/disk/by-id/scsi-" + self.SCSIid
                if not util.wait_for_path(scsiid_path, ISCSISR.MAX_TIMEOUT):
                    util.SMlog("%s not found" %scsiid_path)
                    continue
                for file in filter(self.iscsi.match_lun, util.listdir(self.iscsi.path)):
                    lun_path = os.path.join(self.iscsi.path,file)
                    lun_dev = scsiutil.getdev(lun_path)
                    try:
                        lun_scsiid = scsiutil.getSCSIid(lun_dev)
                    except:
                        util.SMlog("getSCSIid failed on %s in iscsi %s: LUN"
                                   " offline or iscsi path down" %
                                    (lun_dev, self.iscsi.path))
                        continue
                    util.SMlog("dev from lun %s %s" %(lun_dev, lun_scsiid))
                    if lun_scsiid == self.SCSIid:
                        util.SMlog("lun match in %s" %self.iscsi.path)
                        dev_match = True
                        # No more need to raise ISCSITarget exception.
                        # Resetting attempt_discovery
                        attempt_discovery = False
                        break
                if dev_match:
                    if iii == 0:
                        break
                    util.SMlog("IQN reordering needed")
                    new_iscsiSRs = []
                    IQNs = {}
                    IQNstring = ""
                    # iscsiSRs can be seen as a circular buffer: the head now is the matching one
                    for kkk in range(iii, len(self.iscsiSRs)) + range(0, iii):
                        new_iscsiSRs.append(self.iscsiSRs[kkk])
                        ipaddr = self.iscsiSRs[kkk].target
                        port = self.iscsiSRs[kkk].port
                        iqn = self.iscsiSRs[kkk].targetIQN
                        key = "%s,%s,%s" % (ipaddr,port,iqn)
                        # The final string must preserve the order without repetition
                        if not IQNs.has_key(key):
                            IQNs[key] = ""
                            IQNstring += "%s|" % key
                    util.SMlog("IQNstring is now %s" %IQNstring)
                    self.iscsiSRs = new_iscsiSRs
                    util.SMlog("iqn %s is leading now" %self.iscsiSRs[0].targetIQN)
                    # Updating pbd entry, if any
                    try:
                        pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref)
                        if pbd <> None and self.dconf.has_key('multiSession'):
                            util.SMlog("Updating multiSession in PBD")
                            dconf = self.session.xenapi.PBD.get_device_config(pbd)
                            dconf['multiSession'] = IQNstring
                            self.session.xenapi.PBD.set_device_config(pbd, dconf)
                    except:
                        pass
                    break
            if not target_success and attempt_discovery:
                raise xs_errors.XenError('ISCSITarget')

            # Check for any unneeded open iscsi sessions
            if forced_login == True:
                try:
                    iscsilib.ensure_daemon_running_ok(self.iscsi.localIQN)
                    iscsilib.logout(self.iscsi.target, self.iscsi.targetIQN)
                    forced_login = False
                except:
                    raise xs_errors.XenError('ISCSILogout')

        self._pathrefresh(LVHDoISCSISR, load = False)

        LVHDSR.LVHDSR.load(self, sr_uuid)
예제 #34
0
    def load(self, sr_uuid):
        if not sr_uuid:
            # This is a probe call, generate a temp sr_uuid
            sr_uuid = util.gen_uuid()

        driver = SR.driver('iscsi')
        if self.original_srcmd.dconf.has_key('target'):
            self.original_srcmd.dconf[
                'targetlist'] = self.original_srcmd.dconf['target']
        iscsi = driver(self.original_srcmd, sr_uuid)
        self.iscsiSRs = []
        self.iscsiSRs.append(iscsi)

        if self.dconf['target'].find(
                ',') == 0 or self.dconf['targetIQN'] == "*":
            # Instantiate multiple sessions
            self.iscsiSRs = []
            if self.dconf['targetIQN'] == "*":
                IQN = "any"
            else:
                IQN = self.dconf['targetIQN']
            dict = {}
            IQNstring = ""
            IQNs = []
            try:
                if self.dconf.has_key('multiSession'):
                    IQNs = self.dconf['multiSession'].split("|")
                    for IQN in IQNs:
                        if IQN:
                            dict[IQN] = ""
                        else:
                            try:
                                IQNs.remove(IQN)
                            except:
                                # Exceptions are not expected but just in case
                                pass
                    # Order in multiSession must be preserved. It is important for dual-controllers.
                    # IQNstring cannot be built with a dictionary iteration because of this
                    IQNstring = self.dconf['multiSession']
                else:
                    for tgt in self.dconf['target'].split(','):
                        try:
                            tgt_ip = util._convertDNS(tgt)
                        except:
                            raise xs_errors.XenError('DNSError')
                        iscsilib.ensure_daemon_running_ok(iscsi.localIQN)
                        map = iscsilib.discovery(tgt_ip,
                                                 iscsi.port,
                                                 iscsi.chapuser,
                                                 iscsi.chappassword,
                                                 targetIQN=IQN)
                        util.SMlog("Discovery for IP %s returned %s" %
                                   (tgt, map))
                        for i in range(0, len(map)):
                            (portal, tpgt, iqn) = map[i]
                            (ipaddr, port) = iscsilib.parse_IP_port(portal)
                            try:
                                util._testHost(ipaddr, long(port),
                                               'ISCSITarget')
                            except:
                                util.SMlog("Target Not reachable: (%s:%s)" %
                                           (ipaddr, port))
                                continue
                            key = "%s,%s,%s" % (ipaddr, port, iqn)
                            dict[key] = ""
                # Again, do not mess up with IQNs order. Dual controllers will benefit from that
                if IQNstring == "":
                    # Compose the IQNstring first
                    for key in dict.iterkeys():
                        IQNstring += "%s|" % key
                    # Reinitialize and store iterator
                    key_iterator = dict.iterkeys()
                else:
                    key_iterator = IQNs

                # Now load the individual iSCSI base classes
                for key in key_iterator:
                    (ipaddr, port, iqn) = key.split(',')
                    srcmd_copy = copy.deepcopy(self.original_srcmd)
                    srcmd_copy.dconf['target'] = ipaddr
                    srcmd_copy.dconf['targetIQN'] = iqn
                    srcmd_copy.dconf['multiSession'] = IQNstring
                    util.SMlog("Setting targetlist: %s" %
                               srcmd_copy.dconf['targetlist'])
                    self.iscsiSRs.append(driver(srcmd_copy, sr_uuid))
                pbd = util.find_my_pbd(self.session, self.host_ref,
                                       self.sr_ref)
                if pbd <> None and not self.dconf.has_key('multiSession'):
                    dconf = self.session.xenapi.PBD.get_device_config(pbd)
                    dconf['multiSession'] = IQNstring
                    self.session.xenapi.PBD.set_device_config(pbd, dconf)
            except:
                util.logException("OCFSoISCSISR.load")
        self.iscsi = self.iscsiSRs[0]

        # Be extremely careful not to throw exceptions here since this function
        # is the main one used by all operations including probing and creating
        pbd = None
        try:
            pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref)
        except:
            pass

        # Apart from the upgrade case, user must specify a SCSIid
        if not self.dconf.has_key('SCSIid'):
            # Dual controller issue
            self.LUNs = {}  # Dict for LUNs from all the iscsi objects
            for ii in range(0, len(self.iscsiSRs)):
                self.iscsi = self.iscsiSRs[ii]
                self._LUNprint(sr_uuid)
                for key in self.iscsi.LUNs:
                    self.LUNs[key] = self.iscsi.LUNs[key]
            self.print_LUNs_XML()
            self.iscsi = self.iscsiSRs[0]  # back to original value
            raise xs_errors.XenError('ConfigSCSIid')

        self.SCSIid = self.dconf['SCSIid']

        # This block checks if the first iscsi target contains the right SCSIid.
        # If not it scans the other iscsi targets because chances are that more
        # than one controller is present
        dev_match = False
        forced_login = False
        # No need to check if only one iscsi target is present
        if len(self.iscsiSRs) == 1:
            pass
        else:
            target_success = False
            attempt_discovery = False
            for iii in range(0, len(self.iscsiSRs)):
                # Check we didn't leave any iscsi session open
                # If exceptions happened before, the cleanup function has worked on the right target.
                if forced_login == True:
                    try:
                        iscsilib.ensure_daemon_running_ok(self.iscsi.localIQN)
                        iscsilib.logout(self.iscsi.target,
                                        self.iscsi.targetIQN)
                        forced_login = False
                    except:
                        raise xs_errors.XenError('ISCSILogout')
                self.iscsi = self.iscsiSRs[iii]
                util.SMlog("path %s" % self.iscsi.path)
                util.SMlog("iscsci data: targetIQN %s, portal %s" %
                           (self.iscsi.targetIQN, self.iscsi.target))
                iscsilib.ensure_daemon_running_ok(self.iscsi.localIQN)
                if not iscsilib._checkTGT(self.iscsi.targetIQN):
                    attempt_discovery = True
                    try:
                        # Ensure iscsi db has been populated
                        map = iscsilib.discovery(
                            self.iscsi.target,
                            self.iscsi.port,
                            self.iscsi.chapuser,
                            self.iscsi.chappassword,
                            targetIQN=self.iscsi.targetIQN)
                        if len(map) == 0:
                            util.SMlog(
                                "Discovery for iscsi data targetIQN %s,"
                                " portal %s returned empty list"
                                " Trying another path if available" %
                                (self.iscsi.targetIQN, self.iscsi.target))
                            continue
                    except:
                        util.SMlog("Discovery failed for iscsi data targetIQN"
                                   " %s, portal %s. Trying another path if"
                                   " available" %
                                   (self.iscsi.targetIQN, self.iscsi.target))
                        continue
                    try:
                        iscsilib.login(self.iscsi.target, self.iscsi.targetIQN,
                                       self.iscsi.chapuser,
                                       self.iscsi.chappassword,
                                       self.iscsi.incoming_chapuser,
                                       self.iscsi.incoming_chappassword,
                                       self.mpath == "true")
                    except:
                        util.SMlog("Login failed for iscsi data targetIQN %s,"
                                   " portal %s. Trying another path"
                                   " if available" %
                                   (self.iscsi.targetIQN, self.iscsi.target))
                        continue
                    target_success = True
                    forced_login = True
                # A session should be active.
                if not util.wait_for_path(self.iscsi.path,
                                          ISCSISR.MAX_TIMEOUT):
                    util.SMlog("%s has no associated LUNs" %
                               self.iscsi.targetIQN)
                    continue
                scsiid_path = "/dev/disk/by-id/scsi-" + self.SCSIid
                if not util.wait_for_path(scsiid_path, ISCSISR.MAX_TIMEOUT):
                    util.SMlog("%s not found" % scsiid_path)
                    continue
                for file in filter(self.iscsi.match_lun,
                                   util.listdir(self.iscsi.path)):
                    lun_path = os.path.join(self.iscsi.path, file)
                    lun_dev = scsiutil.getdev(lun_path)
                    try:
                        lun_scsiid = scsiutil.getSCSIid(lun_dev)
                    except:
                        util.SMlog("getSCSIid failed on %s in iscsi %s: LUN"
                                   " offline or iscsi path down" %
                                   (lun_dev, self.iscsi.path))
                        continue
                    util.SMlog("dev from lun %s %s" % (lun_dev, lun_scsiid))
                    if lun_scsiid == self.SCSIid:
                        util.SMlog("lun match in %s" % self.iscsi.path)
                        dev_match = True
                        # No more need to raise ISCSITarget exception.
                        # Resetting attempt_discovery
                        attempt_discovery = False
                        break
                if dev_match:
                    if iii == 0:
                        break
                    util.SMlog("IQN reordering needed")
                    new_iscsiSRs = []
                    IQNs = {}
                    IQNstring = ""
                    # iscsiSRs can be seen as a circular buffer: the head now is the matching one
                    for kkk in range(iii, len(self.iscsiSRs)) + range(0, iii):
                        new_iscsiSRs.append(self.iscsiSRs[kkk])
                        ipaddr = self.iscsiSRs[kkk].target
                        port = self.iscsiSRs[kkk].port
                        iqn = self.iscsiSRs[kkk].targetIQN
                        key = "%s,%s,%s" % (ipaddr, port, iqn)
                        # The final string must preserve the order without repetition
                        if not IQNs.has_key(key):
                            IQNs[key] = ""
                            IQNstring += "%s|" % key
                    util.SMlog("IQNstring is now %s" % IQNstring)
                    self.iscsiSRs = new_iscsiSRs
                    util.SMlog("iqn %s is leading now" %
                               self.iscsiSRs[0].targetIQN)
                    # Updating pbd entry, if any
                    try:
                        pbd = util.find_my_pbd(self.session, self.host_ref,
                                               self.sr_ref)
                        if pbd <> None and self.dconf.has_key('multiSession'):
                            util.SMlog("Updating multiSession in PBD")
                            dconf = self.session.xenapi.PBD.get_device_config(
                                pbd)
                            dconf['multiSession'] = IQNstring
                            self.session.xenapi.PBD.set_device_config(
                                pbd, dconf)
                    except:
                        pass
                    break
            if not target_success and attempt_discovery:
                raise xs_errors.XenError('ISCSITarget')

            # Check for any unneeded open iscsi sessions
            if forced_login == True:
                try:
                    iscsilib.ensure_daemon_running_ok(self.iscsi.localIQN)
                    iscsilib.logout(self.iscsi.target, self.iscsi.targetIQN)
                    forced_login = False
                except:
                    raise xs_errors.XenError('ISCSILogout')

        self._pathrefresh(OCFSoISCSISR, load=False)
        OCFSSR.OCFSSR.load(self, sr_uuid)
예제 #35
0
def queryLUN(dbg, path, id):
    vendor = scsiutil.getmanufacturer(dbg, path)
    serial = scsiutil.getserial(dbg, path)
    size = scsiutil.getsize(dbg, path)
    SCSIid = scsiutil.getSCSIid(dbg, path)
    return (id, vendor, serial, size, SCSIid)
예제 #36
0
def queryLUN(dbg, path, id):
    vendor = scsiutil.getmanufacturer(dbg, path)
    serial = scsiutil.getserial(dbg, path)
    size = scsiutil.getsize(dbg, path)
    SCSIid = scsiutil.getSCSIid(dbg, path)
    return (id, vendor, serial, size, SCSIid)