policies.py 21 KB

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