SF.net SVN: fclient: [9] trunk/fclient/fclient_lib/fcp/fcp2_0.py
Status: Pre-Alpha
Brought to you by:
jurner
|
From: <jU...@us...> - 2007-10-20 13:37:47
|
Revision: 9
http://fclient.svn.sourceforge.net/fclient/?rev=9&view=rev
Author: jUrner
Date: 2007-10-20 06:37:51 -0700 (Sat, 20 Oct 2007)
Log Message:
-----------
bit of refactoring
Modified Paths:
--------------
trunk/fclient/fclient_lib/fcp/fcp2_0.py
Modified: trunk/fclient/fclient_lib/fcp/fcp2_0.py
===================================================================
--- trunk/fclient/fclient_lib/fcp/fcp2_0.py 2007-10-20 10:02:28 UTC (rev 8)
+++ trunk/fclient/fclient_lib/fcp/fcp2_0.py 2007-10-20 13:37:51 UTC (rev 9)
@@ -22,79 +22,14 @@
except: pass
SocketTimeout = 0.1
-class JobIdentifiers:
+class FixedJobIdentifiers:
"""Fixed job identifiers
@note: he client can only handle one job of these at a time
"""
ClientHello = 'ClientHello'
ListPeers = 'ListPeers'
-class Messages:
- """All messages supported by the client"""
-
- # client messages
- ClientHello = 'ClientHello'
- ListPeer = 'ListPeer' # (since 1045)
- ListPeers = 'ListPeers'
- ListPeerNotes = 'ListPeerNotes'
- AddPeer = 'AddPeer'
- ModifyPeer = 'ModifyPeer'
- ModifyPeerNote = 'ModifyPeerNote'
- RemovePeer = 'RemovePeer'
- GetNode = 'GetNode'
- GetConfig = 'GetConfig' # (since 1027)
- ModifyConfig = 'ModifyConfig' # (since 1027)
- TestDDARequest = 'TestDDARequest' # (since 1027)
- TestDDAResponse = 'TestDDAResponse' # (since 1027)
- GenerateSSK = 'GenerateSSK'
- ClientPut = 'ClientPut'
- ClientPutDiskDir = 'ClientPutDiskDir'
- ClientPutComplexDir = 'ClientPutComplexDir'
- ClientGet = 'ClientGet'
- SubscribeUSK = 'SubscribeUSK'
- WatchGlobal = 'WatchGlobal'
- GetRequestStatus = 'GetRequestStatus'
- ListPersistentRequests = 'ListPersistentRequests'
- RemovePersistentRequest = 'RemovePersistentRequest'
- ModifyPersistentRequest = 'ModifyPersistentRequest'
- Shutdown = 'Shutdown'
-
- # node messages
- NodeHello = 'NodeHello'
- CloseConnectionDuplicateClientName = 'CloseConnectionDuplicateClientName'
- Peer = 'Peer'
- PeerNote = 'PeerNote'
- EndListPeers = 'EndListPeers'
- EndListPeerNotes = 'EndListPeerNotes'
- PeerRemoved = 'PeerRemoved'
- NodeData = 'NodeData'
- ConfigData = 'ConfigData' # (since 1027)
- TestDDAReply = 'TestDDAReply' # (since 1027)
- TestDDAComplete = 'TestDDAComplete' # (since 1027)
- SSKKeypair = 'SSKKeypair'
- PersistentGet = 'PersistentGet'
- PersistentPut = 'PersistentPut'
- PersistentPutDir = 'PersistentPutDir'
- URIGenerated = 'URIGenerated'
- PutSuccessful = 'PutSuccessful'
- PutFetchable = 'PutFetchable'
- DataFound = 'DataFound'
- AllData = 'AllData'
- StartedCompression = 'StartedCompression'
- FinishedCompression = 'FinishedCompression'
- SimpleProgress = 'SimpleProgress'
- EndListPersistentRequests = 'EndListPersistentRequests'
- PersistentRequestRemoved = 'PersistentRequestRemoved' # (since 1016)
- PersistentRequestModified = 'PersistentRequestModified' # (since 1016)
- PutFailed = 'PutFailed'
- GetFailed = 'GetFailed'
- ProtocolError = 'ProtocolError'
- IdentifierCollision = 'IdentifierCollision'
- UnknownNodeIdentifier = 'UnknownNodeIdentifier'
- UnknownPeerNoteType = 'UnknownPeerNoteType'
- SubscribedUSKUpdate = 'SubscribedUSKUpdate'
-
class Priorities:
"""All priorities supported by the client"""
@@ -109,12 +44,23 @@
PriorityMin = Minimum
PriorityDefault = Bulk
-
-# errors
-
-class FetchErrors:
+#************************************************************************************
+# exceptions
+#************************************************************************************
+class FetchError(Exception):
"""All fetch errors supported by the client"""
+ def __init__(self, msg):
+ """
+ @param msg: (Message) GetFailed message
+ """
+ self.value = '%s (%s, %s)' % (
+ msg.get('CodeDescription', 'Unknown error') ,
+ msg['Code'],
+ msg.get('ExtraDescription', '...'),
+ )
+ def __str__(self): return self.value
+
MaxArchiveRecursionExceeded = '1'
UnknownSplitfileMetadata = '2'
UnknownMetadata = '3'
@@ -145,9 +91,20 @@
NotAllDataFound = '28'
-class InsertErrors:
+class InsertError(Exception):
"""All insert errors supported by the client"""
+ def __init__(self, msg):
+ """
+ @param msg: (Message) PutFailed message
+ """
+ self.value = '%s (%s, %s)' % (
+ msg.get('CodeDescription', 'Unknown error') ,
+ msg['Code'],
+ msg.get('ExtraDescription', '...'),
+ )
+ def __str__(self): return self.value
+
InvalidUri = '1'
BucketError = '2'
InternalError = '3'
@@ -160,9 +117,20 @@
Canceled = '10'
-class ProtocolErrors:
+class ProtocolError(Exception):
"""All protocol errors supported by the client"""
+ def __init__(self, msg):
+ """
+ @param msg: (Message) ProtocolError message
+ """
+ self.value = '%s (%s, %s)' % (
+ msg.get('CodeDescription', 'Unknown error') ,
+ msg['Code'],
+ msg.get('ExtraDescription', '...'),
+ )
+ def __str__(self): return self.value
+
ClientHelloMustBeFirst = '1'
NoLateClientHellos = '2'
MessageParseError = '3'
@@ -195,15 +163,35 @@
OpennetDisabled = '30'
DarknetOnly = '31'
+class SocketError(Exception): pass
#**********************************************************************
# functions
#**********************************************************************
+def fcpBool(pythonBool):
+ """Converts a python bool to a fcp bool
+ @param pythonBool: (bool)
+ @return: (str) 'true' or 'false'
+ """
+ if pythonBool:
+ return 'true'
+ return 'false'
+
+
def newIdentifier():
"""Returns a new unique identifier
@return: (str) uuid
"""
return str(uuid.uuid4())
+
+def pythonBool(fcpBool):
+ """Converts a fcp bool to a python bool
+ @param pythonBool: 'true' or 'false'
+ @return: (bool) True or False
+ """
+ return fcpBool == 'true'
+
+
def saveReadFile(fpath):
"""Reads contents of a file in the savest manner possible
@param fpath: file to write
@@ -267,42 +255,9 @@
stdout, stderr = p.communicate()
return stdout
-
-def fcpBool(pythonBool):
- """Converts a python bool to a fcp bool
- @param pythonBool: (bool)
- @return: (str) 'true' or 'false'
- """
- if pythonBool:
- return 'true'
- return 'false'
-
-def pythonBool(fcpBool):
- """Converts a fcp bool to a python bool
- @param pythonBool: 'true' or 'false'
- @return: (bool) True or False
- """
- return fcpBool == 'true'
-
#**********************************************************************
# classes
#**********************************************************************
-class FcpSocketError(Exception): pass
-class FcpProtocolError(Exception):
- def __init__(self, msg):
- """
- @param msg: (Message) ProtocolError message
- """
- self.value = '%s (%s, %s)' % (
- msg.get('CodeDescription', 'Unknown error') ,
- msg['Code'],
- msg.get('ExtraDescription', '...'),
- )
-
- def __str__(self): return self.value
-
-
-
class FcpUri(object):
"""Wrapper class for freenet uris"""
@@ -397,8 +352,68 @@
class Message(object):
"""Class wrapping a freenet message"""
- Name = 'UMessage'
+ # client messages
+ ClientHello = 'ClientHello'
+ ListPeer = 'ListPeer' # (since 1045)
+ ListPeers = 'ListPeers'
+ ListPeerNotes = 'ListPeerNotes'
+ AddPeer = 'AddPeer'
+ ModifyPeer = 'ModifyPeer'
+ ModifyPeerNote = 'ModifyPeerNote'
+ RemovePeer = 'RemovePeer'
+ GetNode = 'GetNode'
+ GetConfig = 'GetConfig' # (since 1027)
+ ModifyConfig = 'ModifyConfig' # (since 1027)
+ TestDDARequest = 'TestDDARequest' # (since 1027)
+ TestDDAResponse = 'TestDDAResponse' # (since 1027)
+ GenerateSSK = 'GenerateSSK'
+ ClientPut = 'ClientPut'
+ ClientPutDiskDir = 'ClientPutDiskDir'
+ ClientPutComplexDir = 'ClientPutComplexDir'
+ ClientGet = 'ClientGet'
+ SubscribeUSK = 'SubscribeUSK'
+ WatchGlobal = 'WatchGlobal'
+ GetRequestStatus = 'GetRequestStatus'
+ ListPersistentRequests = 'ListPersistentRequests'
+ RemovePersistentRequest = 'RemovePersistentRequest'
+ ModifyPersistentRequest = 'ModifyPersistentRequest'
+ Shutdown = 'Shutdown'
+ # node messages
+ NodeHello = 'NodeHello'
+ CloseConnectionDuplicateClientName = 'CloseConnectionDuplicateClientName'
+ Peer = 'Peer'
+ PeerNote = 'PeerNote'
+ EndListPeers = 'EndListPeers'
+ EndListPeerNotes = 'EndListPeerNotes'
+ PeerRemoved = 'PeerRemoved'
+ NodeData = 'NodeData'
+ ConfigData = 'ConfigData' # (since 1027)
+ TestDDAReply = 'TestDDAReply' # (since 1027)
+ TestDDAComplete = 'TestDDAComplete' # (since 1027)
+ SSKKeypair = 'SSKKeypair'
+ PersistentGet = 'PersistentGet'
+ PersistentPut = 'PersistentPut'
+ PersistentPutDir = 'PersistentPutDir'
+ URIGenerated = 'URIGenerated'
+ PutSuccessful = 'PutSuccessful'
+ PutFetchable = 'PutFetchable'
+ DataFound = 'DataFound'
+ AllData = 'AllData'
+ StartedCompression = 'StartedCompression'
+ FinishedCompression = 'FinishedCompression'
+ SimpleProgress = 'SimpleProgress'
+ EndListPersistentRequests = 'EndListPersistentRequests'
+ PersistentRequestRemoved = 'PersistentRequestRemoved' # (since 1016)
+ PersistentRequestModified = 'PersistentRequestModified' # (since 1016)
+ PutFailed = 'PutFailed'
+ GetFailed = 'GetFailed'
+ ProtocolError = 'ProtocolError'
+ IdentifierCollision = 'IdentifierCollision'
+ UnknownNodeIdentifier = 'UnknownNodeIdentifier'
+ UnknownPeerNoteType = 'UnknownPeerNoteType'
+ SubscribedUSKUpdate = 'SubscribedUSKUpdate'
+
def __init__(self, name, data=None, **params):
"""
@@ -410,29 +425,25 @@
self.data = data
self.name = name
self.params = params
-
-
+
def toString(self):
"""Returns a string with the formated message, ready to be send"""
-
# TODO: "Data" not yet implemented
out = [self.name, ]
for param, value in self.params.items():
out.append('%s=%s' % (param, value))
out.append('EndMessage\n')
return '\n'.join(out)
-
-
+
def pprint(self):
"""Returns the message as nicely formated human readable string"""
-
- out = [self.name, ]
+ out = ['', '>>' + self.name, ]
for param, value in self.params.items():
- out.append(' %s=%s' % (param, value))
- out.append('EndMessage')
+ out.append('>> %s=%s' % (param, value))
+ out.append('>>EndMessage')
out.append('')
return '\n'.join(out)
-
+
def __getitem__(self, name):
"""Returns the message parameter 'name' """
return self.params[name]
@@ -444,14 +455,13 @@
def __setitem__(self, name, value):
"""Sets the message parameter 'name' to 'value' """
self.params[name] = value
-
+
+
class MessageSocketTimeout(Message):
- Name = 'USocketTimeout'
-
def __init__(self):
- Message.__init__(self, self.Name)
+ Message.__init__(self, 'USocketTimeOut')
@@ -474,47 +484,29 @@
@ivar fcpIdentifier: identifier of the job
@ivar fcpMessage: initial message send to the node
@ivar fcpResult: if no error was encountered, holding the result of the job when complete
- @ivar fcpTime: when the job is complete, holding the time the job took to complete
+ @ivar fcpTimeStart: time the job was started
+ @ivar fcpTimeStop: time the job was stopped
"""
-
self.fcpClient = fcpClient # FcpClient() instance the job belongs to
- self.fcpError = None # last error (either this is set or dcpResult)
- self.fcpIdentifier = identifier #
+ self.fcpIdentifier = identifier # job identifier
self.fcpMessage = message # message send to node
- self.fcpResult = None # job result
+ self.fcpResult = None # job result (bool error, Message msg)
self.fcpTimeStart = 0 # time the job was started
self.fcpTimeStop = 0 # time the job was stopped
- self.fcpStopped = False
-
- def displayName(self):
- """Returns the display name of the job
- @return: (str) display name
- """
- return 'JobBase'
-
- def start(self):
+
+ def handleStart(self):
"""Starts the job"""
- self.fcpStopped = False
+ self.fcpResult = None
self.fcpTimeStart = time.time()
self.fcpClient.sendMessageEx(self.fcpMessage)
-
- def error(self, msg):
- """Called on job completion if an error was encounterd while runnng the job
- @param msg: (Message) to pass to the job
- """
- self.fcpStopped = True
- self.fcpTimeStop = time.time()
- self.fcpError = msg
- self.fcpResult = None
-
- def stop(self, msg):
+
+ def handleStop(self, flagError, msg):
"""Called on job completion to stop the job
+ @param flagError: True if an error was encountered, False otherwise
@param msg: (Message) to pass to the job
"""
- self.fcpStopped = True
self.fcpTimeStop = time.time()
- self.fcpError = None
- self.fcpResult = msg
+ self.fcpResult = (flagError, msg)
class JobClientHello(JobBase):
@@ -532,11 +524,11 @@
@param expectedVersion: (str) node version expected
"""
message = Message(
- Messages.ClientHello,
+ Message.ClientHello,
Name=name if name is not None else newIdentifier(),
ExpectedVersion=expectedVersion,
)
- JobBase.__init__(self, fcpClient, JobIdentifiers.ClientHello, message)
+ JobBase.__init__(self, fcpClient, FixedJobIdentifiers.ClientHello, message)
def displayName(self):
return 'ClientHello'
@@ -550,16 +542,13 @@
def __init__(self, fcpClient, withMetaData=False, withVolantile=False):
message = Message(
- Messages.ListPeers,
+ Message.ListPeers,
WithMetadata=fcpBool(withMetaData),
WithVolatile=fcpBool(withVolantile),
)
- JobBase.__init__(self, fcpClient, JobIdentifiers.ListPeers, message)
+ JobBase.__init__(self, fcpClient, FixedJobIdentifiers.ListPeers, message)
- def displayName(self):
- return 'ListPeers'
-
def handlePeer(self,msg):
"""Handles the next peer send by the node in form of a 'Peer' message
while the job is running. Overwrite to process.
@@ -592,7 +581,7 @@
"""
identifier = newIdentifier()
message = Message(
- Messages.ClientGet,
+ Message.ClientGet,
Identifier=identifier,
URI=uri,
MaxSize='0',
@@ -602,37 +591,25 @@
)
JobBase.__init__(self, fcpClient, identifier, message)
-
- def displayName(self):
- return 'GetFileInfo'
-
+
def handleProgress(self, msg):
"""Handles the next progress made. Overwrite to process.
"""
-
-
- def error(self, msg):
- JobBase.error(self, msg)
- if msg.name == Messages.GetFailed:
- if msg['Code'] == FetchErrors.TooBig:
- self.fcpError = None
- self.fcpResult = (
- msg.get('ExpectedMetadata.ContentType', ''),
- msg.get('ExpectedDataLength', '')
- )
- #else:
- # raise ValueError('Unhandled message: %s' % msg.name)
-
- def stop(self, msg):
- JobBase.stop(self, msg)
- if msg.name == Messages.DataFound:
+ def handleStop(self, flagError, msg):
+ JobBase.handleStop(self,flagError, msg)
+ if msg.name == Message.DataFound:
self.fcpResult = (
msg.get('Metadata.ContentType', ''),
msg.get('DataLength', '')
)
- else:
- raise ValueError('Unhandled message: %s' % msg.name)
+ elif msg.name == Message.GetFailed:
+ if msg['Code'] == FetchError.TooBig:
+ self.fcpResult = (False, msg)
+ self.fcpResult = (
+ msg.get('ExpectedMetadata.ContentType', ''),
+ msg.get('ExpectedDataLength', '')
+ )
@@ -648,7 +625,7 @@
raise ValueError('No such directory: %r' % directory)
message = Message(
- Messages.TestDDARequest,
+ Message.TestDDARequest,
Directory=directory,
WantReadDirectory=fcpBool(read),
WantWriteDirectory=fcpBool(write),
@@ -656,9 +633,7 @@
JobBase.__init__(self, fcpClient, directory, message)
self.fcpTmpFile = None
- def displayName(self):
- return 'TestDDA'
-
+
def handleTestDDAReply(self, msg):
fpathWrite = msg.params.get('WriteFilename', None)
fpathRead = msg.params.get('ReadFilename', None)
@@ -677,22 +652,16 @@
readContent = ''
self.fcpClient.sendMessage(
- Messages.TestDDAResponse,
+ Message.TestDDAResponse,
Directory=msg['Directory'],
ReadContent=readContent,
)
- def error(self, msg):
- JobBase.error(self, msg)
+ def handleStop(self, flagError, msg):
+ JobBase.handleStop(self, flagError, msg)
saveRemoveFile(self.fcpTmpFile)
self.fcpTmpFile = None
-
-
- def stop(self, msg):
- JobBase.stop(self, msg)
- saveRemoveFile(self.fcpTmpFile)
- self.fcpTmpFile = None
#**************************************************************************
# fcp client
@@ -706,8 +675,8 @@
ClientClose = 'Closing client'
- MessageSend = 'Message send'
- MessageReceived = 'Message received'
+ MessageSend = 'SendMessage'
+ MessageReceived = 'ReceivedMessage'
JobStart = 'Starting job: '
JobStop = 'Stopping job: '
@@ -733,7 +702,7 @@
"""
@param name: name of the client instance or '' (for debugging)
@param errorHandler: will be called if the socket conncetion to the node is dead
- with two params: FcpSocketError + details. When the handler is called the client
+ with two params: SocketError + details. When the handler is called the client
is already closed.
@param verbosity: verbosity level for debugging
@param logMessages: LogMessages class containing messages
@@ -747,7 +716,7 @@
'complete': [], # ???
}
self._errorHandler = errorHandler
- self._log = logging.getLogger(NameClient + ':' + name)
+ self._log = logging.getLogger(name)
self._logMessages = logMessages
self._lock = thread.allocate_lock()
self._socket = None
@@ -792,10 +761,15 @@
pass
else:
self._log.info(self._logMessages.Connected)
+
+ #NOTE: thought I could leave ClientHelloing up to the caller
+ # but instad of responding with ClientHelloMustBeFirst
+ # as expected the socket simply breaks. So take it over.
job = JobClientHello(self)
self.jobAdd(job, synchron=True)
- assert job.fcpError is None, 'Error should have been caught by handleMessage()'
- return job.fcpResult
+ error, msg = job.fcpResult
+ assert not error, 'Error should have been caught by handleMessage()'
+ return msg
self._log.info(self._logMessages.ConnectionRetry)
@@ -811,45 +785,45 @@
"""Handles the next message from the freenet node
@param msg: Message() to handle
"""
- self._log.debug(self._logMessages.MessageReceived + '\n' + msg.pprint())
+ self._log.debug(self._logMessages.MessageReceived + msg.pprint())
- if msg.name == Messages.NodeHello:
+ if msg.name == Message.NodeHello:
#connectionIdentifier = msg['ConnectionIdentifier']
- self.jobStop(JobIdentifiers.ClientHello, msg)
+ self.jobStop(FixedJobIdentifiers.ClientHello, msg)
- elif msg.name == Messages.ProtocolError:
+ elif msg.name == Message.ProtocolError:
code = msg['Code']
- #if code == ProtocolErrors.NoLateClientHellos:
- # self.jobStop(JobIdentifiers.ClientHello, msg, error=True)
- #elif code == ProtocolErrors.ClientHelloMustBeFirst:
- # self.jobStop(JobIdentifiers.ClientHello, msg, error=True)
+ #if code == ProtocolError.NoLateClientHellos:
+ # self.jobStop(FixedJobIdentifiers.ClientHello, msg, error=True)
+ #elif code == ProtocolError.ClientHelloMustBeFirst:
+ # self.jobStop(FixedJobIdentifiers.ClientHello, msg, error=True)
#else:
identifier = msg.get('Identifier', None)
if identifier is None:
#TODO: inform caller
- raise FcpProtocolError(msg)
+ raise ProtocolError(msg)
else:
- self.jobStop(identifier, msg, error=True)
+ self.jobStop(identifier, msg, flagError=True)
- elif msg.name == Messages.Peer:
- self.jobNotify(JobIdentifiers.ListPeers, 'handlePeer', msg)
+ elif msg.name == Message.Peer:
+ self.jobNotify(FixedJobIdentifiers.ListPeers, 'handlePeer', msg)
- elif msg.name == Messages.EndListPeers:
- self.jobStop(IdentifierListPeers, msg)
+ elif msg.name == Message.EndListPeers:
+ self.jobStop(FixedJobIdentifiers.ListPeers, msg)
- elif msg.name == Messages.GetFailed:
- self.jobStop(msg['Identifier'], msg, error=True)
+ elif msg.name == Message.GetFailed:
+ self.jobStop(msg['Identifier'], msg, flagError=True)
- elif msg.name == Messages.SimpleProgress:
+ elif msg.name == Message.SimpleProgress:
self.jobNotify(msg['Identifier'], 'handleProgress', msg)
- elif msg.name == Messages.TestDDAReply:
+ elif msg.name == Message.TestDDAReply:
self.jobNotify(msg['Directory'], 'handleTestDDAReply', msg)
- elif msg.name == Messages.TestDDAComplete:
+ elif msg.name == Message.TestDDAComplete:
self.jobStop(msg['Directory'], msg)
- elif msg.name == Messages.IdentifierCollision:
+ elif msg.name == Message.IdentifierCollision:
pass
@@ -867,10 +841,10 @@
finally:
self._lock.release()
- self._log.info(self._logMessages.JobStart + job.displayName())
- job.start()
+ self._log.info(self._logMessages.JobStart + job.fcpMessage.name)
+ job.handleStart()
if synchron:
- while not job.fcpStopped:
+ while job.fcpResult is None:
self.next()
@@ -892,11 +866,11 @@
#TODO: quite unclear when to remove a job
- def jobStop(self, identifier, msg, error=False):
+ def jobStop(self, identifier, msg, flagError=False):
"""Stops a job
@param identifier: identifier of the job to stop
@param msg: Message() to pass to the job as result
- @param error: set to True to indicate unsuccessful completion of the job, True otherwisse
+ @param flagError: set to True to indicate unsuccessful completion of the job, True otherwisse
"""
self._lock.acquire(True)
try:
@@ -912,11 +886,8 @@
if job is None:
raise ValueError('No such job: %r' % identifier)
- self._log.info(self._logMessages.JobStop + job.displayName())
- if error:
- job.error(msg)
- else:
- job.stop(msg)
+ self._log.info(self._logMessages.JobStop + job.fcpMessage.name)
+ job.handleStop(flagError, msg)
#TODO: some info when all jobs are completed
@@ -931,7 +902,7 @@
def readMessage(self):
"""Reads the next message directly from the socket and dispatches it
@return: (Message) the next message read from the socket
- @raise FcpSocketError: if the socket connection to the node dies unexpectedly
+ @raise SocketError: if the socket connection to the node dies unexpectedly
If an error handler is passed to the client it is called emidiately before the error
is raised.
"""
@@ -949,8 +920,8 @@
self._log.info(self._logMessages.SocketDead)
self.close()
if self._errorHandler is not None:
- self._errorHandler(FcpSocketError, d)
- raise FcpSocketError(d) #!!
+ self._errorHandler(SocketError, d)
+ raise SocketError(d) #!!
if p == '\r': # ignore
continue
@@ -975,8 +946,8 @@
self._log.info(self._logMessages.SocketDead)
self.close()
if self._errorHandler is not None:
- self._errorHandler(FcpSocketError, d)
- raise FcpSocketError(d) #!!
+ self._errorHandler(SocketError, d)
+ raise SocketError(d) #!!
else:
head, sep, tail = line.partition('=')
@@ -1019,7 +990,7 @@
@param data: data to atatch to the message
@param params: {para-name: param-calue, ...} of parameters to pass along
with the message (see freenet protocol)
- @raise FcpSocketError: if the socket connection to the node dies unexpectedly
+ @raise SocketError: if the socket connection to the node dies unexpectedly
If an error handler is passed to the client it is called emidiately before the error
is raised.
"""
@@ -1030,20 +1001,19 @@
"""Sends a message to freenet
@param msg: (Message) message to send
@return: Message
- @raise FcpSocketError: if the socket connection to the node dies unexpectedly.
+ @raise SocketError: if the socket connection to the node dies unexpectedly.
If an error handler is passed to the client it is called emidiately before the error
is raised.
"""
- rawMsg = msg.toString()
- self._log.debug(self._logMessages.MessageSend + '\n' + msg.pprint())
+ self._log.debug(self._logMessages.MessageSend + msg.pprint())
try:
- self._socket.sendall(rawMsg)
- except Exception, d:
+ self._socket.sendall(msg.toString())
+ except socket.error, d:
self._log.info(self._logMessages.SocketDead)
self.close()
if self._errorHandler is not None:
- self._errorHandler(FcpSocketError, d)
- raise FcpSocketError(d)
+ self._errorHandler(SocketError, d)
+ raise SocketError(d)
return msg
@@ -1061,7 +1031,8 @@
#*****************************************************************************
if __name__ == '__main__':
c = FcpClient(name='test', verbosity=logging.DEBUG)
- if c.connect():
+ nodeHello = c.connect()
+ if nodeHello is not None:
def foo():
job1 = JobClientHello(c)
c.jobAdd(job1)
@@ -1070,8 +1041,8 @@
print '---------------------------'
print job1.fcpError
print job1.fcpResult
- print job1.fcpTime
print '---------------------------'
+ # should raise
#foo()
@@ -1081,18 +1052,25 @@
c.jobAdd(job2)
c.run()
print '---------------------------'
- print job2.fcpError
print job2.fcpResult
- print job2.fcpTime
print '---------------------------'
-
+ #foo()
+
def foo():
+ job2 = JobListPeers(c)
+ c.jobAdd(job2)
+ c.run()
+ print '---------------------------'
+ print job2.fcpResult
+ print '---------------------------'
+ #foo()
+
+
+ def foo():
job2 = JobGetFileInfo(c, 'CHK@sdNenKGj5mupxaSwo44jcW8dsX7vYTLww~BsRPtur0k,ZNRm9reMjtKEl9e-xFByKXbW6q4f6OQyfg~l9GRSAes,AAIC--8/snow_002%20%281%29.jpg')
c.jobAdd(job2)
c.run()
print '---------------------------'
- print job2.fcpError
print job2.fcpResult
- print job2.fcpTime
print '---------------------------'
#foo()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|