示例#1
0
def run(driver, driver_info):
    """Convenience method to run command on the given driver"""
    cmd = SRCommand(driver_info)
    try:
        cmd.parse()
        cmd.run_statics()
        sr = driver(cmd, cmd.sr_uuid)
        sr.direct = True
        ret = cmd.run(sr)

        if ret == None:
            print util.return_nil()
        else:
            print ret

    except Exception, e:
        try:
            util.logException(driver_info['name'])
        except KeyError:
            util.SMlog('driver_info does not contain a \'name\' key.')
        except:
            pass

        # If exception is of type SR.SRException,
        # pass to xapi, else re-raise.
        if isinstance(e, SR.SRException):
            print e.toxml()
        else:
            raise
示例#2
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     util.SMlog("RBDVDI.attach_from_config")
     self.sr.attach(sr_uuid)
     try:
         vdi_name = "%s%s" % (cephutils.VDI_PREFIX, vdi_uuid)
         dev_name = "%s/%s" % (self.sr.SR_ROOT, vdi_name)
         self.path = self.sr._get_path(vdi_uuid)
         if self.mode == "kernel":
             util.pread2([
                 "rbd", "map", vdi_name, "--pool", self.sr.CEPH_POOL_NAME,
                 "--name", self.sr.CEPH_USER
             ])
         elif self.mode == "fuse":
             pass
         elif self.mode == "nbd":
             cmdout = util.pread2([
                 "rbd-nbd", "--nbds_max",
                 str(cephutils.NBDS_MAX), "map",
                 "%s/%s" % (self.sr.CEPH_POOL_NAME, vdi_name), "--name",
                 self.sr.CEPH_USER
             ]).rstrip('\n')
             util.pread2(["ln", "-s", cmdout, dev_name])
         return VDI.VDI.attach(self, sr_uuid, vdi_uuid)
     except:
         util.logException("RBDVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach the heartbeat disk')
示例#3
0
 def pixmapFromSvg(self, pmapSize=None, withBorders=None):
     """returns a pixmap with default size as given in SVG and optional borders/shadows"""
     if withBorders is None:
         withBorders = Preferences.showShadows
     if withBorders:
         wantSize = self.tileset.tileSize.toSize()
     else:
         wantSize = self.tileset.faceSize.toSize()
     if not pmapSize:
         pmapSize = wantSize
     result = QPixmap(pmapSize)
     result.fill(Qt.transparent)
     painter = QPainter(result)
     if not painter.isActive():
         logException('painter is not active. Wanted size: %s' % str(pmapSize))
     try:
         xScale = float(pmapSize.width()) / wantSize.width()
         yScale = float(pmapSize.height()) / wantSize.height()
     except ZeroDivisionError:
         xScale = 1
         yScale = 1
     if not withBorders:
         painter.scale(*self.tileset.tileFaceRelation())
         painter.translate(-self.facePos())
     renderer = self.tileset.renderer()
     renderer.render(painter, self.elementId())
     painter.resetTransform()
     self._drawDarkness(painter)
     if self.showFace():
         faceSize = self.tileset.faceSize.toSize()
         faceSize = QSize(faceSize.width() * xScale, faceSize.height() * yScale)
         painter.translate(self.facePos())
         renderer.render(painter, self.tileset.svgName[self.tile.element.lower()],
                 QRectF(QPointF(), QSizeF(faceSize)))
     return result
示例#4
0
def run(driver, driver_info):
    """Convenience method to run command on the given driver"""
    cmd = SRCommand(driver_info)
    try:
        cmd.parse()
        cmd.run_statics()
        sr = driver(cmd, cmd.sr_uuid)
        sr.direct = True
        ret = cmd.run(sr)

        if ret == None:
            print util.return_nil()
        else:
            print ret

    except (Exception, SR.SRException) as e:
        try:
            util.logException(driver_info['name'])
        except KeyError:
            util.SMlog('driver_info does not contain a \'name\' key.')
        except:
            pass

        # If exception is of type SR.SRException, pass to Xapi.
        # If generic python Exception, print a generic xmlrpclib
        # dump and pass to XAPI.
        if isinstance(e, SR.SRException):
            print e.toxml()
        else:
            print xmlrpclib.dumps(xmlrpclib.Fault(1200, str(e)), "", True)

    sys.exit(0)
示例#5
0
    def mount(self, mountpoint=None):

        mountpoint = self.makeMountPoint(mountpoint)

        new_env, domain = cifutils.getCIFCredentials(self.dconf, self.session)

        options = self.getMountOptions(domain)
        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], new_env=new_env),
                errlist=[errno.EPIPE, errno.EIO],
                maxretry=2, nofail=True)
        except util.CommandException as inst:
            raise SMBException("mount failed with return code %d" % inst.code)

        # Sanity check to ensure that the user has at least RO access to the
        # mounted share. Windows sharing and security settings can be tricky.
        try:
            util.listdir(mountpoint)
        except util.CommandException:
            try:
                self.unmount(mountpoint, True)
            except SMBException:
                util.logException('SMBSR.unmount()')
            raise SMBException("Permission denied. "
                                "Please check user privileges.")
示例#6
0
    def create(self, sr_uuid, size):
        self.__check_license()

        if self.checkmount():
            raise xs_errors.XenError('SMBAttached')

        try:
            self.mount()
        except SMBException as exc:
            try:
                os.rmdir(self.mountpoint)
            except:
                pass
            raise xs_errors.XenError('SMBMount', opterr=exc.errstr)

        if util.ioretry(lambda: util.pathexists(self.linkpath)):
            if len(util.ioretry(lambda: util.listdir(self.linkpath))) != 0:
                self.detach(sr_uuid)
                raise xs_errors.XenError('SRExists')
        else:
            try:
                util.ioretry(lambda: util.makedirs(self.linkpath))
                os.symlink(self.linkpath, self.path)
            except util.CommandException as inst:
                if inst.code != errno.EEXIST:
                    try:
                        self.unmount(self.mountpoint, True)
                    except SMBException:
                        util.logException('SMBSR.unmount()')
                    raise xs_errors.XenError(
                            'SMBCreate',
                            opterr="remote directory creation error: {}"
                                    .format(os.strerror(inst.code))
                    )
        self.detach(sr_uuid)
示例#7
0
文件: board.py 项目: jsj2008/kdegames
 def fset(self, lightSource):
     """set active lightSource"""
     # pylint: disable=W0212
     if self._lightSource != lightSource:
         if lightSource not in LIGHTSOURCES:
             logException(TileException('lightSource %s illegal' % lightSource))
         self._reload(self.tileset, lightSource)
示例#8
0
 def quitProgram(result=None):
     """now all connections to servers are cleanly closed"""
     if isinstance(result, Failure):
         logException(result)
     try:
         Internal.reactor.stop()
     except ReactorNotRunning:
         pass
     StateSaver.saveAll()
     field = Internal.field
     if field:
         # if we have the ruleset editor visible, we get:
         # File "/hdd/pub/src/gitgames/kajongg/src/rulesetselector.py", line 194, in headerData
         #  if role == Qt.DisplayRole and orientation == Qt.Horizontal:
         #  AttributeError: 'NoneType' object has no attribute 'DisplayRole'
         # how can Qt get None? Same happens with QEvent, see statesaver.py
         if field.confDialog:
             field.confDialog.hide()
         field.hide(
         )  # do not make the user see the delay for stopping the reactor
     # we may be in a Deferred callback which would
     # catch sys.exit as an exception
     # and the qt4reactor does not quit the app when being stopped
     Internal.quitWaitTime = 0
     QTimer.singleShot(10, Client.appquit)
示例#9
0
 def startLocalServer(self, port):
     """start a local server"""
     try:
         args = ['kajonggserver']  # the default
         if sys.argv[0].endswith('kajongg.py'):
             tryServer = sys.argv[0].replace('.py', 'server.py')
             if os.path.exists(tryServer):
                 args = ['python', tryServer]
         if self.useSocket or os.name == 'nt':
             args.append('--local')
         if port:
             args.append('--port=%d' % port)
         if self.useSocket:
             args.append('--db=%slocal.db' % appdataDir())
         if Debug.argString:
             args.append('--debug=%s' % Debug.argString)
         if Options.socket:
             args.append('--socket=%s' % Options.socket)
         process = subprocess.Popen(args, shell=os.name == 'nt')
         if Debug.connections:
             logDebug(
                 m18n(
                     'started the local kajongg server: pid=<numid>%1</numid> %2',
                     process.pid, ' '.join(args)))
     except OSError as exc:
         logException(exc)
示例#10
0
def run(driver, driver_info):
    """Convenience method to run command on the given driver"""
    cmd = SRCommand(driver_info)
    try:
        cmd.parse()
        cmd.run_statics()
        sr = driver(cmd, cmd.sr_uuid)
        sr.direct = True
        ret = cmd.run(sr)

        if ret == None:
            print util.return_nil ()
        else:
            print ret

    except (Exception, SR.SRException) as e:
        try:
            util.logException(driver_info['name'])
        except KeyError:
            util.SMlog('driver_info does not contain a \'name\' key.')
        except:
            pass

        # If exception is of type SR.SRException,
        # pass to xapi, else re-raise.
        if isinstance(e, SR.SRException):
            print e.toxml()
        else:
            raise

    sys.exit(0)
示例#11
0
def run(driver, driver_info):
    """Convenience method to run command on the given driver"""
    cmd = SRCommand(driver_info)
    try:
        cmd.parse()
        cmd.run_statics()
        sr = driver(cmd, cmd.sr_uuid)
        sr.direct = True
        ret = cmd.run(sr)

        if ret == None:
            print util.return_nil ()
        else:
            print ret

    except (Exception, SR.SRException) as e:
        try:
            util.logException(driver_info['name'])
        except KeyError:
            util.SMlog('driver_info does not contain a \'name\' key.')
        except:
            pass

        # If exception is of type SR.SRException, pass to Xapi.
        # If generic python Exception, print a generic xmlrpclib
        # dump and pass to XAPI.
        if isinstance(e, SR.SRException):
            print e.toxml()
        else:
            print xmlrpclib.dumps(xmlrpclib.Fault(1200, str(e)), "", True) 

    sys.exit(0)
示例#12
0
 def playerByName(self, playerName):
     """return None or the matching player"""
     if playerName is None:
         return None
     for myPlayer in self.players:
         if myPlayer.name == playerName:
             return myPlayer
     logException('Move references unknown player %s' % playerName)
示例#13
0
 def __getitem__(self, index):
     """allow access by idx or by wind"""
     if isinstance(index, basestring) and len(index) == 1:
         for player in self:
             if player.wind == index:
                 return player
         logException("no player has wind %s" % index)
     return list.__getitem__(self, index)
示例#14
0
 def validateDefinition(self, prevDefinition):
     """check for validity. If wrong, restore prevDefinition."""
     payers = int(self.options.get('payers', 1))
     payees = int(self.options.get('payees', 1))
     if not 2 <= payers + payees <= 4:
         self.definition = prevDefinition
         logException(m18nc('%1 can be a sentence', '%4 have impossible values %2/%3 in rule "%1"',
                               self.name, payers, payees, 'payers/payees'))
示例#15
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     try:
         if not util.pathexists(self.sr.path):
             self.sr.attach(sr_uuid)
     except:
         util.logException("SMBFileVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable',
                                  opterr='Unable to attach from config')
示例#16
0
 def __init__(self, cmdList, args=None, dbHandle=None, silent=False, mayFail=False):
     """we take a list of sql statements. Only the last one is allowed to be
     a select statement.
     Do prepared queries by passing a single query statement in cmdList
     and the parameters in args. If args is a list of lists, execute the
     prepared query for every sublist.
     If dbHandle is passed, use that for db access.
     Else if the default dbHandle (DBHandle.default) is defined, use it."""
     # pylint: disable=R0912
     # pylint says too many branches
     silent |= not Debug.sql
     self.dbHandle = dbHandle or DBHandle.default
     preparedQuery = not isinstance(cmdList, list) and bool(args)
     self.query = QSqlQuery(self.dbHandle)
     self.msg = None
     self.records = []
     if not isinstance(cmdList, list):
         cmdList = list([cmdList])
     self.cmdList = cmdList
     for cmd in cmdList:
         retryCount = 0
         while retryCount < 100:
             self.lastError = None
             if preparedQuery:
                 self.query.prepare(cmd)
                 if not isinstance(args[0], list):
                     args = list([args])
                 for dataSet in args:
                     if not silent:
                         _, utf8Args = xToUtf8(u'', dataSet)
                         logDebug("{cmd} [{args}]".format(cmd=cmd, args=", ".join(utf8Args)))
                     for value in dataSet:
                         self.query.addBindValue(QVariant(value))
                     self.success = self.query.exec_()
                     if not self.success:
                         break
             else:
                 if not silent:
                     logDebug('%s %s' % (self.dbHandle.name, cmd))
                 self.success = self.query.exec_(cmd)
             if self.success or self.query.lastError().number() not in (5, 6):
                 # 5: database locked, 6: table locked. Where can we get symbols for this?
                 break
             time.sleep(0.1)
             retryCount += 1
         if not self.success:
             self.lastError = unicode(self.query.lastError().text())
             self.msg = 'ERROR in %s: %s' % (self.dbHandle.databaseName(), self.lastError)
             if mayFail:
                 if not silent:
                     logDebug(self.msg)
             else:
                 logException(self.msg)
             return
     self.records = None
     self.fields = None
     if self.query.isSelect():
         self.retrieveRecords()
示例#17
0
 def loadGame(self):
     """load a game"""
     selnum = len(self.selection.selectedRows())
     if selnum != 1:
         # should never happen
         logException('loadGame: %d rows selected' % selnum)
     idx = self.view.currentIndex()
     self.selectedGame = self.model.record(idx.row()).value(0).toInt()[0]
     self.buttonBox.accepted.emit()
示例#18
0
def _log_last_triggered(session, sr_uuid):
    try:
        sr_ref = session.xenapi.SR.get_by_uuid(sr_uuid)
        other_config = session.xenapi.SR.get_other_config(sr_ref)
        if other_config.has_key(TRIM_LAST_TRIGGERED_KEY):
            session.xenapi.SR.remove_from_other_config(sr_ref, TRIM_LAST_TRIGGERED_KEY)
        session.xenapi.SR.add_to_other_config(sr_ref, TRIM_LAST_TRIGGERED_KEY, str(time.time()))
    except:
        util.logException("Unable to set other-config:%s" % TRIM_LAST_TRIGGERED_KEY)
示例#19
0
def _log_last_triggered(session, sr_uuid):
    try:
        sr_ref = session.xenapi.SR.get_by_uuid(sr_uuid)
        other_config = session.xenapi.SR.get_other_config(sr_ref)
        if other_config.has_key(TRIM_LAST_TRIGGERED_KEY):
            session.xenapi.SR.remove_from_other_config(sr_ref, TRIM_LAST_TRIGGERED_KEY)
        session.xenapi.SR.add_to_other_config(sr_ref, TRIM_LAST_TRIGGERED_KEY, str(time.time()))
    except:
        util.logException("Unable to set other-config:%s" % TRIM_LAST_TRIGGERED_KEY)
示例#20
0
def initDb():
    """open the db, create or update it if needed.
    sets DBHandle.default."""
    try:
        DBHandle() # sets DBHandle.default
    except BaseException as exc:
        DBHandle.default = None
        logException(exc)
        return False
    return True
示例#21
0
文件: LVHDoISCSISR.py 项目: falaa/sm
 def attach_from_config(self, sr_uuid, vdi_uuid):
     util.SMlog("LVHDoISCSIVDI.attach_from_config")
     try:
         self.sr.iscsi.attach(sr_uuid)
         if not self.sr.iscsi._attach_LUN_bySCSIid(self.sr.SCSIid):
             raise xs_errors.XenError("InvalidDev")
         return LVHDSR.LVHDVDI.attach(self, sr_uuid, vdi_uuid)
     except:
         util.logException("LVHDoISCSIVDI.attach_from_config")
         raise xs_errors.XenError("SRUnavailable", opterr="Unable to attach the heartbeat disk")
示例#22
0
文件: NFSSR.py 项目: BobBall/sm
 def attach_from_config(self, sr_uuid, vdi_uuid):
     """Used for HA State-file only. Will not just attach the VDI but
     also start a tapdisk on the file"""
     util.SMlog("NFSFileVDI.attach_from_config")
     try:
         self.sr.attach(sr_uuid)
     except:
         util.logException("NFSFileVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach from config')
示例#23
0
 def validateDefinition(self, prevDefinition):
     """check for validity. If wrong, restore prevDefinition."""
     payers = int(self.options.get('payers', 1))
     payees = int(self.options.get('payees', 1))
     if not 2 <= payers + payees <= 4:
         self.definition = prevDefinition
         logException(
             m18nc('%1 can be a sentence',
                   '%4 have impossible values %2/%3 in rule "%1"',
                   self.name, payers, payees, 'payers/payees'))
示例#24
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     try:
         self.sr.attach(sr_uuid)
         if not self.sr._attach_LUN_bySCSIid(self.sr.SCSIid):
             raise xs_errors.XenError('InvalidDev')
         return LVHDSR.LVHDVDI.attach(self, sr_uuid, vdi_uuid)
     except:
         util.logException('LVHDoRBDVDI.attach_from_config')
         raise xs_errors.XenError('SRUnavailable',
                                  opterr='Failed to attach RBD')
示例#25
0
def initDb():
    """open the db, create or update it if needed.
    sets DBHandle.default."""
    try:
        DBHandle()  # sets DBHandle.default
    except BaseException as exc:
        DBHandle.default = None
        logException(exc)
        return False
    return True
示例#26
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     """Used for HA State-file only. Will not just attach the VDI but
     also start a tapdisk on the file"""
     util.SMlog("NFSFileVDI.attach_from_config")
     try:
         self.sr.attach(sr_uuid)
     except:
         util.logException("NFSFileVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach from config')
    def create(self, sr_uuid, size):
        try:

            # attach the device
            util.SMlog("Trying to attach iscsi disk")

            self.iscsi.attach(sr_uuid)
            if not self.iscsi.attached:
                raise xs_errors.XenError('SRNotAttached')

            util.SMlog("Attached iscsi disk at %s \n" % self.iscsi.path)

            try:

                # generate new UUIDs for VG and LVs
                old_vg_name = self._getVgName(self.dconf['device'])

                lvm_config_dict = self._getLvmInfo(old_vg_name)
                lvUuidMap = {}  # Maps old lv uuids to new uuids

                for lv_name in lvm_config_dict[old_vg_name]['logical_volumes']:
                    if lv_name == MDVOLUME_NAME:
                        continue
                    oldUuid = lv_name[4:]  # remove the VHD-
                    lvUuidMap[oldUuid] = util.gen_uuid()

                new_vg_name = VG_PREFIX + sr_uuid

                self._resignLvm(sr_uuid, old_vg_name, lvUuidMap,
                                lvm_config_dict)

                # causes creation of nodes and activates the lvm volumes
                LVHDSR.LVHDSR.load(self, sr_uuid)

                new_vdi_info = self._resignSrMetadata(new_vg_name, self.uuid,
                                                      lvUuidMap)
                self._resignVdis(new_vg_name, lvUuidMap)
                self._deleteAllSnapshots(new_vdi_info)

                # Detach LVM
                self.lvmCache.deactivateNoRefcount(MDVOLUME_NAME)
                for newUuid in lvUuidMap.values():
                    new_lv_name = self.LV_VHD_PREFIX + newUuid
                    self.lvmCache.deactivateNoRefcount(new_lv_name)

            except:
                util.logException("RESIGN_CREATE")
                raise

        finally:
            iscsilib.logout(self.iscsi.target, self.iscsi.targetIQN, all=True)

        raise xs_errors.XenError(
            "The SR has been successfully resigned. Use the lvmoiscsi type to attach it"
        )
示例#28
0
 def findFreePort():
     """find an unused port on the current system.
     used when we want to start a local server on windows"""
     for port in range(2000, 9000):
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.settimeout(1)
         try:
             sock.connect(('127.0.0.1', port))
         except socket.error:
             return port
     logException('cannot find a free port')
示例#29
0
 def findFreePort():
     """find an unused port on the current system.
     used when we want to start a local server on windows"""
     for port in range(2000, 9000):
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.settimeout(1)
         try:
             sock.connect(('127.0.0.1', port))
         except socket.error:
             return port
     logException('cannot find a free port')
示例#30
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     util.SMlog("OCFSoISCSIVDI.attach_from_config")
     try:
         self.sr.iscsi.attach(sr_uuid)
         if not self.sr.iscsi._attach_LUN_bySCSIid(self.sr.SCSIid):
             raise xs_errors.XenError('InvalidDev')
         return OCFSSR.OCFSFileVDI.attach(self, sr_uuid, vdi_uuid)
     except:
         util.logException("OCFSoISCSIVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach the heartbeat disk')
示例#31
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     util.SMlog("LVHDoHBAVDI.attach_from_config")
     self.sr.hbasr.attach(sr_uuid)
     if self.sr.mpath == "true":
         self.sr.mpathmodule.refresh(self.sr.SCSIid,0)
     try:
         return self.attach(sr_uuid, vdi_uuid)
     except:
         util.logException("LVHDoHBAVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach the heartbeat disk')
示例#32
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     util.SMlog("OCFSoHBAVDI.attach_from_config")
     self.sr.hbasr.attach(sr_uuid)
     if self.sr.mpath == "true":
         self.sr.mpathmodule.refresh(self.sr.SCSIid,0)
     try:
         return self.attach(sr_uuid, vdi_uuid)
     except:
         util.logException("OCFSoHBAVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach the heartbeat disk')
示例#33
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     util.SMlog("OCFSoISCSIVDI.attach_from_config")
     try:
         self.sr.iscsi.attach(sr_uuid)
         if not self.sr.iscsi._attach_LUN_bySCSIid(self.sr.SCSIid):
             raise xs_errors.XenError('InvalidDev')
         return OCFSSR.OCFSFileVDI.attach(self, sr_uuid, vdi_uuid)
     except:
         util.logException("OCFSoISCSIVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach the heartbeat disk')
示例#34
0
 def run(self, sr):
     try:
         return self._run_locked(sr)
     except (util.SMException, XenAPI.Failure), e:
         util.logException(self.cmd)
         msg = str(e)
         if isinstance(e, util.CommandException):
             msg = "Command %s failed (%s): %s" % (e.cmd, e.code, e.reason)
         excType = EXCEPTION_TYPE.get(self.cmd)
         if not excType:
             excType = "SMGeneral"
         raise xs_errors.XenError(excType, opterr=msg)
示例#35
0
文件: lvmcache.py 项目: BobBall/sm
 def wrapper(self, *args):
     if not self.initialized:
         util.SMlog("LVMCache: will initialize now")
         self.refresh()
         #util.SMlog("%s(%s): %s" % (op, args, self.toString()))
     try:
         ret = op(self, *args)
     except KeyError:
         util.logException("LVMCache")
         util.SMlog("%s(%s): %s" % (op, args, self.toString()))
         raise
     return ret
示例#36
0
文件: lvmcache.py 项目: xcp-ng/sm
 def wrapper(self, *args):
     if not self.initialized:
         util.SMlog("LVMCache: will initialize now")
         self.refresh()
         #util.SMlog("%s(%s): %s" % (op, args, self.toString()))
     try:
         ret = op(self, *args)
     except KeyError:
         util.logException("LVMCache")
         util.SMlog("%s(%s): %s" % (op, args, self.toString()))
         raise
     return ret
示例#37
0
    def create(self, sr_uuid, size):
        try:

            # attach the device
            util.SMlog("Trying to attach iscsi disk")

            self.iscsi.attach(sr_uuid)
            if not self.iscsi.attached:
                raise xs_errors.XenError('SRNotAttached')

            util.SMlog("Attached iscsi disk at %s \n" % self.iscsi.path)

            try:

                # generate new UUIDs for VG and LVs
                old_vg_name = self._getVgName(self.dconf['device'])

                lvm_config_dict = self._getLvmInfo(old_vg_name)
                lvUuidMap = {}  # Maps old lv uuids to new uuids

                for lv_name in lvm_config_dict[old_vg_name]['logical_volumes']:
                    if lv_name == MDVOLUME_NAME:
                        continue
                    oldUuid = lv_name[4:]  # remove the VHD-
                    lvUuidMap[oldUuid] = util.gen_uuid()

                new_vg_name = VG_PREFIX + sr_uuid

                self._resignLvm(sr_uuid, old_vg_name, lvUuidMap, lvm_config_dict)

                # causes creation of nodes and activates the lvm volumes
                LVHDSR.LVHDSR.load(self, sr_uuid)

                new_vdi_info = self._resignSrMetadata(new_vg_name, self.uuid, lvUuidMap)
                self._resignVdis(new_vg_name, lvUuidMap)
                self._deleteAllSnapshots(new_vdi_info)


                # Detach LVM
                self.lvmCache.deactivateNoRefcount(MDVOLUME_NAME)
                for newUuid in lvUuidMap.values():
                    new_lv_name = self.LV_VHD_PREFIX + newUuid
                    self.lvmCache.deactivateNoRefcount(new_lv_name)

            except:
                util.logException("RESIGN_CREATE")
                raise

        finally:
            iscsilib.logout(self.iscsi.target, self.iscsi.targetIQN, all=True)

        raise xs_errors.XenError("The SR has been successfully resigned. Use the lvmoiscsi type to attach it")
示例#38
0
文件: journaler.py 项目: stormi/sm
    def create(self, type, id, val):
        """Create an entry of type "type" for "id" with the value "val".
        Error if such an entry already exists."""
        valExisting = self.get(type, id)
        writeData = False
        if valExisting:
            raise JournalerException("Journal already exists for '%s:%s': %s" \
                    % (type, id, valExisting))
        lvName = self._getNameLV(type, id, val)

        mapperDevice = self._getLVMapperName(lvName)
        if len(mapperDevice) > LVM_MAX_NAME_LEN:
            lvName = self._getNameLV(type, id)
            writeData = True
            mapperDevice = self._getLVMapperName(lvName)
            assert len(mapperDevice) <= LVM_MAX_NAME_LEN

        self.lvmCache.create(lvName, self.LV_SIZE, self.LV_TAG)

        if writeData:
            fullPath = self.lvmCache._getPath(lvName)
            fd = open_file(fullPath, True)
            try:
                e = None
                try:
                    min_block_size = get_min_blk_size_wrapper(fd)
                    data = "%d %s" % (len(val), val)
                    file_write_wrapper(fd, 0, min_block_size, data, len(data))
                except Exception as e:
                    raise
                finally:
                    try:
                        close(fd)
                        self.lvmCache.deactivateNoRefcount(lvName)
                    except Exception as e2:
                        msg = 'failed to close/deactivate %s: %s' \
                                % (lvName, e2)
                        if not e:
                            util.SMlog(msg)
                            raise e2
                        else:
                            util.SMlog('WARNING: %s (error ignored)' % msg)

            except:
                util.logException("journaler.create")
                try:
                    self.lvmCache.remove(lvName)
                except Exception as e:
                    util.SMlog('WARNING: failed to clean up failed journal ' \
                            ' creation: %s (error ignored)' % e)
                raise JournalerException("Failed to write to journal %s" \
                    % lvName)
示例#39
0
文件: lvutil.py 项目: MarkSymsCtx/sm
def scan_srlist(prefix, root):
    VGs = {}
    for dev in root.split(','):
        try:
            sr_uuid = _get_sr_uuid(dev, [prefix]).strip(' \n')
            if len(sr_uuid):
                if VGs.has_key(sr_uuid):
                    VGs[sr_uuid] += ",%s" % dev
                else:
                    VGs[sr_uuid] = dev
        except Exception, e:
            util.logException("exception (ignored): %s" % e)
            continue
示例#40
0
文件: FileSR.py 项目: MarkSymsCtx/sm
 def attach_from_config(self, sr_uuid, vdi_uuid):
     """
     Attach and activate a VDI using config generated by
     vdi_generate_config above. This is used for cases such as
     the HA state-file and the redo-log.
     """
     util.SMlog("FileVDI.attach_from_config")
     try:
         if not util.pathexists(self.sr.path):
             self.sr.attach(sr_uuid)
     except:
         util.logException("FileVDI.attach_from_config")
         raise xs_errors.XenError("SRUnavailable", opterr="Unable to attach from config")
示例#41
0
 def attach(self, sr_uuid, vdi_uuid):
     try:
         vdi_ref = self.sr.srcmd.params['vdi_ref']
         self.session.xenapi.VDI.remove_from_xenstore_data(vdi_ref, \
                                                           "vdi-type")
         self.session.xenapi.VDI.remove_from_xenstore_data(vdi_ref, \
                                                           "storage-type")
         self.session.xenapi.VDI.add_to_xenstore_data(vdi_ref, \
                                                      "storage-type", "nfs")
     except:
         util.logException("NFSSR:attach")
         pass
     return super(NFSFileVDI, self).attach(sr_uuid, vdi_uuid)
示例#42
0
def scan_srlist(prefix, root, sr_alloc=None):
    VGs = {}
    for dev in root.split(','):
        try:
            sr_uuid = _get_sr_uuid(dev, [prefix]).strip(' \n')
            if len(sr_uuid):
                if VGs.has_key(sr_uuid):
                    VGs[sr_uuid] += ",%s" % dev
                else:
                    VGs[sr_uuid] = dev
        except Exception, e:
            util.logException("exception (ignored): %s" % e)
            continue
示例#43
0
 def attach(self, sr_uuid, vdi_uuid):
     try:
         vdi_ref = self.sr.srcmd.params['vdi_ref']
         self.session.xenapi.VDI.remove_from_xenstore_data(vdi_ref, \
                                                           "vdi-type")
         self.session.xenapi.VDI.remove_from_xenstore_data(vdi_ref, \
                                                           "storage-type")
         self.session.xenapi.VDI.add_to_xenstore_data(vdi_ref, \
                                                      "storage-type", "nfs")
     except:
         util.logException("NFSSR:attach")
         pass
     return super(NFSFileVDI, self).attach(sr_uuid, vdi_uuid)
示例#44
0
 def run(self, sr):
     try:
         return self._run_locked(sr)
     except (util.CommandException, util.SMException, XenAPI.Failure), e:
         util.logException(self.cmd)
         msg = str(e)
         if isinstance(e, util.CommandException):
             msg = "Command %s failed (%s): %s" % \
                     (e.cmd, e.reason, os.strerror(abs(e.code)))
         excType = EXCEPTION_TYPE.get(self.cmd)
         if not excType:
             excType = "SMGeneral"
         raise xs_errors.XenError(excType, opterr=msg)
示例#45
0
 def __init__(self):
     QSqlDatabase.__init__(self, "QSQLITE")
     if not DBHandle.default:
         DBHandle.default = self
     if not os.path.exists(self.dbPath()):
         self.createDatabase()
     self.setDatabaseName(self.dbPath())
     if not self.open():
         self.default = None
         logException('opening %s: %s' % (self.dbPath(), self.lastError()))
     # timeout in msec:
     self.setConnectOptions("QSQLITE_BUSY_TIMEOUT=2000")
     with Transaction(silent=True):
         self.upgradeDb()
示例#46
0
 def __init__(self):
     QSqlDatabase.__init__(self, "QSQLITE")
     if not DBHandle.default:
         DBHandle.default = self
     if not os.path.exists(self.dbPath()):
         self.createDatabase()
     self.setDatabaseName(self.dbPath())
     if not self.open():
         self.default = None
         logException('opening %s: %s' % (self.dbPath(), self.lastError()))
     # timeout in msec:
     self.setConnectOptions("QSQLITE_BUSY_TIMEOUT=2000")
     with Transaction(silent=True):
         self.upgradeDb()
示例#47
0
文件: lvutil.py 项目: xcp-ng/sm
def scan_srlist(prefix, root):
    VGs = {}
    for dev in root.split(','):
        try:
            sr_uuid = _get_sr_uuid(dev, [prefix]).strip(' \n')
            if len(sr_uuid):
                if sr_uuid in VGs:
                    VGs[sr_uuid] += ",%s" % dev
                else:
                    VGs[sr_uuid] = dev
        except Exception as e:
            util.logException("exception (ignored): %s" % e)
            continue
    return VGs
示例#48
0
文件: SRCommand.py 项目: xcp-ng/sm
    def run(self, sr):
        try:
            return self._run_locked(sr)
        except (util.CommandException, util.SMException, XenAPI.Failure) as e:
            util.logException(self.cmd)
            msg = str(e)
            if isinstance(e, util.CommandException):
                msg = "Command %s failed (%s): %s" % \
                        (e.cmd, e.reason, os.strerror(abs(e.code)))
            excType = EXCEPTION_TYPE.get(self.cmd)
            if not excType:
                excType = "SMGeneral"
            raise xs_errors.XenError(excType, opterr=msg)

        except blktap2.TapdiskFailed as e:
            util.logException('tapdisk failed exception: %s' % e)
            raise xs_errors.XenError(
                'TapdiskFailed', os.strerror(e.get_error().get_error_code()))

        except blktap2.TapdiskExists as e:
            util.logException('tapdisk exists exception: %s' % e)
            raise xs_errors.XenError('TapdiskAlreadyRunning', e.__str__())

        except:
            util.logException('generic exception: %s' % self.cmd)
            raise
示例#49
0
文件: lvmanager.py 项目: yunleid/sm
 def deactivateAll(self):
     # this is the cleanup step that will be performed even if the original
     # operation failed - don't throw exceptions here
     success = True
     for persistent in [self.TEMPORARY, self.PERSISTENT]:
         for binary in [self.NORMAL, self.BINARY]:
             uuids = self.lvActivations[persistent][binary].keys()
             for uuid in uuids:
                 try:
                     self.deactivate(uuid, binary, persistent)
                 except:
                     success = False
                     util.logException("_deactivateAll")
     return success
示例#50
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     """
     Attach and activate a VDI using config generated by
     vdi_generate_config above. This is used for cases such as
     the HA state-file and the redo-log.
     """
     util.SMlog("FileVDI.attach_from_config")
     try:
         if not util.pathexists(self.sr.path):
             self.sr.attach(sr_uuid)
     except:
         util.logException("FileVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable',
                                  opterr='Unable to attach from config')
 def deactivateAll(self):
     # this is the cleanup step that will be performed even if the original 
     # operation failed - don't throw exceptions here
     success = True
     for persistent in [self.TEMPORARY, self.PERSISTENT]:
         for binary in [self.NORMAL, self.BINARY]:
             uuids = self.lvActivations[persistent][binary].keys()
             for uuid in uuids:
                 try:
                     self.deactivate(uuid, binary, persistent)
                 except:
                     success = False
                     util.logException("_deactivateAll")
     return success
示例#52
0
 def __init__(self):
     if common.Preferences:
         logException('Preferences is not None')
     common.Preferences = self
     KConfigSkeleton.__init__(self)
     self.addString('General', 'tilesetName', 'default')
     self.addString('General', 'windTilesetName', 'traditional')
     self.addString('General', 'backgroundName', 'wood_light')
     self.addBool('Display', 'showShadows', True)
     self.addBool('Display', 'rearrangeMelds', False)
     self.addBool('Display', 'showOnlyPossibleActions', True)
     self.addBool('Display', 'propose', True)
     self.addInteger('Display', 'animationSpeed', 70, 0, 99)
     self.addBool('Display', 'useSounds', True)
     self.addBool('Display', 'uploadVoice', False)
示例#53
0
 def __init__(self):
     if common.Preferences:
         logException('Preferences is not None')
     common.Preferences = self
     KConfigSkeleton.__init__(self)
     self.addString('General', 'tilesetName', 'default')
     self.addString('General', 'windTilesetName', 'traditional')
     self.addString('General', 'backgroundName', 'wood_light')
     self.addBool('Display', 'showShadows', True)
     self.addBool('Display', 'rearrangeMelds', False)
     self.addBool('Display', 'showOnlyPossibleActions', True)
     self.addBool('Display', 'propose', True)
     self.addInteger('Display', 'animationSpeed', 70, 0, 99)
     self.addBool('Display', 'useSounds', True)
     self.addBool('Display', 'uploadVoice', False)
示例#54
0
 def createDatabase(self):
     """use a temp file name. When done, rename to final file name,
     thusly avoiding races if two processes want to build the same
     database"""
     tempName = '%s.new.%d' % (self.dbPath(), os.getpid())
     self.setDatabaseName(tempName)
     if not self.open():
         logException('creating %s: %s' % (tempName, self.lastError()))
     with Transaction(silent=True):
         self.createTables()
         self.__generateDbIdent()
     QSqlDatabase.close(self)
     newName = self.dbPath()
     if os.path.exists(newName):
         os.remove(tempName)
     else:
         os.rename(tempName, newName)
示例#55
0
 def showConcealedTiles(self, tileNames, show=True):
     """show or hide tileNames"""
     if not self.game.playOpen and self != self.game.myself:
         if not isinstance(tileNames, (list, tuple)):
             tileNames = [tileNames]
         assert len(tileNames) <= len(self.__concealedTileNames), \
             '%s: showConcealedTiles %s, we have only %s' % (self, tileNames, self.__concealedTileNames)
         for tileName in tileNames:
             src, dst = ('Xy', tileName) if show else (tileName, 'Xy')
             assert src != dst, (self, src, dst, tileNames, self.__concealedTileNames)
             if not src in self.__concealedTileNames:
                 logException( '%s: showConcealedTiles(%s): %s not in %s.' % \
                         (self, tileNames, src, self.__concealedTileNames))
             idx = self.__concealedTileNames.index(src)
             self.__concealedTileNames[idx] = dst
         self.__hand = None
         self.syncHandBoard()
示例#56
0
 def wrapper(self, *args):
     acquired = False
     if not self.lock.held():
         self.lock.acquire()
         acquired = True
     try:
         try:
             ret = op(self, *args)
         except (util.SMException, XenAPI.Failure), e:
             util.logException("FileSR:%s" % op)
             msg = str(e)
             if isinstance(e, util.CommandException):
                 msg = "Command %s failed (%s): %s" % \
                         (e.cmd, e.code, e.reason)
             raise xs_errors.XenError(excType, opterr=msg)
         except:
             util.logException("FileSR:%s" % op)
             raise
示例#57
0
 def attach_from_config(self, sr_uuid, vdi_uuid):
     util.SMlog("RBDVDI.attach_from_config")
     self.sr.attach(sr_uuid)
     try:
         vdi_name = "%s%s" % (cephutils.VDI_PREFIX, vdi_uuid)
         dev_name = "%s/%s" % (self.sr.SR_ROOT, vdi_name)
         self.path = self.sr._get_path(vdi_uuid)
         if self.mode == "kernel":
             util.pread2(["rbd", "map", vdi_name, "--pool", self.sr.CEPH_POOL_NAME, "--name", self.sr.CEPH_USER])
         elif self.mode == "fuse":
             pass
         elif self.mode == "nbd":
             cmdout = util.pread2(["rbd-nbd", "--nbds_max", str(cephutils.NBDS_MAX), "map", "%s/%s" % (self.sr.CEPH_POOL_NAME, vdi_name), "--name", self.sr.CEPH_USER]).rstrip('\n')
             util.pread2(["ln", "-s", cmdout, dev_name])
         return VDI.VDI.attach(self, sr_uuid, vdi_uuid)
     except:
         util.logException("RBDVDI.attach_from_config")
         raise xs_errors.XenError('SRUnavailable', \
                     opterr='Unable to attach the heartbeat disk')
示例#58
0
 def renderer(self):
     """initialise the svg renderer with the selected svg file"""
     if self.__renderer is None:
         self.__renderer = QSvgRenderer(self.__graphicspath)
         if not self.__renderer.isValid():
             logException(TileException( \
             m18n('file <filename>%1</filename> contains no valid SVG'), self.__graphicspath))
         distance = 0
         if self.desktopFileName == 'classic':
             distance = 2
         distanceSize = QSizeF(distance, distance)
         self.faceSize = self.__renderer.boundsOnElement('BAMBOO_1').size()+distanceSize
         self.tileSize = self.__renderer.boundsOnElement('TILE_2').size()+distanceSize
         if not Internal.scaleScene:
             self.faceSize /= 2
             self.tileSize /= 2
         shW = self.shadowWidth()
         shH = self.shadowHeight()
         self.__shadowOffsets = [[(-shW, 0), (0, 0), (0, shH), (-shH, shW)],
             [(0, 0), (shH, 0), (shW, shH), (0, shW)],
             [(0, -shH), (shH, -shW), (shW, 0), (0, 0)],
             [(-shW, -shH), (0, -shW), (0, 0), (-shH, 0)]]
     return self.__renderer
示例#59
0
 def pixmap(self, size):
     """returns a background pixmap or None for isPlain"""
     self.__pmap = None
     if not self.isPlain:
         width = size.width()
         height = size.height()
         if self.tiled:
             width = self.imageWidth
             height = self.imageHeight
         cachekey = QString("%1W%2H%3") \
             .arg(self.name).arg(width).arg(height)
         self.__pmap = QPixmapCache.find(cachekey)
         if not self.__pmap:
             renderer = QSvgRenderer(self.__graphicspath)
             if not renderer.isValid():
                 logException(BackgroundException( \
                 m18n('file <filename>%1</filename> contains no valid SVG', self.__graphicspath)))
             self.__pmap = QPixmap(width, height)
             self.__pmap.fill(Qt.transparent)
             painter = QPainter(self.__pmap)
             renderer.render(painter)
             QPixmapCache.insert(cachekey, self.__pmap)
     return self.__pmap