/usr/lib/python2.7/dist-packages/twext/web2/test/test_metafd.py is in calendarserver 5.2+dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | ##
# Copyright (c) 2011-2014 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
"""
Tests for twext.web2.metafd.
"""
from socket import error as SocketError, AF_INET
from errno import ENOTCONN
from twext.internet import sendfdport
from twext.web2 import metafd
from twext.web2.channel.http import HTTPChannel
from twext.web2.metafd import ReportingHTTPService, ConnectionLimiter
from twisted.internet.tcp import Server
from twisted.application.service import Service
from twext.internet.test.test_sendfdport import ReaderAdder
from twext.web2.metafd import WorkerStatus
from twisted.trial.unittest import TestCase
class FakeSocket(object):
"""
A fake socket for testing.
"""
def __init__(self, test):
self.test = test
def fileno(self):
return "not a socket"
def setblocking(self, blocking):
return
def getpeername(self):
if self.test.peerNameSucceed:
return ("4.3.2.1", 4321)
else:
raise SocketError(ENOTCONN, "Transport endpoint not connected")
def getsockname(self):
return ("4.3.2.1", 4321)
class InheritedPortForTesting(sendfdport.InheritedPort):
"""
L{sendfdport.InheritedPort} subclass that prevents certain I/O operations
for better unit testing.
"""
def startReading(self):
"Do nothing."
def stopReading(self):
"Do nothing."
def startWriting(self):
"Do nothing."
def stopWriting(self):
"Do nothing."
class ServerTransportForTesting(Server):
"""
tcp.Server replacement for testing purposes.
"""
def startReading(self):
"Do nothing."
def stopReading(self):
"Do nothing."
def startWriting(self):
"Do nothing."
def stopWriting(self):
"Do nothing."
def __init__(self, *a, **kw):
super(ServerTransportForTesting, self).__init__(*a, **kw)
self.reactor = None
class ReportingHTTPServiceTests(TestCase):
"""
Tests for L{ReportingHTTPService}
"""
peerNameSucceed = True
def setUp(self):
def fakefromfd(fd, addressFamily, socketType):
return FakeSocket(self)
def fakerecvfd(fd):
return "not an fd", "not a description"
def fakeclose(fd):
""
def fakegetsockfam(fd):
return AF_INET
self.patch(sendfdport, 'recvfd', fakerecvfd)
self.patch(sendfdport, 'fromfd', fakefromfd)
self.patch(sendfdport, 'close', fakeclose)
self.patch(sendfdport, 'getsockfam', fakegetsockfam)
self.patch(metafd, 'InheritedPort', InheritedPortForTesting)
self.patch(metafd, 'Server', ServerTransportForTesting)
# This last stubbed out just to prevent dirty reactor warnings.
self.patch(HTTPChannel, "callLater", lambda *a, **k: None)
self.svc = ReportingHTTPService(None, None, None)
self.svc.startService()
def test_quickClosedSocket(self):
"""
If a socket is closed very quickly after being {accept()}ed, requesting
its peer (or even host) address may fail with C{ENOTCONN}. If this
happens, its transport should be supplied with a dummy peer address.
"""
self.peerNameSucceed = False
self.svc.reportingFactory.inheritedPort.doRead()
channels = self.svc.reportingFactory.connectedChannels
self.assertEqual(len(channels), 1)
self.assertEqual(list(channels)[0].transport.getPeer().host, "0.0.0.0")
class ConnectionLimiterTests(TestCase):
"""
Tests for L{ConnectionLimiter}
"""
def test_loadReducedStartsReadingAgain(self):
"""
L{ConnectionLimiter.statusesChanged} determines whether the current
"load" of all subprocesses - that is, the total outstanding request
count - is high enough that the listening ports attached to it should
be suspended.
"""
builder = LimiterBuilder(self)
builder.fillUp()
self.assertEquals(builder.port.reading, False) # sanity check
self.assertEquals(builder.highestLoad(), builder.requestsPerSocket)
builder.loadDown()
self.assertEquals(builder.port.reading, True)
def test_processRestartedStartsReadingAgain(self):
"""
L{ConnectionLimiter.statusesChanged} determines whether the current
number of outstanding requests is above the limit, and either stops or
resumes reading on the listening port.
"""
builder = LimiterBuilder(self)
builder.fillUp()
self.assertEquals(builder.port.reading, False)
self.assertEquals(builder.highestLoad(), builder.requestsPerSocket)
builder.processRestart()
self.assertEquals(builder.port.reading, True)
def test_unevenLoadDistribution(self):
"""
Subprocess sockets should be selected for subsequent socket sends by
ascending status. Status should sum sent and successfully subsumed
sockets.
"""
builder = LimiterBuilder(self)
# Give one simulated worker a higher acknowledged load than the other.
builder.fillUp(True, 1)
# There should still be plenty of spare capacity.
self.assertEquals(builder.port.reading, True)
# Then slam it with a bunch of incoming requests.
builder.fillUp(False, builder.limiter.maxRequests - 1)
# Now capacity is full.
self.assertEquals(builder.port.reading, False)
# And everyone should have an even amount of work.
self.assertEquals(builder.highestLoad(), builder.requestsPerSocket)
def test_processStopsReadingEvenWhenConnectionsAreNotAcknowledged(self):
"""
L{ConnectionLimiter.statusesChanged} determines whether the current
number of outstanding requests is above the limit.
"""
builder = LimiterBuilder(self)
builder.fillUp(acknowledged=False)
self.assertEquals(builder.highestLoad(), builder.requestsPerSocket)
self.assertEquals(builder.port.reading, False)
builder.processRestart()
self.assertEquals(builder.port.reading, True)
def test_workerStatusRepr(self):
"""
L{WorkerStatus.__repr__} will show all the values associated with the
status of the worker.
"""
self.assertEquals(repr(WorkerStatus(1, 2, 3, 4, 5, 6, 7, 8)),
"<WorkerStatus acknowledged=1 unacknowledged=2 total=3 "
"started=4 abandoned=5 unclosed=6 starting=7 stopped=8>")
def test_workerStatusNonNegative(self):
"""
L{WorkerStatus.__repr__} will show all the values associated with the
status of the worker.
"""
w = WorkerStatus()
w.adjust(
acknowledged=1,
unacknowledged=-1,
total=1,
)
self.assertEquals(w.acknowledged, 1)
self.assertEquals(w.unacknowledged, 0)
self.assertEquals(w.total, 1)
class LimiterBuilder(object):
"""
A L{LimiterBuilder} can build a L{ConnectionLimiter} and associated objects
for a given unit test.
"""
def __init__(self, test, requestsPerSocket=3, socketCount=2):
# Similar to MaxRequests in the configuration.
self.requestsPerSocket = requestsPerSocket
# Similar to ProcessCount in the configuration.
self.socketCount = socketCount
self.limiter = ConnectionLimiter(
2, maxRequests=requestsPerSocket * socketCount
)
self.dispatcher = self.limiter.dispatcher
self.dispatcher.reactor = ReaderAdder()
self.service = Service()
self.limiter.addPortService("TCP", 4321, "127.0.0.1", 5,
self.serverServiceMakerMaker(self.service))
for ignored in xrange(socketCount):
subskt = self.dispatcher.addSocket()
subskt.start()
subskt.restarted()
# Has to be running in order to add stuff.
self.limiter.startService()
self.port = self.service.myPort
def highestLoad(self):
return max(
skt.status.effective()
for skt in self.limiter.dispatcher._subprocessSockets
)
def serverServiceMakerMaker(self, s):
"""
Make a serverServiceMaker for use with
L{ConnectionLimiter.addPortService}.
"""
class NotAPort(object):
def startReading(self):
self.reading = True
def stopReading(self):
self.reading = False
def serverServiceMaker(port, factory, *a, **k):
s.factory = factory
s.myPort = NotAPort()
# TODO: technically, the following should wait for startService
s.myPort.startReading()
factory.myServer = s
return s
return serverServiceMaker
def fillUp(self, acknowledged=True, count=0):
"""
Fill up all the slots on the connection limiter.
@param acknowledged: Should the virtual connections created by this
method send a message back to the dispatcher indicating that the
subprocess has acknowledged receipt of the file descriptor?
@param count: Amount of load to add; default to the maximum that the
limiter.
"""
for _ignore_x in range(count or self.limiter.maxRequests):
self.dispatcher.sendFileDescriptor(None, "SSL")
if acknowledged:
self.dispatcher.statusMessage(
self.dispatcher._subprocessSockets[0], "+"
)
def processRestart(self):
self.dispatcher._subprocessSockets[0].stop()
self.dispatcher._subprocessSockets[0].start()
self.dispatcher.statusMessage(
self.dispatcher._subprocessSockets[0], "0"
)
def loadDown(self):
self.dispatcher.statusMessage(
self.dispatcher._subprocessSockets[0], "-"
)
|