policies.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. # -*- test-case-name: twisted.test.test_policies -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Resource limiting policies.
  6. @seealso: See also L{twisted.protocols.htb} for rate limiting.
  7. """
  8. from __future__ import division, absolute_import
  9. # system imports
  10. import sys
  11. from zope.interface import directlyProvides, providedBy
  12. # twisted imports
  13. from twisted.internet.protocol import ServerFactory, Protocol, ClientFactory
  14. from twisted.internet import error
  15. from twisted.internet.interfaces import ILoggingContext
  16. from twisted.python import log
  17. def _wrappedLogPrefix(wrapper, wrapped):
  18. """
  19. Compute a log prefix for a wrapper and the object it wraps.
  20. @rtype: C{str}
  21. """
  22. if ILoggingContext.providedBy(wrapped):
  23. logPrefix = wrapped.logPrefix()
  24. else:
  25. logPrefix = wrapped.__class__.__name__
  26. return "%s (%s)" % (logPrefix, wrapper.__class__.__name__)
  27. class ProtocolWrapper(Protocol):
  28. """
  29. Wraps protocol instances and acts as their transport as well.
  30. @ivar wrappedProtocol: An L{IProtocol<twisted.internet.interfaces.IProtocol>}
  31. provider to which L{IProtocol<twisted.internet.interfaces.IProtocol>}
  32. method calls onto this L{ProtocolWrapper} will be proxied.
  33. @ivar factory: The L{WrappingFactory} which created this
  34. L{ProtocolWrapper}.
  35. """
  36. disconnecting = 0
  37. def __init__(self, factory, wrappedProtocol):
  38. self.wrappedProtocol = wrappedProtocol
  39. self.factory = factory
  40. def logPrefix(self):
  41. """
  42. Use a customized log prefix mentioning both the wrapped protocol and
  43. the current one.
  44. """
  45. return _wrappedLogPrefix(self, self.wrappedProtocol)
  46. def makeConnection(self, transport):
  47. """
  48. When a connection is made, register this wrapper with its factory,
  49. save the real transport, and connect the wrapped protocol to this
  50. L{ProtocolWrapper} to intercept any transport calls it makes.
  51. """
  52. directlyProvides(self, providedBy(transport))
  53. Protocol.makeConnection(self, transport)
  54. self.factory.registerProtocol(self)
  55. self.wrappedProtocol.makeConnection(self)
  56. # Transport relaying
  57. def write(self, data):
  58. self.transport.write(data)
  59. def writeSequence(self, data):
  60. self.transport.writeSequence(data)
  61. def loseConnection(self):
  62. self.disconnecting = 1
  63. self.transport.loseConnection()
  64. def getPeer(self):
  65. return self.transport.getPeer()
  66. def getHost(self):
  67. return self.transport.getHost()
  68. def registerProducer(self, producer, streaming):
  69. self.transport.registerProducer(producer, streaming)
  70. def unregisterProducer(self):
  71. self.transport.unregisterProducer()
  72. def stopConsuming(self):
  73. self.transport.stopConsuming()
  74. def __getattr__(self, name):
  75. return getattr(self.transport, name)
  76. # Protocol relaying
  77. def dataReceived(self, data):
  78. self.wrappedProtocol.dataReceived(data)
  79. def connectionLost(self, reason):
  80. self.factory.unregisterProtocol(self)
  81. self.wrappedProtocol.connectionLost(reason)
  82. # Breaking reference cycle between self and wrappedProtocol.
  83. self.wrappedProtocol = None
  84. class WrappingFactory(ClientFactory):
  85. """
  86. Wraps a factory and its protocols, and keeps track of them.
  87. """
  88. protocol = ProtocolWrapper
  89. def __init__(self, wrappedFactory):
  90. self.wrappedFactory = wrappedFactory
  91. self.protocols = {}
  92. def logPrefix(self):
  93. """
  94. Generate a log prefix mentioning both the wrapped factory and this one.
  95. """
  96. return _wrappedLogPrefix(self, self.wrappedFactory)
  97. def doStart(self):
  98. self.wrappedFactory.doStart()
  99. ClientFactory.doStart(self)
  100. def doStop(self):
  101. self.wrappedFactory.doStop()
  102. ClientFactory.doStop(self)
  103. def startedConnecting(self, connector):
  104. self.wrappedFactory.startedConnecting(connector)
  105. def clientConnectionFailed(self, connector, reason):
  106. self.wrappedFactory.clientConnectionFailed(connector, reason)
  107. def clientConnectionLost(self, connector, reason):
  108. self.wrappedFactory.clientConnectionLost(connector, reason)
  109. def buildProtocol(self, addr):
  110. return self.protocol(self, self.wrappedFactory.buildProtocol(addr))
  111. def registerProtocol(self, p):
  112. """
  113. Called by protocol to register itself.
  114. """
  115. self.protocols[p] = 1
  116. def unregisterProtocol(self, p):
  117. """
  118. Called by protocols when they go away.
  119. """
  120. del self.protocols[p]
  121. class ThrottlingProtocol(ProtocolWrapper):
  122. """
  123. Protocol for L{ThrottlingFactory}.
  124. """
  125. # wrap API for tracking bandwidth
  126. def write(self, data):
  127. self.factory.registerWritten(len(data))
  128. ProtocolWrapper.write(self, data)
  129. def writeSequence(self, seq):
  130. self.factory.registerWritten(sum(map(len, seq)))
  131. ProtocolWrapper.writeSequence(self, seq)
  132. def dataReceived(self, data):
  133. self.factory.registerRead(len(data))
  134. ProtocolWrapper.dataReceived(self, data)
  135. def registerProducer(self, producer, streaming):
  136. self.producer = producer
  137. ProtocolWrapper.registerProducer(self, producer, streaming)
  138. def unregisterProducer(self):
  139. del self.producer
  140. ProtocolWrapper.unregisterProducer(self)
  141. def throttleReads(self):
  142. self.transport.pauseProducing()
  143. def unthrottleReads(self):
  144. self.transport.resumeProducing()
  145. def throttleWrites(self):
  146. if hasattr(self, "producer"):
  147. self.producer.pauseProducing()
  148. def unthrottleWrites(self):
  149. if hasattr(self, "producer"):
  150. self.producer.resumeProducing()
  151. class ThrottlingFactory(WrappingFactory):
  152. """
  153. Throttles bandwidth and number of connections.
  154. Write bandwidth will only be throttled if there is a producer
  155. registered.
  156. """
  157. protocol = ThrottlingProtocol
  158. def __init__(self, wrappedFactory, maxConnectionCount=sys.maxsize,
  159. readLimit=None, writeLimit=None):
  160. WrappingFactory.__init__(self, wrappedFactory)
  161. self.connectionCount = 0
  162. self.maxConnectionCount = maxConnectionCount
  163. self.readLimit = readLimit # max bytes we should read per second
  164. self.writeLimit = writeLimit # max bytes we should write per second
  165. self.readThisSecond = 0
  166. self.writtenThisSecond = 0
  167. self.unthrottleReadsID = None
  168. self.checkReadBandwidthID = None
  169. self.unthrottleWritesID = None
  170. self.checkWriteBandwidthID = None
  171. def callLater(self, period, func):
  172. """
  173. Wrapper around
  174. L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
  175. for test purpose.
  176. """
  177. from twisted.internet import reactor
  178. return reactor.callLater(period, func)
  179. def registerWritten(self, length):
  180. """
  181. Called by protocol to tell us more bytes were written.
  182. """
  183. self.writtenThisSecond += length
  184. def registerRead(self, length):
  185. """
  186. Called by protocol to tell us more bytes were read.
  187. """
  188. self.readThisSecond += length
  189. def checkReadBandwidth(self):
  190. """
  191. Checks if we've passed bandwidth limits.
  192. """
  193. if self.readThisSecond > self.readLimit:
  194. self.throttleReads()
  195. throttleTime = (float(self.readThisSecond) / self.readLimit) - 1.0
  196. self.unthrottleReadsID = self.callLater(throttleTime,
  197. self.unthrottleReads)
  198. self.readThisSecond = 0
  199. self.checkReadBandwidthID = self.callLater(1, self.checkReadBandwidth)
  200. def checkWriteBandwidth(self):
  201. if self.writtenThisSecond > self.writeLimit:
  202. self.throttleWrites()
  203. throttleTime = (float(self.writtenThisSecond) / self.writeLimit) - 1.0
  204. self.unthrottleWritesID = self.callLater(throttleTime,
  205. self.unthrottleWrites)
  206. # reset for next round
  207. self.writtenThisSecond = 0
  208. self.checkWriteBandwidthID = self.callLater(1, self.checkWriteBandwidth)
  209. def throttleReads(self):
  210. """
  211. Throttle reads on all protocols.
  212. """
  213. log.msg("Throttling reads on %s" % self)
  214. for p in self.protocols.keys():
  215. p.throttleReads()
  216. def unthrottleReads(self):
  217. """
  218. Stop throttling reads on all protocols.
  219. """
  220. self.unthrottleReadsID = None
  221. log.msg("Stopped throttling reads on %s" % self)
  222. for p in self.protocols.keys():
  223. p.unthrottleReads()
  224. def throttleWrites(self):
  225. """
  226. Throttle writes on all protocols.
  227. """
  228. log.msg("Throttling writes on %s" % self)
  229. for p in self.protocols.keys():
  230. p.throttleWrites()
  231. def unthrottleWrites(self):
  232. """
  233. Stop throttling writes on all protocols.
  234. """
  235. self.unthrottleWritesID = None
  236. log.msg("Stopped throttling writes on %s" % self)
  237. for p in self.protocols.keys():
  238. p.unthrottleWrites()
  239. def buildProtocol(self, addr):
  240. if self.connectionCount == 0:
  241. if self.readLimit is not None:
  242. self.checkReadBandwidth()
  243. if self.writeLimit is not None:
  244. self.checkWriteBandwidth()
  245. if self.connectionCount < self.maxConnectionCount:
  246. self.connectionCount += 1
  247. return WrappingFactory.buildProtocol(self, addr)
  248. else:
  249. log.msg("Max connection count reached!")
  250. return None
  251. def unregisterProtocol(self, p):
  252. WrappingFactory.unregisterProtocol(self, p)
  253. self.connectionCount -= 1
  254. if self.connectionCount == 0:
  255. if self.unthrottleReadsID is not None:
  256. self.unthrottleReadsID.cancel()
  257. if self.checkReadBandwidthID is not None:
  258. self.checkReadBandwidthID.cancel()
  259. if self.unthrottleWritesID is not None:
  260. self.unthrottleWritesID.cancel()
  261. if self.checkWriteBandwidthID is not None:
  262. self.checkWriteBandwidthID.cancel()
  263. class SpewingProtocol(ProtocolWrapper):
  264. def dataReceived(self, data):
  265. log.msg("Received: %r" % data)
  266. ProtocolWrapper.dataReceived(self,data)
  267. def write(self, data):
  268. log.msg("Sending: %r" % data)
  269. ProtocolWrapper.write(self,data)
  270. class SpewingFactory(WrappingFactory):
  271. protocol = SpewingProtocol
  272. class LimitConnectionsByPeer(WrappingFactory):
  273. maxConnectionsPerPeer = 5
  274. def startFactory(self):
  275. self.peerConnections = {}
  276. def buildProtocol(self, addr):
  277. peerHost = addr[0]
  278. connectionCount = self.peerConnections.get(peerHost, 0)
  279. if connectionCount >= self.maxConnectionsPerPeer:
  280. return None
  281. self.peerConnections[peerHost] = connectionCount + 1
  282. return WrappingFactory.buildProtocol(self, addr)
  283. def unregisterProtocol(self, p):
  284. peerHost = p.getPeer()[1]
  285. self.peerConnections[peerHost] -= 1
  286. if self.peerConnections[peerHost] == 0:
  287. del self.peerConnections[peerHost]
  288. class LimitTotalConnectionsFactory(ServerFactory):
  289. """
  290. Factory that limits the number of simultaneous connections.
  291. @type connectionCount: C{int}
  292. @ivar connectionCount: number of current connections.
  293. @type connectionLimit: C{int} or L{None}
  294. @cvar connectionLimit: maximum number of connections.
  295. @type overflowProtocol: L{Protocol} or L{None}
  296. @cvar overflowProtocol: Protocol to use for new connections when
  297. connectionLimit is exceeded. If L{None} (the default value), excess
  298. connections will be closed immediately.
  299. """
  300. connectionCount = 0
  301. connectionLimit = None
  302. overflowProtocol = None
  303. def buildProtocol(self, addr):
  304. if (self.connectionLimit is None or
  305. self.connectionCount < self.connectionLimit):
  306. # Build the normal protocol
  307. wrappedProtocol = self.protocol()
  308. elif self.overflowProtocol is None:
  309. # Just drop the connection
  310. return None
  311. else:
  312. # Too many connections, so build the overflow protocol
  313. wrappedProtocol = self.overflowProtocol()
  314. wrappedProtocol.factory = self
  315. protocol = ProtocolWrapper(self, wrappedProtocol)
  316. self.connectionCount += 1
  317. return protocol
  318. def registerProtocol(self, p):
  319. pass
  320. def unregisterProtocol(self, p):
  321. self.connectionCount -= 1
  322. class TimeoutProtocol(ProtocolWrapper):
  323. """
  324. Protocol that automatically disconnects when the connection is idle.
  325. """
  326. def __init__(self, factory, wrappedProtocol, timeoutPeriod):
  327. """
  328. Constructor.
  329. @param factory: An L{TimeoutFactory}.
  330. @param wrappedProtocol: A L{Protocol} to wrapp.
  331. @param timeoutPeriod: Number of seconds to wait for activity before
  332. timing out.
  333. """
  334. ProtocolWrapper.__init__(self, factory, wrappedProtocol)
  335. self.timeoutCall = None
  336. self.timeoutPeriod = None
  337. self.setTimeout(timeoutPeriod)
  338. def setTimeout(self, timeoutPeriod=None):
  339. """
  340. Set a timeout.
  341. This will cancel any existing timeouts.
  342. @param timeoutPeriod: If not L{None}, change the timeout period.
  343. Otherwise, use the existing value.
  344. """
  345. self.cancelTimeout()
  346. self.timeoutPeriod = timeoutPeriod
  347. if timeoutPeriod is not None:
  348. self.timeoutCall = self.factory.callLater(self.timeoutPeriod, self.timeoutFunc)
  349. def cancelTimeout(self):
  350. """
  351. Cancel the timeout.
  352. If the timeout was already cancelled, this does nothing.
  353. """
  354. self.timeoutPeriod = None
  355. if self.timeoutCall:
  356. try:
  357. self.timeoutCall.cancel()
  358. except (error.AlreadyCalled, error.AlreadyCancelled):
  359. pass
  360. self.timeoutCall = None
  361. def resetTimeout(self):
  362. """
  363. Reset the timeout, usually because some activity just happened.
  364. """
  365. if self.timeoutCall:
  366. self.timeoutCall.reset(self.timeoutPeriod)
  367. def write(self, data):
  368. self.resetTimeout()
  369. ProtocolWrapper.write(self, data)
  370. def writeSequence(self, seq):
  371. self.resetTimeout()
  372. ProtocolWrapper.writeSequence(self, seq)
  373. def dataReceived(self, data):
  374. self.resetTimeout()
  375. ProtocolWrapper.dataReceived(self, data)
  376. def connectionLost(self, reason):
  377. self.cancelTimeout()
  378. ProtocolWrapper.connectionLost(self, reason)
  379. def timeoutFunc(self):
  380. """
  381. This method is called when the timeout is triggered.
  382. By default it calls I{loseConnection}. Override this if you want
  383. something else to happen.
  384. """
  385. self.loseConnection()
  386. class TimeoutFactory(WrappingFactory):
  387. """
  388. Factory for TimeoutWrapper.
  389. """
  390. protocol = TimeoutProtocol
  391. def __init__(self, wrappedFactory, timeoutPeriod=30*60):
  392. self.timeoutPeriod = timeoutPeriod
  393. WrappingFactory.__init__(self, wrappedFactory)
  394. def buildProtocol(self, addr):
  395. return self.protocol(self, self.wrappedFactory.buildProtocol(addr),
  396. timeoutPeriod=self.timeoutPeriod)
  397. def callLater(self, period, func):
  398. """
  399. Wrapper around
  400. L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
  401. for test purpose.
  402. """
  403. from twisted.internet import reactor
  404. return reactor.callLater(period, func)
  405. class TrafficLoggingProtocol(ProtocolWrapper):
  406. def __init__(self, factory, wrappedProtocol, logfile, lengthLimit=None,
  407. number=0):
  408. """
  409. @param factory: factory which created this protocol.
  410. @type factory: L{protocol.Factory}.
  411. @param wrappedProtocol: the underlying protocol.
  412. @type wrappedProtocol: C{protocol.Protocol}.
  413. @param logfile: file opened for writing used to write log messages.
  414. @type logfile: C{file}
  415. @param lengthLimit: maximum size of the datareceived logged.
  416. @type lengthLimit: C{int}
  417. @param number: identifier of the connection.
  418. @type number: C{int}.
  419. """
  420. ProtocolWrapper.__init__(self, factory, wrappedProtocol)
  421. self.logfile = logfile
  422. self.lengthLimit = lengthLimit
  423. self._number = number
  424. def _log(self, line):
  425. self.logfile.write(line + '\n')
  426. self.logfile.flush()
  427. def _mungeData(self, data):
  428. if self.lengthLimit and len(data) > self.lengthLimit:
  429. data = data[:self.lengthLimit - 12] + '<... elided>'
  430. return data
  431. # IProtocol
  432. def connectionMade(self):
  433. self._log('*')
  434. return ProtocolWrapper.connectionMade(self)
  435. def dataReceived(self, data):
  436. self._log('C %d: %r' % (self._number, self._mungeData(data)))
  437. return ProtocolWrapper.dataReceived(self, data)
  438. def connectionLost(self, reason):
  439. self._log('C %d: %r' % (self._number, reason))
  440. return ProtocolWrapper.connectionLost(self, reason)
  441. # ITransport
  442. def write(self, data):
  443. self._log('S %d: %r' % (self._number, self._mungeData(data)))
  444. return ProtocolWrapper.write(self, data)
  445. def writeSequence(self, iovec):
  446. self._log('SV %d: %r' % (self._number, [self._mungeData(d) for d in iovec]))
  447. return ProtocolWrapper.writeSequence(self, iovec)
  448. def loseConnection(self):
  449. self._log('S %d: *' % (self._number,))
  450. return ProtocolWrapper.loseConnection(self)
  451. class TrafficLoggingFactory(WrappingFactory):
  452. protocol = TrafficLoggingProtocol
  453. _counter = 0
  454. def __init__(self, wrappedFactory, logfilePrefix, lengthLimit=None):
  455. self.logfilePrefix = logfilePrefix
  456. self.lengthLimit = lengthLimit
  457. WrappingFactory.__init__(self, wrappedFactory)
  458. def open(self, name):
  459. return open(name, 'w')
  460. def buildProtocol(self, addr):
  461. self._counter += 1
  462. logfile = self.open(self.logfilePrefix + '-' + str(self._counter))
  463. return self.protocol(self, self.wrappedFactory.buildProtocol(addr),
  464. logfile, self.lengthLimit, self._counter)
  465. def resetCounter(self):
  466. """
  467. Reset the value of the counter used to identify connections.
  468. """
  469. self._counter = 0
  470. class TimeoutMixin:
  471. """
  472. Mixin for protocols which wish to timeout connections.
  473. Protocols that mix this in have a single timeout, set using L{setTimeout}.
  474. When the timeout is hit, L{timeoutConnection} is called, which, by
  475. default, closes the connection.
  476. @cvar timeOut: The number of seconds after which to timeout the connection.
  477. """
  478. timeOut = None
  479. __timeoutCall = None
  480. def callLater(self, period, func):
  481. """
  482. Wrapper around
  483. L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
  484. for test purpose.
  485. """
  486. from twisted.internet import reactor
  487. return reactor.callLater(period, func)
  488. def resetTimeout(self):
  489. """
  490. Reset the timeout count down.
  491. If the connection has already timed out, then do nothing. If the
  492. timeout has been cancelled (probably using C{setTimeout(None)}), also
  493. do nothing.
  494. It's often a good idea to call this when the protocol has received
  495. some meaningful input from the other end of the connection. "I've got
  496. some data, they're still there, reset the timeout".
  497. """
  498. if self.__timeoutCall is not None and self.timeOut is not None:
  499. self.__timeoutCall.reset(self.timeOut)
  500. def setTimeout(self, period):
  501. """
  502. Change the timeout period
  503. @type period: C{int} or L{None}
  504. @param period: The period, in seconds, to change the timeout to, or
  505. L{None} to disable the timeout.
  506. """
  507. prev = self.timeOut
  508. self.timeOut = period
  509. if self.__timeoutCall is not None:
  510. if period is None:
  511. try:
  512. self.__timeoutCall.cancel()
  513. except (error.AlreadyCancelled, error.AlreadyCalled):
  514. # Do nothing if the call was already consumed.
  515. pass
  516. self.__timeoutCall = None
  517. else:
  518. self.__timeoutCall.reset(period)
  519. elif period is not None:
  520. self.__timeoutCall = self.callLater(period, self.__timedOut)
  521. return prev
  522. def __timedOut(self):
  523. self.__timeoutCall = None
  524. self.timeoutConnection()
  525. def timeoutConnection(self):
  526. """
  527. Called when the connection times out.
  528. Override to define behavior other than dropping the connection.
  529. """
  530. self.transport.loseConnection()