[Twisted-Python] dataReveived() buffer best practice?
Hey there, I'm currently implementing a Telnet Client, which is actually talking to a Console Server mapping Telnet to an RS232 interface. Further I'm using Twisted's conch.telnet lib to build that client, and I got a little situation here where I wonder if there's already a best practice. I guess the best way to introduce the problem is to show an example in the following. This is the output of a regular Terminal session when connecting to the Telnet Server: #------ drudge:~ rothfuchs$ telnet localhost 8001 Trying ::1... Connected to localhost. Escape character is '^]'.
MM USERID:0004 PASSWORD: #------
In my Twisted Client, I implemented dataReceived() to just do: [] def dataReceived(self, data): ..print 'received: %s' ..print [] and this is the result: #------ drudge:Desktop rothfuchs$ p s12.py received:
received: MM USE received: RID: #------ I also ran a tcpdump to confirm The opposite server is obviously pushing content to the socket in arbitrary frequencies, ending up in my dataReceived() method to get called arbitrarily as well. My question: is there any best practice for buffer techniques here? Thanks Fabian
I'm doing something very similar. I have (greatly simplified, because I'm doing lots of other stuff with the data): def applicationDataReceived(self, data): global savedText, delayCounter newline = "\n" text = savedText + data savedText = "" # normalize text (replace escapes, search for and normalize newlines) text = text.replace("\000","") text = text.replace("\033","$") text = text.replace("\r\n",newline) text = text.replace("\r",newline) lines = text.split(newline) for line in lines[:-1]: if len(line): write( line+newline ) savedText = lines[-1] # (if savedText <> "" then we are waiting for more...) def printPartialMessage(myCounter): global savedText, savedTimestamp, delayCounter #print "delay routine called %i %i" % (myCounter, delayCounter) if myCounter == delayCounter: if savedText <> "": newline = "\n" write( savedText+" (terminator not seen)"+newline ) savedText = "" delayCounter = 0 # If the passed counter (myCounter) equals the current value of # the delay counter, then we know the savedText is that left over # when we were queued. Otherwise, more text has come in and # caused the counter to be incremented and more calls to be # made to printPartialMessage. We'll let them handle it. if savedText <> "": delayCounter += 1 reactor.callLater(60, printPartialMessage, delayCounter) I'm actually writing this to a time-stamped log file, but I've removed all the code to maintain the time stamps, create and roll over the log files, etc. If you are willing to wait indefinitely for partial lines, you can get rid of the "printPartialMessage()" deferred, and the conditional call to it. delayCounter is a "pending calls to printPartialMessage()" counter (reset to 0 when there are none), because the only one we are interested in is the last one. Instead, the deferred could be canceled when new text arrives, but I think the ability to cancel defereds is newer than this code. I just let the deferreds exexute and dismiss them immediately if they aren't current. The constant "60" in the reactor.callLater() is the number of seconds I'm willing to wait for a partial message to receive more data. You might not want to normalize the text (since I'm printing to a text log file, I didn't want embedded escape sequences to cause conniptions when the log file was printed to a terminal), or you might want to use a different line terminator. Also, for conch.telnet, I think you want to override "applicationDataReceived()" and not "dataReceived()" because "dataReceived()" sees all the telnet protocol negotiations, which you might want to let conch.telnet handle. -- John Santos Evans Griffiths & Hart, Inc. 781-861-0670 ext 539
On 04:22 pm, fabian.rothfuchs@googlemail.com wrote:
Hey there,
I'm currently implementing a Telnet Client, which is actually talking to a Console Server mapping Telnet to an RS232 interface.
[snip]
and this is the result: #------ drudge:Desktop rothfuchs$ p s12.py received:
received: MM USE
received: RID: #------
I also ran a tcpdump to confirm � The opposite server is obviously pushing content to the socket in arbitrary frequencies, ending up in my dataReceived() method to get called arbitrarily as well.
This is not so obvious. Any hop along the route may fragment the data.
My question: is there any best practice for buffer techniques here?
This question is too vague. What problem are you trying to solve? Jean-Paul
On 10/6/11 11:06 PM, "exarkun@twistedmatrix.com" <exarkun@twistedmatrix.com> wrote:
On 04:22 pm, fabian.rothfuchs@googlemail.com wrote:
Hey there,
I'm currently implementing a Telnet Client, which is actually talking to a Console Server mapping Telnet to an RS232 interface.
[snip]
and this is the result: #------ drudge:Desktop rothfuchs$ p s12.py received:
received: MM USE
received: RID: #------
I also ran a tcpdump to confirm � The opposite server is obviously pushing content to the socket in arbitrary frequencies, ending up in my dataReceived() method to get called arbitrarily as well.
This is not so obvious. Any hop along the route may fragment the data.
My question: is there any best practice for buffer techniques here?
This question is too vague. What problem are you trying to solve?
Jean-Paul
JP, What do you mean w/ 'any hop along the route' ? My problem is, that I need something similar to telnetlib's `read_until()` method (in my case read_until('USERID:')), although 'USERID:' may be sent in independent events. I wonder if this is up to me to implement, or if there's any Twisted-style best practice. Cheers Fab
_______________________________________________ Twisted-Python mailing list Twisted-Python@twistedmatrix.com http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
On 11:04 pm, fabian.rothfuchs@googlemail.com wrote:
On 10/6/11 11:06 PM, "exarkun@twistedmatrix.com" <exarkun@twistedmatrix.com> wrote:
On 04:22 pm, fabian.rothfuchs@googlemail.com wrote:
Hey there,
I'm currently implementing a Telnet Client, which is actually talking to a Console Server mapping Telnet to an RS232 interface.
[snip]
and this is the result: #------ drudge:Desktop rothfuchs$ p s12.py received:
received: MM USE
received: RID: #------
I also ran a tcpdump to confirm �FD The opposite server is obviously pushing content to the socket in arbitrary frequencies, ending up in my dataReceived() method to get called arbitrarily as well.
This is not so obvious. Any hop along the route may fragment the data.
My question: is there any best practice for buffer techniques here?
This question is too vague. What problem are you trying to solve?
Jean-Paul
JP,
What do you mean w/ 'any hop along the route' ?
Potentially many routers are involved in getting packets from your (client) machine to the console server. Any one of them is allowed to fragment the data. The console server could well be writing "USERID:", but that's no guarantee that you'll receive "USERID:".
My problem is, that I need something similar to telnetlib's `read_until()` method (in my case read_until('USERID:')), although 'USERID:' may be sent in independent events. I wonder if this is up to me to implement, or if there's any Twisted- style best practice.
Take a look at twisted.conch.insults.helper.ExpectableBuffer. You can hook it up to your telnet connection and then use its `expect� method to wait for a particular string to show up. ExpectableBuffer is an ITerminalTransport, so you actually have to hook it up via twisted.conch.insults.insults.ClientProtocol, a vt102 implementation. If the server is incompatible with vt102, then you might need to build your own thing like ExpectableBuffer but without the vt102 layer. Jean-Paul
On 10/06/2011 10:06 PM, exarkun@twistedmatrix.com wrote:
I also ran a tcpdump to confirm � The opposite server is obviously pushing content to the socket in arbitrary frequencies, ending up in my dataReceived() method to get called arbitrarily as well.
This is not so obvious. Any hop along the route may fragment the data.
It is quite unusual (though not unheard of) for something to re-segment the TCP stream. IP level fragmentation might occur, but it's relatively uncommon in todays IP networks, and is anyway irrelevant to TCP - the TCP stack will only see a reassembled IP packet.
On Oct 7, 2011, at 7:47 AM, Phil Mayers wrote:
On 10/06/2011 10:06 PM, exarkun@twistedmatrix.com wrote:
I also ran a tcpdump to confirm � The opposite server is obviously pushing content to the socket in arbitrary frequencies, ending up in my dataReceived() method to get called arbitrarily as well.
This is not so obvious. Any hop along the route may fragment the data.
It is quite unusual (though not unheard of) for something to re-segment the TCP stream. IP level fragmentation might occur, but it's relatively uncommon in todays IP networks, and is anyway irrelevant to TCP - the TCP stack will only see a reassembled IP packet.
I am skeptical; my recollection (the last time I worked at this layer of the network) is that this happens all the time over the public internet between diverse endpoints. However, it's also mostly irrelevant: the thing at issue here is the distinction between the call to send() and the call to recv() - or in Twisted terms, the call to transport.write() and the argument to dataReceived, which will be smashed up into quasi-arbitrary lengths at the very least by your kernel and your router; you can send as much as you want at once via .write() but dataReceived will tend to get called with chunks around 1-2x your path MTU. But the sizes are also not important. The point is that TCP is about streams, not packets, and you have to deal with arbitrary chunking if you want your code to work right. What layer of the network this happens at is not important to your code :). -glyph
On 10/07/2011 02:11 PM, Glyph wrote:
It is quite unusual (though not unheard of) for something to re-segment the TCP stream. IP level fragmentation might occur, but it's relatively uncommon in todays IP networks, and is anyway irrelevant to TCP - the TCP stack will only see a reassembled IP packet.
I am skeptical; my recollection (the last time I worked at this layer of the network) is that this happens all the time over the public internet between diverse endpoints.
Are we talking about TCP re-segmentation, or IP fragmentation? If you mean TCP re-segmentation, then I have no data. The only places I've personally seen it are in TCP terminating load-balancers (F5, etc.), NAT64 devices, and as a side effect in higher-layer proxies (Squid, etc.). If you mean IP fragmentation, I claim that fragmentation by routers in the internet is rare. Whether it's 1% or 0.001% I couldn't say, but the vast majority of the time, routers do not end up fragmenting. For one thing, an awful lot of OSes send TCP segments with "don't fragment" set, to trigger ICMP error messages and path MTU discovery. For another, a lot of low MTU networks employ TCP MSS clamping to prevent this ever happening. For what it's worth, this "layer of the network" is my day job, but I don't claim oracle status.
But the sizes are also not important. The point is that TCP is about streams, not packets, and you have to deal with arbitrary chunking if you want your code to work right. What layer of the network this happens at is not important to your code :).
Agreed.
On Oct 7, 2011, at 6:49 PM, Phil Mayers wrote:
On 10/07/2011 02:11 PM, Glyph wrote:
It is quite unusual (though not unheard of) for something to re-segment the TCP stream. IP level fragmentation might occur, but it's relatively uncommon in todays IP networks, and is anyway irrelevant to TCP - the TCP stack will only see a reassembled IP packet.
I am skeptical; my recollection (the last time I worked at this layer of the network) is that this happens all the time over the public internet between diverse endpoints.
Are we talking about TCP re-segmentation, or IP fragmentation?
Pretty sure I'm talking about TCP re-segmentation.
If you mean TCP re-segmentation, then I have no data. The only places I've personally seen it are in TCP terminating load-balancers (F5, etc.), NAT64 devices, and as a side effect in higher-layer proxies (Squid, etc.).
Hrm. Now that I think of it, the packets I was examining were probably coming from environments that were heavily managed by "smart" networking hardware, although I could only see the edges of the network. So it was probably a combination of high-level transparent proxies and wacky load-balancing and caching hardware.
If you mean IP fragmentation, I claim that fragmentation by routers in the internet is rare. Whether it's 1% or 0.001% I couldn't say, but the vast majority of the time, routers do not end up fragmenting. For one thing, an awful lot of OSes send TCP segments with "don't fragment" set, to trigger ICMP error messages and path MTU discovery. For another, a lot of low MTU networks employ TCP MSS clamping to prevent this ever happening.
That's interesting, and good to know :).
For what it's worth, this "layer of the network" is my day job, but I don't claim oracle status.
But the sizes are also not important. The point is that TCP is about streams, not packets, and you have to deal with arbitrary chunking if you want your code to work right. What layer of the network this happens at is not important to your code :).
Agreed.
Since this is your day job - is there a formally-correct name for this phenomenon? I usually refer to it as "packet fragmentation" even though I know that's not really it - as you say, IP fragmentation doesn't really happen. It's not like it's really TCP re-segmenting either, because one send() is not necessarily one segment. Since it's such an important concept that every Twisted developer needs to know, I'd love to have a good word for it :).
On 10/09/2011 12:56 AM, Glyph wrote:
Since this is your day job - is there a formally-correct name for this phenomenon? I usually refer to it as "packet fragmentation" even though I know that's not really it - as you say, IP fragmentation doesn't really happen. It's not like it's really TCP re-segmenting either, because one send() is not necessarily one segment.
Sorry, only just got round to replying... Sadly there's no consistent name. The vendors all call it different things and implement it in subtly different (occasionally broken...) ways, and either hotly deny or proudly proclaim they're doing it, depending on which single basket they've put all their eggs in... ;o) e.g. F5 make a big thing of the fact that their load balancers do local termination of TCP (and other) protocols, allowing them to do things like multiplex N client connections into M (fewer) server connections, while still optionally preserving client ip/port and server ip/port - although F5 do also have non-terminating "fast" per-packet modes. It's variously called TCP termination, proxy and normalization. Some vendors use "layer 4" instead of TCP. Some incorrectly use "layer 5" or "layer 7" to describe their own idea of what is happening. In my experience it is usually load-balancers that do this, although if/when NAT64 takes off, we may see a lot more of it, depending on whether vendors choose to terminate the TCP connection, or munge the MTU discovery / MSS options to match the payload sizes on the IPv6/IPv4 legs. Ordinary NAT boxes tend to use a fast per-packet rewrite, rather than buffer TCP content. Cheers, Phil
On 10/06/2011 05:22 PM, Fabian Rothfuchs wrote:
I also ran a tcpdump to confirm – The opposite server is obviously pushing content to the socket in arbitrary frequencies, ending up in my dataReceived() method to get called arbitrarily as well.
Yes, this is normal. TCP stacks are free to segment the data as they see fit. Machine-readable protocols have framing for this reason. Sadly, text streams run over telnet/SSH/CLI interfaces are usually badly framed, if at all.
My question: is there any best practice for buffer techniques here?
Twisted comes with a bunch of higher level protocol sub-classes that buffer the data for you, then deliver chunks of the buffer to methods on your class. For example, lineReceiver delivers whole lines. There may well be a conch helper class that does the same. The generic do-it-yourself approach is to append the data to a buffer, then look for complete protocol messages in the buffer and process them in order, possibly with a state machine. e.g. def dataReceived(self, data): self.buffer += data if self.state=='waiting-for-userid': if 'USERID:' in self.buffer: # send userid self.transport.write('0004\r') self.state = 'waiting-for-password' # empty the buffer self.buffer = '' elif self.state=='waiting-for-password': if 'PASSWORD:' in self.buffer: self.transport.write(password+'\r') self.state = 'logged-in' self.buffer = '' ...and so on. This is boring to write by hand, so see if there is something in Twisted you can use already.
participants (5)
-
exarkun@twistedmatrix.com -
Fabian Rothfuchs -
Glyph -
John Santos -
Phil Mayers