o b{S@sBdZddlZddlmZmZddlmZmZddlm Z m Z ddl m Z ddl mZmZmZddlmZd d ZGd d d eZGd ddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdd d eZGd!d"d"eZGd#d$d$Z dS)%z] Resource limiting policies. @seealso: See also L{twisted.protocols.htb} for rate limiting. N)OptionalType)directlyProvides providedBy)error interfaces)ILoggingContext) ClientFactoryProtocol ServerFactory)logcCs0t|r |}n|jj}|d|jjdS)zY Compute a log prefix for a wrapper and the object it wraps. @rtype: C{str} z ())rr logPrefix __class____name__)wrapperwrappedrr} provider to which L{IProtocol} method calls onto this L{ProtocolWrapper} will be proxied. @ivar factory: The L{WrappingFactory} which created this L{ProtocolWrapper}. rfactoryWrappingFactorywrappedProtocolcCs||_||_dSN)rr)selfrrrrr__init__5s zProtocolWrapper.__init__cC t||jS)zo Use a customized log prefix mentioning both the wrapped protocol and the current one. )rrrrrrr;s zProtocolWrapper.logPrefixcCs6t|t|t|||j||j|dS)z When a connection is made, register this wrapper with its factory, save the real transport, and connect the wrapped protocol to this L{ProtocolWrapper} to intercept any transport calls it makes. N)rrr makeConnectionrregisterProtocolr)r transportrrrrBs  zProtocolWrapper.makeConnectioncC|j|dSr)r!writerdatarrrr#OzProtocolWrapper.writecCr"r)r! writeSequencer$rrrr'Rr&zProtocolWrapper.writeSequencecCsd|_|jdSN) disconnectingr!loseConnectionrrrrr+UszProtocolWrapper.loseConnectioncC |jSr)r!getPeerrrrrr-Y zProtocolWrapper.getPeercCr,r)r!getHostrrrrr/\r.zProtocolWrapper.getHostcC|j||dSr)r!registerProducerrproducer streamingrrrr1_z ProtocolWrapper.registerProducercC|jdSr)r!unregisterProducerrrrrr7bz"ProtocolWrapper.unregisterProducercCr6r)r! stopConsumingrrrrr9er8zProtocolWrapper.stopConsumingcCs t|j|Sr)getattrr!rnamerrr __getattr__hs zProtocolWrapper.__getattr__cCr"r)r dataReceivedr$rrrr>mr&zProtocolWrapper.dataReceivedcCs"|j||j|d|_dSr)runregisterProtocolrconnectionLostrreasonrrrr@ps   zProtocolWrapper.connectionLostN)r __module__ __qualname____doc__r*r IProtocolrrrr#r'r+r-r/r1r7r9r=r>r@rrrrr's*    rc@sreZdZUdZeZeeed<ddZ ddZ ddZ d d Z d d Z d dZddZddZddZddZdS)rzE Wraps a factory and its protocols, and keeps track of them. protocolcCs||_i|_dSr)wrappedFactory protocols)rrHrrrrs zWrappingFactory.__init__cCr)zY Generate a log prefix mentioning both the wrapped factory and this one. )rrHrrrrr zWrappingFactory.logPrefixcC|jt|dSr)rHdoStartr rrrrrL zWrappingFactory.doStartcCrKr)rHdoStopr rrrrrNrMzWrappingFactory.doStopcCr"r)rHstartedConnecting)r connectorrrrrOr&z!WrappingFactory.startedConnectingcCr0r)rHclientConnectionFailedrrPrBrrrrQr5z&WrappingFactory.clientConnectionFailedcCr0r)rHclientConnectionLostrRrrrrSr5z$WrappingFactory.clientConnectionLostcCs|||j|Sr)rGrH buildProtocolraddrrrrrTszWrappingFactory.buildProtocolcCsd|j|<dS)z8 Called by protocol to register itself. r)NrIrprrrr sz WrappingFactory.registerProtocolcCs |j|=dS)z8 Called by protocols when they go away. NrWrXrrrr?rJz"WrappingFactory.unregisterProtocolN)rrCrDrErrGrr __annotations__rrrLrNrOrQrSrTr r?rrrrrxs  rc@sXeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ dS)ThrottlingProtocolz, Protocol for L{ThrottlingFactory}. cC |jt|t||dSr)rregisterWrittenlenrr#r$rrrr#zThrottlingProtocol.writecCs&|jttt|t||dSr)rr]summapr^rr'rseqrrrr'sz ThrottlingProtocol.writeSequencecCr\r)r registerReadr^rr>r$rrrr>r_zThrottlingProtocol.dataReceivedcCs||_t|||dSr)r3rr1r2rrrr1sz#ThrottlingProtocol.registerProducercCs|`t|dSr)r3rr7rrrrr7sz%ThrottlingProtocol.unregisterProducercCr6r)r!pauseProducingrrrr throttleReadsr8z ThrottlingProtocol.throttleReadscCr6r)r!resumeProducingrrrrunthrottleReadsr8z"ThrottlingProtocol.unthrottleReadscCt|dr |jdSdSNr3)hasattrr3rerrrrthrottleWrites z!ThrottlingProtocol.throttleWritescCrirj)rkr3rgrrrrunthrottleWritesrmz#ThrottlingProtocol.unthrottleWritesN) rrCrDrEr#r'r>r1r7rfrhrlrnrrrrr[s r[c@s~eZdZdZeZejddfddZddZ ddZ d d Z d d Z d dZ ddZddZddZddZddZddZdS)ThrottlingFactoryz Throttles bandwidth and number of connections. Write bandwidth will only be throttled if there is a producer registered. NcCsLt||d|_||_||_||_d|_d|_d|_d|_ d|_ d|_ dSNr) rrconnectionCountmaxConnectionCount readLimit writeLimitreadThisSecondwrittenThisSecondunthrottleReadsIDcheckReadBandwidthIDunthrottleWritesIDcheckWriteBandwidthID)rrHrrrsrtrrrrs  zThrottlingFactory.__init__cCddlm}|||Sz Wrapper around L{reactor.callLater} for test purpose. r)reactortwisted.internetr} callLaterrperiodfuncr}rrrr  zThrottlingFactory.callLatercC|j|7_dS)zH Called by protocol to tell us more bytes were written. N)rvrlengthrrrr]z!ThrottlingFactory.registerWrittencCr)zE Called by protocol to tell us more bytes were read. N)rurrrrrdrzThrottlingFactory.registerReadcCsR|j|jkr|t|j|jd}|||j|_d|_|d|j|_dS)z: Checks if we've passed bandwidth limits. ?rr)N) rursrffloatrrhrwcheckReadBandwidthrxr throttleTimerrrrs z$ThrottlingFactory.checkReadBandwidthcCsR|j|jkr|t|j|jd}|||j|_d|_|d|j|_dS)Nrrr)) rvrtrlrrrnrycheckWriteBandwidthrzrrrrrs z%ThrottlingFactory.checkWriteBandwidthcC*td||jD]}|q dS)z2 Throttle reads on all protocols. zThrottling reads on %sN)r msgrIkeysrfrXrrrrf zThrottlingFactory.throttleReadscC0d|_td||jD]}|qdS)z9 Stop throttling reads on all protocols. NzStopped throttling reads on %s)rwr rrIrrhrXrrrrh%  z!ThrottlingFactory.unthrottleReadscCr)z3 Throttle writes on all protocols. zThrottling writes on %sN)r rrIrrlrXrrrrl.rz ThrottlingFactory.throttleWritescCr)z: Stop throttling writes on all protocols. NzStopped throttling writes on %s)ryr rrIrrnrXrrrrn6rz"ThrottlingFactory.unthrottleWritescCsb|jdkr|jdur||jdur||j|jkr*|jd7_t||St ddS)Nrr)zMax connection count reached!) rqrsrrtrrrrrTr rrUrrrrT?s      zThrottlingFactory.buildProtocolcCst|||jd8_|jdkr<|jdur|j|jdur&|j|jdur0|j|jdur>|jdSdSdSNr)r)rr?rqrwcancelrxryrzrXrrrr?Ms         z$ThrottlingFactory.unregisterProtocol)rrCrDrEr[rGsysmaxsizerrr]rdrrrfrhrlrnrTr?rrrrros$      roc@seZdZddZddZdS)SpewingProtocolcCtd|t||dS)Nz Received: %r)r rrr>r$rrrr>\zSpewingProtocol.dataReceivedcCr)Nz Sending: %r)r rrr#r$rrrr#`rzSpewingProtocol.writeN)rrCrDr>r#rrrrr[s rc@seZdZeZdS)SpewingFactoryN)rrCrDrrGrrrrresrc@s(eZdZdZddZddZddZdS) LimitConnectionsByPeercCs i|_dSr)peerConnectionsrrrr startFactorymr.z#LimitConnectionsByPeer.startFactorycCs>|d}|j|d}||jkrdS|d|j|<t||S)Nrr))rgetmaxConnectionsPerPeerrrT)rrVpeerHostrqrrrrTps   z$LimitConnectionsByPeer.buildProtocolcCs<|d}|j|d8<|j|dkr|j|=dSdSr)r-r)rrYrrrrr?xs  z)LimitConnectionsByPeer.unregisterProtocolN)rrCrDrrrTr?rrrrris  rc@sFeZdZUdZdZdZdZeee e d<ddZ ddZ d d Z dS) LimitTotalConnectionsFactorya Factory that limits the number of simultaneous connections. @type connectionCount: C{int} @ivar connectionCount: number of current connections. @type connectionLimit: C{int} or L{None} @cvar connectionLimit: maximum number of connections. @type overflowProtocol: L{Protocol} or L{None} @cvar overflowProtocol: Protocol to use for new connections when connectionLimit is exceeded. If L{None} (the default value), excess connections will be closed immediately. rNoverflowProtocolcCsX|jdus |j|jkr|}n |jdurdS|}||_t||}|jd7_|Sr()connectionLimitrqrGrrr)rrVrrGrrrrTs   z*LimitTotalConnectionsFactory.buildProtocolcCsdSrrrXrrrr sz-LimitTotalConnectionsFactory.registerProtocolcCs|jd8_dSr()rqrXrrrr?r5z/LimitTotalConnectionsFactory.unregisterProtocol)rrCrDrErqrrrrr rZrTr r?rrrrrs   rc@sZeZdZdZddZdddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)TimeoutProtocolzN Protocol that automatically disconnects when the connection is idle. cCs(t|||d|_d|_||dS)z Constructor. @param factory: An L{TimeoutFactory}. @param wrappedProtocol: A L{Protocol} to wrapp. @param timeoutPeriod: Number of seconds to wait for activity before timing out. N)rr timeoutCall timeoutPeriod setTimeout)rrrrrrrrs zTimeoutProtocol.__init__NcCs2|||_|dur|j|j|j|_dSdS)z Set a timeout. This will cancel any existing timeouts. @param timeoutPeriod: If not L{None}, change the timeout period. Otherwise, use the existing value. N) cancelTimeoutrrr timeoutFuncr)rrrrrrs  zTimeoutProtocol.setTimeoutc CsDd|_|jr z|jWn tjtjfyYnwd|_dSdS)zg Cancel the timeout. If the timeout was already cancelled, this does nothing. N)rrrr AlreadyCalledAlreadyCancelledrrrrrs zTimeoutProtocol.cancelTimeoutcCs|jr |j|jdSdS)zQ Reset the timeout, usually because some activity just happened. N)rresetrrrrr resetTimeoutszTimeoutProtocol.resetTimeoutcC|t||dSr)rrr#r$rrrr#zTimeoutProtocol.writecCrr)rrr'rbrrrr'rzTimeoutProtocol.writeSequencecCrr)rrr>r$rrrr>rzTimeoutProtocol.dataReceivedcCrr)rrr@rArrrr@rzTimeoutProtocol.connectionLostcCs |dS)z This method is called when the timeout is triggered. By default it calls I{loseConnection}. Override this if you want something else to happen. N)r+rrrrrs zTimeoutProtocol.timeoutFuncr) rrCrDrErrrrr#r'r>r@rrrrrrs  rc@s.eZdZdZeZd ddZddZddZd S) TimeoutFactoryz% Factory for TimeoutWrapper. cCs||_t||dSr)rrr)rrHrrrrrszTimeoutFactory.__init__cCs|j||j||jdS)N)r)rGrHrTrrUrrrrTs  zTimeoutFactory.buildProtocolcCr{r|r~rrrrr rzTimeoutFactory.callLaterN)r) rrCrDrErrGrrTrrrrrrs   rc@sVeZdZdddZddZddZd d Zd d Zd dZddZ ddZ ddZ dS)TrafficLoggingProtocolNrcCs$t|||||_||_||_dS)a @param factory: factory which created this protocol. @type factory: L{protocol.Factory}. @param wrappedProtocol: the underlying protocol. @type wrappedProtocol: C{protocol.Protocol}. @param logfile: file opened for writing used to write log messages. @type logfile: C{file} @param lengthLimit: maximum size of the datareceived logged. @type lengthLimit: C{int} @param number: identifier of the connection. @type number: C{int}. N)rrlogfile lengthLimit_number)rrrrrnumberrrrrs  zTrafficLoggingProtocol.__init__cCs|j|d|jdS)N )rr#flush)rlinerrr_log*szTrafficLoggingProtocol._logcCs.|jrt||jkr|d|jdd}|S)N z <... elided>)rr^r$rrr _mungeData.sz!TrafficLoggingProtocol._mungeDatacCs|dt|S)N*)rrconnectionMaderrrrr4s  z%TrafficLoggingProtocol.connectionMadecC&|d|j||ft||SNzC %d: %r)rrrrr>r$rrrr>8 z#TrafficLoggingProtocol.dataReceivedcCs |d|j|ft||Sr)rrrr@rArrrr@<s z%TrafficLoggingProtocol.connectionLostcCr)NzS %d: %r)rrrrr#r$rrrr#ArzTrafficLoggingProtocol.writecs.djfdd|Dft|S)Nz SV %d: %rcsg|]}|qSr)r).0drrr Fsz8TrafficLoggingProtocol.writeSequence..)rrrr')riovecrrrr'Es" z$TrafficLoggingProtocol.writeSequencecCs|d|jft|S)NzS %d: *)rrrr+rrrrr+Is z%TrafficLoggingProtocol.loseConnectionrp) rrCrDrrrrr>r@r#r'r+rrrrrs  rc@s6eZdZeZdZd ddZddZddZd d Z dS) TrafficLoggingFactoryrNcCs||_||_t||dSr) logfilePrefixrrr)rrHrrrrrrSszTrafficLoggingFactory.__init__cCs t|dS)Nw)openr;rrrrXr.zTrafficLoggingFactory.opencCsF|jd7_||jdt|j}|||j|||j|jS)Nr)-)_counterrrstrrGrHrTr)rrVrrrrrT[s z#TrafficLoggingFactory.buildProtocolcCs d|_dS)zN Reset the value of the counter used to identify connections. rN)rrrrr resetCounterfs z"TrafficLoggingFactory.resetCounterr) rrCrDrrGrrrrTrrrrrrNs  rc@sNeZdZUdZdZeeed<dZddZ ddZ dd Z d d Z d d Z dS) TimeoutMixinaL Mixin for protocols which wish to timeout connections. Protocols that mix this in have a single timeout, set using L{setTimeout}. When the timeout is hit, L{timeoutConnection} is called, which, by default, closes the connection. @cvar timeOut: The number of seconds after which to timeout the connection. NtimeOutcCr{r|r~rrrrr|rzTimeoutMixin.callLatercCs.|jdur|jdur|j|jdSdSdS)a Reset the timeout count down. If the connection has already timed out, then do nothing. If the timeout has been cancelled (probably using C{setTimeout(None)}), also do nothing. It's often a good idea to call this when the protocol has received some meaningful input from the other end of the connection. "I've got some data, they're still there, reset the timeout". N)_TimeoutMixin__timeoutCallrrrrrrrs zTimeoutMixin.resetTimeoutc Cs~|j}||_|jdur1|dur)z|jWn tjtjfy#Ynwd|_|S|j||S|dur=|||j|_|S)z Change the timeout period @type period: C{int} or L{None} @param period: The period, in seconds, to change the timeout to, or L{None} to disable the timeout. N) rrrrrrrr_TimeoutMixin__timedOut)rrprevrrrrs   zTimeoutMixin.setTimeoutcCsd|_|dSr)rtimeoutConnectionrrrr __timedOuts zTimeoutMixin.__timedOutcCs|jdS)z Called when the connection times out. Override to define behavior other than dropping the connection. N)r!r+rrrrrszTimeoutMixin.timeoutConnection)rrCrDrErrintrZrrrrrrrrrrrms    r)!rErtypingrrzope.interfacerrrrrtwisted.internet.interfacesrtwisted.internet.protocolr r r twisted.pythonr rrrr[rorrrrrrrrrrrrrs.   Q2* )R7