fclient-commit Mailing List for fclient (Page 21)
Status: Pre-Alpha
Brought to you by:
jurner
You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(23) |
Nov
(54) |
Dec
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(17) |
Feb
(209) |
Mar
(63) |
Apr
(31) |
May
(7) |
Jun
(39) |
Jul
(390) |
Aug
(122) |
Sep
(6) |
Oct
|
Nov
|
Dec
|
From: <jU...@us...> - 2008-07-01 11:27:38
|
Revision: 462 http://fclient.svn.sourceforge.net/fclient/?rev=462&view=rev Author: jUrner Date: 2008-07-01 04:27:47 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/test_fcp/dummy_io.py Modified: trunk/fcp2/src/fcp2/test_fcp/dummy_io.py =================================================================== --- trunk/fcp2/src/fcp2/test_fcp/dummy_io.py 2008-07-01 11:27:41 UTC (rev 461) +++ trunk/fcp2/src/fcp2/test_fcp/dummy_io.py 2008-07-01 11:27:47 UTC (rev 462) @@ -11,9 +11,8 @@ def __del__(self): sys.path.pop(0) hack = _RelImportHack(3) -from fcp2 import client -from fcp2.client import iohandler -from fcp2 import consts +import fcp2 +from fcp2 import iohandler del hack #<-- rel import hack @@ -33,30 +32,30 @@ def connect(self, **kwargs): if not self._allowConnect: - raise consts.IOConnectFailedError('Refused') + raise fcp2.ErrorIOConnectFailed('Refused') self._isOpen = True def read(self, n): if self._isBroken: - raise consts.IOBrokenError('Broken') + raise fcp2.ErrorIOBroken('Broken') if not self.isOpen(): - raise consts.IOClosedError('Closed') + raise fcp2.ErrorIOClosed('Closed') if self._reverseDirection: if not self.writeBuffer: - raise consts.IOTimeoutError('Timeout') + raise fcp2.ErrorIOTimeout('Timeout') bytes, self.writeBuffer = self.writeBuffer[ :n], self.writeBuffer[n: ] else: if not self.readBuffer: - raise consts.IOTimeoutError('Timeout') + raise fcp2.ErrorIOTimeout('Timeout') bytes, self.readBuffer = self.readBuffer[ :n], self.readBuffer[n: ] return bytes def write(self, bytes): if self._isBroken: - raise consts.IOBrokenError('Broken') + raise fcp2.ErrorIOBroken('Broken') if not self.isOpen(): - raise consts.IOClosedError('Closed') + raise fcp2.ErrorIOClosed('Closed') self.writeBuffer += bytes def close(self): @@ -68,7 +67,7 @@ self.readBuffer = '' self.writeBuffer = '' else: - raise consts.IOClosedError('Closed') + raise fcp2.ErrorIOClosed('Closed') def isOpen(self): return self._isOpen This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 11:27:32
|
Revision: 461 http://fclient.svn.sourceforge.net/fclient/?rev=461&view=rev Author: jUrner Date: 2008-07-01 04:27:41 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/message.py Modified: trunk/fcp2/src/fcp2/message.py =================================================================== --- trunk/fcp2/src/fcp2/message.py 2008-07-01 11:27:35 UTC (rev 460) +++ trunk/fcp2/src/fcp2/message.py 2008-07-01 11:27:41 UTC (rev 461) @@ -15,13 +15,14 @@ hack = _RelImportHack(2) from fcp2 import consts +from fcp2 import config from fcp2 import types from fcp2 import key from fcp2.fcp_lib import node from fcp2.fcp_lib import uuid -del hack +del hack, _RelImportHack #<-- rel import hack #******************************************************************************** # consts @@ -32,20 +33,20 @@ #******************************************************************************** # #******************************************************************************** -class Node(node.Node): - """Node tree used along with messages""" +class _Node(node.Node): + """_Node tree used along with messages""" ComponentSep = '.' #******************************************************************************** # #******************************************************************************** -class PrivateParam(str): - """Helper class to mark a message parameter as PrivateParam to the package""" +class _PrivateParam(str): + """Helper class to mark a message parameter as _PrivateParam to the package""" #******************************************************************************** # #******************************************************************************** -class MessageMeta(type): +class _PMessageMeta(type): def __new__(klass, name, bases, kws): newClass = type.__new__(klass, name, bases, kws) @@ -58,7 +59,7 @@ #******************************************************************************** # #******************************************************************************** -class MessageBase(object): +class _PMessageBase(object): """Class wrapping a Fcp message Sample use:: @@ -76,7 +77,7 @@ @ivar name: (str) message name @ivar params: (dict) message params """ - __metaclass__ = MessageMeta + __metaclass__ = _PMessageMeta name = '' _additional_params_ = {} @@ -123,7 +124,7 @@ """Returns the message as nicely formated human readable string""" out = ['', '>>' + self.name, ] for param, value in self.params.items(): - if isinstance(param, PrivateParam): + if isinstance(param, _PrivateParam): continue # convert python to fcp value if necessary @@ -145,7 +146,7 @@ """Returns the message as formated string ready to be send""" out = [self.name, ] for param, value in self.params.items(): - if isinstance(param, PrivateParam): + if isinstance(param, _PrivateParam): continue # convert python to fcp value if necessary @@ -165,12 +166,12 @@ def toTree(self): """Converts message params to a tree of nodes - @return: (L{Node}) root node + @return: (L{_Node}) root node @note: some messages have hirarchicaly organized (dotted) parameters. Use this method to convert the parameters to a tree of nodes """ - node_ = Node() + node_ = _Node() for name, value in self.params.iteritems(): node_[name] = value @@ -213,211 +214,7 @@ def _getDataLength(self): return 0 - -#*************************************************************************************** -# -# param types for config message -# -# ..bit more efford here, cos we need types for user input checking -# ...a sloppy implementation of a dict should be enough -# -#*************************************************************************************** -class _ConfigMessageParamTypes(object): - """Parameter --> FcpType mapping for config related messages - - @note: we use this instead of _param_types_ dict to handle param classes - in L{ConfigData} and L{ModifyConfig} - """ - - - - # all known config keys (param class stripped) - Params = { - - 'console.allowedHosts': types.FcpTypeIPList, # host names, single IPs CIDR-maskip IPs likee 192.168.0.0/24 - 'console.bindTo': types.FcpTypeIPList, - 'console.directEnabled': types.FcpTypeBool, - 'console.enabled': types.FcpTypeBool, - 'console.port': types.FcpTypeIPort, - 'console.ssl': types.FcpTypeBool, - - 'fcp.allowedHosts': types.FcpTypeIPList, - 'fcp.allowedHostsFullAccess': types.FcpTypeIPList, - 'fcp.assumeDownloadDDAIsAllowed': types.FcpTypeBool, - 'fcp.assumeUploadDDAIsAllowed': types.FcpTypeBool, - 'fcp.bindTo': types.FcpTypeIP, - 'fcp.enabled': types.FcpTypeBool, - 'fcp.persistentDownloadsEnabled': types.FcpTypeBool, - 'fcp.persistentDownloadsFile': types.FcpTypeFilename, - 'fcp.persistentDownloadsInterval': types.FcpTypeTimeDelta, - 'fcp.port': types.FcpTypeIPort, - 'fcp.ssl': types.FcpTypeBool, - - 'fproxy.CSSOverride': types.FcpTypeBool, - 'fproxy.advancedModeEnabled': types.FcpTypeBool, - 'fproxy.allowedHosts': types.FcpTypeIPList, - 'fproxy.allowedHostsFullAccess': types.FcpTypeIPList, - 'fproxy.bindTo': types.FcpTypeIPList, - 'fproxy.css': types.FcpTypeChoiceFProxyCss, - 'fproxy.doRobots': types.FcpTypeBool, - 'fproxy.enabled': types.FcpTypeBool, - 'fproxy.javascriptEnabled': types.FcpTypeBool, - 'fproxy.port': types.FcpTypeIPort, - 'fproxy.showPanicButton': types.FcpTypeBool, - 'fproxy.ssl': types.FcpTypeBool, - - 'logger.dirname': types.FcpTypeDirname, - 'logger.enabled': types.FcpTypeBool, - 'logger.interval': types.FcpTypeTimeDelta, - 'logger.maxCachedBytes': types.FcpTypeByteAmount, - 'logger.maxCachedLines': types.FcpTypeByteAmount, # ??? - 'logger.maxZippedLogsSize': types.FcpTypeByteAmount, # ??? - 'logger.priority': types.FcpTypeChoiceLoggerPriority, - 'logger.priorityDetail': types.FcpType, # ???? is it Detailed priority thresholds ??? - - 'node.alwaysAllowLocalAddresses': types.FcpTypeBool, - 'node.assumeNATed': types.FcpTypeBool, - 'node.bindTo': types.FcpTypeIP, - 'node.clientThrottleFile': types.FcpTypeFilename, - 'node.databaseMaxMemory': types.FcpTypeByteAmount, - 'node.disableHangCheckers': types.FcpTypeBool, - 'node.disableProbabilisticHTLs': types.FcpTypeBool, - 'node.downloadAllowedDirs': types.FcpTypeChoiceNodeDownloadAllowedDirs, - 'node.downloadsDir': types.FcpTypeDirname, - 'node.enableARKs': types.FcpTypeBool, - 'node.enablePacketCoalescing': types.FcpTypeBool, - 'node.enablePerNodeFailureTables': types.FcpTypeBool, - 'node.enableSwapping': types.FcpTypeBool, - 'node.enableSwapQueueing': types.FcpTypeBool, - 'node.enableULPRDataPropagation': types.FcpTypeBool, - 'node.extraPeerDataDir': types.FcpTypeDirname, - 'node.includeLocalAddressesInNoderefs': types.FcpTypeBool, - 'node.inputBandwidthLimit': types.FcpTypeByteAmount, # -1 is possible as value aswell - 'node.ipAddressOverride': types.FcpTypeIP, - 'node.l10n': types.FcpType, # ??? - 'node.lazyResume': types.FcpTypeBool, - 'node.listenPort': types.FcpTypeIPort, - 'node.maxBackgroundUSKFetchers': types.FcpTypeIntWithBounds(0, None), - 'node.maxHTL': types.FcpTypeIntWithBounds(0, None), - 'node.name': types.FcpTypeString, - 'node.nodeDir': types.FcpTypeDirname, - 'node.oneConnectionPerIP': types.FcpTypeBool, - 'node.outputBandwidthLimit': types.FcpTypeByteAmount, - 'node.passOpennetPeersThroughDarknet': types.FcpTypeBool, - 'node.persistentTempDir': types.FcpTypeDirname, - 'node.storeDir': types.FcpTypeDirname, - 'node.storeForceBigShrinks': types.FcpTypeBool, - 'node.storeSize': types.FcpTypeByteAmount, - 'node.storeType': types.FcpTypeString, - 'node.tempDir': types.FcpTypeDirname, - 'node.tempIPAddressHint': types.FcpTypeIP, # ??? - 'node.testingDropPacketsEvery': types.FcpTypeIntWithBounds(0, None), - 'node.uploadAllowedDirs': types.FcpTypeChoiceNodeDownloadAllowedDirs, - - 'node.testnet.enabled': types.FcpTypeBool, - - 'node.load.aggressiveGC': types.FcpType, # ??? - 'node.load.freeHeapBytesThreshold': types.FcpTypeByteAmount, - 'node.load.freeHeapPercentThreshold': types.FcpTypePercent, - 'node.load.memoryChecker': types.FcpTypeBool, - 'node.load.nodeThrottleFile': types.FcpTypeFilename, - 'node.load.threadLimit': types.FcpTypeIntWithBounds(0, None), - - 'node.opennet.acceptSeedConnections': types.FcpTypeBool, - 'node.opennet.alwaysAllowLocalAddresses': types.FcpTypeBool, - 'node.opennet.assumeNATed': types.FcpTypeBool, - 'node.opennet.bindTo': types.FcpTypeIP, - 'node.opennet.enabled': types.FcpTypeBool, - 'node.opennet.listenPort': types.FcpTypeIPort, - 'node.opennet.maxOpennetPeers': types.FcpTypeIntWithBounds(0, None), - 'node.opennet.oneConnectionPerIP': types.FcpTypeBool, - 'node.opennet.testingDropPacketsEvery': types.FcpTypeIntWithBounds(0, None), - - 'node.scheduler.CHKinserter_priority_policy': types.FcpTypeChoicePriorityPolicy, - 'node.scheduler.CHKrequester_priority_policy': types.FcpTypeChoicePriorityPolicy, - 'node.scheduler.SSKinserter_priority_policy': types.FcpTypeChoicePriorityPolicy, - 'node.scheduler.SSKrequester_priority_policy': types.FcpTypeChoicePriorityPolicy, - - 'node.updater.URI': key.FcpTypeKey, - 'node.updater.autoupdate': types.FcpTypeBool, - 'node.updater.enabled': types.FcpTypeBool, - 'node.updater.extURI': key.FcpTypeKey, - 'node.updater.revocationURI': key.FcpTypeKey, - - 'pluginmanager.loadplugin': types.FcpTypeStringList, - 'pluginmanager2.loadedPlugins': types.FcpTypeStringList, - - 'ssl.sslEnable': types.FcpTypeBool, - 'ssl.sslKeyPass': types.FcpTypeString, - 'ssl.sslKeyStore': types.FcpTypeFilename, - 'ssl.sslKeyStorePass': types.FcpTypeString, - 'ssl.sslVersion': types.FcpTypeChoiceSSLVersion, - - 'toadletsymlinker.symlinks': types.FcpTypeStringList, - } - - def __init__(self): - pass - - def splitAll(self, paramName): - """Splits a parameter name into its components - @param paramName: (str) parameter name to split - @return: (list) components - """ - return paramName.split(consts.ConfigKeySep) - - - def splitParamClass(self, paramName): - """Splits the parameter class from a parameter name - @param paramName: (str) parameter name to split - @return: (tuple) paramClass, tail - """ - result = paramName.split(consts.ConfigKeySep, 1) - if len(result) == 2: - if result[0] in consts.ConfigValueClass.ClassesAll: - return result - return '', paramName - - - def get(self, paramName, default=None): - """Returns the type of a parameter or default - @param paramName: (str) name of the parameter to retuen the type for - @return: (FcpType) - """ - try: - return self[paramName] - except KeyError: - return default - - - def __getitem__(self, paramName): - """Returns the type of a parameter - @param paramName: (str) name of the parameter to retuen the type for - @return: (FcpType) - """ - paramClass, paramKey = self.splitParamClass(paramName) - if paramClass == consts.ConfigValueClass.Current or paramClass == '': - return self.Params[paramKey] - elif paramClass == consts.ConfigValueClass.Default: - return self.Params[paramKey] - elif paramClass == consts.ConfigValueClass.ExpertFlag: - return types.FcpTypeBool - elif paramClass == consts.ConfigValueClass.ForceWriteFlag: - return types.FcpTypeBool - elif paramClass == consts.ConfigValueClass.ShortDescription: - return types.FcpTypeString - elif paramClass == consts.ConfigValueClass.LongDescription: - return types.FcpTypeString - elif paramClass == consts.ConfigValueClass.SortOrder: - return types.FcpTypeInt - elif paramClass == consts.ConfigValueClass.DataType: - return types.FcpTypeString - else: - raise ValueError('Unknown param class in: %r' % paramName) - -ConfigMessageParamTypes = _ConfigMessageParamTypes() - #******************************************************************************** # at runtime we store a few additional params in msg.params # @@ -425,88 +222,88 @@ # as private so they don't get send to the node # #******************************************************************************** -AdditionalGetParams = { +_GetParams = { # persistent params that will go into identifier - PrivateParam('RequestType'): consts.RequestType.Null, # identifies sub message types - PrivateParam('InitTime'): 0, # when was the request started? - PrivateParam('FilenameCollision'): consts.FilenameCollision.HandleNever, # handle fielanem collisions? - PrivateParam('PersistentUserData'): '', # any user defined persistent data + _PrivateParam('RequestType'): consts.ConstRequestType.Null, # identifies sub message types + _PrivateParam('InitTime'): 0, # when was the request started? + _PrivateParam('FilenameCollision'): consts.ConstFilenameCollision.HandleNever, # handle fielanem collisions? + _PrivateParam('PersistentUserData'): '', # any user defined persistent data # non persistent params - PrivateParam('RequestStatus'): consts.RequestStatus.Null, - PrivateParam('ErrorMessage'): None, # error message in case an error occured - PrivateParam('UserData'): None, # any user defined runtime data here + _PrivateParam('RequestStatus'): consts.ConstRequestStatus.Null, + _PrivateParam('ErrorMessage'): None, # error message in case an error occured + _PrivateParam('UserData'): None, # any user defined runtime data here # params from DataFound - PrivateParam('MetadataContentType'): '', # content type - PrivateParam('MetadataSize'): 0, # content size + _PrivateParam('MetadataContentType'): '', # content type + _PrivateParam('MetadataSize'): 0, # content size # params from PersistentRequestModified - PrivateParam('Modified'): {}, + _PrivateParam('Modified'): {}, # params for DDA test - PrivateParam('TestDDA'): {}, + _PrivateParam('TestDDA'): {}, # params for SimpleProgress - PrivateParam('ProgressTotal'): 0, - PrivateParam('ProgressRequired'): 0, - PrivateParam('ProgressFailed'): 0, - PrivateParam('ProgressFatalyFailed'): 0, - PrivateParam('ProgressSucceeeded'): 0, + _PrivateParam('ProgressTotal'): 0, + _PrivateParam('ProgressRequired'): 0, + _PrivateParam('ProgressFailed'): 0, + _PrivateParam('ProgressFatalyFailed'): 0, + _PrivateParam('ProgressSucceeeded'): 0, } -AdditionalPutParams = { +_PutParams = { # persistent params that will go into identifier - PrivateParam('RequestType'): consts.RequestType.Null, # identifies sub message types - PrivateParam('InitTime'): 0, # when was the request started? + _PrivateParam('RequestType'): consts.ConstRequestType.Null, # identifies sub message types + _PrivateParam('InitTime'): 0, # when was the request started? #TODO: not really necessary, but we need it for persistent params - PrivateParam('PersistentUserData'): '', # any user defined persistent data + _PrivateParam('PersistentUserData'): '', # any user defined persistent data # non persistent params - PrivateParam('RequestStatus'): consts.RequestStatus.Null, - PrivateParam('ErrorMessage'): None, # error message in case an error occured - PrivateParam('UserData'): None, # any user defined runtime data here + _PrivateParam('RequestStatus'): consts.ConstRequestStatus.Null, + _PrivateParam('ErrorMessage'): None, # error message in case an error occured + _PrivateParam('UserData'): None, # any user defined runtime data here # params from DataFound - PrivateParam('MetadataContentType'): '', # contecnt type - PrivateParam('MetadataSize'): 0, # content size + _PrivateParam('MetadataContentType'): '', # contecnt type + _PrivateParam('MetadataSize'): 0, # content size # params from PersistentRequestModified - PrivateParam('Modified'): {}, + _PrivateParam('Modified'): {}, # params for DDA test - PrivateParam('TestDDA'): {}, + _PrivateParam('TestDDA'): {}, # params for SimpleProgress - PrivateParam('ProgressTotal'): 0, - PrivateParam('ProgressRequired'): 0, - PrivateParam('ProgressFailed'): 0, - PrivateParam('ProgressFatalyFailed'): 0, - PrivateParam('ProgressSucceeeded'): 0, + _PrivateParam('ProgressTotal'): 0, + _PrivateParam('ProgressRequired'): 0, + _PrivateParam('ProgressFailed'): 0, + _PrivateParam('ProgressFatalyFailed'): 0, + _PrivateParam('ProgressSucceeeded'): 0, } -AdditionalGenerateSSKParams = { - PrivateParam('RequestType'): consts.RequestType.Null, # identifies sub message types - PrivateParam('RequestStatus'): consts.RequestStatus.Null, - PrivateParam('InitTime'): 0, # when was the request started? +_GenerateSSKParams = { + _PrivateParam('RequestType'): consts.ConstRequestType.Null, # identifies sub message types + _PrivateParam('RequestStatus'): consts.ConstRequestStatus.Null, + _PrivateParam('InitTime'): 0, # when was the request started? } -AdditionalSubscribeUSKParams = { - PrivateParam('RequestType'): consts.RequestType.Null, # identifies sub message types - PrivateParam('RequestStatus'): consts.RequestStatus.Null, - PrivateParam('InitTime'): 0, # when was the request started? - PrivateParam('UserData'): None, - PrivateParam('Edition'): -1, +_SubscribeUSKParams = { + _PrivateParam('RequestType'): consts.ConstRequestType.Null, # identifies sub message types + _PrivateParam('RequestStatus'): consts.ConstRequestStatus.Null, + _PrivateParam('InitTime'): 0, # when was the request started? + _PrivateParam('UserData'): None, + _PrivateParam('Edition'): -1, } -AdditionalPluginInfoParams = { - PrivateParam('RequestType'): consts.RequestType.Null, # identifies sub message types - PrivateParam('RequestStatus'): consts.RequestStatus.Null, - PrivateParam('InitTime'): 0, # when was the request started? +_PluginInfoParams = { + _PrivateParam('RequestType'): consts.ConstRequestType.Null, # identifies sub message types + _PrivateParam('RequestStatus'): consts.ConstRequestStatus.Null, + _PrivateParam('InitTime'): 0, # when was the request started? } #******************************************************************************** @@ -515,7 +312,7 @@ # these params are stored in ClientToken # #******************************************************************************** -PersistentParamsGet = ( +_PersistentParamsGet = ( ( lambda msg: str(msg.__getitem__('RequestType')), lambda msg, value: msg.__setitem__('RequestType', int(value)), @@ -534,7 +331,7 @@ ), ) -PersistentParamsPut = ( +_PersistentParamsPut = ( ( lambda msg: str(msg.__getitem__('RequestType')), lambda msg, value: msg.__setitem__('RequestType', int(value)), @@ -559,27 +356,27 @@ '_persistent_params_': () if persistentParams is None else persistentParams, '_param_types_': {} if paramTypes is None else paramTypes, } - return type(name, (MessageBase, ), kws) + return type(name, (_PMessageBase, ), kws) #******************************************************************************** # some messages defined by the client #******************************************************************************** -class ClientDisconnected(MessageBase): - name = consts.Message.ClientDisconnected +class MsgClientDisconnected(_PMessageBase): + name = consts.ConstMessage.ClientDisconnected _additional_params_ = {} _param_types_ = { - 'DisconnectReason': types.FcpTypeInt, + 'DisconnectReason': types.TypeInt, } -class ClientSocketDied(MessageBase): - name = consts.Message.ClientSocketDied +class MsgClientSocketDied(_PMessageBase): + name = consts.ConstMessage.ClientSocketDied _additional_params_ = {} _param_types_ = { } -class ClientSocketTimeout(MessageBase): - name = consts.Message.ClientSocketTimeout +class MsgClientSocketTimeout(_PMessageBase): + name = consts.ConstMessage.ClientSocketTimeout _additional_params_ = {} _param_types_ = { } @@ -587,33 +384,33 @@ #******************************************************************************** # fcp messages #******************************************************************************** -class AddPeer(MessageBase): - name = consts.Message.AddPeer +class MsgAddPeer(_PMessageBase): + name = consts.ConstMessage.AddPeer _additional_params_ = {} _param_types_ = { - 'ark.number': types.FcpTypeInt, - 'auth.negTypes': types.FcpTypeInt, - 'ark.pubURI': key.FcpTypeKey, + 'ark.number': types.TypeInt, + 'auth.negTypes': types.TypeInt, + 'ark.pubURI': key.TypeKey, - 'location': types.FcpTypeFloat, - 'opennet': types.FcpTypeBool, - 'testnet': types.FcpTypeBool, + 'location': types.TypeFloat, + 'opennet': types.TypeBool, + 'testnet': types.TypeBool, # passed in Peer message - 'metadata.timeLastConnected': types.FcpTypeTime, - 'metadata.timeLastReceivedPacket': types.FcpTypeTime, - 'metadata.timeLastRoutable': types.FcpTypeTime, - 'metadata.timeLastSuccess': types.FcpTypeTime, - 'metadata.routableConnectionCheckCount': types.FcpTypeInt, - 'metadata.hadRoutableConnectionCount': types.FcpTypeInt, + 'metadata.timeLastConnected': types.TypeTime, + 'metadata.timeLastReceivedPacket': types.TypeTime, + 'metadata.timeLastRoutable': types.TypeTime, + 'metadata.timeLastSuccess': types.TypeTime, + 'metadata.routableConnectionCheckCount': types.TypeInt, + 'metadata.hadRoutableConnectionCount': types.TypeInt, - 'volatile.averagePingTime': types.FcpTypeFloat, - 'volatile.overloadProbability': types.FcpTypePercent, - 'volatile.routingBackoff': types.FcpTypeInt, - 'volatile.routingBackoffPercent': types.FcpTypePercent, - 'volatile.totalBytesIn': types.FcpTypeInt, - 'volatile.totalBytesOut': types.FcpTypeInt, - 'volatile.routingBackoffLength': types.FcpTypeInt, + 'volatile.averagePingTime': types.TypeFloat, + 'volatile.overloadProbability': types.TypePercent, + 'volatile.routingBackoff': types.TypeInt, + 'volatile.routingBackoffPercent': types.TypePercent, + 'volatile.totalBytesIn': types.TypeInt, + 'volatile.totalBytesOut': types.TypeInt, + 'volatile.routingBackoffLength': types.TypeInt, } '''all other Peer message params here.... @@ -635,104 +432,104 @@ ''' -class AllData(MessageBase): - name = consts.Message.AllData +class MsgAllData(_PMessageBase): + name = consts.ConstMessage.AllData _additional_params_ = {} _param_types_ = { - 'DataLength': types.FcpTypeInt, - 'Global': types.FcpTypeBool, + 'DataLength': types.TypeInt, + 'Global': types.TypeBool, } def _getDataLength(self): return self['DataLength'] -class ClientGet(MessageBase): - name = consts.Message.ClientGet - _additional_params_ = AdditionalGetParams - _persistent_params_ = PersistentParamsGet +class MsgClientGet(_PMessageBase): + name = consts.ConstMessage.ClientGet + _additional_params_ = _GetParams + _persistent_params_ = _PersistentParamsGet _param_types_ = { - 'BinaryBlob': types.FcpTypeBool, - 'DSOnly': types.FcpTypeBool, - 'Global': types.FcpTypeBool, - 'IgnoreDS': types.FcpTypeBool, - 'MaxRetries': types.FcpTypeInt, - 'MaxSize': types.FcpTypeInt, - 'MaxTempSize': types.FcpTypeInt, - 'URI': key.FcpTypeKey, - 'Verbosity': types.FcpTypeInt, + 'BinaryBlob': types.TypeBool, + 'DSOnly': types.TypeBool, + 'Global': types.TypeBool, + 'IgnoreDS': types.TypeBool, + 'MaxRetries': types.TypeInt, + 'MaxSize': types.TypeInt, + 'MaxTempSize': types.TypeInt, + 'URI': key.TypeKey, + 'Verbosity': types.TypeInt, } def _restoreParams(self, params): - MessageBase._restoreParams(self, params) + _PMessageBase._restoreParams(self, params) try: - MessageBase._setPersistentParams(self, self['ClientToken']) + _PMessageBase._setPersistentParams(self, self['ClientToken']) except Exception, d: #print Exception, d return False return True def updatePersistentParams(self): - self['ClientToken'] = MessageBase._getPersistentParams(self) + self['ClientToken'] = _PMessageBase._getPersistentParams(self) -class ClientHello(MessageBase): - name = consts.Message.ClientHello +class MsgClientHello(_PMessageBase): + name = consts.ConstMessage.ClientHello _additional_params_ = {} _param_types_ = { - 'ExpectedVersion': types.FcpTypeFloat, + 'ExpectedVersion': types.TypeFloat, } -class ClientPut(MessageBase): - name = consts.Message.ClientPut - _additional_params_ = AdditionalPutParams - _persistent_params_ = PersistentParamsPut +class MsgClientPut(_PMessageBase): + name = consts.ConstMessage.ClientPut + _additional_params_ = _PutParams + _persistent_params_ = _PersistentParamsPut _param_types_ = { - 'BinaryBlob': types.FcpTypeBool, - 'DataLength': types.FcpTypeInt, - 'DontCompress': types.FcpTypeBool, - 'EarlyEncode': types.FcpTypeBool, - 'GetCHKOnly': types.FcpTypeBool, - 'Global': types.FcpTypeBool, - 'MaxRetries': types.FcpTypeInt, - 'URI': key.FcpTypeKey, - 'Verbosity': types.FcpTypeInt, + 'BinaryBlob': types.TypeBool, + 'DataLength': types.TypeInt, + 'DontCompress': types.TypeBool, + 'EarlyEncode': types.TypeBool, + 'GetCHKOnly': types.TypeBool, + 'Global': types.TypeBool, + 'MaxRetries': types.TypeInt, + 'URI': key.TypeKey, + 'Verbosity': types.TypeInt, } def _getDataLength(self): return self['DataLength'] def _restoreParams(self, params): - MessageBase._restoreParams(self, params) + _PMessageBase._restoreParams(self, params) try: - MessageBase._setPersistentParams(self, self['ClientToken']) + _PMessageBase._setPersistentParams(self, self['ClientToken']) except Exception, d: #print Exception, d return False return True def updatePersistentParams(self): - self['ClientToken'] = MessageBase._getPersistentParams(self) + self['ClientToken'] = _PMessageBase._getPersistentParams(self) -class ClientPutComplexDir(ClientPut): - name = consts.Message.ClientPutComplexDir +class MsgClientPutComplexDir(MsgClientPut): + name = consts.ConstMessage.ClientPutComplexDir def __init__(self, *args, **kwargs): - ClientPut.__init__(self, *args, **kwargs) + MsgClientPut.__init__(self, *args, **kwargs) self._dataLength = 0 def _restoreParams(self, params): - result = ClientPut._restoreParams(self, params) + result = MsgClientPut._restoreParams(self, params) for paramName, paramValue in self.params.items(): tmp_paramName = paramName.split('.') if len(tmp_paramName) == 3: if tmp_paramName[-1] == 'DataLength': - n = types.FcpTypeInt.fcpToPython(paramValue) + n = types.TypeInt.fcpToPython(paramValue) self._dataLength += n self[paramName] = n return result @@ -743,302 +540,302 @@ -class ClientPutDiskDir(ClientPut): - name = consts.Message.ClientPutDiskDir +class MsgClientPutDiskDir(MsgClientPut): + name = consts.ConstMessage.ClientPutDiskDir -class CloseConnectionDuplicateClientName(MessageBase): - name = consts.Message.CloseConnectionDuplicateClientName +class MsgCloseConnectionDuplicateClientName(_PMessageBase): + name = consts.ConstMessage.CloseConnectionDuplicateClientName _additional_params_ = {} _param_types_ = { } ######################################### ######################################### -class ConfigData(MessageBase): - name = consts.Message.ConfigData +class MsgConfigData(_PMessageBase): + name = consts.ConstMessage.ConfigData _additional_params_ = {} - _param_types_ = ConfigMessageParamTypes + _param_types_ = config._ConfigMessageParamTypes -class DataFound(MessageBase): - name = consts.Message.DataFound +class MsgDataFound(_PMessageBase): + name = consts.ConstMessage.DataFound _additional_params_ = {} _param_types_ = { - 'DataLength': types.FcpTypeInt, - 'Global': types.FcpTypeBool, + 'DataLength': types.TypeInt, + 'Global': types.TypeBool, } -class EndListPeerNotes(MessageBase): - name = consts.Message.EndListPeerNotes +class MsgEndListPeerNotes(_PMessageBase): + name = consts.ConstMessage.EndListPeerNotes _additional_params_ = {} _param_types_ = { } -class EndListPeers(MessageBase): - name = consts.Message.EndListPeers +class MsgEndListPeers(_PMessageBase): + name = consts.ConstMessage.EndListPeers _additional_params_ = {} _param_types_ = { } -class EndListPersistentRequests(MessageBase): - name = consts.Message.EndListPersistentRequests +class MsgEndListPersistentRequests(_PMessageBase): + name = consts.ConstMessage.EndListPersistentRequests _additional_params_ = {} _param_types_ = { } -class FCPPluginMessage(MessageBase): - name = consts.Message.FCPPluginMessage +class MsgFCPPluginMessage(_PMessageBase): + name = consts.ConstMessage.FCPPluginMessage _additional_params_ = {} _param_types_ = { } -class FCPPluginReply(MessageBase): - name = consts.Message.FCPPluginReply +class MsgFCPPluginReply(_PMessageBase): + name = consts.ConstMessage.FCPPluginReply _additional_params_ = {} _param_types_ = { - 'DataLength': types.FcpTypeInt, + 'DataLength': types.TypeInt, } -class FinishedCompression(MessageBase): - name = consts.Message.FinishedCompression +class MsgFinishedCompression(_PMessageBase): + name = consts.ConstMessage.FinishedCompression _additional_params_ = {} _param_types_ = { - 'CompressedSize': types.FcpTypeInt, - 'OriginalSize': types.FcpTypeInt, + 'CompressedSize': types.TypeInt, + 'OriginalSize': types.TypeInt, } -class GenerateSSK(MessageBase): - name = consts.Message.GenerateSSK - _additional_params_ = AdditionalGenerateSSKParams +class MsgGenerateSSK(_PMessageBase): + name = consts.ConstMessage.GenerateSSK + _additional_params_ = _GenerateSSKParams _param_types_ = { } -class GetConfig(MessageBase): - name = consts.Message.GetConfig +class MsgGetConfig(_PMessageBase): + name = consts.ConstMessage.GetConfig _additional_params_ = {} _param_types_ = { - 'WithCurrent': types.FcpTypeBool, - 'WithDefaults': types.FcpTypeBool, - 'WithExpertFlag': types.FcpTypeBool, - 'WithForceWriteFlag': types.FcpTypeBool, - 'WithLongDescription': types.FcpTypeBool, - 'WithShortDescription': types.FcpTypeBool, - 'WithSortOrder': types.FcpTypeBool, - 'WithDataTypes': types.FcpTypeBool, + 'WithCurrent': types.TypeBool, + 'WithDefaults': types.TypeBool, + 'WithExpertFlag': types.TypeBool, + 'WithForceWriteFlag': types.TypeBool, + 'WithLongDescription': types.TypeBool, + 'WithShortDescription': types.TypeBool, + 'WithSortOrder': types.TypeBool, + 'WithDataTypes': types.TypeBool, } -class GetFailed(MessageBase): - name = consts.Message.GetFailed +class MsgGetFailed(_PMessageBase): + name = consts.ConstMessage.GetFailed _additional_params_ = {} _param_types_ = { - 'Code': types.FcpTypeInt, - 'ExpectedDataLength': types.FcpTypeInt_GetFailed_ExpectedDataLenght, - 'Fatal': types.FcpTypeBool, - 'FinalizedExpected': types.FcpTypeBool, - 'Global': types.FcpTypeBool, - 'RedirectURI': key.FcpTypeKey, + 'Code': types.TypeInt, + 'ExpectedDataLength': types.TypeInt_GetFailed_ExpectedDataLenght, + 'Fatal': types.TypeBool, + 'FinalizedExpected': types.TypeBool, + 'Global': types.TypeBool, + 'RedirectURI': key.TypeKey, } -class GetNode(MessageBase): - name = consts.Message.GetNode +class MsgGetNode(_PMessageBase): + name = consts.ConstMessage.GetNode _additional_params_ = {} _param_types_ = { - 'GiveOpennetRef': types.FcpTypeBool, - 'WithPrivate': types.FcpTypeBool, - 'WithVolatile': types.FcpTypeBool, + 'GiveOpennetRef': types.TypeBool, + 'WithPrivate': types.TypeBool, + 'WithVolatile': types.TypeBool, } -class GetPluginInfo(MessageBase): - name = consts.Message.GetPluginInfo - _additional_params_ = AdditionalPluginInfoParams +class MsgGetPluginInfo(_PMessageBase): + name = consts.ConstMessage.GetPluginInfo + _additional_params_ = _PluginInfoParams _param_types_ = { - 'Started': types.FcpTypeBool, + 'Started': types.TypeBool, } -class GetRequestStatus(MessageBase): - name = consts.Message.GetRequestStatus +class MsgGetRequestStatus(_PMessageBase): + name = consts.ConstMessage.GetRequestStatus _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, - 'OnlyData': types.FcpTypeBool, + 'Global': types.TypeBool, + 'OnlyData': types.TypeBool, } -class IdentifierCollision(MessageBase): - name = consts.Message.IdentifierCollision +class MsgIdentifierCollision(_PMessageBase): + name = consts.ConstMessage.IdentifierCollision _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, + 'Global': types.TypeBool, } -class ListPeer(MessageBase): - name = consts.Message.ListPeer +class MsgListPeer(_PMessageBase): + name = consts.ConstMessage.ListPeer _additional_params_ = {} _param_types_ = { - 'WithMetadata': types.FcpTypeBool, - 'WithVolantile': types.FcpTypeBool, + 'WithMetadata': types.TypeBool, + 'WithVolantile': types.TypeBool, } -class ListPeerNotes(MessageBase): - name = consts.Message.ListPeerNotes +class MsgListPeerNotes(_PMessageBase): + name = consts.ConstMessage.ListPeerNotes _additional_params_ = {} _param_types_ = { } -class ListPeers(MessageBase): - name = consts.Message.ListPeers +class MsgListPeers(_PMessageBase): + name = consts.ConstMessage.ListPeers _additional_params_ = {} _param_types_ = { - 'WithMetadata': types.FcpTypeBool, - 'WithVolantile': types.FcpTypeBool, + 'WithMetadata': types.TypeBool, + 'WithVolantile': types.TypeBool, } -class ListPersistentRequests(MessageBase): - name = consts.Message.ListPersistentRequests +class MsgListPersistentRequests(_PMessageBase): + name = consts.ConstMessage.ListPersistentRequests _additional_params_ = {} _param_types_ = { } ##################################### ##################################### -class ModifyConfig(MessageBase): - name = consts.Message.ModifyConfig +class MsgModifyConfig(_PMessageBase): + name = consts.ConstMessage.ModifyConfig _additional_params_ = {} - _param_types_ = ConfigMessageParamTypes + _param_types_ = config._ConfigMessageParamTypes ##################################### ##################################### -class ModifyPeer(MessageBase): - name = consts.Message.ModifyPeer +class MsgModifyPeer(_PMessageBase): + name = consts.ConstMessage.ModifyPeer _additional_params_ = {} _param_types_ = { } -class ModifyPeerNote(MessageBase): - name = consts.Message.ModifyPeerNote +class MsgModifyPeerNote(_PMessageBase): + name = consts.ConstMessage.ModifyPeerNote _additional_params_ = {} _param_types_ = { - #'Peernotetype': types.FcpTypeInt, #???? + #'Peernotetype': types.TypeInt, #???? } -class ModifyPersistentRequest(MessageBase): - name = consts.Message.ModifyPersistentRequest +class MsgModifyPersistentRequest(_PMessageBase): + name = consts.ConstMessage.ModifyPersistentRequest _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, + 'Global': types.TypeBool, } ################################### ################################### -class NodeData(MessageBase): - name = consts.Message.NodeData +class MsgNodeData(_PMessageBase): + name = consts.ConstMessage.NodeData _additional_params_ = {} _param_types_ = { - 'ark.number': types.FcpTypeInt, - 'ark.privURI': key.FcpTypeKey, - 'auth.negTypes': types.FcpTypeInt, - 'location': types.FcpTypeFloat, - 'opennet': types.FcpTypeBool, - 'testnet': types.FcpTypeBool, + 'ark.number': types.TypeInt, + 'ark.privURI': key.TypeKey, + 'auth.negTypes': types.TypeInt, + 'location': types.TypeFloat, + 'opennet': types.TypeBool, + 'testnet': types.TypeBool, - 'volatile.allocatedJavaMemory': types.FcpTypeInt, - 'volatile.availableCPUs': types.FcpTypeInt, - 'volatile.averagePingTime': types.FcpTypeFloat, - 'volatile.avgStoreAccessRate': types.FcpTypePercent, - 'volatile.backedOffPercent': types.FcpTypePercent, - 'volatile.bwlimitDelayTime': types.FcpTypeFloat, - 'volatile.cacheAccess': types.FcpTypeInt, - 'volatile.cachedKeys': types.FcpTypeInt, - 'volatile.cachedSize': types.FcpTypeInt, - 'volatile.cachedStoreHits': types.FcpTypeInt, - 'volatile.cachedStoreMisses': types.FcpTypeInt, - 'volatile.freeJavaMemory': types.FcpTypeInt, - 'volatile.isUsingWrapper': types.FcpTypeBool, - 'volatile.locationChangePerMinute': types.FcpTypeFloat, - 'volatile.locationChangePerSession': types.FcpTypeFloat, - 'volatile.locationChangePerSwap': types.FcpTypeFloat, - 'volatile.maximumJavaMemory': types.FcpTypeInt, - 'volatile.maxOverallKeys': types.FcpTypeInt, - 'volatile.maxOverallSize': types.FcpTypeInt, - 'volatile.networkSizeEstimate24hourRecent': types.FcpTypeInt, - 'volatile.networkSizeEstimate48hourRecent': types.FcpTypeInt, - 'volatile.networkSizeEstimateSession': types.FcpTypeInt, - 'volatile.noSwaps': types.FcpTypeFloat, - 'volatile.noSwapsPerMinute': types.FcpTypeFloat, - 'volatile.numberOfARKFetchers': types.FcpTypeInt, - 'volatile.numberOfBursting': types.FcpTypeInt, - 'volatile.numberOfConnected': types.FcpTypeInt, - 'volatile.numberOfDisabled': types.FcpTypeInt, - 'volatile.numberOfDisconnected': types.FcpTypeInt, - 'volatile.numberOfInsertSenders': types.FcpTypeInt, - 'volatile.numberOfListening': types.FcpTypeInt, - 'volatile.numberOfListenOnly': types.FcpTypeInt, - 'volatile.numberOfNeverConnected': types.FcpTypeInt, - 'volatile.numberOfNotConnected': types.FcpTypeInt, - 'volatile.numberOfRemotePeerLocationsSeenInSwaps': types.FcpTypeFloat, - 'volatile.numberOfRequestSenders': types.FcpTypeInt, - 'volatile.numberOfRoutingBackedOff': types.FcpTypeInt, - 'volatile.numberOfSimpleConnected': types.FcpTypeInt, - 'volatile.numberOfTooNew': types.FcpTypeInt, - 'volatile.numberOfTooOld': types.FcpTypeInt, - 'volatile.numberOfTransferringRequestSenders': types.FcpTypeInt, - 'volatile.numberWithRoutingBackoffReasons.ForwardRejectedOverload': types.FcpTypeInt, - 'volatile.overallAccesses': types.FcpTypeInt, - 'volatile.overallKeys': types.FcpTypeInt, - 'volatile.overallSize': types.FcpTypeInt, - 'volatile.percentCachedStoreHitsOfAccesses': types.FcpTypePercent, - 'volatile.percentOverallKeysOfMax': types.FcpTypePercent, - 'volatile.percentStoreHitsOfAccesses': types.FcpTypePercent, - 'volatile.pInstantReject': types.FcpTypeFloat, # or percent? - 'volatile.recentInputRate': types.FcpTypeFloat, - 'volatile.recentOutputRate': types.FcpTypeFloat, - 'volatile.routingMissDistance': types.FcpTypeFloat, - 'volatile.runningThreadCount': types.FcpTypeInt, - 'volatile.startedSwaps': types.FcpTypeInt, - 'volatile.startupTime': types.FcpTypeTime, - 'volatile.storeAccesses': types.FcpTypeInt, - 'volatile.storeHits': types.FcpTypeInt, - 'volatile.storeKeys': types.FcpTypeInt, - 'volatile.storeMisses': types.FcpTypeInt, - 'volatile.storeSize': types.FcpTypeInt, - 'volatile.swaps': types.FcpTypeFloat, - 'volatile.swapsPerMinute': types.FcpTypeFloat, - 'volatile.swapsPerNoSwaps': types.FcpTypeFloat, - 'volatile.swapsRejectedAlreadyLocked': types.FcpTypeInt, - 'volatile.swapsRejectedLoop': types.FcpTypeInt, - 'volatile.swapsRejectedNowhereToGo': types.FcpTypeInt, - 'volatile.swapsRejectedRateLimit': types.FcpTypeInt, - 'volatile.swapsRejectedRecognizedID': types.FcpTypeInt, - 'volatile.totalInputBytes': types.FcpTypeInt, - 'volatile.totalInputRate': types.FcpTypeInt, - 'volatile.totalOutputBytes': types.FcpTypeInt, - 'volatile.totalOutputRate': types.FcpTypeInt, - 'volatile.totalPayloadOutputBytes': types.FcpTypeInt, - 'volatile.totalPayloadOutputPercent': types.FcpTypePercent, - 'volatile.totalPayloadOutputRate': types.FcpTypeInt, - 'volatile.unclaimedFIFOSize': types.FcpTypeInt, - 'volatile.uptimeSeconds': types.FcpTypeInt, - 'volatile.usedJavaMemory': types.FcpTypeInt, + 'volatile.allocatedJavaMemory': types.TypeInt, + 'volatile.availableCPUs': types.TypeInt, + 'volatile.averagePingTime': types.TypeFloat, + 'volatile.avgStoreAccessRate': types.TypePercent, + 'volatile.backedOffPercent': types.TypePercent, + 'volatile.bwlimitDelayTime': types.TypeFloat, + 'volatile.cacheAccess': types.TypeInt, + 'volatile.cachedKeys': types.TypeInt, + 'volatile.cachedSize': types.TypeInt, + 'volatile.cachedStoreHits': types.TypeInt, + 'volatile.cachedStoreMisses': types.TypeInt, + 'volatile.freeJavaMemory': types.TypeInt, + 'volatile.isUsingWrapper': types.TypeBool, + 'volatile.locationChangePerMinute': types.TypeFloat, + 'volatile.locationChangePerSession': types.TypeFloat, + 'volatile.locationChangePerSwap': types.TypeFloat, + 'volatile.maximumJavaMemory': types.TypeInt, + 'volatile.maxOverallKeys': types.TypeInt, + 'volatile.maxOverallSize': types.TypeInt, + 'volatile.networkSizeEstimate24hourRecent': types.TypeInt, + 'volatile.networkSizeEstimate48hourRecent': types.TypeInt, + 'volatile.networkSizeEstimateSession': types.TypeInt, + 'volatile.noSwaps': types.TypeFloat, + 'volatile.noSwapsPerMinute': types.TypeFloat, + 'volatile.numberOfARKFetchers': types.TypeInt, + 'volatile.numberOfBursting': types.TypeInt, + 'volatile.numberOfConnected': types.TypeInt, + 'volatile.numberOfDisabled': types.TypeInt, + 'volatile.numberOfDisconnected': types.TypeInt, + 'volatile.numberOfInsertSenders': types.TypeInt, + 'volatile.numberOfListening': types.TypeInt, + 'volatile.numberOfListenOnly': types.TypeInt, + 'volatile.numberOfNeverConnected': types.TypeInt, + 'volatile.numberOfNotConnected': types.TypeInt, + 'volatile.numberOfRemotePeerLocationsSeenInSwaps': types.TypeFloat, + 'volatile.numberOfRequestSenders': types.TypeInt, + 'volatile.numberOfRoutingBackedOff': types.TypeInt, + 'volatile.numberOfSimpleConnected': types.TypeInt, + 'volatile.numberOfTooNew': types.TypeInt, + 'volatile.numberOfTooOld': types.TypeInt, + 'volatile.numberOfTransferringRequestSenders': types.TypeInt, + 'volatile.numberWithRoutingBackoffReasons.ForwardRejectedOverload': types.TypeInt, + 'volatile.overallAccesses': types.TypeInt, + 'volatile.overallKeys': types.TypeInt, + 'volatile.overallSize': types.TypeInt, + 'volatile.percentCachedStoreHitsOfAccesses': types.TypePercent, + 'volatile.percentOverallKeysOfMax': types.TypePercent, + 'volatile.percentStoreHitsOfAccesses': types.TypePercent, + 'volatile.pInstantReject': types.TypeFloat, # or percent? + 'volatile.recentInputRate': types.TypeFloat, + 'volatile.recentOutputRate': types.TypeFloat, + 'volatile.routingMissDistance': types.TypeFloat, + 'volatile.runningThreadCount': types.TypeInt, + 'volatile.startedSwaps': types.TypeInt, + 'volatile.startupTime': types.TypeTime, + 'volatile.storeAccesses': types.TypeInt, + 'volatile.storeHits': types.TypeInt, + 'volatile.storeKeys': types.TypeInt, + 'volatile.storeMisses': types.TypeInt, + 'volatile.storeSize': types.TypeInt, + 'volatile.swaps': types.TypeFloat, + 'volatile.swapsPerMinute': types.TypeFloat, + 'volatile.swapsPerNoSwaps': types.TypeFloat, + 'volatile.swapsRejectedAlreadyLocked': types.TypeInt, + 'volatile.swapsRejectedLoop': types.TypeInt, + 'volatile.swapsRejectedNowhereToGo': types.TypeInt, + 'volatile.swapsRejectedRateLimit': types.TypeInt, + 'volatile.swapsRejectedRecognizedID': types.TypeInt, + 'volatile.totalInputBytes': types.TypeInt, + 'volatile.totalInputRate': types.TypeInt, + 'volatile.totalOutputBytes': types.TypeInt, + 'volatile.totalOutputRate': types.TypeInt, + 'volatile.totalPayloadOutputBytes': types.TypeInt, + 'volatile.totalPayloadOutputPercent': types.TypePercent, + 'volatile.totalPayloadOutputRate': types.TypeInt, + 'volatile.unclaimedFIFOSize': types.TypeInt, + 'volatile.uptimeSeconds': types.TypeInt, + 'volatile.usedJavaMemory': types.TypeInt, } @@ -1063,52 +860,52 @@ ''' -class NodeHello(MessageBase): - name = consts.Message.NodeHello +class MsgNodeHello(_PMessageBase): + name = consts.ConstMessage.NodeHello _additional_params_ = {} _param_types_ = { - 'Build': types.FcpTypeInt, - 'CompressionCodecs': types.FcpTypeInt, - 'ExtBuild': types.FcpTypeInt, - 'FCPVersion': types.FcpTypeFloat, - 'Testnet': types.FcpTypeBool, + 'Build': types.TypeInt, + 'CompressionCodecs': types.TypeInt, + 'ExtBuild': types.TypeInt, + 'FCPVersion': types.TypeFloat, + 'Testnet': types.TypeBool, } ####################################### ####################################### -class Peer(MessageBase): - name = consts.Message.Peer +class MsgPeer(_PMessageBase): + name = consts.ConstMessage.Peer _additional_params_ = {} - _param_types_ = AddPeer._param_types_ + _param_types_ = MsgAddPeer._param_types_ -class PeerNote(MessageBase): - name = consts.Message.PeerNote +class MsgPeerNote(_PMessageBase): + name = consts.ConstMessage.PeerNote _additional_params_ = {} _param_types_ = { - 'NoteText': types.FcpTypeBase64EncodedString, + 'NoteText': types.TypeBase64EncodedString, } -class PeerRemoved(MessageBase): - name = consts.Message.PeerRemoved +class MsgPeerRemoved(_PMessageBase): + name = consts.ConstMessage.PeerRemoved _additional_params_ = {} _param_types_ = { } ####################################### ####################################### -class PersistentGet(MessageBase): - name = consts.Message.PersistentGet - _additional_params_ = AdditionalGetParams - _persistent_params_ = PersistentParamsGet - _param_types_ = ClientGet._param_types_.copy() - _param_types_['Started'] = types.FcpTypeBool +class MsgPersistentGet(_PMessageBase): + name = consts.ConstMessage.PersistentGet + _additional_params_ = _GetParams + _persistent_params_ = _PersistentParamsGet + _param_types_ = MsgClientGet._param_types_.copy() + _param_types_['Started'] = types.TypeBool def _restoreParams(self, params): - MessageBase._restoreParams(self, params) + _PMessageBase._restoreParams(self, params) try: - MessageBase._setPersistentParams(self, self['ClientToken']) + _PMessageBase._setPersistentParams(self, self['ClientToken']) except Exception, d: #print Exception, d return False @@ -1116,240 +913,244 @@ ####################################### ####################################### -class PersistentPut(MessageBase): - name = consts.Message.PersistentPut - _additional_params_ = AdditionalPutParams - _persistent_params_ = PersistentParamsPut - _param_types_ = ClientPut._param_types_.copy() - _param_types_['Started'] = types.FcpTypeBool +class MsgPersistentPut(_PMessageBase): + name = consts.ConstMessage.PersistentPut + _additional_params_ = _PutParams + _persistent_params_ = _PersistentParamsPut + _param_types_ = MsgClientPut._param_types_.copy() + _param_types_['Started'] = types.TypeBool def _restoreParams(self, params): - MessageBase._restoreParams(self, params) + _PMessageBase._restoreParams(self, params) try: - MessageBase._setPersistentParams(self, self['ClientToken']) + _PMessageBase._setPersistentParams(self, self['ClientToken']) except Exception, d: #print Exception, d return False return True -class PersistentPutDir(MessageBase): - name = consts.Message.PersistentPutDir - _additional_params_ = AdditionalPutParams - _persistent_params_ = PersistentParamsPut - _param_types_ = ClientPutDiskDir._param_types_.copy() - _param_types_['Started'] = types.FcpTypeBool +class MsgPersistentPutDir(_PMessageBase): + name = consts.ConstMessage.PersistentPutDir + _additional_params_ = _PutParams + _persistent_params_ = _PersistentParamsPut + _param_types_ = MsgClientPutDiskDir._param_types_.copy() + _param_types_['Started'] = types.TypeBool def _restoreParams(self, params): - MessageBase._restoreParams(self, params) + _PMessageBase._restoreParams(self, params) for paramName, paramValue in self.params.items(): tmp_paramName = paramName.split('.') if len(tmp_paramName) == 3: if tmp_paramName[-1] == 'DataLength': - n = types.FcpTypeInt.fcpToPython(paramValue) + n = types.TypeInt.fcpToPython(paramValue) self[paramName] = n try: - MessageBase._setPersistentParams(self, self['ClientToken']) + _PMessageBase._setPersistentParams(self, self['ClientToken']) except Exception, d: #print Exception, d return False return True -class PersistentRequestModified(MessageBase): - name = consts.Message.PersistentRequestModified +class MsgPersistentRequestModified(_PMessageBase): + name = consts.ConstMessage.PersistentRequestModified _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, + 'Global': types.TypeBool, } -class PersistentRequestRemoved(MessageBase): - name = consts.Message.PersistentRequestRemoved +class MsgPersistentRequestRemoved(_PMessageBase): + name = consts.ConstMessage.PersistentRequestRemoved _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, + 'Global': types.TypeBool, } -class PluginInfo(MessageBase): - name = consts.Message.PluginInfo +class MsgPluginInfo(_PMessageBase): + name = consts.ConstMessage.PluginInfo _additional_params_ = {} _param_types_ = { } -class ProtocolError(MessageBase): - name = consts.Message.ProtocolError +class MsgProtocolError(_PMessageBase): + name = consts.ConstMessage.ProtocolError _additional_params_ = {} _param_types_ = { - 'Code': types.FcpTypeInt, - 'Global': types.FcpTypeBool, + 'Code': types.TypeInt, + 'Global': types.TypeBool, } -class PutFailed(MessageBase): - name = consts.Message.PutFailed +class MsgPutFailed(_PMessageBase): + name = consts.ConstMessage.PutFailed _additional_params_ = {} _param_types_ = { - 'Code': types.FcpTypeInt, - 'ExpectedURI': key.FcpTypeKey, - 'Global': types.FcpTypeBool, + 'Code': types.TypeInt, + 'ExpectedURI': key.TypeKey, + 'Global': types.TypeBool, } -class PutFetchable(MessageBase): - name = consts.Message.PutFetchable +class MsgPutFetchable(_PMessageBase): + name = consts.ConstMessage.PutFetchable _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, - 'URI': key.FcpTypeKey, + 'Global': types.TypeBool, + 'URI': key.TypeKey, } ##################################### ###################################### #!! not implemented #TODO: has more params -class PutSuccessful(MessageBase): - name = consts.Message.PutSuccessful +class MsgPutSuccessful(_PMessageBase): + name = consts.ConstMessage.PutSuccessful _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, - 'URI': key.FcpTypeKey, + 'Global': types.TypeBool, + 'URI': key.TypeKey, } -class RemovePeer(MessageBase): - name = consts.Message.RemovePeer +class MsgRemovePeer(_PMessageBase): + name = consts.ConstMessage.RemovePeer _additional_params_ = {} _param_types_ = { } -class RemoveRequest(MessageBase): - name = consts.Message.RemoveRequest +class MsgRemoveRequest(_PMessageBase): + name = consts.ConstMessage.RemoveRequest _additional_params_ = {} _param_types_ = { - 'Global': types.FcpTypeBool, + 'Global': types.TypeBool, } -class SSKKeypair(MessageBase): - name = consts.Message. SSKKeypair +class MsgSSKKeypair(_PMessageBase): + name = consts.ConstMessage. SSKKeypair _additional_params_ = {} _param_types_ = { - 'InsertURI': key.FcpTypeKey, - 'RequestURI': key.FcpTypeKey, + 'InsertURI': key.TypeKey, + 'RequestURI': key.TypeKey, } -class Shutdown(MessageBase): - name = consts.Message.Shutdown +class MsgShutdown(_PMessageBase): + name = consts.ConstMessage.Shutdown _additional_params_ = {} _param_types_ = { } -class SimpleProgress(MessageBase): - name = consts.Message.SimpleProgress +class MsgSimpleProgress(_PMessageBase): + name = consts.ConstMessage.SimpleProgress _additional_params_ = {} _param_types_ = { - 'Failed': types.FcpTypeInt, - 'FatalyFailed': types.FcpTypeInt, - 'FinalizedTotal': types.FcpTypeBool, - 'Required': types.FcpTypeInt, - 'Succeeded': types.FcpTypeInt, - 'Total': types.FcpTypeInt, + 'Failed': types.TypeInt, + 'FatalyFailed': types.TypeInt, + 'FinalizedTotal': types.TypeBool, + 'Required': types.TypeInt, + 'Succeeded': types.TypeInt, + 'Total': types.TypeInt, } -class StartedCompression(MessageBase): - name = consts.Message.StartedCompression +class MsgStartedCompression(_PMessageBase): + name = consts.ConstMessage.StartedCompression _additional_params_ = {} _param_types_ = { } -class SubscribeUSK(MessageBase): - name = consts.Message.SubscribeUSK - _additional_params_ = AdditionalSubscribeUSKParams +class MsgSubscribeUSK(_PMessageBase): + name = consts.ConstMessage.SubscribeUSK + _additional_params_ = _SubscribeUSKParams _param_types_ = { - 'DontPoll': types.FcpTypeBool, - 'URI': key.FcpTypeKey, + 'DontPoll': types.TypeBool, + 'URI': key.TypeKey, } -class SubscribedUSKUpdate(MessageBase): - name = consts.Message.SubscribedUSKUpdate +class MsgSubscribedUSKUpdate(_PMessageBase): + name = consts.ConstMessage.SubscribedUSKUpdate _additional_params_ = {} _param_types_ = { - 'Edition': types.FcpTypeInt, - 'URI': key.FcpTypeKey, + 'Edition': types.TypeInt, + 'URI': key.TypeKey, } -class TestDDAComplete(MessageBase): - name = consts.Message.TestDDAComplete +class MsgTestDDAComplete(_PMessageBase): + name = consts.ConstMessage.TestDDAComplete _additional_params_ = {} _param_types_ = { - 'ReadDirectoryAllowed': types.FcpTypeBool, - 'WriteDirectoryAllowed': types.FcpTypeBool, + 'ReadDirectoryAllowed': types.TypeBool, + 'WriteDirectoryAllowed': types.TypeBool, } -class TestDDAReply(MessageBase): - name = consts.Message.TestDDAReply +class MsgTestDDAReply(_PMessageBase): + name = consts.ConstMessage.TestDDAReply _additional_params_ = {} _param_types_ = { } -class TestDDARequest(MessageBase): - name = consts.Message.TestDDARequest +class MsgTestDDARequest(_PMessageBase): + name = consts.ConstMessage.TestDDARequest _additional_params_ = {} _param_types_ = { - 'WantReadDirectory': types.FcpTypeBool, - 'WantWriteDirectory': types.FcpTypeBool, + 'WantReadDirectory': types.TypeBool, + 'WantWriteDirectory': types.TypeBool, } -class TestDDAResponse(MessageBase): - name = consts.Message.TestDDAResponse +class MsgTestDDAResponse(_PMessageBase): + name = consts.ConstMessage.TestDDAResponse _additional_params_ = {} _param_types_ = { } -class URIGenerated(MessageBase): - name = consts.Message.URIGenerated +class MsgURIGenerated(_PMessageBase): + name = consts.ConstMessage.URIGenerated _additional_params_ = {} _param_types_ = { - 'URI': key.FcpTypeKey, + 'URI': key.TypeKey, } -class UnknownNodeIdentifier(MessageBase): - name = consts.Message.UnknownNodeIdentifier +class MsgUnknownNodeIdentifier(_PMessageBase): + name = consts.ConstMessage.UnknownNodeIdentifier _additional_params_ = {} _param_types_ = { } -class UnknownPeerNoteType(MessageBase): - name = consts.Message.UnknownPeerNoteType +class MsgUnknownPeerNoteType(_PMessageBase): + name = consts.ConstMessage.UnknownPeerNoteType _additional_params_ = {} _param_types_ = { } -class WatchGlobal(MessageBase): - name = consts.Message.WatchGlobal +class MsgWatchGlobal(_PMessageBase): + name = consts.ConstMessage.WatchGlobal _additional_params_ = {} _param_types_ = { - 'Enabled': types.FcpTypeBool, - 'VerbosityMask': types.FcpTypeInt, + 'Enabled': types.TypeBool, + 'VerbosityMask': types.TypeInt, } + + +__all__ = [i for i in dir() if i[0].isupper() and not i.startswith('_')] +__all__.append('newMessageClass') \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 11:27:25
|
Revision: 460 http://fclient.svn.sourceforge.net/fclient/?rev=460&view=rev Author: jUrner Date: 2008-07-01 04:27:35 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/key.py Modified: trunk/fcp2/src/fcp2/key.py =================================================================== --- trunk/fcp2/src/fcp2/key.py 2008-07-01 11:27:28 UTC (rev 459) +++ trunk/fcp2/src/fcp2/key.py 2008-07-01 11:27:35 UTC (rev 460) @@ -16,17 +16,14 @@ from fcp2 import consts -del hack +del hack, _RelImportHack #<-- rel import hack #************************************************************************************** # consts #************************************************************************************** -ReMatchExact = '\A%s\Z' +_ReMatchExact = '\A%s\Z' KeyTypesAll = {} -# for testing, arbitrary but valid key data -DummyKeyData = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,AAAAAAA' - #************************************************************************************** # freenet base64 for keys #************************************************************************************** @@ -73,7 +70,7 @@ # see: [freenet/src/support/base64.java] # #*************************************************************************************** -class KeyMeta(type): +class _KeyMeta(type): """Metaclass for freenet keys""" def __new__(klass, name, bases, kws): @@ -90,7 +87,7 @@ # #************************************************************************************** #TODO: too bad, can not move this to types.py ...cross import -class FcpTypeKey(object): +class TypeKey(object): """key type for type conversions >>> key = FcpTypeKey.fcpToPython('CHK@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,AAAAAAA/foo') @@ -146,20 +143,20 @@ return key.toString() -def key(string): +def Key(string): """creates a key object from a string @return: L{KeyBase} """ - return FcpTypeKey.fcpToPython(string) + return TypeKey.fcpToPython(string) #************************************************************************************** # #************************************************************************************** -class KeyBase(object): +class _KeyBase(object): """Base class for freenet keys """ - __metaclass__ = KeyMeta + __metaclass__ = _KeyMeta KeyType = None def __eq__(self, other): @@ -179,7 +176,7 @@ raise NotImplementedError() -class CHK(KeyBase): +class KeyCHK(_KeyBase): """""" _key_pattern_ = ''' (?P<keyType>CHK@) @@ -190,9 +187,9 @@ ) (?: / (?P<filename>[^/]+?)? (?: /)?)? ''' - KeyType = consts.KeyType.CHK + KeyType = consts.ConstKeyType.CHK KeyPattern = re.compile(_key_pattern_, re.I | re.X) - ExactKeyPattern = re.compile(ReMatchExact % _key_pattern_, re.I | re.X) + ExactKeyPattern = re.compile(_ReMatchExact % _key_pattern_, re.I | re.X) def __init__(self, keyData=None, filename=None): """Creates a CHK key @@ -218,9 +215,10 @@ d = result.groupdict() key = clss(d['keyData'], filename=d['filename']) return key - + + -class SSK(KeyBase): +class KeySSK(_KeyBase): _key_pattern_ = ''' (?P<keyType>SSK@) (?P<keyData> @@ -233,9 +231,9 @@ (?: /)? )? ''' - KeyType = consts.KeyType.SSK + KeyType = consts.ConstKeyType.SSK KeyPattern = re.compile(_key_pattern_, re.I | re.X) - ExactKeyPattern = re.compile(ReMatchExact % _key_pattern_, re.I | re.X) + ExactKeyPattern = re.compile(_ReMatchExact % _key_pattern_, re.I | re.X) def __init__(self, keyData, filename=None): self.filename = filename @@ -255,17 +253,18 @@ if result is not None: d = result.groupdict() return clss(d['keyData'], d['filename']) - -class KSK(KeyBase): + + +class KeyKSK(_KeyBase): _key_pattern_ = ''' (?P<keyType>KSK@) (?P<filename>[^/]+?) (?: /)? ''' - KeyType = consts.KeyType.KSK + KeyType = consts.ConstKeyType.KSK KeyPattern = re.compile(_key_pattern_, re.I | re.X) - ExactKeyPattern = re.compile(ReMatchExact % _key_pattern_, re.I | re.X) + ExactKeyPattern = re.compile(_ReMatchExact % _key_pattern_, re.I | re.X) def __init__(self, filename): @@ -283,9 +282,10 @@ if result is not None: d = result.groupdict() return clss(filename=d['filename']) - + -class USK(KeyBase): + +class KeyUSK(_KeyBase): _key_pattern_ = ''' (?P<keyType>USK@) (?P<keyData> @@ -298,9 +298,9 @@ (?: /)? ''' - KeyType = consts.KeyType.USK + KeyType = consts.ConstKeyType.USK KeyPattern = re.compile(_key_pattern_, re.I | re.X) - ExactKeyPattern = re.compile(ReMatchExact % _key_pattern_, re.I | re.X) + ExactKeyPattern = re.compile(_ReMatchExact % _key_pattern_, re.I | re.X) def __init__(self, keyData, filename=None, edition=0): """Creates a USK key @@ -330,6 +330,8 @@ d = result.groupdict() return clss(d['keyData'], d['filename'], edition=d['edition']) + +__all__ = [i for i in dir() if i[0].isupper() and not i.startswith('_')] #***************************************************************************** # #***************************************************************************** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 11:27:20
|
Revision: 459 http://fclient.svn.sourceforge.net/fclient/?rev=459&view=rev Author: jUrner Date: 2008-07-01 04:27:28 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/iohandler.py Modified: trunk/fcp2/src/fcp2/iohandler.py =================================================================== --- trunk/fcp2/src/fcp2/iohandler.py 2008-07-01 11:27:21 UTC (rev 458) +++ trunk/fcp2/src/fcp2/iohandler.py 2008-07-01 11:27:28 UTC (rev 459) @@ -23,7 +23,7 @@ from fcp2 import message from fcp2 import types -del hack +del hack, _RelImportHack #<-- rel import hack #***************************************************************************** # @@ -50,7 +50,7 @@ @return: always None @raise L{consts.IOConnectFailedError}: in case something goes wrong """ - raise consts.IOConnectFailedError('Failed', consts.Logger.IO.error) + raise consts.ErrorIOConnectFailed('Failed', consts.ConstLogger.IO.error) def read(self, n): """Should read n bytes from the device @@ -59,7 +59,7 @@ @raise L{consts.IOBrokenError}: in case something goes wrong @raise L{consts.IOTimeoutError}: if the read operation times out """ - raise consts.IOBrokenError('Broken', consts.Logger.IO.error) + raise consts.ErrorIOBroken('Broken', consts.ConstLogger.IO.error) def write(self, bytes): """Should write bytes to the device @@ -67,7 +67,7 @@ @return: always None @raise L{consts.IOBrokenError}: in case something goes wrong """ - raise consts.IOBrokenError('Broken', consts.Logger.IO.error) + raise consts.ErrorIOBroken('Broken', consts.ConstLogger.IO.error) def close(self): """Should close the io device @@ -75,7 +75,7 @@ @return: always None @raise L{consts.IOClosedError}: if the device is already closed """ - raise consts.IOClosedError('Closed', consts.Logger.IO.error) + raise consts.ErrorIOClosed('Closed', consts.ConstLogger.IO.error) def isOpen(self): """Should check if the device is open @@ -117,7 +117,7 @@ try: self.socket.connect((host, port)) except socket.error, details: - raise consts.IOConnectFailedError(details, consts.Logger.IO.error) + raise consts.ErrorIOConnectFailed(details, consts.ConstLogger.IO.error) def read(self, n): try: @@ -125,10 +125,10 @@ if p == '': raise socket.error('Socket closed by host') except socket.timeout, details: - raise consts.IOTimeoutError(details, consts.Logger.IO.log, consts.DebugVerbosity.Chatty) + raise consts.ErrorIOTimeout(details, consts.ConstLogger.IO.log, consts.DebugVerbosity.Chatty) except socket.error, details: self.close() - raise consts.IOBrokenError(details, consts.Logger.IO.error) + raise consts.ErrorIOBroken(details, consts.ConstLogger.IO.error) else: return p @@ -140,11 +140,11 @@ totalSend += n except socket.error, details: self.close() - raise consts.IOBrokenError(details, consts.Logger.IO.error) + raise consts.ErrorIOBroken(details, consts.ConstLogger.IO.error) def close(self): if self.socket is None: - raise consts.IOClosedError('Closed', consts.Logger.IO.error) + raise consts.ErrorIOClosed('Closed', consts.ConstLogger.IO.error) self.socket.close() self.socket = None @@ -204,21 +204,21 @@ if self.isOpen(): self.close() - consts.Logger.IOHandler.info(consts.LogMessages.Connecting + ' %r' % kwargs) + consts.ConstLogger.IOHandler.info(consts.ConstLogMessages.Connecting + ' %r' % kwargs) self.io = self._ioPrototype() yield False # have to yield at least once to make unittests work (io has to be created!!) try: self.io.connect(**kwargs) - except consts.IOConnectFailedError, details: - consts.Logger.IOHandler.info(consts.LogMessages.ConnectingFailed + ' (%s)' % details) + except consts.ErrorIOConnectFailed, details: + consts.ConstLogger.IOHandler.info(consts.ConstLogMessages.ConnectingFailed + ' (%s)' % details) yield False else: - consts.Logger.IOHandler.info(consts.LogMessages.Connected) + consts.ConstLogger.IOHandler.info(consts.ConstLogMessages.Connected) yield True break # continue polling - consts.Logger.IOHandler.info(consts.LogMessages.Retry) + consts.ConstLogger.IOHandler.info(consts.ConstLogMessages.Retry) timeElapsed += timeout time.sleep(timeout) @@ -227,7 +227,7 @@ def close(self): """Closes the handler""" - consts.Logger.IOHandler.debug(consts.LogMessages.Closing) + consts.ConstLogger.IOHandler.debug(consts.ConstLogMessages.Closing) self._receiveBuffer = '' if self.io is not None: self.io.close() @@ -254,8 +254,8 @@ if not p: raise RuntimeError('No bytes received and IO did not raise as expected?!?') self._receiveBuffer += p - except consts.IOTimeoutError, details: # nothing in queue - raise consts.IOTimeoutError(details) + except consts.ErrorIOTimeout, details: # nothing in queue + raise consts.ErrorIOTimeout(details) def readMessage(self, hackyInvalidMessageCallback=None): @@ -297,11 +297,11 @@ p = [i for i in chunk.split('\n') if i] # Fcp ignores empty lines, so do we p.pop() if not p: - raise self.MessageParseError('No message name present') + raise self.ErrorMessageParse('No message name present') msgName = p.pop(0) msgClass = message.MessagesAll.get(msgName, None) if msgClass is None: - consts.Logger.IOHandler.debug(consts.LogMessages.CreatingNewMessageType + ' "%s"' % msgClassname) + consts.ConstLogger.IOHandler.debug(consts.ConstLogMessages.CreatingNewMessageType + ' "%s"' % msgClassname) msgClass = message.newMessageClass(msgName) msg = msgClass() @@ -311,7 +311,7 @@ #HACK: if hackyInvalidMessageCallback is not None: hackyInvalidMessageCallback(msg) - raise consts.MessageParseError('Invalid message parameters: ' + msg.pprint(), consts.Logger.IOHandler.error) + raise consts.ErrorMessageParse('Invalid message parameters: ' + msg.pprint(), consts.ConstLogger.IOHandler.error) # get associated data if necessary if mayHaveData: @@ -320,7 +320,7 @@ #HACK: if hackyInvalidMessageCallback is not None: ackyInvalidMessageCallback(msg) - raise consts.MessageParseError('DataLength must be type(int)') + raise consts.ErrorMessageParse('DataLength must be type(int)') if n > 0: while self._receiveBuffer: @@ -329,11 +329,11 @@ break try: self.readBytes(self.io.BufferSize) - except IOTimeout, details: # try again later + except ErrorIOTimeout, details: # try again later self._receiveBuffer = chunk + self._receiveBuffer - raise IOTimeout(details) + raise ErrorIOTimeout(details) - consts.Logger.IOHandler.debug(consts.LogMessages.Received + msg.pprint()) + consts.ConstLogger.IOHandler.debug(consts.ConstLogMessages.Received + msg.pprint()) return msg @@ -343,7 +343,7 @@ @return: Message @raise L{consts.IOBrokenError}: if the connection to the io dies unexpectedly """ - consts.Logger.IOHandler.debug(consts.LogMessages.Sending + msg.pprint()) + consts.ConstLogger.IOHandler.debug(consts.ConstLogMessages.Sending + msg.pprint()) self.io.write(msg.toString()) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 11:27:12
|
Revision: 458 http://fclient.svn.sourceforge.net/fclient/?rev=458&view=rev Author: jUrner Date: 2008-07-01 04:27:21 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/events.py Modified: trunk/fcp2/src/fcp2/events.py =================================================================== --- trunk/fcp2/src/fcp2/events.py 2008-07-01 11:27:11 UTC (rev 457) +++ trunk/fcp2/src/fcp2/events.py 2008-07-01 11:27:21 UTC (rev 458) @@ -18,7 +18,7 @@ from fcp2.fcp_lib import events -del hack +del hack, _RelImportHack #<-- rel import hack #******************************************************************************* # This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 11:27:04
|
Revision: 457 http://fclient.svn.sourceforge.net/fclient/?rev=457&view=rev Author: jUrner Date: 2008-07-01 04:27:11 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/consts.py Modified: trunk/fcp2/src/fcp2/consts.py =================================================================== --- trunk/fcp2/src/fcp2/consts.py 2008-07-01 11:27:03 UTC (rev 456) +++ trunk/fcp2/src/fcp2/consts.py 2008-07-01 11:27:11 UTC (rev 457) @@ -7,7 +7,7 @@ #***************************************************************************** # exceptions #***************************************************************************** -class FcpError(Exception): +class Error(Exception): def __init__(self, message, logMethod=None, logLevel=None): if logMethod is not None: if logLevel is None: @@ -16,25 +16,25 @@ logMethod(logLevel, self.__class__.__name__ + ': %s' % message) Exception.__init__(self, message) -class MessageParseError(FcpError): +class ErrorMessageParse(Error): """Exception raised when a message could not be parsed succesfuly""" -class IOConnectFailedError(FcpError): +class ErrorIOConnectFailed(Error): """Exception raised if the object can not be connected""" -class IOClosedError(FcpError): +class ErrorIOClosed(Error): """Exception raised if the object is closed""" -class IOBrokenError(FcpError): +class ErrorIOBroken(Error): """Exception raised if the IO connection is broken""" -class IOTimeoutError(Exception): +class ErrorIOTimeout(Error): """Exception raised when the io connection is closed""" #************************************************************************ # #************************************************************************ -class BaseBitFlags(object): +class _BaseBitFlags(object): """Base class for classes containing bitflags (bitflags only that is)""" @classmethod @@ -58,12 +58,11 @@ #************************************************************************ # #************************************************************************ -ConfigKeySep = '.' FcpTrue = 'true' FcpFalse = 'false' -class ByteAmountPostfix: +class ConstByteAmountPostfix: Bytes = '' Kilobytes = 'k' Kibibytes = 'K' @@ -90,46 +89,8 @@ Exibytes, ) -class ConfigDataType: - """Basic data types in config messages""" - Boolean = 'boolean' - Number = 'number' - String = 'string' - StringArray = 'atringArray' - - TypesAll = ( - Boolean, - Number, - String, - StringArray, - ) - -class ConfigValueClass: - """Value classes Fcp passes in config messages""" - - Current = 'current' - Default = 'default' - ExpertFlag = 'expertFlag' - ForceWriteFlag = 'forceWriteFlag' - ShortDescription = 'shortDescription' - LongDescription = 'longDescription' - SortOrder = 'sortOrder' - DataType = 'dataType' - - ClassesAll = ( - Current, - Default, - ExpertFlag, - ForceWriteFlag, - ShortDescription, - LongDescription, - SortOrder, - DataType, - ) - - -class ConnectReason: +class ConstConnectReason: """Reason for connecting to the node @cvar Connect: reason is a regualr connect @cvar Reconnect: reason is a reconnect @@ -137,8 +98,7 @@ Connect = 1 Reconnect = 2 - -class DebugVerbosity: +class ConstDebugVerbosity: """Consts indicating the verbosity level for debugging""" Chatty = logging.DEBUG - 1 Debug = logging.DEBUG @@ -147,9 +107,8 @@ Error = logging.ERROR Critical = logging.CRITICAL Quiet = 1000000 - -class DisconnectReason(BaseBitFlags): +class ConstDisconnectReason(_BaseBitFlags): """Reasons for client disconnect @cvar Close: the clent is about to close down @cvar ConnectionDied: the connection died unexpectedly @@ -171,8 +130,7 @@ UnknownNodeHello = 7 VersionMissmatch = 8 - -class FetchError(Exception): +class ConstFetchError(Exception): """All fetch errors supported by the client""" def __init__(self, msg): @@ -215,8 +173,7 @@ PermanentRedirect = 27 NotAllDataFound = 28 - -class FilenameCollision(BaseBitFlags): +class ConstFilenameCollision(_BaseBitFlags): """Filename collision flags @cvar HandleNever: don't handle filename collisions @cvar HandleRename: rename file on collisions @@ -230,8 +187,7 @@ CollisionHandled = 0x10000000 # a filename collision has already been handled - -class InsertError(Exception): +class ConstInsertError(Exception): """All insert errors supported by the client""" def __init__(self, msg): @@ -256,8 +212,7 @@ Collision = 9 Canceled = 10 - -class KeyType: +class ConstKeyType: """Supported key types""" SSK = 'SSK@' KSK = 'KSK@' @@ -266,9 +221,8 @@ SVK = 'SVK@' Invalid = '' TypesAll = (SSK, KSK, CHK, USK, SVK) - -class Logger: +class ConstLogger: """Package loggers""" Fcp = logging.getLogger('Fcp') Client = logging.getLogger('Fcp.Client') @@ -277,13 +231,11 @@ IOHandler =logging.getLogger('Fcp.Client.IOHandler') IO =logging.getLogger('Fcp.Client.IOHandler.IO') Message = logging.getLogger('Fcp.Client.Message') -logging.addLevelName(DebugVerbosity.Chatty, 'chatty') -logging.addLevelName(DebugVerbosity.Quiet, 'quiet') +logging.addLevelName(ConstDebugVerbosity.Chatty, 'chatty') +logging.addLevelName(ConstDebugVerbosity.Quiet, 'quiet') logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) - - -class LogMessages: +class ConstLogMessages: """Strings used for log infos""" Connecting = 'connecting' @@ -308,9 +260,7 @@ InvalidPersistentParams = 'Invalid peristent params' - - -class Message: +class ConstMessage: """Fcp messages""" # client --> node @@ -383,9 +333,8 @@ ClientSocketTimeout = 'FcSocketTimeout' ClientSocketDied = 'FcSocketDied' ClientDisconnected = 'FcClientDisconnected' - -class PeerNodeStatus: +class ConstPeerNodeStatus: Connected = 'CONNECTED' BackedOff = 'BACKED OFF' TooNew = 'TOO NEW' @@ -401,19 +350,17 @@ Bursting = 'BURSTING' Disconnecting = 'DISCONNECTING' Unknown = 'UNKNOWN STATUS' - -class PeerNoteType: +class ConstPeerNoteType: """All known peer note types""" Private = '1' - -class Persistence: +class ConstPersistence: Connection = 'connection' Reboot = 'reboot' Forever = 'forever' -class Priority: +class ConstPriority: Highest = '0' Higher = '1' High = '2' @@ -422,8 +369,7 @@ Lower = '5' Lowest = '6' - -class ProtocolError(Exception): +class ConstProtocolError(Exception): """All protocol errors supported by the client""" def __init__(self, msg): @@ -470,13 +416,11 @@ DarknetPeerOnly = 31 NoSuchPlugin = 32 - -class PutDirType: +class ConstPutDirType: Complex = 'complex' Disk = 'disk' - -class RequestModified(BaseBitFlags): +class ConstRequestModified(_BaseBitFlags): """Flags indicating what aspect of a request has been modified @cvar Filename: the filename has been modified @cvar Identifier: the identifier has been moodified @@ -492,8 +436,7 @@ PersistentUserData = 0x1 PriorityClass = 0x2 - -class RequestStatus(BaseBitFlags): +class ConstRequestStatus(_BaseBitFlags): """Request status flags @cvar Null: no status @cvar Restored: the request was restored when the client was started @@ -520,9 +463,8 @@ Completed =0x10000000 RemovedFromQueue = 0x2000000 - -class RequestType(BaseBitFlags): +class ConstRequestType(_BaseBitFlags): """Consts indicating the type of a request""" Null = 0 @@ -548,14 +490,12 @@ MaskPlugin = PluginInfo | PluginMessage MaskPut = PutData | PutFile | PutDir | PutMultiple | PutRedirect - -class ReturnType: +class ConstReturnType: Direct = 'direct' Disk = 'disk' Nothing = 'none' - -class TimeDeltaPostfix: +class ConstTimeDeltaPostfix: Second = '' Minute = 'minute' Hour = 'hour' @@ -571,16 +511,16 @@ Month, Year, ) - -class UploadFrom: +class ConstUploadFrom: Direct = 'direct' Disk = 'disk' Redirect = 'redirect' - -class Verbosity(BaseBitFlags): +class ConstVerbosity(_BaseBitFlags): ReportCompletion = 0x0 ReportProgress = 0x1 ReportCompression = 0x200 - + + +__all__ = [i for i in dir() if i[0].isupper() and not i.startswith('_')] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 11:26:55
|
Revision: 456 http://fclient.svn.sourceforge.net/fclient/?rev=456&view=rev Author: jUrner Date: 2008-07-01 04:27:03 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/config.py Modified: trunk/fcp2/src/fcp2/config.py =================================================================== --- trunk/fcp2/src/fcp2/config.py 2008-07-01 11:26:47 UTC (rev 455) +++ trunk/fcp2/src/fcp2/config.py 2008-07-01 11:27:03 UTC (rev 456) @@ -59,15 +59,259 @@ from fcp2 import consts from fcp2 import types -from fcp2 import message +from fcp2 import key from fcp2.fcp_lib import uuid -del hack +del hack, _RelImportHack #<-- rel import hack #**************************************************************************************** # #**************************************************************************************** +ConfigKeySep = '.' + +class ConfigDataType:# + """Basic data types in config messages""" + Boolean = 'boolean' + Number = 'number' + String = 'string' + StringArray = 'atringArray' + + TypesAll = ( + Boolean, + Number, + String, + StringArray, + ) + + +class ConfigValueClass: + """Value classes Fcp passes in config messages""" + + Current = 'current' + Default = 'default' + ExpertFlag = 'expertFlag' + ForceWriteFlag = 'forceWriteFlag' + ShortDescription = 'shortDescription' + LongDescription = 'longDescription' + SortOrder = 'sortOrder' + DataType = 'dataType' + + ClassesAll = ( + Current, + Default, + ExpertFlag, + ForceWriteFlag, + ShortDescription, + LongDescription, + SortOrder, + DataType, + ) + +#*************************************************************************************** +# +# param types for config message +# +# ..bit more efford here, cos we need types for user input checking +# ...a sloppy implementation of a dict should be enough +# +#*************************************************************************************** +class _ConfigMessageParamTypes(object): + """Parameter --> Type mapping for config related messages + + @note: we use this instead of _param_types_ dict to handle param classes + in L{ConfigData} and L{ModifyConfig} + """ + + # all known config keys (param class stripped) + Params = { + + 'console.allowedHosts': types.TypeIPList, # host names, single IPs CIDR-maskip IPs likee 192.168.0.0/24 + 'console.bindTo': types.TypeIPList, + 'console.directEnabled': types.TypeBool, + 'console.enabled': types.TypeBool, + 'console.port': types.TypeIPort, + 'console.ssl': types.TypeBool, + + 'fcp.allowedHosts': types.TypeIPList, + 'fcp.allowedHostsFullAccess': types.TypeIPList, + 'fcp.assumeDownloadDDAIsAllowed': types.TypeBool, + 'fcp.assumeUploadDDAIsAllowed': types.TypeBool, + 'fcp.bindTo': types.TypeIP, + 'fcp.enabled': types.TypeBool, + 'fcp.persistentDownloadsEnabled': types.TypeBool, + 'fcp.persistentDownloadsFile': types.TypeFilename, + 'fcp.persistentDownloadsInterval': types.TypeTimeDelta, + 'fcp.port': types.TypeIPort, + 'fcp.ssl': types.TypeBool, + + 'fproxy.CSSOverride': types.TypeBool, + 'fproxy.advancedModeEnabled': types.TypeBool, + 'fproxy.allowedHosts': types.TypeIPList, + 'fproxy.allowedHostsFullAccess': types.TypeIPList, + 'fproxy.bindTo': types.TypeIPList, + 'fproxy.css': types.TypeChoiceFProxyCss, + 'fproxy.doRobots': types.TypeBool, + 'fproxy.enabled': types.TypeBool, + 'fproxy.javascriptEnabled': types.TypeBool, + 'fproxy.port': types.TypeIPort, + 'fproxy.showPanicButton': types.TypeBool, + 'fproxy.ssl': types.TypeBool, + + 'logger.dirname': types.TypeDirname, + 'logger.enabled': types.TypeBool, + 'logger.interval': types.TypeTimeDelta, + 'logger.maxCachedBytes': types.TypeByteAmount, + 'logger.maxCachedLines': types.TypeByteAmount, # ??? + 'logger.maxZippedLogsSize': types.TypeByteAmount, # ??? + 'logger.priority': types.TypeChoiceLoggerPriority, + 'logger.priorityDetail': types.Type, # ???? is it Detailed priority thresholds ??? + + 'node.alwaysAllowLocalAddresses': types.TypeBool, + 'node.assumeNATed': types.TypeBool, + 'node.bindTo': types.TypeIP, + 'node.clientThrottleFile': types.TypeFilename, + 'node.databaseMaxMemory': types.TypeByteAmount, + 'node.disableHangCheckers': types.TypeBool, + 'node.disableProbabilisticHTLs': types.TypeBool, + 'node.downloadAllowedDirs': types.TypeChoiceNodeDownloadAllowedDirs, + 'node.downloadsDir': types.TypeDirname, + 'node.enableARKs': types.TypeBool, + 'node.enablePacketCoalescing': types.TypeBool, + 'node.enablePerNodeFailureTables': types.TypeBool, + 'node.enableSwapping': types.TypeBool, + 'node.enableSwapQueueing': types.TypeBool, + 'node.enableULPRDataPropagation': types.TypeBool, + 'node.extraPeerDataDir': types.TypeDirname, + 'node.includeLocalAddressesInNoderefs': types.TypeBool, + 'node.inputBandwidthLimit': types.TypeByteAmount, # -1 is possible as value aswell + 'node.ipAddressOverride': types.TypeIP, + 'node.l10n': types.Type, # ??? + 'node.lazyResume': types.TypeBool, + 'node.listenPort': types.TypeIPort, + 'node.maxBackgroundUSKFetchers': types.TypeIntWithBounds(0, None), + 'node.maxHTL': types.TypeIntWithBounds(0, None), + 'node.name': types.TypeString, + 'node.nodeDir': types.TypeDirname, + 'node.oneConnectionPerIP': types.TypeBool, + 'node.outputBandwidthLimit': types.TypeByteAmount, + 'node.passOpennetPeersThroughDarknet': types.TypeBool, + 'node.persistentTempDir': types.TypeDirname, + 'node.storeDir': types.TypeDirname, + 'node.storeForceBigShrinks': types.TypeBool, + 'node.storeSize': types.TypeByteAmount, + 'node.storeType': types.TypeString, + 'node.tempDir': types.TypeDirname, + 'node.tempIPAddressHint': types.TypeIP, # ??? + 'node.testingDropPacketsEvery': types.TypeIntWithBounds(0, None), + 'node.uploadAllowedDirs': types.TypeChoiceNodeDownloadAllowedDirs, + + 'node.testnet.enabled': types.TypeBool, + + 'node.load.aggressiveGC': types.Type, # ??? + 'node.load.freeHeapBytesThreshold': types.TypeByteAmount, + 'node.load.freeHeapPercentThreshold': types.TypePercent, + 'node.load.memoryChecker': types.TypeBool, + 'node.load.nodeThrottleFile': types.TypeFilename, + 'node.load.threadLimit': types.TypeIntWithBounds(0, None), + + 'node.opennet.acceptSeedConnections': types.TypeBool, + 'node.opennet.alwaysAllowLocalAddresses': types.TypeBool, + 'node.opennet.assumeNATed': types.TypeBool, + 'node.opennet.bindTo': types.TypeIP, + 'node.opennet.enabled': types.TypeBool, + 'node.opennet.listenPort': types.TypeIPort, + 'node.opennet.maxOpennetPeers': types.TypeIntWithBounds(0, None), + 'node.opennet.oneConnectionPerIP': types.TypeBool, + 'node.opennet.testingDropPacketsEvery': types.TypeIntWithBounds(0, None), + + 'node.scheduler.CHKinserter_priority_policy': types.TypeChoicePriorityPolicy, + 'node.scheduler.CHKrequester_priority_policy': types.TypeChoicePriorityPolicy, + 'node.scheduler.SSKinserter_priority_policy': types.TypeChoicePriorityPolicy, + 'node.scheduler.SSKrequester_priority_policy': types.TypeChoicePriorityPolicy, + + 'node.updater.URI': key.TypeKey, + 'node.updater.autoupdate': types.TypeBool, + 'node.updater.enabled': types.TypeBool, + 'node.updater.extURI': key.TypeKey, + 'node.updater.revocationURI': key.TypeKey, + + 'pluginmanager.loadplugin': types.TypeStringList, + 'pluginmanager2.loadedPlugins': types.TypeStringList, + + 'ssl.sslEnable': types.TypeBool, + 'ssl.sslKeyPass': types.TypeString, + 'ssl.sslKeyStore': types.TypeFilename, + 'ssl.sslKeyStorePass': types.TypeString, + 'ssl.sslVersion': types.TypeChoiceSSLVersion, + + 'toadletsymlinker.symlinks': types.TypeStringList, + } + + def __init__(self): + pass + + def splitAll(self, paramName): + """Splits a parameter name into its components + @param paramName: (str) parameter name to split + @return: (list) components + """ + return paramName.split(ConfigKeySep) + + + def splitParamClass(self, paramName): + """Splits the parameter class from a parameter name + @param paramName: (str) parameter name to split + @return: (tuple) paramClass, tail + """ + result = paramName.split(ConfigKeySep, 1) + if len(result) == 2: + if result[0] in ConfigValueClass.ClassesAll: + return result + return '', paramName + + + def get(self, paramName, default=None): + """Returns the type of a parameter or default + @param paramName: (str) name of the parameter to retuen the type for + @return: (Type) + """ + try: + return self[paramName] + except KeyError: + return default + + + def __getitem__(self, paramName): + """Returns the type of a parameter + @param paramName: (str) name of the parameter to retuen the type for + @return: (Type) + """ + paramClass, paramKey = self.splitParamClass(paramName) + if paramClass == ConfigValueClass.Current or paramClass == '': + return self.Params[paramKey] + elif paramClass == ConfigValueClass.Default: + return self.Params[paramKey] + elif paramClass == ConfigValueClass.ExpertFlag: + return types.TypeBool + elif paramClass == ConfigValueClass.ForceWriteFlag: + return types.TypeBool + elif paramClass == ConfigValueClass.ShortDescription: + return types.TypeString + elif paramClass == ConfigValueClass.LongDescription: + return types.TypeString + elif paramClass == ConfigValueClass.SortOrder: + return types.TypeInt + elif paramClass == ConfigValueClass.DataType: + return types.TypeString + else: + raise ValueError('Unknown param class in: %r' % paramName) + +_ConfigMessageParamTypes = _ConfigMessageParamTypes() + +#**************************************************************************************** +# +#**************************************************************************************** class ConfigItem(object): """Config item @@ -110,7 +354,7 @@ for x in walker(child): yield x return walker(self) - + #**************************************************************************************** # #**************************************************************************************** @@ -161,14 +405,14 @@ @note: if the item does not already exist it is created @note: if the key is unknown its type will always be set to L{types.FcpType} """ - paramClass, components = message.ConfigMessageParamTypes.splitParamClass(key) - paramType = message.ConfigMessageParamTypes.get(key, None) + paramClass, components = _ConfigMessageParamTypes.splitParamClass(key) + paramType = _ConfigMessageParamTypes.get(key, None) if paramType is None: paramType = types.FcpType consts.Logger.Config.warning('Unknown key: %r' % components) # find or create new config item if necessary - components = message.ConfigMessageParamTypes.splitAll(components) + components = _ConfigMessageParamTypes.splitAll(components) parent = self for component in components: item = parent.children.get(component, None) @@ -217,7 +461,8 @@ yield x return walker(self) - + +__all__ = [i for i in dir() if i[0].isupper() and not i.startswith('_')] #**************************************************************************************************** # #**************************************************************************************************** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 11:26:39
|
Revision: 455 http://fclient.svn.sourceforge.net/fclient/?rev=455&view=rev Author: jUrner Date: 2008-07-01 04:26:47 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/client.py Modified: trunk/fcp2/src/fcp2/client.py =================================================================== --- trunk/fcp2/src/fcp2/client.py 2008-07-01 11:26:28 UTC (rev 454) +++ trunk/fcp2/src/fcp2/client.py 2008-07-01 11:26:47 UTC (rev 455) @@ -226,8 +226,10 @@ from fcp2.fcp_lib import uuid -del hack +del hack, _RelImportHack #<-- rel import hack + +__all__ = ['Client', ] #************************************************************************************************* # #************************************************************************************************* @@ -257,11 +259,11 @@ MaxSizeKeyInfo = 32768 MinimumRunTime = 1 # FIX: 0001931 - consts = consts - config = config - message = message - types = types - key = key + #consts = consts + #config = config + #message = message + #types = types + #key = key def __init__(self, @@ -270,7 +272,7 @@ ): """ @param connectionName: name of the connection or None to use an arbitrary connection name - @param debugVerbosity: verbosity level for debugging. Default is L{consts.DebugVerbosity.Warning} + @param debugVerbosity: verbosity level for debugging. Default is L{consts.ConstDebugVerbosity.Warning} """ self._connectionName = self.setConnectionName(connectionName) @@ -282,7 +284,7 @@ for event in self.events: event += self._captureEvent - self.setDebugVerbosity(consts.DebugVerbosity.Warning if debugVerbosity is None else debugVerbosity) + self.setDebugVerbosity(consts.ConstDebugVerbosity.Warning if debugVerbosity is None else debugVerbosity) atexit.register(self.close) ############################################################### @@ -292,9 +294,9 @@ ############################################################### def _captureEvent(self, event, request): if event == self.events.Idle: - consts.Logger.Event.log(consts.DebugVerbosity.Chatty, consts.LogMessages.EventTriggered + event.name) + consts.ConstLogger.Event.log(consts.ConstDebugVerbosity.Chatty, consts.ConstLogMessages.EventTriggered + event.name) else: - consts.Logger.Event.info(consts.LogMessages.EventTriggered + event.name) + consts.ConstLogger.Event.info(consts.ConstLogMessages.EventTriggered + event.name) def _close(self, msg): @@ -305,7 +307,7 @@ @todo: trigger ClientDisconnected() if the client is already closed? should be yes. otherwise we'd have to distinguish between intentional and unintentional closing like on a broken io """ - consts.Logger.Client.info(consts.LogMessages.Closing) + consts.ConstLogger.Client.info(consts.ConstLogMessages.Closing) # clean left over DDA test tmp files for initialRequest in self._ddaTests: @@ -328,21 +330,21 @@ @param request: request to finalize @param event: event to trigger or None - @note: this method sets the requests L{consts.RequestStatus.RemovedFromQueue} and - L{consts.RequestStatus.Completed} flags accordingly + @note: this method sets the requests L{consts.ConstRequestStatus.RemovedFromQueue} and + L{consts.ConstRequestStatus.Completed} flags accordingly @note: Fcp removes Get / Put requests with Persistence == connection emidiately from its queue. Same goes all requests on ProtocolError. We inform the caller that the request has been completed and remove it fom our queue if necessary. Non Get / Put requests will be removed in any case. """ - removeRequest = msg == message.ProtocolError or msg == message.PersistentRequestRemoved # TODO: PersistentRequestRemoved??? + removeRequest = msg == message.MsgProtocolError or msg == message.MsgPersistentRequestRemoved # TODO: PersistentRequestRemoved??? if not removeRequest: #NOTE: non Get / Put related requests do not have a Persistence param - removeRequest = request.params.get('Persistence', consts.Persistence.Connection) == consts.Persistence.Connection + removeRequest = request.params.get('Persistence', consts.ConstPersistence.Connection) == consts.ConstPersistence.Connection if removeRequest: - request['RequestStatus'] |= consts.RequestStatus.RemovedFromQueue + request['RequestStatus'] |= consts.ConstRequestStatus.RemovedFromQueue - request['RequestStatus'] |= consts.RequestStatus.Completed + request['RequestStatus'] |= consts.ConstRequestStatus.Completed if event is not None: event(request) @@ -370,13 +372,13 @@ identifier=None, initTime=None, persistentUserData='', - filenameCollision=consts.FilenameCollision.HandleNever, + filenameCollision=consts.ConstFilenameCollision.HandleNever, ): """Registers a request @param msg: message to register - @param requestType: (L{consts.RequestType}) type of request to register - @param filenameCollision: (L{consts.FilenameCollision}) how to handle filename collisions. - Default is L{consts.FilenameCollision.HandleNever} + @param requestType: (L{consts.ConstRequestType}) type of request to register + @param filenameCollision: (L{consts.ConstFilenameCollision}) how to handle filename collisions. + Default is L{consts.ConstFilenameCollision.HandleNever} @param identifier: (str) identifier of the request or None to create a new one @param initTime: (int) init time of the request or None to set it to now @param persistentUserData: (str) anyuser defined persistent data @@ -390,39 +392,27 @@ # equip requests with some additional params #TODO: keep an eye on additional params, they may collide with Fcp parameters - Private = message.PrivateParam - - """ - @requestparam: B{ErrorMessage:} (L{messageMessage}) if an error occured - @requestparam: B{Modified:} (dict) - @requestparam: B{Modified:} (dict) - @requestparam: B{PrivateKey:} None. Will contain the private key as soon as the key is generated - @requestparam: B{PublicKey:} None. Will contain the public key as soon as the key is generated - @requestparam: B{RequestStatus:} one or more of the L{consts.RequestStatus} flags - @requestparam: B{RequestType:} one or more of the L{consts.RequestType} flags - @requestparam: B{Identifier:} identifier of the request - """ msg['Identifier'] = self._newUuid(uuids=self._requests) if identifier is None else identifier msg['RequestType'] = requestType msg['InitTime'] = time.time() if initTime is None else initTime - if requestType & consts.RequestType.MaskGet: + if requestType & consts.ConstRequestType.MaskGet: msg['FilenameCollision'] = filenameCollision msg['UserData'] = userData msg['PersistentUserData'] = persistentUserData msg['ClientToken'] = '' msg.updatePersistentParams() - elif requestType & consts.RequestType.MaskPut: + elif requestType & consts.ConstRequestType.MaskPut: msg['UserData'] = userData msg['PersistentUserData'] = persistentUserData msg['ClientToken'] = '' msg.updatePersistentParams() - elif requestType & consts.RequestType.MaskGenerateKeypair: + elif requestType & consts.ConstRequestType.MaskGenerateKeypair: pass - elif requestType & consts.RequestType.SubscribeUSK: + elif requestType & consts.ConstRequestType.SubscribeUSK: msg['UserData'] = userData - elif requestType & consts.RequestType.PluginInfo: + elif requestType & consts.ConstRequestType.PluginInfo: pass else: raise ValueError('Can not register request: ' + msg.name) @@ -438,15 +428,15 @@ """Closes the client @note: make shure to call close() when done with the client """ - msg = message.ClientDisconnected( - DisconnectReason=consts.DisconnectReason.Close, + msg = message.MsgClientDisconnected( + DisconnectReason=consts.ConstDisconnectReason.Close, ) self._close(msg) def closeNode(self): """Shuts down the freenet node""" - self.sendMessage(message.Shutdown()) + self.sendMessage(message.MsgShutdown()) def connect(self, host=DefaultFcpHost, port=DefaultFcpPort, duration=20, timeout=0.5): @@ -456,7 +446,7 @@ @param duration: (int) how many seconds try to connect before giving up @param timeout: (int) how much time to wait before another attempt to connect - @return: (L{message.Message}) NodeHello or None if no connection could be established + @return: (L{message.MsgMessage}) NodeHello or None if no connection could be established """ nodeHello = None for nodeHello in self.iterConnect(host=host, port=port, duration=duration, timeout=timeout): @@ -479,7 +469,7 @@ @param duration: (int) how many seconds try to connect before giving up @param timeout: (int) how much time to wait before another attempt to connect - @return: (L{message.Message}) NodeHello if successful, None otherwise for the next iteration + @return: (L{message.MsgMessage}) NodeHello if successful, None otherwise for the next iteration @event: ClientConnected(event, message) is triggered as soon as the client is connected """ @@ -487,12 +477,12 @@ #TODO: we have to yield a few round here to make NodeHello injection work in unittests # no idea exactly how many... if self.ioHandler.isOpen(): - disconnectMsg = message.ClientDisconnected( - DisconnectReason=consts.DisconnectReason.Reconnect, + disconnectMsg = message.MsgClientDisconnected( + DisconnectReason=consts.ConstDisconnectReason.Reconnect, ) self._close(disconnectMsg) - disconnectReason = consts.DisconnectReason.IOConnectFailed + disconnectReason = consts.ConstDisconnectReason.IOConnectFailed t0 = time.time() for result in self.ioHandler.iterConnect(duration=duration, timeout=timeout, host=host, port=port): yield None @@ -501,7 +491,7 @@ timeElapsed = time.time() - t0 if result: self.sendMessage( - message.ClientHello( + message.MsgClientHello( Name=self._connectionName, ExpectedVersion=self.ExpectedFcpVersion, ) @@ -510,11 +500,11 @@ while timeElapsed <= duration: yield None msg = self.next(dispatch=False) - if msg == message.ClientSocketTimeout: - disconnectReason = consts.DisconnectReason.NoNodeHello + if msg == message.MsgClientSocketTimeout: + disconnectReason = consts.ConstDisconnectReason.NoNodeHello timeElapsed += max(self.ioHandler.io.Timeout, 0.1) yield None - elif msg == message.NodeHello: + elif msg == message.MsgNodeHello: self._nodeHelloMessage = msg # check if version is ok if self.versionCheckNodeHello(msg): @@ -522,13 +512,13 @@ yield self._nodeHelloMessage raise StopIteration else: - disconnectReason = consts.DisconnectReason.VersionMissmatch + disconnectReason = consts.ConstDisconnectReason.VersionMissmatch break else: - disconnectReason = consts.DisconnectReason.UnknownNodeHello + disconnectReason = consts.ConstDisconnectReason.UnknownNodeHello break - disconnectMsg = message.ClientDisconnected( + disconnectMsg = message.MsgClientDisconnected( DisconnectReason=disconnectReason, ) self._close(disconnectMsg) @@ -553,17 +543,17 @@ def getDebugVerbosity(self): """Returns the current verbosity level of the client - @return: L{consts.DebugVerbosity} + @return: L{consts.ConstDebugVerbosity} """ - return consts.Logger.Client.getEffectiveLevel() + return consts.ConstLogger.Client.getEffectiveLevel() def setDebugVerbosity(self, debugVerbosity): """Sets the verbosity level of the client - @param debugVerbosity: L{consts.DebugVerbosity} + @param debugVerbosity: L{consts.ConstDebugVerbosity} """ - consts.Logger.Client.setLevel(debugVerbosity) + consts.ConstLogger.Client.setLevel(debugVerbosity) @@ -616,7 +606,7 @@ ## errors ## #################################################### - if msg == message.IdentifierCollision: + if msg == message.MsgIdentifierCollision: if initialRequest is None: self.events.IdentifierCollision(msg) return False @@ -626,17 +616,17 @@ self._requests[newIdentifier] = initialRequest del self._requests[requestIdentifier] initialRequest['Identifier'] = newIdentifier - initialRequest['Modified'] = {consts.RequestModified.Identifier: requestIdentifier} + initialRequest['Modified'] = {consts.ConstRequestModified.Identifier: requestIdentifier} self.events.RequestModified(initialRequest) self.sendMessage(initialRequest) return True - elif msg == message.ProtocolError: + elif msg == message.MsgProtocolError: code = msg['Code'] - if code == consts.ProtocolError.ShuttingDown: - disconnectMsg = message.ClientDisconnected( - DisconnectReason=consts.DisconnectReason.NodeClosing, + if code == consts.ConstProtocolError.ShuttingDown: + disconnectMsg = message.MsgClientDisconnected( + DisconnectReason=consts.ConstDisconnectReason.NodeClosing, ) self._close(disconnectMsg) return True @@ -651,9 +641,9 @@ return False # handle DDA errors - elif code == consts.ProtocolError.DDADenied: - ddaRequestMsg = message.TestDDARequest() - if initialRequest == message.ClientGet: + elif code == consts.ConstProtocolError.DDADenied: + ddaRequestMsg = message.MsgTestDDARequest() + if initialRequest == message.MsgClientGet: ddaRequestMsg['WantWriteDirectory'] = True directory = os.path.dirname(initialRequest['Filename']) else: @@ -675,31 +665,31 @@ # handle filename collisions - elif code == consts.ProtocolError.DiskTargetExists: - handleCollision = initialRequest.get('FilenameCollision', consts.FilenameCollision.HandleNever) - collisionHandled = bool(handleCollision & consts.FilenameCollision.CollisionHandled) + elif code == consts.ConstProtocolError.DiskTargetExists: + handleCollision = initialRequest.get('FilenameCollision', consts.ConstFilenameCollision.HandleNever) + collisionHandled = bool(handleCollision & consts.ConstFilenameCollision.CollisionHandled) # rename filename - if handleCollision & consts.FilenameCollision.HandleRename: + if handleCollision & consts.ConstFilenameCollision.HandleRename: filename = initialRequest['Filename'] - initialRequest['FilenameCollision'] |= consts.FilenameCollision.CollisionHandled + initialRequest['FilenameCollision'] |= consts.ConstFilenameCollision.CollisionHandled newFilename = namespace.unique_filename(filename, extensions=1, ispostfixed=collisionHandled) initialRequest['Filename'] = newFilename - initialRequest['Modified'] = {consts.RequestModified.Filename: filename} + initialRequest['Modified'] = {consts.ConstRequestModified.Filename: filename} self.sendMessage(initialRequest) self.events.RequestModified(initialRequest) return True # don't handle else: - initialRequest['FilenameCollision'] &= ~consts.FilenameCollision.CollisionHandled + initialRequest['FilenameCollision'] &= ~consts.ConstFilenameCollision.CollisionHandled # handle plugin related request failures - elif code == consts.ProtocolError.NoSuchPlugin or code == consts.ProtocolError.AccessDenied: - if initialRequest == message.GetPluginInfo: + elif code == consts.ConstProtocolError.NoSuchPlugin or code == consts.ConstProtocolError.AccessDenied: + if initialRequest == message.MsgGetPluginInfo: initialRequest['ErrorMessage'] = msg - initialRequest['RequestStatus'] |= consts.RequestStatus.Error + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Error self._finalizeRequest(msg, initialRequest, self.events.PluginInfoFailed) return True @@ -707,7 +697,7 @@ # NOTE: Fcp already removed the request initialRequest['ErrorMessage'] = msg - initialRequest['RequestStatus'] |= consts.RequestStatus.Error + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Error self._finalizeRequest(msg, initialRequest, self.events.RequestFailed) return True @@ -721,7 +711,7 @@ ## TestDDA drill. ## #################################################### - elif msg == message.TestDDAReply: + elif msg == message.MsgTestDDAReply: directory = msg['Directory'] # find message that triggered the call @@ -752,7 +742,7 @@ initialRequest['TestDDA']['TmpFile'] = fpathWrite self.sendMessage( - message.TestDDAResponse( + message.MsgTestDDAResponse( Directory=msg['Directory'], ReadContent=readContent, ) @@ -760,7 +750,7 @@ return True - elif msg == message.TestDDAComplete: + elif msg == message.MsgTestDDAComplete: # clean up tmp file directory = msg['Directory'] @@ -787,7 +777,7 @@ testFailed = not msg.params.get('ReadDirectoryAllowed', False) if testFailed: - initialRequest['RequestStatus'] = consts.RequestStatus.Error + initialRequest['RequestStatus'] = consts.ConstRequestStatus.Error initialRequest['ErrorMessage'] = initialRequest['TestDDA']['ErrorMsg'] self._finalizeRequest(msg, initialRequest, self.events.RequestFailed) return True @@ -801,11 +791,11 @@ ## config related ## #################################################### - elif msg == message.ConfigData: + elif msg == message.MsgConfigData: self.events.ConfigData(msg) return True - elif msg == message.NodeData: + elif msg == message.MsgNodeData: self.events.NodeData(msg) return True @@ -814,20 +804,20 @@ ## get / put related ## #################################################### - elif msg == message.AllData: + elif msg == message.MsgAllData: if initialRequest is None: return False - initialRequest['RequestStatus'] |= consts.RequestStatus.Success + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Success initialRequest.data = msg.data self._finalizeRequest(msg, initialRequest, self.events.RequestCompleted) return True - elif msg == message.DataFound: + elif msg == message.MsgDataFound: if initialRequest is None: return False - initialRequest['RequestStatus'] |= consts.RequestStatus.Success + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Success initialRequest['MetadataContentType'] = msg.get('Metadata.ContentType', '') initialRequest['MetadataSize'] = msg.get('DataLength', '') @@ -836,10 +826,10 @@ # For GetData with persistence != connection the node sends no All Data message # whatever that is good for ..fix this here to get all GetData request to complete on # All Data. - if initialRequest['RequestType'] == consts.RequestType.GetData: - if initialRequest['Persistence'] != consts.Persistence.Connection: + if initialRequest['RequestType'] == consts.ConstRequestType.GetData: + if initialRequest['Persistence'] != consts.ConstPersistence.Connection: self.sendMessage( - message.GetRequestStatus( + message.MsgGetRequestStatus( Identifier=initialRequest['Identifier'], Global=False, OnlyData=True @@ -851,37 +841,37 @@ return True - elif msg == message.GetFailed: + elif msg == message.MsgGetFailed: if initialRequest is None: return False code = msg['Code'] - if code == consts.FetchError.Canceled: - initialRequest['RequestStatus'] |= consts.RequestStatus.Removed | consts.RequestStatus.Completed | consts.RequestStatus.RemovedFromQueue + if code == consts.ConstFetchError.Canceled: + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Removed | consts.ConstRequestStatus.Completed | consts.ConstRequestStatus.RemovedFromQueue del self._requests[requestIdentifier] self.events.RequestRemoved(initialRequest) return True # check if it is one of our requests for key information - if code == consts.FetchError.TooBig and initialRequest['RequestType'] == consts.RequestType.GetKeyInfo: + if code == consts.ConstFetchError.TooBig and initialRequest['RequestType'] == consts.ConstRequestType.GetKeyInfo: initialRequest['MetadataContentType'] = msg.get('ExpectedMetadata.ContentType', '') initialRequest['DataLength'] = msg.get('ExpectedDataLength', -1) - initialRequest['RequestStatus'] |= consts.RequestStatus.Success + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Success self._finalizeRequest(msg, initialRequest, self.events.RequestCompleted) else: initialRequest['ErrorMessage'] = msg - initialRequest['RequestStatus'] |= consts.RequestStatus.Error + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Error self._finalizeRequest(msg, initialRequest, self.events.RequestFailed) return True - elif msg == message.PersistentGet or msg == message.PersistentPut or msg == message.PersistentPutDir: + elif msg == message.MsgPersistentGet or msg == message.MsgPersistentPut or msg == message.MsgPersistentPutDir: # unknown request... try to restore it if initialRequest is None: if CancelPersistentRequests: self.sendMessage( - message.RemoveRequest( + message.MsgRemoveRequest( Identifier=msg['Identifier'], Global=msg['Global'], ) @@ -889,13 +879,13 @@ return True requestType = msg['RequestType'] - if msg == message.PersistentGet: - initialRequest = message.ClientGet() - elif msg == message.PersistentPut: - initialRequest = message.ClientPut() + if msg == message.MsgPersistentGet: + initialRequest = message.MsgClientGet() + elif msg == message.MsgPersistentPut: + initialRequest = message.MsgClientPut() else: #NOTE: PutDiskDir is just a subtype of PutComplexDir. check PutDirType param to tell appart - initialRequest = message.ClientPutComplexDir() + initialRequest = message.MsgClientPutComplexDir() initialRequest.params.update(msg.params) self._requests[initialRequest['Identifier']] = initialRequest @@ -903,7 +893,7 @@ #FIX: remove Started param from PersistentGet / Put, not interesting if 'Started' in initialRequest.params: del initialRequest.params['Started'] - initialRequest['RequestStatus'] |= consts.RequestStatus.Restored + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Restored self.events.RequestRestored(initialRequest) return True @@ -911,7 +901,7 @@ return False - elif msg == message.PersistentRequestModified: + elif msg == message.MsgPersistentRequestModified: if initialRequest is None: return False @@ -920,7 +910,7 @@ # check if PersistentUserData has changed clientToken = msg.get('ClientToken', None) if clientToken is not None: - modified[consts.RequestModified.PersistentUserData] = None + modified[consts.ConstRequestModified.PersistentUserData] = None #TODO: its more or less a guess that PersistentUserData has changed # ...as long as no other param is changed at runtime we are ok @@ -937,7 +927,7 @@ # check if PriorityClass has changed priorityClass = msg.get('PriorityClass', None) if priorityClass is not None: - modified[consts.RequestModified.PriorityClass] = None + modified[consts.ConstRequestModified.PriorityClass] = None initialRequest['PriorityClass'] = priorityClass initialRequest['Modified'] = modified @@ -945,16 +935,16 @@ return True #NOTE: fcp sends a GetFailed / PutFailed if the request was still running (code=canceled) - elif msg == message.PersistentRequestRemoved: + elif msg == message.MsgPersistentRequestRemoved: if initialRequest is None: return False - initialRequest['RequestStatus'] |= consts.RequestStatus.Removed | consts.RequestStatus.Completed | consts.RequestStatus.RemovedFromQueue + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Removed | consts.ConstRequestStatus.Completed | consts.ConstRequestStatus.RemovedFromQueue del self._requests[requestIdentifier] self.events.RequestRemoved(initialRequest) return True - elif msg == message.SimpleProgress: + elif msg == message.MsgSimpleProgress: if initialRequest is None: return False @@ -968,24 +958,24 @@ ## put related - elif msg == message.PutFailed: + elif msg == message.MsgPutFailed: if initialRequest is None: return False code = msg['Code'] - if code == consts.InsertError.Canceled: - initialRequest['RequestStatus'] |= consts.RequestStatus.Removed | consts.RequestStatus.Completed | consts.RequestStatus.RemovedFromQueue + if code == consts.ConstInsertError.Canceled: + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Removed | consts.ConstRequestStatus.Completed | consts.ConstRequestStatus.RemovedFromQueue del self._requests[requestIdentifier] self.events.RequestRemoved(initialRequest) return True - initialRequest['RequestStatus'] |= consts.RequestStatus.Error + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Error initialRequest['ErrorMessage'] = msg self._finalizeRequest(msg, initialRequest, self.events.RequestFailed) return True - elif msg == message.PutFetchable: + elif msg == message.MsgPutFetchable: if initialRequest is None: # something went wrong return False @@ -994,35 +984,35 @@ return True - elif msg == message.PutSuccessful: + elif msg == message.MsgPutSuccessful: if initialRequest is None: return False # TODO: StartupTime and CompletionTime are passed, but # as long as no corrosponding params are passed in DataFound # we ignore them - initialRequest['RequestStatus'] |= consts.RequestStatus.Success + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Success initialRequest['URI'] = msg['URI'] self._finalizeRequest(msg, initialRequest, self.events.RequestCompleted) return True - elif msg == message.URIGenerated: + elif msg == message.MsgURIGenerated: if initialRequest is None: return False initialRequest['URI'] = msg['URI'] return True - elif msg == message.FinishedCompression: + elif msg == message.MsgFinishedCompression: if initialRequest is None: return False - initialRequest['RequestStatus'] |= consts.RequestStatus.Compressed + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Compressed self.events.RequestCompressionCompleted(initialRequest) return True - elif msg == message.StartedCompression: + elif msg == message.MsgStartedCompression: if initialRequest is None: return False - initialRequest['RequestStatus'] |= consts.RequestStatus.Compressing + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Compressing self.events.RequestCompressionStarted(initialRequest) return True @@ -1031,31 +1021,31 @@ ## Peer related messages ## #################################################### - elif msg == message.EndListPeers: + elif msg == message.MsgEndListPeers: self.events.EndListPeers(msg) return True - elif msg == message.EndListPeerNotes: + elif msg == message.MsgEndListPeerNotes: self.events.EndListPeerNotes(msg.params) return True - elif msg == message.Peer: + elif msg == message.MsgPeer: self.events.Peer(msg) return True - elif msg == message.PeerNote: + elif msg == message.MsgPeerNote: self.events.PeerNote(msg) return True - elif msg == message.PeerRemoved: + elif msg == message.MsgPeerRemoved: self.events.PeerRemoved(msg) return True - elif msg == message.UnknownNodeIdentifier: + elif msg == message.MsgUnknownNodeIdentifier: self.events.PeerUnknown(msg) return True - elif msg == message.UnknownPeerNoteType: + elif msg == message.MsgUnknownPeerNoteType: self.events.PeerNoteTypeUnknown(msg) return True #################################################### @@ -1063,15 +1053,15 @@ ## plugins ## #################################################### - elif msg == message.PluginInfo: + elif msg == message.MsgPluginInfo: if initialRequest is None: return False - initialRequest['RequestStatus'] |= consts.RequestStatus.Success + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Success self._finalizeRequest(msg, initialRequest, self.events.PluginInfo) return True - elif msg == message.FCPPluginReply: + elif msg == message.MsgFCPPluginReply: self.events.PluginMessage(msg) return True @@ -1080,31 +1070,31 @@ ## others ## #################################################### - elif msg == message.CloseConnectionDuplicateClientName: - disconnectMsg = message.ClientDisconnected( - DisconnectReason=consts.DisconnectReason.DuplicateClientName, + elif msg == message.MsgCloseConnectionDuplicateClientName: + disconnectMsg = message.MsgClientDisconnected( + DisconnectReason=consts.ConstDisconnectReason.DuplicateClientName, ) self._close(disconnectMsg) return True - elif msg == message.SSKKeypair: + elif msg == message.MsgSSKKeypair: if initialRequest is None: return False insertURI = msg['InsertURI'] requestURI = msg['RequestURI'] - if initialRequest['RequestType'] == consts.RequestType.GenerateUSKKeypair: - insertURI = key.USK(insertURI.keyData, filename=insertURI.filename) - requestURI = key.USK(requestURI.keyData, filename=requestURI.filename) + if initialRequest['RequestType'] == consts.ConstRequestType.GenerateUSKKeypair: + insertURI = key.KeyUSK(insertURI.keyData, filename=insertURI.filename) + requestURI = key.KeyUSK(requestURI.keyData, filename=requestURI.filename) initialRequest['InsertURI'] = insertURI initialRequest['RequestURI'] = requestURI - initialRequest['RequestStatus'] |= consts.RequestStatus.Success + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Success self._finalizeRequest(msg, initialRequest, self.events.KeypairGenerated) return True - elif msg == message.SubscribedUSKUpdate: + elif msg == message.MsgSubscribedUSKUpdate: if initialRequest is None: return False @@ -1127,24 +1117,24 @@ #FIX: [0002083] we may run into persistents of other clients by accident. the client can not handle them. # so remove them, no matter what.... def hackyInvalidMessageCallback(msg, requests=self._requests): - if msg == message.PersistentGet or msg == message.PersistentPut or msg == message.PersistentPutDir: + if msg == message.MsgPersistentGet or msg == message.MsgPersistentPut or msg == message.MsgPersistentPutDir: requestIdentifier = msg['Identifier'] if requestIdentifier not in requests: - msgRemove = message.RemoveRequest(Identifier=msg['Identifier'], Global=msg['Global']) + msgRemove = message.MsgRemoveRequest(Identifier=msg['Identifier'], Global=msg['Global']) self.sendMessage(msgRemove) try: msg = self.ioHandler.readMessage(hackyInvalidMessageCallback=hackyInvalidMessageCallback) - except consts.IOTimeoutError, details: - msg = message.ClientSocketTimeout() + except consts.ErrorIOTimeout, details: + msg = message.MsgClientSocketTimeout() if dispatch: self.events.Idle(msg) - except consts.IOBrokenError, details: - msg = message.ClientDisconnected( - DisconnectReason=consts.DisconnectReason.ConnectionDied, + except consts.ErrorIOBroken, details: + msg = message.MsgClientDisconnected( + DisconnectReason=consts.ConstDisconnectReason.ConnectionDied, ) self._close(msg) - raise consts.IOBrokenError(details) + raise consts.ErrorIOBroken(details) else: if dispatch: self.handleMessage(msg) @@ -1163,9 +1153,9 @@ try: msg = self.next() except KeyboardInterrupt: - consts.Logger.Client.info(consts.LogMessages.KeyboardInterrupt) + consts.ConstLogger.Client.info(consts.ConstLogMessages.KeyboardInterrupt) return - if msg == message.ClientSocketDied: + if msg == message.MsgClientSocketDied: return #n = 0 @@ -1176,28 +1166,28 @@ # check if we have running requests. Assert False haveRunningRequests = False for request in self._requests.values(): - if not request['RequestStatus'] & consts.RequestStatus.Completed: + if not request['RequestStatus'] & consts.ConstRequestStatus.Completed: haveRunningRequests = True break if not haveRunningRequests: - consts.Logger.Client.info(consts.LogMessages.AllRequestsCompleted) + consts.ConstLogger.Client.info(consts.ConstLogMessages.AllRequestsCompleted) break try: msg = self.next() except KeyboardInterrupt: - sconsts.Logger.Client.info(consts.LogMessages.KeyboardInterrupt) + sconsts.ConstLogger.Client.info(consts.ConstLogMessages.KeyboardInterrupt) break - if msg == message.ClientSocketDied: + if msg == message.MsgClientSocketDied: break def sendMessage(self, msg): """Sends a message to freenet - @param msg: (L{message.Message}) message to send - @return: (L{message.Message}) disconnect if something went wrong + @param msg: (L{message.MsgMessage}) message to send + @return: (L{message.MsgMessage}) disconnect if something went wrong @note: If an error occurs the client is closed @note: you can use this method to send a message to the node, bypassing all @@ -1210,12 +1200,12 @@ # ...so assume data was send, cos there is no way to proove it was not send try: self.ioHandler.sendMessage(msg) - except consts.IOBrokenError, details: - errorMsg = message.ClientDisconnected( - DisconnectReason=consts.DisconnectReason.ConnectionDied, + except consts.ErrorIOBroken, details: + errorMsg = message.MsgClientDisconnected( + DisconnectReason=consts.ConstDisconnectReason.ConnectionDied, ) self._close(errorMsg) - raise consts.IOBrokenError(details) + raise consts.ErrorIOBroken(details) ######################################################### ## @@ -1236,7 +1226,7 @@ @event: ConfigData(event, msg) """ self.sendMessage( - message.GetConfig( + message.MsgGetConfig( WithSortOrder=withSortOrder, WithCurrent=withCurrent, WithDefaults=withDefaults, @@ -1254,7 +1244,7 @@ """Modifies node configuration values @param params: (dict) containing parameters to modify """ - msg = message.ModifyConfig() + msg = message.MsgModifyConfig() msg.params = params self.sendMessage(msg) @@ -1273,7 +1263,7 @@ ): """Requests a key from the node @param uri: (L{key.KeyBase}) key to request - @param requestType: (L{consts.RequestType}) sub type of the message + @param requestType: (L{consts.ConstRequestType}) sub type of the message @param userData: any non persistent data to associate to the request or None @param persistentUserData: any string to associate to the request as persistent data or None @param filenameCollision: what to do if the disk target alreaady exists. One of the FilenameCollision.* consts @@ -1282,7 +1272,7 @@ @return: (str) request identifier """ - msg = message.ClientGet(URI=uri) + msg = message.MsgClientGet(URI=uri) for paramName, value in messageParams.items(): if value is not None: msg[paramName] = value @@ -1308,8 +1298,8 @@ ignoreDS=False, maxRetries=None, maxSize=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, userData=None, persistentUserData='', @@ -1324,8 +1314,8 @@ @param ignoreDS: (bool) if True, ignores the local data store @param maxRetries: (int) maximum number of retries or -1 to retry forver or None to leave it to the node to decide @param maxSize: (int) maximum size of the file in bytes or None to set no limited - @param persistence: (L{consts.Persistence}) persistence of the request - @param priorityClass: (L{consts.Priority}) priority of the request + @param persistence: (L{consts.ConstPersistence}) persistence of the request + @param priorityClass: (L{consts.ConstPriority}) priority of the request @param userData: any non persistent data to associate to the request @param persistentUserData: any string to associate to the request as persistent data @@ -1338,15 +1328,15 @@ @note: the identifier of the request may change at any time. You should be prepaired to handle this - @note: if persistence is L{consts.Persistence.Connection} the request is removed from the client + @note: if persistence is L{consts.ConstPersistence.Connection} the request is removed from the client as soon as it completes or failes """ return self.clientGet( uri, - consts.RequestType.GetData, + consts.ConstRequestType.GetData, userData, persistentUserData, - consts.FilenameCollision.HandleNever, + consts.ConstFilenameCollision.HandleNever, # Fcp params AllowedMimeTypes = allowedMimeTypes, @@ -1359,8 +1349,8 @@ MaxSize = maxSize, Persistence=persistence, PriorityClass=priorityClass, - ReturnType=consts.ReturnType.Direct, - Verbosity=consts.Verbosity.ReportProgress, + ReturnType=consts.ConstReturnType.Direct, + Verbosity=consts.ConstVerbosity.ReportProgress, ) @@ -1375,12 +1365,12 @@ ignoreDS=False, maxRetries=None, maxSize=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, userData=None, persistentUserData='', - filenameCollision=consts.FilenameCollision.HandleNever, + filenameCollision=consts.ConstFilenameCollision.HandleNever, ): """Requests a file from the node @@ -1393,8 +1383,8 @@ @param ignoreDS: If True, ignores the local data store @param maxRetries: (int) maximum number of retries or -1 to retry forver or None to leave it to the node to decide @param maxSize: (int) maximum size of the file in bytes or None to set no limited - @param persistence: (L{consts.Persistence}) persistence of the request - @param priorityClass: (L{consts.Priority}) priority of the request + @param persistence: (L{consts.ConstPersistence}) persistence of the request + @param priorityClass: (L{consts.ConstPriority}) priority of the request @param filenameCollision: what to do if the disk target alreaady exists. One of the FilenameCollision.* consts @param userData: any non persistent data to associate to the request @param persistentUserData: any string to associate to the request as persistent data @@ -1407,12 +1397,12 @@ filename changes or the request is modified otherwise (see L{modifyRequest}) - @note: if persistence is L{consts.Persistence.Connection} the request is removed from the client + @note: if persistence is L{consts.ConstPersistence.Connection} the request is removed from the client as soon as it completes or failes """ return self.clientGet( uri, - consts.RequestType.GetFile, + consts.ConstRequestType.GetFile, userData, persistentUserData, filenameCollision, @@ -1429,8 +1419,8 @@ MaxSize = maxSize, Persistence=persistence, PriorityClass=priorityClass, - ReturnType=consts.ReturnType.Disk, - Verbosity=consts.Verbosity.ReportProgress, + ReturnType=consts.ConstReturnType.Disk, + Verbosity=consts.ConstVerbosity.ReportProgress, ) @@ -1441,8 +1431,8 @@ dsOnly=False, ignoreDS=False, maxRetries=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, userData=None, persistentUserData='', @@ -1454,8 +1444,8 @@ @param dsOnly: if True, retrieves the file from the local data store only @param ignoreDS: If True, ignores the local data store @param maxRetries: (int) maximum number of retries or -1 to retry forver or None to leave it to the node to decide - @param persistence: (L{consts.Persistence}) persistence of the request - @param priorityClass: (L{consts.Priority}) priority of the request + @param persistence: (L{consts.ConstPersistence}) persistence of the request + @param priorityClass: (L{consts.ConstPriority}) priority of the request @param userData: any non persistent data to associate to the request @param persistentUserData: any string to associate to the request as persistent data @@ -1467,16 +1457,16 @@ @event: RequestModified(event, message) trigggered if the request identifier changes or the request is modified otherwise (see L{modifyRequest}) - @note: if persistence is L{consts.Persistence.Connection} the request is removed from the client + @note: if persistence is L{consts.ConstPersistence.Connection} the request is removed from the client as soon as it completes or failes """ # how to retrieve meta info about a key? ...idea is to provoke a GetFailed (TooBig) return self.clientGet( uri, - consts.RequestType.GetKeyInfo, + consts.ConstRequestType.GetKeyInfo, userData, persistentUserData, - consts.FilenameCollision.HandleNever, + consts.ConstFilenameCollision.HandleNever, # Fcp params Global=False, @@ -1487,8 +1477,8 @@ MaxSize=self.MaxSizeKeyInfo, Persistence=persistence, PriorityClass=priorityClass, - ReturnType=consts.ReturnType.Nothing, - Verbosity=consts.Verbosity.ReportProgress, + ReturnType=consts.ConstReturnType.Nothing, + Verbosity=consts.ConstVerbosity.ReportProgress, ) @@ -1499,17 +1489,17 @@ @param dontPoll: if True, does whatever ??? @return: (str) identifer of the request - @note: this request can not be removed or modified so the L{consts.RequestStatus.Completed} + @note: this request can not be removed or modified so the L{consts.ConstRequestStatus.Completed} flag is always set @todo: looks like USK subscribes will persist untill connection is closed. Can they be removed somehow? """ - msg = message.SubscribeUSK( + msg = message.MsgSubscribeUSK( URI=uri, DontPoll=dontPoll, ) - self._registerRequest(msg, consts.RequestType.SubscribeUSK) - msg['RequestStatus'] |= consts.RequestStatus.Completed + self._registerRequest(msg, consts.ConstRequestType.SubscribeUSK) + msg['RequestStatus'] |= consts.ConstRequestStatus.Completed self.sendMessage(msg) return msg['Identifier'] @@ -1529,22 +1519,22 @@ **msgParams ): """Uploads to the node - @param requestType: (L{consts.RequestType}). Can be PutData, PutDir or PutMultiple + @param requestType: (L{consts.ConstRequestType}). Can be PutData, PutDir or PutMultiple @param uri: (str) key or Uri - @param data: (str) for L{consts.RequestType.PutData} data to upload or None + @param data: (str) for L{consts.ConstRequestType.PutData} data to upload or None @param persistentUserData: (str) persistent data to be assosiated to the request @param userData: (any) any data to be associated to the request at runtime - @param items: for L{consts.RequestType.PutMultiple}, items to upload + @param items: for L{consts.ConstRequestType.PutMultiple}, items to upload @param msgParams: (dict) Fcp parameters to pass along with the message @note: the Fcp message parameter 'Metadata.ContentType' may be passed as 'ContentType' to this method @note: to upload multiple items at once pass a dict for each item containig the following members: - - RequestType: L{consts.RequestType.PutData}, L{consts.RequestType.PutFile} or L{consts.RequestType.PutRedirect} - - Data: if requestType is L{consts.RequestType.PutData}, data to upload - - Filename: if requestType is L{consts.RequestType.PutFile}, filepath of the file to upload - - TargetURI: if requestType is L{consts.RequestType.PutRedirect}, uri to redirect to + - RequestType: L{consts.ConstRequestType.PutData}, L{consts.ConstRequestType.PutFile} or L{consts.ConstRequestType.PutRedirect} + - Data: if requestType is L{consts.ConstRequestType.PutData}, data to upload + - Filename: if requestType is L{consts.ConstRequestType.PutFile}, filepath of the file to upload + - TargetURI: if requestType is L{consts.ConstRequestType.PutRedirect}, uri to redirect to - Name: name under wich the item will be accesible via freenet - Metadata.ContentType: (optional) may be passed as 'ContentType' @@ -1559,18 +1549,18 @@ msgParams['Metadata.ContentType'] = contentType # find out wich message to use - if requestType & (consts.RequestType.PutData | consts.RequestType.PutFile | consts.RequestType.PutRedirect): - msgClass = message.ClientPut - elif requestType == consts.RequestType.PutDir: - msgClass = message.ClientPutDiskDir - elif requestType == consts.RequestType.PutMultiple: - msgClass = message.ClientPutComplexDir + if requestType & (consts.ConstRequestType.PutData | consts.ConstRequestType.PutFile | consts.ConstRequestType.PutRedirect): + msgClass = message.MsgClientPut + elif requestType == consts.ConstRequestType.PutDir: + msgClass = message.MsgClientPutDiskDir + elif requestType == consts.ConstRequestType.PutMultiple: + msgClass = message.MsgClientPutComplexDir else: raise ValueError('Unsupported request type') msg = msgClass(URI=uri) # add params - if uri.KeyType == consts.KeyType.CHK: + if uri.KeyType == consts.ConstKeyType.CHK: if uri.filename is not None: msg['TargetFilename'] = uri.filename for param, value in msgParams.items(): @@ -1578,32 +1568,32 @@ msg[param] = value if data is not None: - if requestType != consts.RequestType.PutData: + if requestType != consts.ConstRequestType.PutData: raise ValueError('Data can only be passed along with putData uploads') msg.data = data if items is not None: - if requestType != consts.RequestType.PutMultiple: + if requestType != consts.ConstRequestType.PutMultiple: raise ValueError('Items can only be passed along with PutMultiple uploads') uploadTypeMapping = { - consts.RequestType.PutData: consts.UploadFrom.Direct, - consts.RequestType.PutFile: consts.UploadFrom.Disk, - consts.RequestType.PutRedirect: consts.UploadFrom.Redirect, + consts.ConstRequestType.PutData: consts.ConstUploadFrom.Direct, + consts.ConstRequestType.PutFile: consts.ConstUploadFrom.Disk, + consts.ConstRequestType.PutRedirect: consts.ConstUploadFrom.Redirect, } # requestType --> [(allowedParam: boolParamIsRequired), ...] paramMapping = { - consts.RequestType.PutData: [ + consts.ConstRequestType.PutData: [ ('Name', True), ('Data', True), ('ContentType', False), ], - consts.RequestType.PutFile: [ + consts.ConstRequestType.PutFile: [ ('Name', True), ('Filename', True), ('Metadata.ContentType', False), ], - consts.RequestType.PutRedirect: [ + consts.ConstRequestType.PutRedirect: [ ('Name', True), ('TargetURI', True), ], @@ -1668,8 +1658,8 @@ contentType=None, dontCompress=None, maxRetries=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, userData=None, persistentUserData='', @@ -1682,7 +1672,7 @@ @param contentType: (str) content type. If not specified, the node will guess the content type @param dontCompress: (bool) if True, the node won't try to compress the data @param maxRetries: (int) maximum number of retries or -1 to retry forver or None to leave it to the node to decide - @param priorityClass: (L{consts.Priority}) priority of the request + @param priorityClass: (L{consts.ConstPriority}) priority of the request @param userData: any non persistent data to associate to the request @param persistentUserData: any string to associate to the request as persistent data @@ -1693,7 +1683,7 @@ @event: (L{events.Events.RequestCompressionStarted}) triggered when the request is about to be compressed @event: (L{events.Events.RequestCompressionCompleted}) triggered as soon as compressing of the request is completed - @note: if the upload is successful the node will create a L{consts.KeyType.CHK} key under wich + @note: if the upload is successful the node will create a L{consts.ConstKeyType.CHK} key under wich the data can be retreieved. The key can be accessed as 'URI' member of the request as soon as the L{events.Events.RequestFetchable} or the L{events.Events.RequestCompleted} event is triggered. @@ -1701,7 +1691,7 @@ @todo: EarlyEncode and GetCHKOnly message params not implemented """ return self.clientPut( - consts.RequestType.PutData, + consts.ConstRequestType.PutData, uri, userData, persistentUserData, @@ -1718,8 +1708,8 @@ DontCompress=dontCompress, Persistence=persistence, PriorityClass=priorityClass, - UploadFrom=consts.UploadFrom.Direct, - Verbosity=consts.Verbosity.ReportProgress | consts.Verbosity.ReportCompression, + UploadFrom=consts.ConstUploadFrom.Direct, + Verbosity=consts.ConstVerbosity.ReportProgress | consts.ConstVerbosity.ReportCompression, ) @@ -1732,8 +1722,8 @@ dontCompress=None, maxRetries=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, targetFilename=None, userData=None, @@ -1756,7 +1746,7 @@ @todo: 2MiB compressed zize allowed? """ return self.clientPut( - consts.RequestType.PutDir, + consts.ConstRequestType.PutDir, uri, userData, persistentUserData, @@ -1773,8 +1763,8 @@ DontCompress=dontCompress, Persistence=persistence, PriorityClass=priorityClass, - UploadFrom=consts.UploadFrom.Disk, - Verbosity=consts.Verbosity.ReportProgress | consts.Verbosity.ReportCompression, + UploadFrom=consts.ConstUploadFrom.Disk, + Verbosity=consts.ConstVerbosity.ReportProgress | consts.ConstVerbosity.ReportCompression, ) @@ -1784,8 +1774,8 @@ contentType=None, dontCompress=None, maxRetries=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, userData=None, persistentUserData='', @@ -1800,7 +1790,7 @@ @todo: EarlyEncode and GetCHKOnly message params not implemented """ return self.clientPut( - consts.RequestType.PutFile, + consts.ConstRequestType.PutFile, uri, userData, persistentUserData, @@ -1816,8 +1806,8 @@ DontCompress=dontCompress, Persistence=persistence, PriorityClass=priorityClass, - UploadFrom=consts.UploadFrom.Disk, - Verbosity=consts.Verbosity.ReportProgress | consts.Verbosity.ReportCompression, + UploadFrom=consts.ConstUploadFrom.Disk, + Verbosity=consts.ConstVerbosity.ReportProgress | consts.ConstVerbosity.ReportCompression, ) def putMultiple(self, @@ -1827,8 +1817,8 @@ defaultName=None, dontCompress=None, maxRetries=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, targetFilename=None, userData=None, @@ -1843,10 +1833,10 @@ @note: for other params see L{putDir} @note: to upload multiple items at once pass a dict for each item containig the following members: - - RequestType: L{consts.RequestType.PutData}, L{consts.RequestType.PutFile} or L{consts.RequestType.PutRedirect} - - Data: if requestType is L{consts.RequestType.PutData}, data to upload - - Filename: if requestType is L{consts.RequestType.PutFile}, filepath of the file to upload - - TargetURI: if requestType is L{consts.RequestType.PutRedirect}, uri to redirect to + - RequestType: L{consts.ConstRequestType.PutData}, L{consts.ConstRequestType.PutFile} or L{consts.ConstRequestType.PutRedirect} + - Data: if requestType is L{consts.ConstRequestType.PutData}, data to upload + - Filename: if requestType is L{consts.ConstRequestType.PutFile}, filepath of the file to upload + - TargetURI: if requestType is L{consts.ConstRequestType.PutRedirect}, uri to redirect to - Name: name under wich the item will be accesible via freenet - Metadata.ContentType: (optional) may be passed as 'ContentType' @@ -1857,7 +1847,7 @@ @todo: EarlyEncode and GetCHKOnly message params not implemented """ return self.clientPut( - consts.RequestType.PutMultiple, + consts.ConstRequestType.PutMultiple, uri, userData, persistentUserData, @@ -1873,8 +1863,8 @@ DontCompress=dontCompress, Persistence=persistence, PriorityClass=priorityClass, - UploadFrom=consts.UploadFrom.Disk, - Verbosity=consts.Verbosity.ReportProgress | consts.Verbosity.ReportCompression, + UploadFrom=consts.ConstUploadFrom.Disk, + Verbosity=consts.ConstVerbosity.ReportProgress | consts.ConstVerbosity.ReportCompression, ) @@ -1883,8 +1873,8 @@ uri, targetKey, maxRetries=None, - persistence=consts.Persistence.Connection, - priorityClass=consts.Priority.Medium, + persistence=consts.ConstPersistence.Connection, + priorityClass=consts.ConstPriority.Medium, userData=None, persistentUserData='', ): @@ -1892,21 +1882,21 @@ @param uri: (L{key.KSK}) to insert as redirect @param targetKey: (key.KeyBase) key to redirect to @param maxRetries: (int) maximum number of tretries or -1 to leave the decission up to the node - @param persistence: (L{consts.Persistence}) of the request - @param priorityClass: (L{consts.Priority}) priority of the request + @param persistence: (L{consts.ConstPersistence}) of the request + @param priorityClass: (L{consts.ConstPriority}) priority of the request @param persistentUserData: (str) persistent data to be assosiated to the request @param userData: (any) any data to be associated to the request at runtime @return: (str) request identifier """ return self.clientPut( - consts.RequestType.PutRedirect, + consts.ConstRequestType.PutRedirect, uri, userData, persistentUserData, Persistence=persistence, PriorityClass=priorityClass, TargetURI=targetKey, - UploadFrom=consts.UploadFrom.Redirect, + UploadFrom=consts.ConstUploadFrom.Redirect, ) ######################################################## @@ -1917,7 +1907,7 @@ def getRequest(self, requestIdentifier): """Returns a (initial) message, given its identifier @param requestIdentifier: identifier of the message - @return: L{message.Message} + @return: L{message.MsgMessage} """ return self._requests[requestIdentifier] @@ -1933,25 +1923,25 @@ """Modifies a request @param requestIdentifier: identifier of the request to modify @param persistentUserData: (str) persistent user data or None - @param priorityClass: (L{consts.Priority}) new priority or None + @param priorityClass: (L{consts.ConstPriority}) new priority or None @note: you can use this method to modify get / put related requests All attempts to modify other requests will fail @note: a RequestModified event is triggered as soon as the request has actually been modified - @note: you can not change the priority of requests with Persistence=L{consts.Persistence.Connection}. + @note: you can not change the priority of requests with Persistence=L{consts.ConstPersistence.Connection}. All attempts to do so are ignored. Too bad, but doing so is not implemented in the client protocol. @todo: currently we ignore any attempts to change priority class for requests with persistence == connection Fcp does not provide means to do so. """ initialRequest = self._requests[requestIdentifier] - if not initialRequest['RequestType'] & (consts.RequestType.MaskGet | consts.RequestType.MaskPut): + if not initialRequest['RequestType'] & (consts.ConstRequestType.MaskGet | consts.ConstRequestType.MaskPut): raise ValueError('Can not modify request: %s' % initialRequest.name) #FIX: [0002083] # no way to change priority for non-persistent requests..this is simply not implemented in the protocol # persistentUserData is ok, priority can not be changed. no idea how to handle this. - if initialRequest['Persistence'] == consts.Persistence.Connection: + if initialRequest['Persistence'] == consts.ConstPersistence.Connection: modified = {} #if priorityClass is not None: # raise ValueError('Can not modify priority of requests with Persistence=connection') @@ -1959,14 +1949,14 @@ if persistentUserData is not None: initialRequest['PersistentUserData'] = persistentUserData initialRequest['ClientToken'] = initialRequest.updatePersistentParams() - modified[consts.RequestModified.PersistentUserData] = None + modified[consts.ConstRequestModified.PersistentUserData] = None initialRequest['Modified'] = modified self.events.RequestModified(initialRequest) return #/FIX: [0002083] - msg = message.ModifyPersistentRequest( + msg = message.MsgModifyPersistentRequest( Identifier=initialRequest['Identifier'], Global=False, ) @@ -1984,10 +1974,10 @@ @param requestIdentifier: (str) identifier of the request to remove """ initialRequest = self._requests[requestIdentifier] - initialRequest['RequestStatus'] |= consts.RequestStatus.Removed | consts.RequestStatus.Completed - if initialRequest['RequestType'] & (consts.RequestType.MaskGet | consts.RequestType.MaskPut): + initialRequest['RequestStatus'] |= consts.ConstRequestStatus.Removed | consts.ConstRequestStatus.Completed + if initialRequest['RequestType'] & (consts.ConstRequestType.MaskGet | consts.ConstRequestType.MaskPut): self.sendMessage( - message.RemoveRequest( + message.MsgRemoveRequest( Global=False, Identifier=requestIdentifier, ) @@ -2012,7 +2002,7 @@ @param giveOpennetRef: if True, the opennet reference is retuned instead of the darknet """ self.sendMessage( - message.GetNode( + message.MsgGetNode( WithPrivate=withPrivate, WithVolatile=withVolatile, GiveOpennetRef=giveOpennetRef, @@ -2025,7 +2015,7 @@ @param identity: identity of the peer to request information for """ self.sendMessage( - message.ListPeer( + message.MsgListPeer( NodeIdentifier=identity, ) ) @@ -2039,7 +2029,7 @@ @note: listPeerNotes() is only available for darknet nodes """ self.sendMessage( - message.ListPeerNotes( + message.MsgListPeerNotes( NodeIdentifier=identity ) ) @@ -2054,7 +2044,7 @@ @event: EndListPeers(event, params). """ self.sendMessage( - message.ListPeers( + message.MsgListPeers( WithMetadata=withMetaData, WithVolatile=withVolantile, ) @@ -2071,7 +2061,7 @@ @note: you can only modify darknet peers """ msg = MessageEx( - message.ModifyPeer( + message.MsgModifyPeer( NodeIdentifier=identity, ) ) @@ -2092,10 +2082,10 @@ @note: you can only modify notes of darknet peers """ self.sendMessage( - message.ModifyPeerNote( + message.MsgModifyPeerNote( NodeIdentifier=identity, #NOTE: currently fcp supports only this one type - PeerNoteType=consts.PeerNoteType.Private, + PeerNoteType=consts.ConstPeerNoteType.Private, NoteText=note ) ) @@ -2106,7 +2096,7 @@ @param identity: identity of the peer node to remove """ self.sendMessage( - message.RemovePeer( + message.MsgRemovePeer( NodeIdentifier=identity, ) ) @@ -2122,11 +2112,11 @@ @param detailed: ... [truncated message content] |
From: <jU...@us...> - 2008-07-01 11:26:27
|
Revision: 454 http://fclient.svn.sourceforge.net/fclient/?rev=454&view=rev Author: jUrner Date: 2008-07-01 04:26:28 -0700 (Tue, 01 Jul 2008) Log Message: ----------- for ease of use, all necessary symbols are now imported to main Modified Paths: -------------- trunk/fcp2/src/fcp2/__init__.py Modified: trunk/fcp2/src/fcp2/__init__.py =================================================================== --- trunk/fcp2/src/fcp2/__init__.py 2008-07-01 08:17:17 UTC (rev 453) +++ trunk/fcp2/src/fcp2/__init__.py 2008-07-01 11:26:28 UTC (rev 454) @@ -2,16 +2,36 @@ See: [http://www.freenetproject.org] and [http://wiki.freenetproject.org/FreenetFCPSpec2Point0] """ +import os, sys - __author__ = 'Juergen Urner' __copyright__ = '(c) 2008 - Juergen Urner' __email__ = 'jue...@ar...' __licence__ = 'Mit' __version__ = '0.1' + +#--> rel import hack +class _RelImportHack(object): + def __init__(self, n): + fpath = os.path.abspath(__file__) + for i in xrange(n): fpath = os.path.dirname(fpath) + sys.path.insert(0, fpath) + def __del__(self): sys.path.pop(0) +hack = _RelImportHack(2) + +from fcp2.client import * +from fcp2.config import * +from fcp2.consts import * +from fcp2.key import * +from fcp2.message import * +from fcp2.types import * + +del hack, _RelImportHack +#<-- rel import hack + #**************************************************************************************** # #**************************************************************************************** -def getFcpClient(): - pass +for i in sorted(dir()): print i +print '<<<<<<<<<<<<<<<<<<<' \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 08:17:08
|
Revision: 453 http://fclient.svn.sourceforge.net/fclient/?rev=453&view=rev Author: jUrner Date: 2008-07-01 01:17:17 -0700 (Tue, 01 Jul 2008) Log Message: ----------- some notes Modified Paths: -------------- trunk/fcp2/src/fcp2/client.py Modified: trunk/fcp2/src/fcp2/client.py =================================================================== --- trunk/fcp2/src/fcp2/client.py 2008-07-01 08:04:06 UTC (rev 452) +++ trunk/fcp2/src/fcp2/client.py 2008-07-01 08:17:17 UTC (rev 453) @@ -184,11 +184,14 @@ # TODO: check if this is a bug in Fcp # NOTE: seems to be fixed in [build 1112], fixes removed #------------------------------------------------------------------------------------------------------------------------------------------------- -# PersistentPutDiskDir vs PutComplexDir + + +# reminders to self +#------------------------------------------------------------------------------------------------------------------------------------------------ +# Key() # -# x. currently not handled on PersistentPutDir. have to test this -# Fcp provides a new field "PutDirType": "complex" or "disk" to distinguish PutComplexDir and PutDiskDir -# +# we do not allow passing strings as uris. putting a CHK gets in the way here. would have to add another +# special case to handle 'CHK@myfilename' on input. so for uniformity reasons keys are enforced. #------------------------------------------------------------------------------------------------------------------------------------------------ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 08:04:00
|
Revision: 452 http://fclient.svn.sourceforge.net/fclient/?rev=452&view=rev Author: jUrner Date: 2008-07-01 01:04:06 -0700 (Tue, 01 Jul 2008) Log Message: ----------- added hack to handle persistents from other clients (kill them with fire ;-) Modified Paths: -------------- trunk/fcp2/src/fcp2/test_fcp/test_client.py Modified: trunk/fcp2/src/fcp2/test_fcp/test_client.py =================================================================== --- trunk/fcp2/src/fcp2/test_fcp/test_client.py 2008-07-01 08:03:55 UTC (rev 451) +++ trunk/fcp2/src/fcp2/test_fcp/test_client.py 2008-07-01 08:04:06 UTC (rev 452) @@ -1090,6 +1090,7 @@ 'PersistentGet', Identifier=myIdentifier, ClientToken='i-am-invalid', + Global='false', callNext=False ) @@ -2485,9 +2486,12 @@ # the client should not trigger any events self.assertHasNextEvent(None) - self.assertHasNextMessage(None) + + #NOTE: the client will recognize it as unknown request and query to remove it + #self.assertHasNextMessage(None) + self.assertHasNextMessage(consts.Message.RemoveRequest) - + def test_restorePersistentGet_validIdentifier(self): self.connectClient() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 08:03:45
|
Revision: 451 http://fclient.svn.sourceforge.net/fclient/?rev=451&view=rev Author: jUrner Date: 2008-07-01 01:03:55 -0700 (Tue, 01 Jul 2008) Log Message: ----------- added hack to handle persistents from other clients (kill them with fire ;-) Modified Paths: -------------- trunk/fcp2/src/fcp2/client.py Modified: trunk/fcp2/src/fcp2/client.py =================================================================== --- trunk/fcp2/src/fcp2/client.py 2008-07-01 08:03:27 UTC (rev 450) +++ trunk/fcp2/src/fcp2/client.py 2008-07-01 08:03:55 UTC (rev 451) @@ -142,7 +142,7 @@ # # suggested dropping of global persistents. pretty dangerous and unhandy imo. # -# +#FIX: at least some are implemented in the client #-------------------------------------------------------------------------------------------------------------------------------------------------- @@ -878,7 +878,7 @@ if initialRequest is None: if CancelPersistentRequests: self.sendMessage( - message.RemovePersistentRequest( + message.RemoveRequest( Identifier=msg['Identifier'], Global=msg['Global'], ) @@ -1120,8 +1120,18 @@ @note: use this method to run the client step by step. If you want to run the client unconditionally use L{run} """ + + #FIX: [0002083] we may run into persistents of other clients by accident. the client can not handle them. + # so remove them, no matter what.... + def hackyInvalidMessageCallback(msg, requests=self._requests): + if msg == message.PersistentGet or msg == message.PersistentPut or msg == message.PersistentPutDir: + requestIdentifier = msg['Identifier'] + if requestIdentifier not in requests: + msgRemove = message.RemoveRequest(Identifier=msg['Identifier'], Global=msg['Global']) + self.sendMessage(msgRemove) + try: - msg = self.ioHandler.readMessage() + msg = self.ioHandler.readMessage(hackyInvalidMessageCallback=hackyInvalidMessageCallback) except consts.IOTimeoutError, details: msg = message.ClientSocketTimeout() if dispatch: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 08:03:18
|
Revision: 450 http://fclient.svn.sourceforge.net/fclient/?rev=450&view=rev Author: jUrner Date: 2008-07-01 01:03:27 -0700 (Tue, 01 Jul 2008) Log Message: ----------- added hack to handle persistents from other clients (kill them with fire ;-) Modified Paths: -------------- trunk/fcp2/src/fcp2/iohandler.py Modified: trunk/fcp2/src/fcp2/iohandler.py =================================================================== --- trunk/fcp2/src/fcp2/iohandler.py 2008-07-01 07:22:08 UTC (rev 449) +++ trunk/fcp2/src/fcp2/iohandler.py 2008-07-01 08:03:27 UTC (rev 450) @@ -258,8 +258,11 @@ raise consts.IOTimeoutError(details) - def readMessage(self): + def readMessage(self, hackyInvalidMessageCallback=None): """Reads the next message from io device + @param hackyInvalidMessageCallback: in case a message drops in we can't handle this callback + will be called emidiately before raising, giving the caller a chance to do something about it..... + @return: (Message) next message from the socket @raise IOBrokenError: (L{consts.IOBrokenError}) if the io breaks unexpectedly @@ -305,12 +308,18 @@ # process param --> value fields params = dict([line.split('=', 1) for line in p]) if not msg._restoreParams(params): + #HACK: + if hackyInvalidMessageCallback is not None: + hackyInvalidMessageCallback(msg) raise consts.MessageParseError('Invalid message parameters: ' + msg.pprint(), consts.Logger.IOHandler.error) # get associated data if necessary if mayHaveData: n = msg._getDataLength() if not isinstance(n, (int, long)): + #HACK: + if hackyInvalidMessageCallback is not None: + ackyInvalidMessageCallback(msg) raise consts.MessageParseError('DataLength must be type(int)') if n > 0: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 07:22:12
|
Revision: 449 http://fclient.svn.sourceforge.net/fclient/?rev=449&view=rev Author: jUrner Date: 2008-07-01 00:22:08 -0700 (Tue, 01 Jul 2008) Log Message: ----------- typos Modified Paths: -------------- trunk/fcp2/src/fcp2/client.py Modified: trunk/fcp2/src/fcp2/client.py =================================================================== --- trunk/fcp2/src/fcp2/client.py 2008-07-01 07:21:36 UTC (rev 448) +++ trunk/fcp2/src/fcp2/client.py 2008-07-01 07:22:08 UTC (rev 449) @@ -1482,7 +1482,7 @@ def subscribeUSK(self, uri, dontPoll=True): """Asks the node to notify the client when an USK is updated - @param key: (L{key.USK}) key to subscribe to + @param uri: (L{key.USK}) key to subscribe to @param dontPoll: if True, does whatever ??? @return: (str) identifer of the request @@ -1827,7 +1827,7 @@ @param uri: (L{key.KeyBase}) key under wich to upload the file @param items: (list) list of items to upload - @note: for other params see L{chkPutDir} + @note: for other params see L{putDir} @note: to upload multiple items at once pass a dict for each item containig the following members: - RequestType: L{consts.RequestType.PutData}, L{consts.RequestType.PutFile} or L{consts.RequestType.PutRedirect} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 07:21:33
|
Revision: 448 http://fclient.svn.sourceforge.net/fclient/?rev=448&view=rev Author: jUrner Date: 2008-07-01 00:21:36 -0700 (Tue, 01 Jul 2008) Log Message: ----------- worked over exceptions Modified Paths: -------------- trunk/fcp2/src/fcp2/iohandler.py Modified: trunk/fcp2/src/fcp2/iohandler.py =================================================================== --- trunk/fcp2/src/fcp2/iohandler.py 2008-07-01 07:20:49 UTC (rev 447) +++ trunk/fcp2/src/fcp2/iohandler.py 2008-07-01 07:21:36 UTC (rev 448) @@ -251,7 +251,8 @@ try: #TODO: if \r\n is possible in Fcp, replace it by \n p = self.io.read(n) - assert p, 'No bytes received and IO did not raise as expected?!?' + if not p: + raise RuntimeError('No bytes received and IO did not raise as expected?!?') self._receiveBuffer += p except consts.IOTimeoutError, details: # nothing in queue raise consts.IOTimeoutError(details) @@ -261,6 +262,10 @@ """Reads the next message from io device @return: (Message) next message from the socket + @raise IOBrokenError: (L{consts.IOBrokenError}) if the io breaks unexpectedly + @raise IOTimeoutError: (L{consts.IOTimeoutError}) if no message is in the io + @raise MessageParseError: (L{consts.IMessageParseError}) if the message is invalid + @note: if something goes wrong the according exception is raised """ # read message from io @@ -294,7 +299,7 @@ msgClass = message.MessagesAll.get(msgName, None) if msgClass is None: consts.Logger.IOHandler.debug(consts.LogMessages.CreatingNewMessageType + ' "%s"' % msgClassname) - msgClass = message.newMessageType(msgName) + msgClass = message.newMessageClass(msgName) msg = msgClass() # process param --> value fields @@ -306,7 +311,7 @@ if mayHaveData: n = msg._getDataLength() if not isinstance(n, (int, long)): - raise ValueError('DataLength must be type(int)') + raise consts.MessageParseError('DataLength must be type(int)') if n > 0: while self._receiveBuffer: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 07:20:40
|
Revision: 447 http://fclient.svn.sourceforge.net/fclient/?rev=447&view=rev Author: jUrner Date: 2008-07-01 00:20:49 -0700 (Tue, 01 Jul 2008) Log Message: ----------- newMessageType() is now newMessageClass() Modified Paths: -------------- trunk/fcp2/src/fcp2/test_fcp/test_client.py Modified: trunk/fcp2/src/fcp2/test_fcp/test_client.py =================================================================== --- trunk/fcp2/src/fcp2/test_fcp/test_client.py 2008-07-01 07:20:40 UTC (rev 446) +++ trunk/fcp2/src/fcp2/test_fcp/test_client.py 2008-07-01 07:20:49 UTC (rev 447) @@ -259,7 +259,7 @@ if messageName in message.MessagesAll: msgClass = message.MessagesAll[messageName] else: - msgClass = message.newMessageType(messageName) + msgClass = message.newMessageClass(messageName) msg = msgClass(data=data, **params) self.client.ioHandler.io.readBuffer += msg.toString() if callNext: @@ -1382,7 +1382,7 @@ self.getIO().setBroken(True) # send a test message - self.assertRaises(consts.IOBrokenError, self.client.sendMessage, message.newMessageType('test')()) + self.assertRaises(consts.IOBrokenError, self.client.sendMessage, message.newMessageClass('test')()) # check if ClientDisconnected events has been triggered msg = self.assertHasNextEvent( This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 07:20:31
|
Revision: 446 http://fclient.svn.sourceforge.net/fclient/?rev=446&view=rev Author: jUrner Date: 2008-07-01 00:20:40 -0700 (Tue, 01 Jul 2008) Log Message: ----------- newMessageType() is now newMessageClass() Modified Paths: -------------- trunk/fcp2/src/fcp2/message.py Modified: trunk/fcp2/src/fcp2/message.py =================================================================== --- trunk/fcp2/src/fcp2/message.py 2008-07-01 06:48:53 UTC (rev 445) +++ trunk/fcp2/src/fcp2/message.py 2008-07-01 07:20:40 UTC (rev 446) @@ -551,8 +551,8 @@ #******************************************************************************** # #******************************************************************************** -#TODO: do we need this? -def newMessageType(name, paramTypes=None, additionalParams=None, persistentParams=None): +def newMessageClass(name, paramTypes=None, additionalParams=None, persistentParams=None): + """creates a new message class""" kws = { 'name': name, '_additional_params_': {} if additionalParams is None else additionalParams, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-07-01 06:48:54
|
Revision: 445 http://fclient.svn.sourceforge.net/fclient/?rev=445&view=rev Author: jUrner Date: 2008-06-30 23:48:53 -0700 (Mon, 30 Jun 2008) Log Message: ----------- beautify Modified Paths: -------------- trunk/fcp2/src/fcp2/client.py Modified: trunk/fcp2/src/fcp2/client.py =================================================================== --- trunk/fcp2/src/fcp2/client.py 2008-06-30 12:15:39 UTC (rev 444) +++ trunk/fcp2/src/fcp2/client.py 2008-07-01 06:48:53 UTC (rev 445) @@ -886,13 +886,13 @@ return True requestType = msg['RequestType'] - if requestType & consts.RequestType.MaskGet: + if msg == message.PersistentGet: initialRequest = message.ClientGet() - elif requestType & (onsts.RequestType.PutDir | consts.RequestType.PutMultiple): - #NOTE: PutDiskDir is just a subtype of PutComplexDir + elif msg == message.PersistentPut: + initialRequest = message.ClientPut() + else: + #NOTE: PutDiskDir is just a subtype of PutComplexDir. check PutDirType param to tell appart initialRequest = message.ClientPutComplexDir() - else: - initialRequest = message.ClientPut() initialRequest.params.update(msg.params) self._requests[initialRequest['Identifier']] = initialRequest @@ -904,7 +904,7 @@ self.events.RequestRestored(initialRequest) return True - # known request ..don't handle it + # ignore return False This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-06-30 12:15:31
|
Revision: 444 http://fclient.svn.sourceforge.net/fclient/?rev=444&view=rev Author: jUrner Date: 2008-06-30 05:15:39 -0700 (Mon, 30 Jun 2008) Log Message: ----------- move fcp2 from sandbox to trunk Added Paths: ----------- trunk/fcp2/src/fcp2/ Removed Paths: ------------- trunk/sandbox/fcp2/ Copied: trunk/fcp2/src/fcp2 (from rev 443, trunk/sandbox/fcp2) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-06-30 12:14:30
|
Revision: 443 http://fclient.svn.sourceforge.net/fclient/?rev=443&view=rev Author: jUrner Date: 2008-06-30 05:14:37 -0700 (Mon, 30 Jun 2008) Log Message: ----------- ... Added Paths: ----------- trunk/fcp2/ trunk/fcp2/src/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-06-30 11:12:48
|
Revision: 442 http://fclient.svn.sourceforge.net/fclient/?rev=442&view=rev Author: jUrner Date: 2008-06-30 04:12:57 -0700 (Mon, 30 Jun 2008) Log Message: ----------- added boilerplate code for more tests Modified Paths: -------------- trunk/sandbox/fcp2/test_fcp/test_client.py Modified: trunk/sandbox/fcp2/test_fcp/test_client.py =================================================================== --- trunk/sandbox/fcp2/test_fcp/test_client.py 2008-06-30 11:01:49 UTC (rev 441) +++ trunk/sandbox/fcp2/test_fcp/test_client.py 2008-06-30 11:12:57 UTC (rev 442) @@ -2795,10 +2795,46 @@ #*********************************************************************************** # #*********************************************************************************** -#TODO: class TestNodeAndPeers(BaseTestConnectedClient): +#TODO: not tested +class Test_getNode(BaseTestClient): pass #*********************************************************************************** # #*********************************************************************************** +#TODO: not tested +class Test_listPeer(BaseTestClient): pass +#*********************************************************************************** +# +#*********************************************************************************** +#TODO: not tested +class Test_listPeers(BaseTestClient): pass +#*********************************************************************************** +# +#*********************************************************************************** +#TODO: not tested +class Test_listPeerNotes(BaseTestClient): pass +#*********************************************************************************** +# +#*********************************************************************************** +#TODO: not tested +class Test_modifyPeer(BaseTestClient): pass +#*********************************************************************************** +# +#*********************************************************************************** +#TODO: not tested +class Test_modifyPeer(BaseTestClient): pass +#*********************************************************************************** +# +#*********************************************************************************** +#TODO: not tested +class Test_modifyPeerNote(BaseTestClient): pass +#*********************************************************************************** +# +#*********************************************************************************** +#TODO: not tested +class Test_removePeer(BaseTestClient): pass +#*********************************************************************************** +# +#*********************************************************************************** class Test_getPluginInfo(BaseTestClient): def test_getPluginInfo_Success(self): @@ -3138,14 +3174,21 @@ Test_modifyRequest, Test_removeRequest, + Test_restoreRequests, - Test_restoreRequests, Test_DDA, TestCollisions, Test_getPluginInfo, Test_sendPluginMessage, Test_generateKeypair, Test_subscribeUSK, + + Test_getNode, + Test_listPeer, + Test_listPeers, + Test_listPeerNotes, + Test_modifyPeerNote, + Test_removePeer, ) suite = unittest.TestSuite() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-06-30 11:02:34
|
Revision: 441 http://fclient.svn.sourceforge.net/fclient/?rev=441&view=rev Author: jUrner Date: 2008-06-30 04:01:49 -0700 (Mon, 30 Jun 2008) Log Message: ----------- refactor plugin message tests Modified Paths: -------------- trunk/sandbox/fcp2/test_fcp/test_client.py Modified: trunk/sandbox/fcp2/test_fcp/test_client.py =================================================================== --- trunk/sandbox/fcp2/test_fcp/test_client.py 2008-06-30 09:38:21 UTC (rev 440) +++ trunk/sandbox/fcp2/test_fcp/test_client.py 2008-06-30 11:01:49 UTC (rev 441) @@ -2799,10 +2799,9 @@ #*********************************************************************************** # #*********************************************************************************** -class Test_plugins(BaseTestClient): +class Test_getPluginInfo(BaseTestClient): - - def testGet_8000_PluginInfo_Success(self): + def test_getPluginInfo_Success(self): self.connectClient() myIdentifier = self.client.getPluginInfo('hi there') myRequest = self.client.getRequest(myIdentifier) @@ -2839,10 +2838,9 @@ self.assertHasNextMessage(None) self.failIf(requestsAll) - - def test_8001_GetPluginInfo_Failure(self): + def test_getPluginInfo_Failure(self): self.connectClient() myIdentifier = self.client.getPluginInfo('hi there') myRequest = self.client.getRequest(myIdentifier) @@ -2879,9 +2877,13 @@ self.assertHasNextMessage(None) self.failIf(requestsAll) - - - def test_8002_SendPluginMessage_Success(self): + +#*********************************************************************************** +# +#*********************************************************************************** +class Test_sendPluginMessage(BaseTestClient): + + def test_sendPluginMessage_Success(self): self.connectClient() myIdentifier = '123456789' myRequest = self.client.sendPluginMessage('hi there', myIdentifier, {'foo': "bar"}) @@ -2916,7 +2918,7 @@ self.failIf(requestsAll) - def test_8003_GetSendPluginMessage_Failure(self): + def test_sendPluginMessage_Failure(self): self.connectClient() myIdentifier = '1234567889' myRequest = self.client.sendPluginMessage('hi there', myIdentifier, {'foo': "bar"}) @@ -2949,7 +2951,7 @@ self.failIf(requestsAll) - def test_8003_GetSendPluginMessage_Identifiercollision(self): + def test_sendPluginMessage_Identifiercollision(self): self.connectClient() myIdentifier = '1234567889' myRequest = self.client.sendPluginMessage('hi there', myIdentifier, {'foo': "bar"}) @@ -3140,7 +3142,8 @@ Test_restoreRequests, Test_DDA, TestCollisions, - Test_plugins, + Test_getPluginInfo, + Test_sendPluginMessage, Test_generateKeypair, Test_subscribeUSK, ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-06-30 09:38:37
|
Revision: 440 http://fclient.svn.sourceforge.net/fclient/?rev=440&view=rev Author: jUrner Date: 2008-06-30 02:38:21 -0700 (Mon, 30 Jun 2008) Log Message: ----------- beautifications Modified Paths: -------------- trunk/sandbox/fcp2/message.py Modified: trunk/sandbox/fcp2/message.py =================================================================== --- trunk/sandbox/fcp2/message.py 2008-06-30 09:36:21 UTC (rev 439) +++ trunk/sandbox/fcp2/message.py 2008-06-30 09:38:21 UTC (rev 440) @@ -24,6 +24,12 @@ del hack #<-- rel import hack #******************************************************************************** +# consts +#******************************************************************************** +MessagesAll = {} +PersistentParamsSep = '0x01' + +#******************************************************************************** # #******************************************************************************** class Node(node.Node): @@ -39,9 +45,6 @@ #******************************************************************************** # #******************************************************************************** -MessagesAll = {} -PersistentParamsSep = '0x01' - class MessageMeta(type): def __new__(klass, name, bases, kws): @@ -507,7 +510,7 @@ } #******************************************************************************** -# equipp Get / Put messages with some persistent params +# equip Get / Put messages with some persistent params # # these params are stored in ClientToken # This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-06-30 09:36:23
|
Revision: 439 http://fclient.svn.sourceforge.net/fclient/?rev=439&view=rev Author: jUrner Date: 2008-06-30 02:36:21 -0700 (Mon, 30 Jun 2008) Log Message: ----------- no longer needed Removed Paths: ------------- trunk/sandbox/fcp2/fcp_lib/pmstruct.py Deleted: trunk/sandbox/fcp2/fcp_lib/pmstruct.py =================================================================== --- trunk/sandbox/fcp2/fcp_lib/pmstruct.py 2008-06-30 09:35:54 UTC (rev 438) +++ trunk/sandbox/fcp2/fcp_lib/pmstruct.py 2008-06-30 09:36:21 UTC (rev 439) @@ -1,131 +0,0 @@ -"""Poor mans structure - - - -""" - -import base64 -#**************************************************************************** -# -#**************************************************************************** -Str = (base64.b64decode, base64.b64encode, (str, unicode)) -Int = (int, str, int) -Float = (float, float) - - - -class PoorMansStruct(object): - """Poor mans structure - - Converts a maping to a string and vice versa - - - Subclasses must define a _fields_ attribute wich is a mapping from field name - to conversion methods (fieldName, (getter, setter, fieldType)). getter() should convert - the fields value to the desired python type, setter should convert the python - type to string. Both will be called with one argument: the value to convert - and should rasise if the value can not be converted. fieldType is the data type - expected on mappping conversion. - - For convenience the module defines some standard types like Int, Float - and String. - - >>> class S(PoorMansStruct): - ... _fields_ = [ - ... ('Foo', (int, str, int)), - ... ('Bar', Str), - ... ] - - To convert a mapping to a string, call toString() with the mapping to convert - >>> p = S.toString({'Foo': 123456, 'Bar': 'abcdefg'}) - >>> p - '123456\\x01YWJjZGVmZw==' - - To convert a string to a mapping call fromString() with the string to convert - >>> d = S.fromString(p) - >>> sorted(d.items()) - [('Bar', 'abcdefg'), ('Foo', 123456)] - - - Field names must corrospond to mapping names - >>> p = S.toString({'IAmInvalid': 123456, 'Bar': 'abcdefg'}) - Traceback (most recent call last): - ... - KeyError: 'Foo' - - - All field names must be present in the mapping passed - >>> p = S.toString({'Bar': 'abcdefg'}) - Traceback (most recent call last): - ... - KeyError: 'Foo' - - types of the mapping have to corrospond to field types - >>> p = S.toString({'Foo': 'invalid-int', 'Bar': 'abcdefg'}) - Traceback (most recent call last): - ... - ValueError: Invalid type for field "Foo, expected: <type 'int'>" - - invalid field types are detected on converting the string back to a mapping - >>> p = 'invalid-int\\x01YWJjZGVmZw==' - >>> S.fromString(p) - Traceback (most recent call last): - ... - ValueError: Invalid field #0: (invalid literal for int() with base 10: 'invalid-int') - - too few fields in the input strig will be recognized - >>> p = 'YWJjZGVmZw==' - >>> S.fromString(p) - Traceback (most recent call last): - ... - ValueError: Too few fields in input string - - ...aswell as too many - >>> p = '999\x01123456\x01YWJjZGVmZw==' - >>> S.fromString(p) - Traceback (most recent call last): - ... - ValueError: Too many fields in input string - """ - - _sep_ = '\x01' - _fields_ = [] - - - @classmethod - def fromString(klass, string): - params = string.split(klass._sep_) - if len(params) > len(klass._fields_): - raise ValueError('Too many fields in input string') - if len(params) < len(klass._fields_): - raise ValueError('Too few fields in input string') - out = {} - for n, (fieldName, (getter, setter, fieldType)) in enumerate(klass._fields_): - try: - out[fieldName] = getter(params[n]) - except Exception, details: - raise ValueError('Invalid field #%s: (%s)' % (n, details)) - return out - - @classmethod - def toString(klass, mapping): - out = [] - for n, (fieldName, (getter, setter, fieldType)) in enumerate(klass._fields_): - value = mapping[fieldName] - if not isinstance(value, fieldType): - raise ValueError('Invalid type for field "%s, expected: %s"' % (fieldName, fieldType)) - try: - value = setter(value) - assert isinstance(value, str) - out.append(value) - except Exception, details: - raise ValueError('Invalid field "%s": (%s)' % (fieldName, details)) - return klass._sep_.join(out) - -#**************************************************************************** -# -#**************************************************************************** -if __name__ == '__main__': - import doctest - print 'doctests failed: %s/%s' % doctest.testmod() - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jU...@us...> - 2008-06-30 09:35:46
|
Revision: 438 http://fclient.svn.sourceforge.net/fclient/?rev=438&view=rev Author: jUrner Date: 2008-06-30 02:35:54 -0700 (Mon, 30 Jun 2008) Log Message: ----------- removed some left over code Modified Paths: -------------- trunk/sandbox/fcp2/message.py Modified: trunk/sandbox/fcp2/message.py =================================================================== --- trunk/sandbox/fcp2/message.py 2008-06-30 09:17:24 UTC (rev 437) +++ trunk/sandbox/fcp2/message.py 2008-06-30 09:35:54 UTC (rev 438) @@ -17,7 +17,6 @@ from fcp2 import consts from fcp2 import types from fcp2 import key -from fcp2.fcp_lib import pmstruct from fcp2.fcp_lib import node from fcp2.fcp_lib import uuid @@ -417,21 +416,6 @@ ConfigMessageParamTypes = _ConfigMessageParamTypes() #******************************************************************************** -# equipp Get / Put messages with some persistent params -# -# these params are stored in ClientToken -# -#******************************************************************************** -class PeristentParamsGet(pmstruct.PoorMansStruct): - _fields_ = ( - ('Flags', pmstruct.Int), - ('InitTime', pmstruct.Float), - ('PersistentUserData', pmstruct.Str), - ) - -PeristentParamsPut = PeristentParamsGet - -#******************************************************************************** # at runtime we store a few additional params in msg.params # # for uniformity reasons we store them in msg.params and mark them @@ -522,7 +506,12 @@ PrivateParam('InitTime'): 0, # when was the request started? } - +#******************************************************************************** +# equipp Get / Put messages with some persistent params +# +# these params are stored in ClientToken +# +#******************************************************************************** PersistentParamsGet = ( ( lambda msg: str(msg.__getitem__('RequestType')), This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |