Ejemplo n.º 1
0
    def __ShutdownTimer(self):
        while self.state == SERVICE_RUNNING:
            try:
                if self.shutdownTime and self.shutdownTime - blue.os.GetWallclockTime(
                ) < 5 * const.MIN:
                    timeLeft = max(
                        0L, self.shutdownTime - blue.os.GetWallclockTime())
                    self.Say(
                        localization.GetByLabel(
                            'UI/Shared/ClusterShutdownInSeconds',
                            timeLeft=timeLeft))
            except:
                log.LogException()
                sys.exc_clear()

            blue.pyos.synchro.SleepWallclock(5000)
Ejemplo n.º 2
0
    def _Receiver(self):
        ch = self._channel
        while True:
            try:
                args, kw = ch.receive()
                blue.pyos.synchro.SleepWallclock(self._delay)
                while ch.balance != 0:
                    args, kw = ch.receive()

                self._fn(*args, **kw)
            except self._StopExc:
                sys.exc_clear()
                return
            except Exception:
                log.LogException()
                sys.exc_clear()
Ejemplo n.º 3
0
 def LoadScroll(self):
     if self is None or self.destroyed:
         return
     if not self.sr.Get('scroll'):
         return
     try:
         scrolllist = []
         sm.GetService('corpui').ShowLoad()
         self.ShowMyAllianceDetails(scrolllist)
         self.ShowMyAllianceSystems(scrolllist)
         self.sr.scroll.Load(contentList=scrolllist)
     except:
         log.LogException()
         sys.exc_clear()
     finally:
         sm.GetService('corpui').HideLoad()
Ejemplo n.º 4
0
    def Miner(self):
        try:
            while self.minerThread is threading.current_thread():
                time.sleep(self.threshold)
                now = time.time()
                self.minerTimestamp = now
                if not self.timestamp:
                    continue
                next_timestamp = self.timestamp + self.interval
                late = now - next_timestamp
                if late < self.threshold:
                    continue
                self.Report(late)

        except:
            log.LogException('canaryService.Miner thread errored out')
Ejemplo n.º 5
0
    def MoveCursor_thread(self):
        self.isMoving = True
        lib = uicore.uilib
        while lib.leftbtn:
            if self.currentCursor:
                x, y, z = self.GetSelectionCenter()
                dungeonOrigin = self.GetDungeonOrigin()
                playerPos = self.GetPlayerOffset()
                try:
                    rotation = self.GetSelectionRotation()
                    singleObjectRotation = self.currentCursor == 'Rotation' and len(
                        self.selection) == 1
                    multipleObjectRotation = self.currentCursor == 'Rotation' and len(
                        self.selection) > 1
                    if singleObjectRotation:
                        self.cursors[self.currentCursor].Rotate(
                            (rotation[0], rotation[1], rotation[2],
                             rotation[3]))
                    elif multipleObjectRotation:
                        self.cursors[self.currentCursor].Rotate(
                            (rotation[0], rotation[1], rotation[2],
                             -rotation[3]))
                    self.cursors[self.currentCursor].Translate(
                        trinity.TriVector(x - playerPos.x, y - playerPos.y,
                                          z - playerPos.z))
                    self.cursors[self.currentCursor].Transform(
                        uicore.uilib.x, uicore.uilib.y)
                    if multipleObjectRotation:
                        rotation = self.cursors[
                            self.currentCursor].GetRotation()
                        self.SetGroupSelectionRotation(
                            (rotation[0], rotation[1], rotation[2],
                             -rotation[3]))
                except:
                    self.LogError(
                        'Error when attempting to move the dungeon editor object manipulation tool.'
                    )
                    log.LogException()
                    sys.exc_clear()
                    self.isMoving = False
                    return

            self.lastChangeTimestamp = blue.os.GetWallclockTime()
            blue.synchro.Yield()

        self.isMoving = False
        self.StopMovingCursor()
Ejemplo n.º 6
0
    def Write(self, message):
        if self.transport:
            MachoTransport.Write(self, message)
        try:
            uthread.Lock(self, 'httpReaders')
            if len(
                    self.readers
            ) > 0 and message.command == const.cluster.MACHONETMSG_TYPE_NOTIFICATION:
                with bluepy.Timer(
                        'machoNet::StreamingHTTPMachoTransport::Write::MPT-Megahack'
                ):
                    sent = False
                    try:
                        data = message.__getstate__()
                        if data[0] == 12:
                            if data[2].__getstate__()[1] == '__MultiEvent':
                                self.LogInfo(
                                    'Splitting __MultiEvent into multiple chunks'
                                )
                                jsonMessage = json.loads(
                                    httpUtil.ToComplexJSON(data))
                                innerMessages = jsonMessage[4][0][1][1][1]
                                innerMessage = (12, None, [[], None], None,
                                                [[0, [0, [1, None]]]])
                                with bluepy.Timer(
                                        'machoNet::StreamingHTTPMachoTransport::Write::MPT-Megahack::Multiplex'
                                ):
                                    for msg in innerMessages:
                                        innerMessage[2][1] = msg[0]
                                        innerMessage[4][0][1][1][1] = msg[1]
                                        for reader in self.readers:
                                            reader.write(innerMessage)

                                    sent = True
                    except:
                        self.LogError('MultiEvent exception', message)
                        log.LogException()

                with bluepy.Timer(
                        'machoNet::StreamingHTTPMachoTransport::Write::Multiplex'
                ):
                    if not sent:
                        for reader in self.readers.copy():
                            reader.write(message)

        finally:
            uthread.UnLock(self, 'httpReaders')
Ejemplo n.º 7
0
    def ExceptionHandler(self, exctype, exc, tb, message=''):
        try:
            if isinstance(exc, UserError):
                self.Message(exc.msg, exc.dict)
            else:
                toMsgWindow = prefs.GetValue('showExceptions', 0)
                if isinstance(exc, RuntimeError) and len(
                        exc.args) and exc.args[0] == 'ErrMessageNotFound':
                    if toMsgWindow:
                        self.Message('ErrMessageNotFound', exc.args[1])
                else:
                    toMsgWindow = toMsgWindow and not self.noErrorPopups
                    if isinstance(exc, AttributeError):
                        deadWindowCheck = self.IsDestroyedWindow(tb)
                        if deadWindowCheck:
                            name = ''
                            try:
                                nameIdx = deadWindowCheck.find('name=')
                                if nameIdx != -1:
                                    nameIdx += 6
                                    endNameIdx = deadWindowCheck[
                                        nameIdx:].find('",')
                                    if endNameIdx != -1:
                                        name = deadWindowCheck[
                                            nameIdx:nameIdx + endNameIdx]
                            except:
                                sys.exc_clear()

                            log.LogWarn('Message sent to dead window:', name)
                            exctype = exc = tb = None
                            return
                    if getattr(exc, 'msg', None) == 'DisconnectedFromServer':
                        toMsgWindow = 0
                    severity = log.LGERR
                    extraText = '; caught by eve.ExceptionHandler'
                    if message:
                        extraText += '\nContext info: ' + message
                    return log.LogException(extraText=extraText,
                                            toMsgWindow=toMsgWindow,
                                            exctype=exctype,
                                            exc=exc,
                                            tb=tb,
                                            severity=severity)
        except:
            exctype = exc = tb = None
            traceback.print_exc()
            sys.exc_clear()
Ejemplo n.º 8
0
    def __FlushCache(self, yieldFirst):
        """
            If the cache has been changed since last flush, we dump it to disk.
        """
        if yieldFirst:
            blue.pyos.synchro.Yield()
        while self.lastChange:
            flushWhat, lastChange = self.lastChange.items()[0]
            del self.lastChange[flushWhat]
            what, key = flushWhat
            filename = self.cachePath + what + '/%s.cache' % self.KeyToFileName(
                key)
            if os.access(filename,
                         os.F_OK) and not os.access(filename, os.W_OK):
                try:
                    os.chmod(filename, 666)
                except StandardError:
                    self.LogWarn(
                        'Failed to reset access priviledges on file from file system (',
                        filename, ')')
                    sys.exc_clear()

            try:
                store = getattr(self, what)
                if key not in store:
                    try:
                        os.unlink(filename)
                        self.LogInfo('Deleted ', key, ' from file system (',
                                     filename, ')')
                    except StandardError as e:
                        self.LogWarn(
                            'Failed to delete file from file system (',
                            filename, '):', e)
                        sys.exc_clear()

                else:
                    ob = store[key]
                    if not isinstance(ob, uthread.Semaphore):
                        blue.win32.AtomicFileWrite(
                            filename, blue.marshal.Save((key, ob)))
                        self.LogInfo('Wrote ', key, ' to file (', filename,
                                     ')')
                        self.lastFileWriteTime[self.__KeyFromFileName(
                            filename)] = os.path.getmtime(filename)
            except Exception:
                log.LogException('Error while writing cached data')
                sys.exc_clear()
Ejemplo n.º 9
0
    def _RegisterComponents(self, entity, initData=None):
        """
        Called when the entity is registered with a scene
        """
        with uthread.BlockTrapSection():
            with entity.entityLock:
                try:
                    if entity.state == const.cef.ENTITY_STATE_CREATING:
                        entity.state = const.cef.ENTITY_STATE_READY
                        entity.scene.AddEntityToRegisteredList(entity)
                        registerCalls = []
                        for name, component in entity.components.iteritems():
                            systems = self.GetComponentSystems(name)
                            if systems:
                                for system in systems:
                                    f = getattr(system, 'RegisterComponent',
                                                None)
                                    if f:
                                        registerCalls.append(
                                            (f, (entity, component)))

                        if registerCalls:
                            for f, args in registerCalls:
                                f(*args)

                        del self.loadingEntities[entity.entityID]
                    elif entity.state in (const.cef.ENTITY_STATE_UNINITIALIZED,
                                          const.cef.ENTITY_STATE_DEAD,
                                          const.cef.ENTITY_STATE_READY):
                        self.LogError(
                            'RegisterComponents: Entity state should be either',
                            const.cef.ENTITY_STATE_NAMES[
                                const.cef.ENTITY_STATE_CREATING], 'or',
                            const.cef.ENTITY_STATE_NAMES[
                                const.cef.ENTITY_STATE_DESTROYING],
                            ', is instead',
                            const.cef.ENTITY_STATE_NAMES[entity.state],
                            '. Entity:', str(entity))
                    sm.ScatterEvent('OnEntityCreated', entity.entityID)
                    GameWorld.GetNetworkEntityQueueManager().ClearEntity(
                        entity.entityID)
                except Exception as e:
                    log.LogException(e)
                    self._deadEntityList[entity.entityID] = entity
                    if entity.scene and entity.entityID in entity.scene.entities:
                        del entity.scene.entities[entity.entityID]
                        self.entitySceneManager.Unregister(entity.entityID)
Ejemplo n.º 10
0
    def __init__(self):
        service.Service.__init__(self)
        self.certificates = {}
        try:
            for key, value in cfg.certificates['certificates'].iteritems():
                if hasattr(value, 'recommendedFor'):
                    recommendedFor = value.recommendedFor
                else:
                    recommendedFor = []
                self.certificates[key] = Certificate(key, value.groupID,
                                                     value.nameID,
                                                     value.descriptionID,
                                                     value.skillTypes,
                                                     recommendedFor)

        except KeyError:
            log.LogException()
Ejemplo n.º 11
0
    def Run(self, *args):
        service.Service.Run(self, *args)
        expire_hours, expire_mins = (2, 5)
        expire_ms = 1000 * (3600 * expire_hours + 60 * expire_mins)
        self.viewedWrecks = {}
        for itemID, time in settings.char.ui.Get('viewedWrecks', {}).iteritems():
            try:
                if blue.os.TimeDiffInMs(time, blue.os.GetWallclockTime()) < expire_ms:
                    self.viewedWrecks[itemID] = time
            except blue.error:
                sys.exc_clear()

        try:
            self._PersistSettings()
        except:
            log.LogException()
            sys.exc_clear()
Ejemplo n.º 12
0
 def _CreateChannel(self, vivoxChannelName):
     self.LogInfo('Requesting Creation of channel with name',
                  vivoxChannelName)
     try:
         isPersistent = self.IsChannelPersistent(vivoxChannelName)
         isProtected = self.IsChannelProtected(vivoxChannelName)
         uri = self.voiceMgr.CreateChannel(vivoxChannelName, isPersistent,
                                           isProtected)
     except:
         log.LogException()
         sys.exc_clear()
     finally:
         if len(uri) > 0:
             uthread.pool('vivox::JoinChannel', self._JoinChannel,
                          vivoxChannelName)
         else:
             raise UserError('VivoxError42')
Ejemplo n.º 13
0
    def __LongCallTimer(self):
        longWarningSecs = prefs.GetValue('longOutstandingCallWarningSeconds',
                                         DEFAULTLONGWAITWARNINGSECS)
        sleepSecs = 60
        if longWarningSecs < sleepSecs:
            sleepSecs = longWarningSecs
        self.LogInfo('__LongCallTimer reporting warnings after',
                     longWarningSecs, 'seconds and checking every', sleepSecs,
                     'seconds')

        def ShouldWarn(method):
            for w in LONGWAITWARNINGMETHODS:
                if w in repr(method):
                    return True

            return False

        while self.state == service.SERVICE_RUNNING:
            if sm.GetService('machoNet').GetGlobalConfig().get(
                    'disableLongCallWarning'):
                self.LogWarn('__LongCallTimer should not be running! Exiting.')
                return
            blue.pyos.synchro.SleepWallclock(sleepSecs * 1000)
            try:
                maxDiff = 0
                for ct in base.outstandingCallTimers:
                    method = ct[0]
                    t = ct[1]
                    diff = blue.os.GetWallclockTimeNow() - t
                    if diff > maxDiff and ShouldWarn(method):
                        maxDiff = diff
                    if diff > 60 * const.SEC:
                        self.LogWarn('Have waited', FmtTime(diff), 'for',
                                     method)

                if maxDiff > longWarningSecs * const.SEC and self.lastLongCallTimestamp < blue.os.GetWallclockTimeNow(
                ) - longWarningSecs * const.SEC:
                    modalWnd = uicore.registry.GetModalWindow()
                    if modalWnd:
                        modalWnd.SetModalResult(uiconst.ID_CLOSE)
                    uthread.new(uicore.Message, 'LongWaitForRemoteCall',
                                {'time': int(maxDiff / const.MIN)})
                    self.lastLongCallTimestamp = blue.os.GetWallclockTimeNow()
            except:
                log.LogException()
                sys.exc_clear()
 def TryFlyUpdate(self):
     """Update my FlyMode velocity, but only if I'm actually *in* FlyMode."""
     me = self.entityService.GetPlayerEntity()
     if me is not None:
         myMovement = me.GetComponent('movement')
         if myMovement and myMovement.IsFlyMode:
             newVel = (0, 0, 0)
             if self.drive:
                 activeCamera = self.cameraClient.GetActiveCamera()
                 cameraDir = geo2.Vec3Subtract(activeCamera.GetPointOfInterest(), activeCamera.GetPosition())
                 newVel = geo2.Vec3Scale(geo2.Vec3Normalize(cameraDir), myMovement.flySpeed)
             try:
                 myMovement.moveModeManager.GetCurrentMode().velocity = newVel
             except AttributeError:
                 log.LogException()
                 sys.exc_clear()
                 myMovement.IsFlyMode = False
Ejemplo n.º 15
0
    def _GetGenderRU(self, typeID, *args, **kwargs):
        try:
            messageID = cfg.invtypes.Get(typeID).typeNameID
        except KeyError:
            log.LogException()
            return localization.GENDER_MALE

        try:
            return localization.GetMetaData(
                messageID,
                'gender',
                languageID=localization.LOCALE_SHORT_RUSSIAN)
        except KeyError:
            localization.LogWarn(
                "itemID %s does not have the requested metadata 'gender' in language '%s. Returning masculine gender by default."
                % (typeID, localization.LOCALE_SHORT_RUSSIAN))
            return localization.GENDER_MALE
Ejemplo n.º 16
0
    def CmdCloseAllWindows(self):
        for wnd in uicore.registry.GetWindows()[:]:
            if not uicore.registry.IsWindow(wnd):
                continue
            if wnd.IsKillable():
                if hasattr(wnd, 'CloseByUser'):
                    wnd.CloseByUser()
                else:
                    try:
                        wnd.Close()
                    except:
                        log.LogException()

            elif not wnd.InStack():
                wnd.Minimize()

        return True
Ejemplo n.º 17
0
 def RunWorkerProcesses(self):
     seconds = 0
     while self.state == service.SERVICE_RUNNING:
         if prefs.GetValue('disableProcessHealthService', 0):
             self.LogWarn(
                 'Process Health Service is disabled in prefs. Disabling loop.'
             )
             return
         blue.pyos.synchro.SleepWallclock(10000)
         try:
             seconds += 10
             self.DoOnceEvery10Secs()
             if seconds % 600 == 0:
                 self.DoOnceEvery10Minutes()
         except:
             log.LogException()
             sys.exc_clear()
Ejemplo n.º 18
0
    def GetConditions(self, advancedMatches):
        conditions = []
        for word, value in advancedMatches:
            try:
                for kw in self.searchKeywords:
                    if kw.keyword.lower().startswith(word):
                        kw.matchFunction(conditions, value)
                        break

            except:
                import log
                log.LogException()
                sm.GetService('assets').LogInfo('Failed parsing keyword', word,
                                                'value', value,
                                                'and happily ignoring it')

        return conditions
Ejemplo n.º 19
0
 def OptionalUpgradeGetDescription(self):
     try:
         n = nasty.GetAppDataCompiledCodePath()
         fromversion = n.build or boot.build
         if self.upgradeInfo is None:
             return
         toversion = self.upgradeInfo.build
         from appPatch import optionalPatchInfoURLs
         url = '%snoformat.asp?from=%s&to=%s' % (optionalPatchInfoURLs[boot.region], fromversion, toversion)
         socket = urllib2.urlopen(url)
         response = socket.read()
         socket.close()
         return response
     except:
         log.LogException()
         sys.exc_clear()
         return
def _QueueTicker(queue, name, svc):
    """ Calls queue.Tick() every 60 seconds, optionally timing out items before each Tick(). """
    while queue.ticker is not None:
        svc.LogInfo('Started Login Queue Ticker task for queue ', name)
        blue.pyos.synchro.SleepWallclock(60000)
        if queue.ticker is not None:
            try:
                if queue.queueTimeout > 0:
                    l = queue.Timeout(queue.queueTimeout)
                    if len(l) > 0:
                        svc.LogWarn('Timed ', len(l),
                                    " clients out of login queue '", name,
                                    "' (timeout = ", queue.queueTimeout,
                                    ' sec)')
                queue.Tick()
            except:
                log.LogException('Exception in _QueueTicker tasklet')
Ejemplo n.º 21
0
    def GetSolarSystemTrace(self, itemID, altText=None, traceFontSize=12):
        if util.IsStation(itemID):
            solarSystemID = cfg.stations.Get(itemID).solarSystemID
        else:
            solarSystemID = itemID
        try:
            sec, col = util.FmtSystemSecStatus(
                sm.GetService('map').GetSecurityStatus(solarSystemID), 1)
            col.a = 1.0
            securityLabel = "</b> <color=%s><hint='%s'>%s</hint></color>" % (
                util.StrFromColor(col),
                localization.GetByLabel('UI/Map/StarMap/SecurityStatus'), sec)
        except KeyError:
            self.LogError('Neocom failed to get security status for item',
                          solarSystemID, 'displaying BROKEN')
            log.LogException()
            sys.exc_clear()
            securityLabel = ''

        si = cfg.mapSystemCache.Get(solarSystemID)
        constellationID = si.constellationID
        regionID = si.regionID
        if altText:
            solarSystemAlt = " alt='%s'" % uiutil.StripTags(
                altText, stripOnly=['localized'])
        else:
            solarSystemAlt = ''
        locationTrace = '<url=showinfo:%s//%s%s>%s</url>%s' % (
            const.typeSolarSystem, solarSystemID, solarSystemAlt,
            cfg.evelocations.Get(solarSystemID).locationName, securityLabel)
        if traceFontSize:
            locationTrace += '<fontsize=12>'
        if not util.IsWormholeRegion(regionID):
            seperator = '<fontsize=%(fontsize)s> </fontsize>&lt;<fontsize=%(fontsize)s> </fontsize>' % {
                'fontsize': 8
            }
            locationTrace += seperator
            locationTrace += '<url=showinfo:%s//%s>%s</url>' % (
                const.typeConstellation, constellationID,
                cfg.evelocations.Get(constellationID).locationName)
            locationTrace += seperator
            locationTrace += '<url=showinfo:%s//%s>%s</url>' % (
                const.typeRegion, regionID,
                cfg.evelocations.Get(regionID).locationName)
        return locationTrace
Ejemplo n.º 22
0
 def LogInfoEvent(self,
                  eventTypeID,
                  itemID=None,
                  itemID2=None,
                  int_1=None,
                  int_2=None,
                  int_3=None,
                  char_1=None,
                  char_2=None,
                  char_3=None,
                  float_1=None,
                  float_2=None,
                  float_3=None):
     try:
         if eventTypeID in self.serverEvents:
             if eventTypeID in self.serverOncePerRunEvents:
                 self.serverOncePerRunEvents.remove(eventTypeID)
                 self.serverEvents.remove(eventTypeID)
             if eventTypeID not in self.loggedEvents:
                 if eventTypeID in self.logTypeAggregates:
                     self.aggregateDict[eventTypeID] = {}
                 self.loggedEvents[eventTypeID] = []
             if eventTypeID in self.logTypeAggregates:
                 if itemID2 is not None:
                     itemID2 = long(itemID2)
                 ln = [
                     blue.os.GetWallclockTime(),
                     long(itemID), itemID2, int_1, int_2, int_3, char_1,
                     char_2, char_3, float_1, float_2, float_3
                 ]
                 valueIx = self.infoTypeParameters[eventTypeID].difference(
                     self.logTypeAggregates[eventTypeID])
                 igsUtil.AggregateEvent(eventTypeID, ln, self.loggedEvents,
                                        self.aggregateDict[eventTypeID],
                                        self.logTypeAggregates[eventTypeID],
                                        valueIx)
             else:
                 self.loggedEvents[eventTypeID].append([
                     blue.os.GetWallclockTime(), itemID, itemID2, int_1,
                     int_2, int_3, char_1, char_2, char_3, float_1, float_2,
                     float_3
                 ])
     except Exception:
         log.LogException('Error logging IGS information')
         sys.exc_clear()
Ejemplo n.º 23
0
    def _TearDownComponents(self, entity):
        with entity.entityLock:
            try:
                if entity.state == const.cef.ENTITY_STATE_DESTROYING:
                    entity.state = const.cef.ENTITY_STATE_DEAD
                    preTearDownCalls = []
                    for name, component in entity.components.iteritems():
                        systems = self.GetComponentSystems(name)
                        if systems:
                            for system in systems:
                                f = getattr(system, 'PreTearDownComponent',
                                            None)
                                if f:
                                    preTearDownCalls.append(
                                        (f, (entity, component)))

                    if preTearDownCalls:
                        uthread.parallel(preTearDownCalls)
                    tearDownCalls = []
                    for name, component in entity.components.iteritems():
                        systems = self.GetComponentSystems(name)
                        if systems:
                            for system in systems:
                                f = getattr(system, 'TearDownComponent', None)
                                if f:
                                    tearDownCalls.append(
                                        (f, (entity, component)))

                    if tearDownCalls:
                        uthread.parallel(tearDownCalls)
                else:
                    self.LogError(
                        'SetupComponents: Entity state should be ',
                        const.cef.ENTITY_STATE_NAMES[
                            const.cef.ENTITY_STATE_DESTROYING],
                        ', is instead ',
                        const.cef.ENTITY_STATE_NAMES[entity.state],
                        '. Entity:', str(entity))
                sm.ScatterEvent('OnEntityDeleted', entity.entityID,
                                entity.scene.sceneID)
                GameWorld.GetNetworkEntityQueueManager().RemoveEntity(
                    entity.entityID)
            except Exception as e:
                self._deadEntityList[entity.entityID] = entity
                log.LogException(e)
Ejemplo n.º 24
0
    def GuessNodeIDFromAddress(self, serviceName, address):
        """
        Tries to guess which nodeID a address lives at based on some magic mappings
        and what's currently in the address cache. But it's only a guess.
        
        Note that server is a serviceName, not a serviceMask name, since this is just
        used for bound object which have live at a service rather than a serviceMask
        """
        alternatives = []
        if service in ('aggressionMgr', 'director', 'entity'):
            alternatives = [('beyonce', address)]
            for each in ('aggressionMgr', 'director', 'entity'):
                alternatives.append((each, address))

        elif service == 'brokerMgr':
            alternatives = [('station', address)]
        elif service in ('i2', 'skillMgr', 'dogmaIM', 'invbroker', 'ship'):
            if address[1] == const.groupSolarSystem:
                alternatives = [('beyonce', address[0])]
            elif address[1] == const.groupStation:
                alternatives = [('station', address[0])]
            for each in ('i2', 'skillMgr', 'dogmaIM', 'invbroker', 'ship'):
                alternatives.append((each, address))

        elif service in ('corpStationMgr', 'factory', 'broker'):
            alternatives = [('station', address)]
        elif service == 'tradeMgr':
            alternatives = [('station', address[0])]
        elif service == 'station' and macho.mode == 'server':
            try:
                key = ('beyonce', sm.services['stationSvc'].GetStation(
                    address, prime=0).solarSystemID)
                if key[1]:
                    alternatives.append(key)
            except StandardError:
                log.LogException(
                    'Could not locate the station you asked for without blocking'
                )
                sys.exc_clear()

        for alt_service, alt_address in alternatives:
            nodeID = self._addressCache.Get(alt_service, alt_address)
            if nodeID is not None:
                self._addressCache.Set(serviceName, address, nodeID)
                return nodeID
Ejemplo n.º 25
0
    def ExpandGroupBeans(self, compressedGroupBeans):
        if isinstance(compressedGroupBeans, dict):
            return compressedGroupBeans
        res = None
        try:
            res = blue.marshal.Load(zlib.decompress(compressedGroupBeans))
        except (UnmarshalError, zlib.error):
            firstBit = '<error encoding>'
            with util.ExceptionEater('Encoding some badness in the beancounter'):
                firstBit = base64.b64encode(compressedGroupBeans[:1000])
            self.LogError('BeanDelivery recieved a non-standard bean payload, likely not exefile in origin.  Session:', repr(session), 'First 1000char of compressed payload:', firstBit)
            log.LogException('BeanDelivery recieved a non-standard bean payload')
            with util.ExceptionEater('Reporting BeanDelivery error to Alert'):
                message = 'The following session sent us a set of Beans that are probably all attacky:\n%s\n\n' % (repr(session),)
                message += 'The compressed payload follows (base64 encoded):\n%s' % (base64.b64encode(compressedGroupBeans),)
                self.Alert('BeanDelivery', 'Non-standard BeanCounting payload', message)

        return res
Ejemplo n.º 26
0
    def GetWebRequestParameters(self):
        details = {}
        try:
            details['n'] = boot.build
            details['s'] = util.GetServerName()
            details['u'] = settings.public.ui.Get('username', '')
            details['language_id'] = prefs.GetValue('languageID', 'EN')
            details['edition'] = getattr(boot, 'edition', 'classic')
            details['protocol'] = 2
            details['intended_platform'] = 'win'
            details['client_bitcount'] = 32
            details['client_fullversion'] = '%s.%s' % (boot.keyval['version'].split('=', 1)[1], boot.build)
            if not blue.win32.IsTransgaming():
                versionEx = blue.win32.GetVersionEx()
                details['actual_platform'] = 'win'
                details['platform_version'] = str(blue.os.osMajor) + '.' + str(blue.os.osMinor)
                details['platform_extra'] = str(versionEx.get('wServicePackMajor', 0))
                if versionEx.get('wProductType', 1) > 1:
                    details['platform_type'] = 'server'
                else:
                    details['platform_type'] = ['workstation', 'desktop'][versionEx.get('wSuiteMask', 512) & 512 > 0]
                if blue.win32.GetNativeSystemInfo().get('ProcessorArchitecture', '') == 'PROCESSOR_ARCHITECTURE_AMD64':
                    details['platform_bitcount'] = 64
                else:
                    details['platform_bitcount'] = 32
            else:
                versionEx = blue.win32.TGGetSystemInfo()
                details['actual_platform'] = ['mac', 'linux'][blue.win32.TGGetOS() == 'Linux']
                details['platform_type'] = versionEx.get('platform_type', 'desktop')
                details['platform_version'] = str(versionEx.get('platform_major_version', 0)) + '.' + str(versionEx.get('platform_minor_version', 0))
                details['platform_extra'] = versionEx.get('platform_extra', '0')
                details['platform_bitcount'] = versionEx.get('platform_bitcount', 32)
            cardName = ''
            ident = trinity.adapters.GetAdapterInfo(trinity.adapters.DEFAULT_ADAPTER)
            cardName = str(ident.description)
            cardName = cardName[0:64]
            details['card_name'] = cardName
            details['affiliate_id'] = self.GetClientAffiliateID()
        except:
            log.LogException(toAlertSvc=0)
            sys.exc_clear()

        queryString = urllib.urlencode(details)
        return queryString
Ejemplo n.º 27
0
    def GetStaticHeader(self):
        """
        Return a bunch of information in the response header about the server if he has not authenticated yet.
        The reason this is only returned into the header when you are not authenticated is that this is quite
        a lot of data that we don't want to be shoveling out with every request.
        The proxy only returns a subset of the data while the server returns the whole thing. Nothing is returned on the client
        Most of the information here is fetched once and then stored but online user count is fetched every 5 minutes.
        """
        uthread.Lock('http.GetStaticHeader')
        try:
            if self.staticHeader is None:
                self.staticHeader = {}
                self.staticHeader['CCP-codename'] = boot.codename
                self.staticHeader['CCP-version'] = boot.version
                self.staticHeader['CCP-build'] = boot.build
                self.staticHeader['CCP-sync'] = boot.sync
                self.staticHeader['CCP-clustermode'] = prefs.GetValue('clusterMode', 'n/a')
                if boot.role == 'server':
                    product = sm.GetService('cache').Setting('zsystem', 'Product')
                    ebsVersion = sm.GetService('DB2').CallProc('zsystem.Versions_Select', product)[0].version
                    bsdChangeList = sm.GetService('DB2').SQLInt('TOP 1 changeID', 'zstatic.changes', 'submitDate IS NOT NULL', 'submitDate DESC', 'branchID', sm.GetService('BSD').Setting(1))
                    self.staticHeader['CCP-product'] = product
                    self.staticHeader['CCP-EBS'] = ebsVersion
                    self.staticHeader['CCP-StaticBranch'] = sm.GetService('BSD').BranchName()
                    if len(bsdChangeList) > 0:
                        self.staticHeader['CCP-StaticCL'] = bsdChangeList[0].changeID
            if boot.role == 'proxy':
                machoNet = sm.GetService('machoNet')
                onlineCountEve = machoNet.GetClusterSessionCounts('EVE:Online')[0]
                onlineCountDust = machoNet.GetClusterSessionCounts('DUST:Online')[0]
                acl = machoNet.CheckACL(None, espCheck=True)
                vipMode = machoNet.vipMode
                self.staticHeader['CCP-onlineCount'] = onlineCountEve + onlineCountDust
                self.staticHeader['CCP-onlineCountEve'] = onlineCountEve
                self.staticHeader['CCP-onlineCountDust'] = onlineCountDust
                self.staticHeader['CCP-ACL'] = acl[1] if acl else None
                self.staticHeader['CCP-VIP'] = machoNet.vipMode
        except Exception:
            self.staticHeader = {'BADHEADER': ''}
            log.LogException()
        finally:
            uthread.UnLock('http.GetStaticHeader')

        return self.staticHeader
Ejemplo n.º 28
0
 def PerformHorridSessionAttributeUpdate(self, clientID, dict):
     try:
         if machobase.mode == 'server':
             proxyNodeID = self.GetProxyNodeFromID('clientID', clientID)
             return self.GetProxySessionManager(
                 proxyNodeID).PerformHorridSessionAttributeUpdate(
                     clientID, dict)
         s = sm.services['machoNet'].GetSessionByClientID(clientID)
         if s:
             s.LogSessionHistory(
                 'Updating session information via sessionMgr::UpdateSessionAttributes'
             )
             s.SetAttributes(dict)
             s.LogSessionHistory(
                 'Updated session information via sessionMgr::UpdateSessionAttributes'
             )
     except StandardError:
         log.LogException()
         sys.exc_clear()
Ejemplo n.º 29
0
def UnterMachoRemoteServiceCall(self, dude, retvals, sess, nodeID, service, method, args, keywords):
    try:
        if nodeID == sm.services['machoNet'].GetNodeID():
            if 'machoTimeout' in keywords:
                keywords = copy.copy(keywords)
                del keywords['machoTimeout']
            retvals.append((0, nodeID, apply(getattr(sess.ConnectToService(service), method), args, keywords)))
        else:
            retvals.append((0, nodeID, self.RemoteServiceCallWithoutTheStars(sess, nodeID, service, method, args, keywords)))
    except StandardError as e:
        log.LogException()
        retvals.append((1, nodeID, e))
        sys.exc_clear()
    except Exception as e:
        log.LogTraceback()
        retvals.append((1, nodeID, e))
        raise 
    finally:
        dude.Done()
Ejemplo n.º 30
0
    def SafeThreadLoop(self, now):
        shapesToKill = []
        if self.debugRender:
            try:
                for shape in self.shapes:
                    shape.Render()
                    if shape.currentTime > shape.time:
                        shapesToKill.append(shape)

            except:
                log.LogException(
                    'Error rendering shape in debugRenderClient.SafeThreadLoop'
                )
                self.shapes = []

        else:
            self.ClearAllShapes()
        for shape in shapesToKill:
            self.shapes.remove(shape)