def remote_registerClasses(self, *args): """ Instructs my broker to register the classes specified by the argument(s). The classes will be registered for B{all} jobs, and are specified by their string representations:: <package(s).module.class> """ modules = [] for stringRep in args: # Load the class for the string representation cls = reflect.namedObject(stringRep) # Register instances of the class, including its type and module pb.setUnjellyableForClass(stringRep, cls) if cls.__module__ not in modules: modules.append(cls.__module__) # Try to build the modules for the classes in case they've changed # since the last run for module in modules: try: rebuild(reflect.namedModule(module), doLog=False) except: pass
def networkify(cacheable, remote_cache, implementation, method_names): """Wraps methods in a Cacheable/RemoteCache class pair to make a sequence of methods network aware The first three parameter are classes, the methods_names parameter should be a list of methods_names. """ delegate_and_call_observers(cacheable, implementation, method_names) observe_and_delegate(remote_cache, implementation, method_names) pb.setUnjellyableForClass(cacheable, remote_cache)
def discover(): for m in __all__: for name, obj in inspect.getmembers(sys.modules[m]): if inspect.isclass(obj) and \ issubclass(obj, operators.Operator): if hasattr(obj, "operator_name"): installed_ops[obj.operator_name] = obj # register all operators with the perspective broker # so we can remote-call them if we want to. pb.setUnjellyableForClass(obj, obj)
createAvatar = staticmethod(createAvatar) class RoleAvatar(Persistent): name = StringCol(notNone=True) role = ForeignKey('Role') class RoleAvatarGhost(PersistentGhost): def __init__(self): PersistentGhost.__init__(self) self.primaryKey = 'name' pb.setUnjellyableForClass(RoleAvatar, RoleAvatarGhost) class RoleEnumAvatar(Avatar): def __init__(self, username, role, mind): self.username = username self.role = role self.mind = mind def logout(self): pass def perspective_getRoles(self): #get roles user = User.byName(self.username) d = []
def __eq__(self, other): """Based on all the attributes of the Action, and its class.""" return self.__class__ == other.__class__ and hash(self) == hash(other) def __ne__(self, other): return not self.__eq__(other) def undo_action(self): """If this action is undoable, construct the appropriate UndoAction.""" return None def undoable(self): return (self.undo_action() is not None) pb.setUnjellyableForClass(Action, Action) class UndoAction(Action): """Abstract base class for Undo actions""" pass class EphemeralAction(Action): """Abstract base class for actions that we don't want to save.""" pass class AddUsername(Action):
port=self.zSnmpPort, timeout=self.zSnmpTimeout, tries=retries, snmpVersion=self.zSnmpVer, community=self.zSnmpCommunity, cmdLineArgs=cmdLineArgs, protocol=protocol, allowCache=allowCache) p.snmpConnInfo = self return p def __repr__(self): return '<%s for %s>' % (self.__class__, self.id) pb.setUnjellyableForClass(SnmpConnInfo, SnmpConnInfo) class PerformanceConfig(HubService, ThresholdMixin): def __init__(self, dmd, instance): HubService.__init__(self, dmd, instance) self.config = self.dmd.Monitors.Performance._getOb(self.instance) self.procrastinator = Procrastinate(self.pushConfig) self._collectorMap = {} self._notifier = component.getUtility(IBatchNotifier) @translateError def remote_propertyItems(self): return self.config.propertyItems() def remote_getDefaultRRDCreateCommand(self, *args, **kwargs):
if get_manage_ip is None: return default return get_manage_ip() class SnmpDeviceProxy(DeviceProxy, pb.Copyable, pb.RemoteCopy): def __repr__(self): sci = getattr(self, "snmpConnInfo", None) scimi = None if (sci is None) else sci.manageIp return pformat({"id": self.id, "_config_id": getattr(self, "_config_id", None), "manageIp": self.manageIp, "snmpConnInfo.manageIp": scimi, "oids": getattr(self, "oids", None)}) pb.setUnjellyableForClass(SnmpDeviceProxy, SnmpDeviceProxy) class SnmpPerformanceConfig(CollectorConfigService): def __init__(self, dmd, instance): deviceProxyAttributes = ('zMaxOIDPerRequest', 'zSnmpMonitorIgnore', 'zSnmpAuthPassword', 'zSnmpAuthType', 'zSnmpCommunity', 'zSnmpPort', 'zSnmpPrivPassword', 'zSnmpPrivType', 'zSnmpSecurityName', 'zSnmpTimeout', 'zSnmpTries',
""" Created on 2015-4-24 @author: kong.lihua This module is used to send complex object between sever and client. """ from twisted.spread import pb class Request: def __init__(self, name, paraDict): self.name = name self.paraDict = paraDict class ClientRequest(Request, pb.Copyable): pass class ServerRequest(pb.RemoteCopy, Request): pass pb.setUnjellyableForClass(ClientRequest, ServerRequest)
Subclasses should override to add additional information. """ return {'id': self.id, 'requester': self.requesterId, 'domain': self.domain} def __repr__(self): return "<%s for requesterId %r in state %s>" % ( self.__class__.__name__, self.requesterId, _statesEnum[self.state]) class KeycardGeneric(Keycard, object): pass pb.setUnjellyableForClass(KeycardGeneric, KeycardGeneric) # class KeycardUACCP: username, address, crypt password # from UsernameCryptPasswordCrypt UCPP = credentials.UsernameCryptPasswordPlaintext class KeycardUACPP(Keycard, UCPP): """ I am a keycard with a username, plaintext password and IP address. I get authenticated against a crypt password. """ def __init__(self, username, password, address): UCPP.__init__(self, username, password)
self.observers.append(observer) # you should ignore pb.Cacheable-specific state, like self.observers return self.ducks # in this case, just a list of ducks def stoppedObserving(self, perspective, observer): self.observers.remove(observer) class SlaveDuckPond(pb.RemoteCache): # This is a cache of a remote MasterDuckPond def count(self): return len(self.cacheducks) def getDucks(self): return self.cacheducks def setCopyableState(self, state): print(" cache - sitting, er, setting ducks") self.cacheducks = state def observe_addDuck(self, newDuck): print(" cache - addDuck") self.cacheducks.append(newDuck) def observe_removeDuck(self, deadDuck): print(" cache - removeDuck") self.cacheducks.remove(deadDuck) pb.setUnjellyableForClass(MasterDuckPond, SlaveDuckPond)
#! /usr/bin/python from twisted.spread import pb class FrogPond: def __init__(self, numFrogs, numToads): self.numFrogs = numFrogs self.numToads = numToads def count(self): return self.numFrogs + self.numToads class SenderPond(FrogPond, pb.Copyable): def getStateToCopy(self): d = self.__dict__.copy() d['frogsAndToads'] = d['numFrogs'] + d['numToads'] del d['numFrogs'] del d['numToads'] return d class ReceiverPond(pb.RemoteCopy): def setCopyableState(self, state): self.__dict__ = state def count(self): return self.frogsAndToads pb.setUnjellyableForClass(SenderPond, ReceiverPond)
(maxval, color, legend or self.getMaxLabel(maxval, relatedGps)) ] return gopts + result def getMinLabel(self, minval, relatedGps): """build a label for a Range threshold""" return "Range %s >= %s" % (self.getNames(relatedGps), self.setPower(minval)) def getMaxLabel(self, maxval, relatedGps): """build a label for a Range threshold""" return "Range %s <= %s" % (self.getNames(relatedGps), self.setPower(maxval)) def getNames(self, relatedGps): legends = [getattr(gp, 'legend', gp) for gp in relatedGps.values()] return ', '.join(legends) def setPower(self, number): powers = ("k", "M", "G") if number < 1000: return number for power in powers: number = number / 1000.0 if number < 1000: return "%0.2f%s" % (number, power) return "%.2f%s" % (number, powers[-1]) from twisted.spread import pb pb.setUnjellyableForClass(RangeThresholdInstance, RangeThresholdInstance)
(interfacegl.DrawMenu, RemoteDrawMenu), (interfacegl.DrawObjectPick, RemoteDrawObjectPick), (interfacegl.DrawObjectHilight, RemoteDrawObjectHilight), (interfacegl.DrawObjectHighLight, RemoteDrawObjectHighLight), (interfacegl.DrawTmpVertex, RemoteDrawTmpVertex), (interfacegl.DrawTmpEdge, RemoteDrawTmpEdge), (camera.Camera, RemoteCamera), (camera.OrthoCamera, RemoteCamera), (graph.Graph, RemoteGraph), (graph.Vertex, RemoteVertex), (graph.DummyVertex, RemoteDummyVertex), (graph.Edge, RemoteEdge), (graph.SuperEdge, RemoteSuperEdge), ] for src, tgt in mappings: pb.setUnjellyableForClass(src, tgt) class Handler: def __init__(self, reactor, deliver): self.serverRef = None self.reactor = reactor self.deliver = deliver def error(self, obj): print "error:", str(obj) self.reactor.stop() def getmaker(self, obj): print "got maker:", obj self.serverRef = obj
from twisted.spread import pb import engine.Light import engine.Map import engine.Unit import engine.Ability import engine.Class import engine.Scenario import engine.Range import engine.Effect import engine.Light import engine.Equipment import engine.Battle pb.setUnjellyableForClass(engine.Light.Light, engine.Light.Light) pb.setUnjellyableForClass(engine.Map.MapSquare, engine.Map.MapSquare) pb.setUnjellyableForClass(engine.Map.Map, engine.Map.Map) pb.setUnjellyableForClass(engine.Unit.Unit, engine.Unit.Unit) pb.setUnjellyableForClass(engine.Unit.StatusEffects, engine.Unit.StatusEffects) pb.setUnjellyableForClass(engine.Ability.Ability, engine.Ability.Ability) pb.setUnjellyableForClass(engine.Class.Class, engine.Class.Class) pb.setUnjellyableForClass(engine.Scenario.Scenario, engine.Scenario.Scenario) pb.setUnjellyableForClass(engine.Range.Line, engine.Range.Line) pb.setUnjellyableForClass(engine.Range.Cross, engine.Range.Cross) pb.setUnjellyableForClass(engine.Range.Diamond, engine.Range.Diamond) pb.setUnjellyableForClass(engine.Range.DiamondExtend, engine.Range.DiamondExtend) pb.setUnjellyableForClass(engine.Range.Single, engine.Range.Single) pb.setUnjellyableForClass(engine.Effect.Damage, engine.Effect.Damage) pb.setUnjellyableForClass(engine.Effect.DamageSP, engine.Effect.DamageSP) pb.setUnjellyableForClass(engine.Effect.DrainLife, engine.Effect.DrainLife) pb.setUnjellyableForClass(engine.Effect.HealFriendlyDamageHostile, engine.Effect.HealFriendlyDamageHostile)
DEFAULT_LIMIT = 524288 #512k LIMITS = {'summary': 256, 'message': 4096} class RemoteException(Exception, pb.Copyable, pb.RemoteCopy): """Exception that can cross the PB barrier""" def __init__(self, msg, tb): Exception.__init__(self, msg) self.traceback = tb def __str__(self): return "%s: %s" % (Exception.__str__(self), self.traceback or '<no traceback>') pb.setUnjellyableForClass(RemoteException, RemoteException) # ZODB conflicts class RemoteConflictError(RemoteException): pass pb.setUnjellyableForClass(RemoteConflictError, RemoteConflictError) # Invalid monitor specified class RemoteBadMonitor(RemoteException): pass
return retval if (retval is not None) else self.id @property def deviceGuid(self): """ """ return getattr(self, "_device_guid", None) def __str__(self): return self.id def __repr__(self): return '%s:%s' % (self.__class__.__name__, self.id) pb.setUnjellyableForClass(DeviceProxy, DeviceProxy) # TODO: doc me! BASE_ATTRIBUTES = ('id', 'manageIp', ) class CollectorConfigService(HubService, ThresholdMixin): def __init__(self, dmd, instance, deviceProxyAttributes=()): """ Constructs a new CollectorConfig instance. Subclasses must call this __init__ method but cannot do so with the super() since parents of this class are not new-style classes.
p = AgentProxy(ip=self.manageIp, port=self.zSnmpPort, timeout=self.zSnmpTimeout, tries=retries, snmpVersion=self.zSnmpVer, community=self.zSnmpCommunity, cmdLineArgs=cmdLineArgs, protocol=protocol, allowCache=allowCache) p.snmpConnInfo = self return p def __repr__(self): return '<%s for %s>' % (self.__class__, self.id) pb.setUnjellyableForClass(SnmpConnInfo, SnmpConnInfo) class PerformanceConfig(HubService, ThresholdMixin): def __init__(self, dmd, instance): HubService.__init__(self, dmd, instance) self.config = self.dmd.Monitors.Performance._getOb(self.instance) self.procrastinator = Procrastinate(self.pushConfig) self._collectorMap = {} self._notifier = component.getUtility(IBatchNotifier) @translateError def remote_propertyItems(self): return self.config.propertyItems()
except: return [] if not status: return [] msg = 'threshold of %s exceeded: current status %s' % (self.name(), status[2]) return [ dict(device=self.context().deviceName, summary=msg, compStatus=value, compClass=self.mtype, eventKey=self.id, eventClass=self.eventClass, component=self.context().componentName, severity=status[1]) ] def getGraphElements(self, template, context, gopts, namespace, color, legend, relatedGps): """Produce a visual indication on the graph of where the threshold applies.""" unused(template, namespace) return gopts def getNames(self, relatedGps): legends = [getattr(gp, 'legend', gp) for gp in relatedGps.values()] return ', '.join(legends) from twisted.spread import pb pb.setUnjellyableForClass(StatusThresholdInstance, StatusThresholdInstance)
'message':4096 } class RemoteException(Exception, pb.Copyable, pb.RemoteCopy): """Exception that can cross the PB barrier""" def __init__(self, msg, tb): Exception.__init__(self, msg) self.traceback = tb def __str__(self): return "%s: %s" % ( Exception.__str__(self), self.traceback or '<no traceback>') pb.setUnjellyableForClass(RemoteException, RemoteException) # ZODB conflicts class RemoteConflictError(RemoteException): pass pb.setUnjellyableForClass(RemoteConflictError, RemoteConflictError) # Invalid monitor specified class RemoteBadMonitor(RemoteException): pass def translateError(callable): """ Decorator function to wrap remote exceptions into something understandable by our daemon.
self.d = d return d class Observer(pb.Referenceable): notified = 0 obj = None def remote_notify(self, other, obj): self.obj = obj self.notified = self.notified + 1 other.callRemote('unobserve',self) class NewStyleCopy(pb.Copyable, pb.RemoteCopy, object): def __init__(self, s): self.s = s pb.setUnjellyableForClass(NewStyleCopy, NewStyleCopy) class NewStyleCopy2(pb.Copyable, pb.RemoteCopy, object): allocated = 0 initialized = 0 value = 1 def __new__(self): NewStyleCopy2.allocated += 1 inst = object.__new__(self) inst.value = 2 return inst def __init__(self): NewStyleCopy2.initialized += 1 pb.setUnjellyableForClass(NewStyleCopy2, NewStyleCopy2)
raise except: import traceback log.debug(traceback.format_exc()) raise PluginImportError( plugin=self.modPath, traceback=traceback.format_exc().splitlines()) finally: try: sys.path.remove(self.package) except ValueError: # It's already been removed pass pb.setUnjellyableForClass(PluginLoader, PluginLoader) def _coreModPaths(walker, package): "generates modPath strings for the modules in a core directory" for absolutePath, dirname, filenames in walker.walk(package): if absolutePath == package: modPathBase = [] elif absolutePath.startswith(package): modPathBase = absolutePath[len(package) + 1:].split(os.path.sep) else: log.debug( 'absolutePath must start with package: ' 'absolutePath=%s, package=%s', absolutePath, package) continue for filename in filenames:
""" if pid in self.pids: del self.pids[pid] def updateConfig(self, update): """ """ if self is update: return self.name = update.name self.originalName = update.originalName self.ignoreParameters = update.ignoreParameters self.restart = update.restart self.severity = update.severity pb.setUnjellyableForClass(Process, Process) class Device(pb.Copyable, pb.RemoteCopy): """ Track device data """ name = '' snmpConnInfo = None proxy = None lastScan = 0. snmpStatus = 0 lastChange = 0 maxOidsPerRequest = 40 def __init__(self):
"""Represents the result of a completed round of duplicate bridge.""" def _getScore(self): """Duplicate bridge scoring scheme. @return: score value: positive for declarer, negative for defenders. """ score = 0 if self.contract and self.tricksMade: for key, value in list(self._getScoreComponents().items()): if key in ('odd', 'over', 'under', 'slambonus', 'gamebonus', 'partscore', 'insultbonus'): score += value return score pb.setUnjellyableForClass(DuplicateResult, DuplicateResult) class RubberResult(GameResult, pb.Copyable, pb.RemoteCopy): """Represents the result of a completed round of rubber bridge.""" def _getScore(self): """Rubber bridge scoring scheme. @return: 2-tuple of numeric scores (above the line, below the line): positive for declarer, negative for defenders. """ above, below = 0, 0 if self.contract and self.tricksMade: for key, value in list(self._getScoreComponents().items()): # Note: gamebonus/partscore are not assigned in rubber bridge. if key in ('over', 'under', 'slambonus', 'insultbonus'):
class ManagerComponentUIState(flavors.StateCacheable, flavors.StateRemoteCache): def processUniqueID(self): # Make sure proxies for the same object are the same, if we are # later cached by someone else. See bug #519. return id(self.__dict__) class AdminComponentUIState(flavors.StateRemoteCache): pass pb.setUnjellyableForClass(WorkerComponentUIState, ManagerComponentUIState) pb.setUnjellyableForClass(ManagerComponentUIState, AdminComponentUIState) class WizardEntryState(pb.RemoteCopy): def getAcceptedMediaTypes(self): """ Fetches a list of media types this components accepts. @returns: a list of strings """ return [format.media_type for format in self.accepts] def getProvidedMediaTypes(self): """ Fetches a list of media types this components provides.
meta) def userJoined(self, group, user): return self.callRemote( 'userJoined', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user)) def userLeft(self, group, user, reason=None): assert reason is None or isinstance(reason, unicode) return self.callRemote( 'userLeft', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user), reason) pb.setUnjellyableForClass(PBMind, PBMindReference) class PBGroup(pb.Referenceable): def __init__(self, realm, avatar, group): self.realm = realm self.avatar = avatar self.group = group def processUniqueID(self): return hash((self.realm.name, self.avatar.name, self.group.name)) def jellyFor(self, jellier): return reflect.qual(self.__class__), self.group.name.encode('utf-8'), jellier.invoker.registerReference(self)
class MetricId(pb.Copyable, pb.RemoteCopy): instance = "" def __init__(self, counterId, instance=""): self.counterId = counterId self.instance = instance def __str__(self): retString = str(self.counterId) if self.instance and len(self.instance) > 0: retString += "|" + self.instance return retString pb.setUnjellyableForClass(MetricId, MetricId) clientCache = {} def createGAEClient(username, password, printTrace=False, nocache=False, logseverity=logging.INFO): client = None if not nocache and clientCache.has_key(username): client = clientCache[username] if not client.loggedIn: client = None if not client: client = GAEClient(username, password, printTrace, logseverity) if not nocache: clientCache[username] = client
""" Helper used to test remote methods which raise exceptions which are L{pb.Error} subclasses. """ #class JellyError(flavors.Jellyable, pb.Error): pass class JellyError(flavors.Jellyable, pb.Error, pb.RemoteCopy): pass class SecurityError(pb.Error, pb.RemoteCopy): pass pb.setUnjellyableForClass(JellyError, JellyError) pb.setUnjellyableForClass(SecurityError, SecurityError) pb.globalSecurity.allowInstancesOf(SecurityError) #### # server-side #### class SimpleRoot(pb.Root): def remote_asynchronousException(self): """ Fail asynchronously with a non-pb.Error exception. """ return defer.fail( AsynchronousException("remote asynchronous exception"))
if self.team == 1: return 2 else: return 1 def calculateScore(self, team): #print "score ==================================" if team == None: team = self.team # print "=== Our Team: " + str(team) score = 0; for playerId in self.players: #score = score + 100 player = self.players[playerId] #print "player team: " + str(player.team) if player.team == team: score = score + player.sides score = score + player.resources for buildingId in self.buildings: #score = score + 10000 building = self.buildings[buildingId] #print "bildg team: " + str(building.team) if building.team == team: score = score + building.sides score = score + building.resources return score * 1000; pb.setUnjellyableForClass(Environment, Environment)
from twisted.spread import pb class AddressBookEntry(pb.Copyable, pb.RemoteCopy): def __init__(self, name="", email="", phone="", address=""): self.name = name self.email = email self.phone = phone self.address = address pb.setUnjellyableForClass(AddressBookEntry, AddressBookEntry)
return self.callRemote('groupMetaUpdate', PBGroup(self.realm, self.avatar, group), meta) def userJoined(self, group, user): return self.callRemote('userJoined', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user)) def userLeft(self, group, user, reason=None): assert reason is None or isinstance(reason, unicode) return self.callRemote('userLeft', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user), reason) pb.setUnjellyableForClass(PBMind, PBMindReference) class PBGroup(pb.Referenceable): def __init__(self, realm, avatar, group): self.realm = realm self.avatar = avatar self.group = group def processUniqueID(self): return hash((self.realm.name, self.avatar.name, self.group.name)) def jellyFor(self, jellier): return reflect.qual(self.__class__), self.group.name.encode( 'utf-8'), jellier.invoker.registerReference(self)
self.port = port self.use_ssl = use_ssl self.authenticator = authenticator def __str__(self): # have to use getattr in the case that the authenticator was # transferred over the wire, because the remote reference is not # an authenticator if (self.authenticator and getattr(self.authenticator, 'username', None)): return '%s@%s:%d' % (self.authenticator.username, self.host, self.port) else: return '%s:%d' % (self.host, self.port) pb.setUnjellyableForClass(PBConnectionInfo, PBConnectionInfo) _pat = re.compile('^(([^:@]*)(:([^:@]+))?@)?([^:@]+)(:([0-9]+))?$') def parsePBConnectionInfo(string, username='******', password='******', port=7531, use_ssl=True): """ Parse a string representation of a PB connection into a PBConnectionInfo object. The expected format is [user[:pass]@]host[:port]. Only the host is mandatory. The default values for username, password, and port will be taken from the optional username, password and port arguments.
from twisted.spread import pb from .cookies import RemoteCookieJar, RemotelyAccessibleCookieJar pb.setUnjellyableForClass(RemotelyAccessibleCookieJar, RemoteCookieJar)
def __init__(self): pass def __str__(self): """ Override the Python default to represent ourselves as a string """ return str(self.name) __repr__ = __str__ def processClassPrimaryUrlPath(self): return self.primaryUrlPath pb.setUnjellyableForClass(ProcessProxy, ProcessProxy) class ProcessConfig(CollectorConfigService): def __init__(self, dmd, instance): deviceProxyAttributes = ('zMaxOIDPerRequest',) CollectorConfigService.__init__(self, dmd, instance, deviceProxyAttributes) def _filterDevice(self, device): include = CollectorConfigService._filterDevice(self, device) include = include and device.snmpMonitorDevice() return include def _createDeviceProxy(self, device, proxy=None):
return iter(self.maps) def append(self, obj): self.maps.append(obj) def extend(self, objmaps): self.maps.extend(objmaps) def asUnitTest(self): """ Return the results of the relationship map as something that can be used directly for unit tests. """ return pformat(dict((map.id, map.asUnitTest()) for map in self.maps)) pb.setUnjellyableForClass(RelationshipMap, RelationshipMap) class ObjectMap(PBSafe): """ ObjectMap defines a mapping of some data to a ZenModel object. To be valid it must specify modname the full path to the module where the class to be created is defined. If the class name is the same as the module classname doesn't need to be defined. """ compname = "" modname = "" classname = "" _blockattrs = ('compname', 'modname', 'classname') _attrs = []
result = [] if pointval: result += [ "COMMENT:%s(%s)\\j" % (self.SeverityString, pointval), ] log.warn(gopts + result) return gopts + result def getPointLabel(self, pointval, relatedGps): """build a label for a point threshold""" return "%s == %s" % (self.getNames(relatedGps), self.setPower(pointval)) def getNames(self, relatedGps): legends = [getattr(gp, 'legend', gp) for gp in relatedGps.values()] return ', '.join(legends) def setPower(self, number): powers = ("k", "M", "G") if number < 1000: return number for power in powers: number = number / 1000.0 if number < 1000: return "%0.2f%s" % (number, power) return "%.2f%s" % (number, powers[-1]) from twisted.spread import pb pb.setUnjellyableForClass(PointThresholdInstance, PointThresholdInstance)
from ZenPacks.zenoss.PythonCollector.services.PythonConfig import PythonDataSourceConfig try: from Products.ZenUtils.Utils import varPath except ImportError: # Zenoss 4 doesn't have varPath. Implement it here. from Products.ZenUtils.Utils import zenPath def varPath(*args): all_args = ['var'] + list(args) return zenPath(*all_args) unused(Globals) pb.setUnjellyableForClass(PythonDataSourceConfig, PythonDataSourceConfig) # allowStaleDatapoint isn't available in Zenoss 4.1. if 'allowStaleDatapoint' in inspect.getargspec(CollectorDaemon.writeRRD).args: WRITERRD_ARGS = {'allowStaleDatapoint': False} else: WRITERRD_ARGS = {} class Preferences(object): zope.interface.implements(ICollectorPreferences) collectorName = 'zenpython' configurationService = 'ZenPacks.zenoss.PythonCollector.services.PythonConfig' cycleInterval = 5 * 60 # 5 minutes configCycleInterval = 60 * 60 * 12 # 12 hours
gopts.append("HRULE:%s%s" % (maxval, color)) elif minval is not None : gopts.append( "HRULE:%s%s:%s less than %s\\j" % (minval, color, self.getNames(relatedGps), minstr)) elif maxval is not None: gopts.append( "HRULE:%s%s:%s greater than %s\\j" % (maxval, color, self.getNames(relatedGps), maxstr)) return gopts def getNames(self, relatedGps): names = sorted(set(x.split('_', 1)[1] for x in self.dataPointNames)) return ', '.join(names) def setPower(self, number): powers = ("k", "M", "G") if number < 1000: return number for power in powers: number = number / 1000.0 if number < 1000: return "%0.2f%s" % (number, power) return "%.2f%s" % (number, powers[-1]) def _checkImpl(self, dataPoint, value): return self.checkRange(dataPoint, value) from twisted.spread import pb pb.setUnjellyableForClass(MinMaxThresholdInstance, MinMaxThresholdInstance)
return False except AttributeError: return False return True class Container(BaseContainer, pb.Copyable, pb.RemoteCopy): pass #class ReceiverContainer(Container, pb.RemoteCopy): # pass pb.setUnjellyableForClass(Container, Container) if __name__ == "__main__": b1 = Container() b1.set('name', 'Device1') b1.set('type', 'PseudoDevice') b2 = Container() b2.set('name', 'Device2') b2.set('type', 'Camera') b3 = copy(b1) print hash(b1)
#------------------------------------------------------------------------------ # For each event class, if it is sendable over the network, we have # to Mix In the "copy classes", or make a replacement event class that is # copyable #------------------------------------------------------------------------------ # TickEvent # Direction: don't send. #The Tick event happens hundreds of times per second. If we think we need #to send it over the network, we should REALLY re-evaluate our design #------------------------------------------------------------------------------ # QuitEvent # Direction: Client to Server only MixInCopyClasses( QuitEvent ) pb.setUnjellyableForClass(QuitEvent, QuitEvent) clientToServerEvents.append( QuitEvent ) #------------------------------------------------------------------------------ # GameStartRequest # Direction: Client to Server only MixInCopyClasses( GameStartRequest ) pb.setUnjellyableForClass(GameStartRequest, GameStartRequest) clientToServerEvents.append( GameStartRequest ) #------------------------------------------------------------------------------ # CharactorMoveRequest # Direction: Client to Server only # this has an additional attribute, direction. it is an int, so it's safe MixInCopyClasses( CharactorMoveRequest ) pb.setUnjellyableForClass(CharactorMoveRequest, CharactorMoveRequest)
context = self.context() deviceName = context.deviceName componentName = context.componentName except Exception: return [] msg = 'threshold of %s exceeded: current status %s' %(self.name(), status[2]) return [dict(device=deviceName, summary=msg, compStatus=value, compClass=self.mtype, eventKey=self.id, eventClass=self.eventClass, component=componentName, severity=status[1])] def getGraphElements(self, template, context, gopts, namespace, color, legend, relatedGps): """Produce a visual indication on the graph of where the threshold applies.""" unused(template, namespace) return gopts def getNames(self, relatedGps): legends = [ getattr(gp, 'legend', gp) for gp in relatedGps.values() ] return ', '.join(legends) # This makes our threshold instance able to be serialized and sent to collectors # in their configurations. from twisted.spread import pb pb.setUnjellyableForClass(StatusThresholdInstance, StatusThresholdInstance)
self.meta = [] def remote_userJoined(self, user, group): self.joins.append((user, group)) def remote_userLeft(self, user, group, reason): self.parts.append((user, group, reason)) def remote_receive(self, sender, recipient, message): self.messages.append((sender, recipient, message)) def remote_groupMetaUpdate(self, group, meta): self.meta.append((group, meta)) pb.setUnjellyableForClass(TestMind, service.PBMindReference) class PBProtocolTests(unittest.TestCase): def setUp(self): self.realm = service.InMemoryWordsRealm("realmname") self.checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() self.portal = portal.Portal(self.realm, [self.checker]) self.serverFactory = pb.PBServerFactory(self.portal) self.serverFactory.protocol = self._protocolFactory self.serverFactory.unsafeTracebacks = True self.clientFactory = pb.PBClientFactory() self.clientFactory.unsafeTracebacks = True self.serverPort = reactor.listenTCP(0, self.serverFactory) self.clientConn = reactor.connectTCP("127.0.0.1", self.serverPort.getHost().port,
from hashlib import sha1 from twisted.internet import reactor from twisted.spread import pb from twisted.cred import credentials from twisted.python import log from zope.interface import implements from pymacco.interfaces import ISubject from pymacco.common.user import LocalUserManager, RemoteUserManager pb.setUnjellyableForClass(LocalUserManager, RemoteUserManager) from pymacco.common.table import LocalTable, RemoteTable pb.setUnjellyableForClass(LocalTable, RemoteTable) from pymacco.common.tablemanager import LocalTableManager, RemoteTableManager pb.setUnjellyableForClass(LocalTableManager, RemoteTableManager) def requireConnect(func): """ A decorator that raises an exception if 'self.connected' is False. """ def wrapped(self, *args, **kwargs): if not self.connected: raise Exception("You must be connected before using '%s'" % func.__name__) return func(self, *args, **kwargs) return wrapped
from twisted.spread import pb #Events that are local to server class Event(object): def __init__(self): self.name = "Generic Event" self.pass_through = True #i.e. goes through gamestack to game class TickEvent(Event): def __init__(self): Event.__init__(self) self.name = "Tick Event" #Events which need to be sent through network class CopyableEvent(pb.RemoteCopy, pb.Copyable, Event): def __init__(self): super(CopyableEvent, self).__init__() self.name = "Generic Event" pb.setUnjellyableForClass(CopyableEvent, CopyableEvent)
from twisted.spread import pb class OrdType(pb.Copyable,pb.RemoteCopy): lookup = {} def __init__(self, name, isMarket): self.name = name self.isTerminal = isTerminal OrdType.lookup[name] = self MARKET = OrdType( 'MARKET', True) LIMIT = OrdType( 'LIMIT' , False) pb.setUnjellyableForClass(OrdType,OrdType)
from Products.ZenRelations.ZenPropertyManager import iszprop from Products.ZenHub.services.ModelerService import ModelerService from Products.ZenRelations.zPropertyCategory import getzPropertyCategory DEFAULT_PING_THRESH = 168 class JobPropertiesProxy(pb.Copyable, pb.RemoteCopy): def __init__(self, jobrecord): self.zProperties = {} for prop in jobrecord.__dict__: if iszprop(prop): self.zProperties[prop] = getattr(jobrecord, prop) pb.setUnjellyableForClass(JobPropertiesProxy, JobPropertiesProxy) class IpNetProxy(pb.Copyable, pb.RemoteCopy): "A class that will represent a ZenModel/IpNetwork in zendisc" id = '' _children = None netmask = None def __init__(self, ipnet): self.id = ipnet.id self._children = map(IpNetProxy, ipnet.children()) self.netmask = ipnet.netmask for prop in 'zAutoDiscover zDefaultNetworkTree zPingFailThresh'.split( ):
class SynchronousError(pb.Error): """ Helper used to test remote methods which raise exceptions which are L{pb.Error} subclasses. """ #class JellyError(flavors.Jellyable, pb.Error): pass class JellyError(flavors.Jellyable, pb.Error, pb.RemoteCopy): pass class SecurityError(pb.Error, pb.RemoteCopy): pass pb.setUnjellyableForClass(JellyError, JellyError) pb.setUnjellyableForClass(SecurityError, SecurityError) pb.globalSecurity.allowInstancesOf(SecurityError) #### # server-side #### class SimpleRoot(pb.Root): def remote_asynchronousException(self): """ Fail asynchronously with a non-pb.Error exception. """ return defer.fail(AsynchronousException("remote asynchronous exception")) def remote_synchronousException(self):
if isinstance(other, Card): return self.suit == other.suit and self.rank == other.rank return False def __lt__(self, other): """Compare cards for hand sorting. Care must be taken when comparing cards of different suits. """ if not isinstance(other, Card): raise TypeError("Expected Card, got %s" % type(other)) selfIndex = self.suit.value * 13 + self.rank.value otherIndex = other.suit.value * 13 + other.rank.value return selfIndex < otherIndex def __hash__(self): return hash((self.rank, self.suit)) def __repr__(self): return "Card(%s, %s)" % (self.rank, self.suit) def getStateToCopy(self): return self.rank, self.suit def setCopyableState(self, state): self.__rank, self.__suit = state pb.setUnjellyableForClass(Card, Card)
def getTimeStamp(self): """Get the timestamp for the message @returns: the timestamp or None @rtype: int """ # F0.4: timestamp was added in 0.4.2 return getattr(self, 'timestamp', None) def getDescription(self): """Get the description for the message @returns: the description or None @rtype: str """ return getattr(self, 'description', None) pb.setUnjellyableForClass(Message, Message) # these are implemented as factory functions instead of classes because # properly proxying to the correct subclass is hard with Copyable/RemoteCopy def Error(*args, **kwargs): """ Create a L{Message} at ERROR level, indicating a failure that needs intervention to be resolved. """ return Message(ERROR, *args, **kwargs) # FIXME: figure out a way to not be shadowing the Warning builtin without # breaking all other code __pychecker__ = 'no-shadowbuiltin'
break def registerProducer(self, producer, streaming): self.remote.callRemote("registerProducer", _ReferenceableProducerWrapper(producer), streaming).addErrback(self.fail) def unregisterProducer(self): self.remote.callRemote("unregisterProducer").addErrback(self.fail) def fail(self, failure): log.err(failure) pb.setUnjellyableForClass(server.Request, Request) class Issue: def __init__(self, request): self.request = request def finished(self, result): if result != server.NOT_DONE_YET: assert isinstance(result, types.StringType),\ "return value not a string" self.request.write(result) self.request.finish() def failed(self, failure): #XXX: Argh. FIXME. failure = str(failure)
class User(pb.Copyable, pb.RemoteCopy): version = None engine_id = None username = None authentication_type = None # MD5 or SHA authentication_passphrase = None privacy_protocol = None # DES or AES privacy_passphrase = None def __str__(self): fmt = "<User(version={0.version},engine_id={0.engine_id},username={0.username},authentication_type={0.authentication_type},privacy_protocol={0.privacy_protocol})>" return fmt.format(self) pb.setUnjellyableForClass(User, User) class SnmpTrapConfig(CollectorConfigService): # Override _notifyAll, notifyAffectedDevices, _filterDevice and # _filterDevicesOnly to guarantee that only one MibConfigTask is ever # sent down to zentrap. def _notifyAll(self, object): pass @onUpdate(None) # Matches all def notifyAffectedDevices(self, object, event): pass
lastValue = ValueChangeThresholdInstance.lastValues.get(dpKey, None) # get also updates the access time, so only set if the value changes. if lastValue != value: # Update the value in the map. ValueChangeThresholdInstance.lastValues[dpKey] = value # .. Only create a change event if this isn't the first collection if lastValue != None: event = dict(device=self.context().deviceName, summary="Value changed from %s to %s" % (lastValue, value), eventKey=self.id, eventClass=self.eventClass, component=self.context().componentName, current=value, previous=lastValue, severity=self.severity) return (event, ) return tuple() def _getDpKey(self, dp): return ':'.join(self.context().key()) + ':' + dp def getGraphValues(self, relatedGps, context): # currently, no visualization implemented for this threshold type return () from twisted.spread import pb pb.setUnjellyableForClass(ValueChangeThresholdInstance, ValueChangeThresholdInstance)
''' Created on 2015-4-24 @author: kong.lihua This module is used to send complex object between sever and client. ''' from twisted.spread import pb class Request: def __init__(self, name, paraDict): self.name = name self.paraDict = paraDict class ClientRequest(Request, pb.Copyable): pass class ServerRequest(pb.RemoteCopy, Request): pass pb.setUnjellyableForClass(ClientRequest, ServerRequest)
from twisted.spread import pb class FrogPond: def __init__(self, numFrogs, numToads): self.numFrogs = numFrogs self.numToads = numToads def count(self): return self.numFrogs + self.numToads class SenderPond(FrogPond, pb.Copyable): def getStateToCopy(self): d = self.__dict__.copy() d['frogsAndToads'] = d['numFrogs'] + d['numToads'] del d['numFrogs'] del d['numToads'] return d class ReceiverPond(pb.RemoteCopy): def setCopyableState(self, state): self.__dict__ = state def count(self): return self.frogsAndToads pb.setUnjellyableForClass(SenderPond, ReceiverPond)
id = '' component = '' rrdPath = '' rrdType = None rrdCreateCommand = '' rrdMin = None rrdMax = None metadata = None def __init__(self): self.data = {} def __repr__(self): return pformat((self.data, self.id)) pb.setUnjellyableForClass(DataPointConfig, DataPointConfig) class Cmd(pb.Copyable, pb.RemoteCopy): """ Holds the config of every command to be run """ device = '' command = None ds = '' useSsh = False cycleTime = None eventClass = None eventKey = None severity = 3 lastStart = 0