| 1 |
# |
| 2 |
# Licensed to the Apache Software Foundation (ASF) under one |
| 3 |
# or more contributor license agreements. See the NOTICE file |
| 4 |
# distributed with this work for additional information |
| 5 |
# regarding copyright ownership. The ASF licenses this file |
| 6 |
# to you under the Apache License, Version 2.0 (the |
| 7 |
# "License"); you may not use this file except in compliance |
| 8 |
# with the License. You may obtain a copy of the License at |
| 9 |
# |
| 10 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
# |
| 12 |
# Unless required by applicable law or agreed to in writing, |
| 13 |
# software distributed under the License is distributed on an |
| 14 |
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 |
# KIND, either express or implied. See the License for the |
| 16 |
# specific language governing permissions and limitations |
| 17 |
# under the License. |
| 18 |
# |
| 19 |
|
| 20 |
from __future__ import absolute_import |
| 21 |
|
| 22 |
from unittest import TestCase |
| 23 |
from unittest import SkipTest |
| 24 |
|
| 25 |
import sys |
| 26 |
import os |
| 27 |
import subprocess |
| 28 |
from random import randint |
| 29 |
from threading import Thread |
| 30 |
from socket import socket, AF_INET, SOCK_STREAM |
| 31 |
from subprocess import Popen, PIPE, STDOUT |
| 32 |
from string import Template |
| 33 |
|
| 34 |
from proton import SASL, SSL |
| 35 |
from proton.reactor import Container |
| 36 |
from proton.handlers import Handshaker, FlowController |
| 37 |
|
| 38 |
|
| 39 |
def free_tcp_ports(count=1): |
| 40 |
""" return a list of 'count' TCP ports that are free to used (ie. unbound) |
| 41 |
""" |
| 42 |
retry = 0 |
| 43 |
ports = [] |
| 44 |
sockets = [] |
| 45 |
while len(ports) != count: |
| 46 |
port = randint(49152, 65535) |
| 47 |
sockets.append(socket(AF_INET, SOCK_STREAM)) |
| 48 |
try: |
| 49 |
sockets[-1].bind(("0.0.0.0", port)) |
| 50 |
ports.append(port) |
| 51 |
retry = 0 |
| 52 |
except: |
| 53 |
retry += 1 |
| 54 |
assert retry != 100, "No free sockets available for test!" |
| 55 |
for s in sockets: |
| 56 |
s.close() |
| 57 |
return ports |
| 58 |
|
| 59 |
|
| 60 |
def free_tcp_port(): |
| 61 |
return free_tcp_ports(1)[0] |
| 62 |
|
| 63 |
|
| 64 |
def pump_uni(src, dst, buffer_size=1024): |
| 65 |
p = src.pending() |
| 66 |
c = dst.capacity() |
| 67 |
|
| 68 |
if c < 0: |
| 69 |
if p < 0: |
| 70 |
return False |
| 71 |
else: |
| 72 |
src.close_head() |
| 73 |
return True |
| 74 |
|
| 75 |
if p < 0: |
| 76 |
dst.close_tail() |
| 77 |
elif p == 0 or c == 0: |
| 78 |
return False |
| 79 |
else: |
| 80 |
binary = src.peek(min(c, buffer_size)) |
| 81 |
dst.push(binary) |
| 82 |
src.pop(len(binary)) |
| 83 |
|
| 84 |
return True |
| 85 |
|
| 86 |
|
| 87 |
def pump(transport1, transport2, buffer_size=1024): |
| 88 |
""" Transfer all pending bytes between two Proton engines |
| 89 |
by repeatedly calling peek/pop and push. |
| 90 |
Asserts that each engine accepts some bytes every time |
| 91 |
(unless it's already closed). |
| 92 |
""" |
| 93 |
while (pump_uni(transport1, transport2, buffer_size) or |
| 94 |
pump_uni(transport2, transport1, buffer_size)): |
| 95 |
pass |
| 96 |
|
| 97 |
|
| 98 |
def findfileinpath(filename, searchpath): |
| 99 |
"""Find filename in the searchpath |
| 100 |
return absolute path to the file or None |
| 101 |
""" |
| 102 |
paths = searchpath.split(os.pathsep) |
| 103 |
for path in paths: |
| 104 |
if os.path.exists(os.path.join(path, filename)): |
| 105 |
return os.path.abspath(os.path.join(path, filename)) |
| 106 |
return None |
| 107 |
|
| 108 |
|
| 109 |
def isSSLPresent(): |
| 110 |
return SSL.present() |
| 111 |
|
| 112 |
|
| 113 |
createdSASLDb = False |
| 114 |
|
| 115 |
|
| 116 |
def _cyrusSetup(conf_dir): |
| 117 |
"""Write out simple SASL config. |
| 118 |
""" |
| 119 |
saslpasswd = "" |
| 120 |
if 'SASLPASSWD' in os.environ: |
| 121 |
saslpasswd = os.environ['SASLPASSWD'] |
| 122 |
else: |
| 123 |
saslpasswd = findfileinpath('saslpasswd2', os.getenv('PATH')) or "" |
| 124 |
if os.path.exists(saslpasswd): |
| 125 |
t = Template("""sasldb_path: ${db} |
| 126 |
mech_list: EXTERNAL DIGEST-MD5 SCRAM-SHA-1 CRAM-MD5 PLAIN ANONYMOUS |
| 127 |
""") |
| 128 |
abs_conf_dir = os.path.abspath(conf_dir) |
| 129 |
subprocess.call(args=['rm', '-rf', abs_conf_dir]) |
| 130 |
os.mkdir(abs_conf_dir) |
| 131 |
db = os.path.join(abs_conf_dir, 'proton.sasldb') |
| 132 |
conf = os.path.join(abs_conf_dir, 'proton-server.conf') |
| 133 |
f = open(conf, 'w') |
| 134 |
f.write(t.substitute(db=db)) |
| 135 |
f.close() |
| 136 |
|
| 137 |
cmd_template = Template("echo password | ${saslpasswd} -c -p -f ${db} -u proton user") |
| 138 |
cmd = cmd_template.substitute(db=db, saslpasswd=saslpasswd) |
| 139 |
subprocess.call(args=cmd, shell=True) |
| 140 |
|
| 141 |
os.environ['PN_SASL_CONFIG_PATH'] = abs_conf_dir |
| 142 |
global createdSASLDb |
| 143 |
createdSASLDb = True |
| 144 |
|
| 145 |
|
| 146 |
# Globally initialize Cyrus SASL configuration |
| 147 |
if SASL.extended(): |
| 148 |
_cyrusSetup('sasl-conf') |
| 149 |
|
| 150 |
|
| 151 |
def ensureCanTestExtendedSASL(): |
| 152 |
if not SASL.extended(): |
| 153 |
raise Skipped('Extended SASL not supported') |
| 154 |
if not createdSASLDb: |
| 155 |
raise Skipped("Can't Test Extended SASL: Couldn't create auth db") |
| 156 |
|
| 157 |
|
| 158 |
class DefaultConfig: |
| 159 |
defines = {} |
| 160 |
|
| 161 |
|
| 162 |
class Test(TestCase): |
| 163 |
config = DefaultConfig() |
| 164 |
|
| 165 |
def __init__(self, name): |
| 166 |
super(Test, self).__init__(name) |
| 167 |
self.name = name |
| 168 |
|
| 169 |
def configure(self, config): |
| 170 |
self.config = config |
| 171 |
|
| 172 |
def default(self, name, value, **profiles): |
| 173 |
default = value |
| 174 |
profile = self.config.defines.get("profile") |
| 175 |
if profile: |
| 176 |
default = profiles.get(profile, default) |
| 177 |
return self.config.defines.get(name, default) |
| 178 |
|
| 179 |
@property |
| 180 |
def delay(self): |
| 181 |
return float(self.default("delay", "1", fast="0.1")) |
| 182 |
|
| 183 |
@property |
| 184 |
def timeout(self): |
| 185 |
return float(self.default("timeout", "60", fast="10")) |
| 186 |
|
| 187 |
@property |
| 188 |
def verbose(self): |
| 189 |
return int(self.default("verbose", 0)) |
| 190 |
|
| 191 |
|
| 192 |
class Skipped(SkipTest): |
| 193 |
skipped = True |
| 194 |
|
| 195 |
|
| 196 |
class TestServer(object): |
| 197 |
""" Base class for creating test-specific message servers. |
| 198 |
""" |
| 199 |
|
| 200 |
def __init__(self, **kwargs): |
| 201 |
self.args = kwargs |
| 202 |
self.reactor = Container(self) |
| 203 |
self.host = "127.0.0.1" |
| 204 |
self.port = 0 |
| 205 |
if "host" in kwargs: |
| 206 |
self.host = kwargs["host"] |
| 207 |
if "port" in kwargs: |
| 208 |
self.port = kwargs["port"] |
| 209 |
self.handlers = [FlowController(10), Handshaker()] |
| 210 |
self.thread = Thread(name="server-thread", target=self.run) |
| 211 |
self.thread.daemon = True |
| 212 |
self.running = True |
| 213 |
self.conditions = [] |
| 214 |
|
| 215 |
def start(self): |
| 216 |
self.reactor.start() |
| 217 |
retry = 0 |
| 218 |
if self.port == 0: |
| 219 |
self.port = str(randint(49152, 65535)) |
| 220 |
retry = 10 |
| 221 |
while retry > 0: |
| 222 |
try: |
| 223 |
self.acceptor = self.reactor.acceptor(self.host, self.port) |
| 224 |
break |
| 225 |
except IOError: |
| 226 |
self.port = str(randint(49152, 65535)) |
| 227 |
retry -= 1 |
| 228 |
assert retry > 0, "No free port for server to listen on!" |
| 229 |
self.thread.start() |
| 230 |
|
| 231 |
def stop(self): |
| 232 |
self.running = False |
| 233 |
self.reactor.wakeup() |
| 234 |
self.thread.join() |
| 235 |
|
| 236 |
# Note: all following methods all run under the thread: |
| 237 |
|
| 238 |
def run(self): |
| 239 |
self.reactor.timeout = 3.14159265359 |
| 240 |
while self.reactor.process(): |
| 241 |
if not self.running: |
| 242 |
self.acceptor.close() |
| 243 |
self.reactor.stop() |
| 244 |
break |
| 245 |
|
| 246 |
def on_connection_bound(self, event): |
| 247 |
if "idle_timeout" in self.args: |
| 248 |
event.transport.idle_timeout = self.args["idle_timeout"] |
| 249 |
|
| 250 |
def on_connection_local_close(self, event): |
| 251 |
self.conditions.append(event.connection.condition) |
| 252 |
|
| 253 |
def on_delivery(self, event): |
| 254 |
event.delivery.settle() |
| 255 |
|
| 256 |
# |
| 257 |
# Classes that wrap the messenger applications msgr-send and msgr-recv. |
| 258 |
# These applications reside in the c/tools directory |
| 259 |
# |
| 260 |
|
| 261 |
|
| 262 |
class MessengerApp(object): |
| 263 |
""" Interface to control a MessengerApp """ |
| 264 |
|
| 265 |
def __init__(self): |
| 266 |
self._cmdline = None |
| 267 |
# options common to Receivers and Senders: |
| 268 |
self.ca_db = None |
| 269 |
self.certificate = None |
| 270 |
self.privatekey = None |
| 271 |
self.password = None |
| 272 |
self._output = None |
| 273 |
|
| 274 |
def start(self, verbose=False): |
| 275 |
""" Begin executing the test """ |
| 276 |
cmd = self.cmdline() |
| 277 |
self._verbose = verbose |
| 278 |
if self._verbose: |
| 279 |
print("COMMAND='%s'" % str(cmd)) |
| 280 |
#print("ENV='%s'" % str(os.environ.copy())) |
| 281 |
try: |
| 282 |
# Handle python launch by replacing script 'filename' with |
| 283 |
# 'python abspath-to-filename' in cmdline arg list. |
| 284 |
if cmd[0].endswith('.py'): |
| 285 |
foundfile = findfileinpath(cmd[0], os.getenv('PATH')) |
| 286 |
if foundfile is None: |
| 287 |
msg = "Unable to locate file '%s' in PATH" % cmd[0] |
| 288 |
raise Skipped("Skipping test - %s" % msg) |
| 289 |
|
| 290 |
del cmd[0:1] |
| 291 |
cmd.insert(0, foundfile) |
| 292 |
cmd.insert(0, sys.executable) |
| 293 |
self._process = Popen(cmd, stdout=PIPE, |
| 294 |
bufsize=4096, universal_newlines=True) |
| 295 |
except OSError: |
| 296 |
e = sys.exc_info()[1] |
| 297 |
print("ERROR: '%s'" % e) |
| 298 |
msg = "Unable to execute command '%s', is it in your PATH?" % cmd[0] |
| 299 |
|
| 300 |
# NOTE(flaper87): Skip the test if the command is not found. |
| 301 |
if e.errno == 2: |
| 302 |
raise Skipped("Skipping test - %s" % msg) |
| 303 |
assert False, msg |
| 304 |
|
| 305 |
self._ready() # wait for it to initialize |
| 306 |
|
| 307 |
def stop(self): |
| 308 |
""" Signal the client to start clean shutdown """ |
| 309 |
pass |
| 310 |
|
| 311 |
def wait(self): |
| 312 |
""" Wait for client to complete """ |
| 313 |
self._output = self._process.communicate() |
| 314 |
if self._verbose: |
| 315 |
print("OUTPUT='%s'" % self.stdout()) |
| 316 |
|
| 317 |
def status(self): |
| 318 |
""" Return status from client process """ |
| 319 |
return self._process.returncode |
| 320 |
|
| 321 |
def stdout(self): |
| 322 |
# self._process.communicate()[0] |
| 323 |
if not self._output or not self._output[0]: |
| 324 |
return "*** NO STDOUT ***" |
| 325 |
return self._output[0] |
| 326 |
|
| 327 |
def stderr(self): |
| 328 |
if not self._output or not self._output[1]: |
| 329 |
return "*** NO STDERR ***" |
| 330 |
return self._output[1] |
| 331 |
|
| 332 |
def cmdline(self): |
| 333 |
if not self._cmdline: |
| 334 |
self._build_command() |
| 335 |
return self._cmdline |
| 336 |
|
| 337 |
def _build_command(self): |
| 338 |
assert False, "_build_command() needs override" |
| 339 |
|
| 340 |
def _ready(self): |
| 341 |
assert False, "_ready() needs override" |
| 342 |
|
| 343 |
def _do_common_options(self): |
| 344 |
""" Common option handling """ |
| 345 |
if self.ca_db is not None: |
| 346 |
self._cmdline.append("-T") |
| 347 |
self._cmdline.append(str(self.ca_db)) |
| 348 |
if self.certificate is not None: |
| 349 |
self._cmdline.append("-C") |
| 350 |
self._cmdline.append(str(self.certificate)) |
| 351 |
if self.privatekey is not None: |
| 352 |
self._cmdline.append("-K") |
| 353 |
self._cmdline.append(str(self.privatekey)) |
| 354 |
if self.password is not None: |
| 355 |
self._cmdline.append("-P") |
| 356 |
self._cmdline.append("pass:" + str(self.password)) |
| 357 |
|
| 358 |
|
| 359 |
class MessengerSender(MessengerApp): |
| 360 |
""" Interface to configure a sending MessengerApp """ |
| 361 |
|
| 362 |
def __init__(self): |
| 363 |
MessengerApp.__init__(self) |
| 364 |
self._command = None |
| 365 |
# @todo make these properties |
| 366 |
self.targets = [] |
| 367 |
self.send_count = None |
| 368 |
self.msg_size = None |
| 369 |
self.send_batch = None |
| 370 |
self.outgoing_window = None |
| 371 |
self.report_interval = None |
| 372 |
self.get_reply = False |
| 373 |
self.timeout = None |
| 374 |
self.incoming_window = None |
| 375 |
self.recv_count = None |
| 376 |
self.name = None |
| 377 |
|
| 378 |
# command string? |
| 379 |
def _build_command(self): |
| 380 |
self._cmdline = self._command |
| 381 |
self._do_common_options() |
| 382 |
assert self.targets, "Missing targets, required for sender!" |
| 383 |
self._cmdline.append("-a") |
| 384 |
self._cmdline.append(",".join(self.targets)) |
| 385 |
if self.send_count is not None: |
| 386 |
self._cmdline.append("-c") |
| 387 |
self._cmdline.append(str(self.send_count)) |
| 388 |
if self.msg_size is not None: |
| 389 |
self._cmdline.append("-b") |
| 390 |
self._cmdline.append(str(self.msg_size)) |
| 391 |
if self.send_batch is not None: |
| 392 |
self._cmdline.append("-p") |
| 393 |
self._cmdline.append(str(self.send_batch)) |
| 394 |
if self.outgoing_window is not None: |
| 395 |
self._cmdline.append("-w") |
| 396 |
self._cmdline.append(str(self.outgoing_window)) |
| 397 |
if self.report_interval is not None: |
| 398 |
self._cmdline.append("-e") |
| 399 |
self._cmdline.append(str(self.report_interval)) |
| 400 |
if self.get_reply: |
| 401 |
self._cmdline.append("-R") |
| 402 |
if self.timeout is not None: |
| 403 |
self._cmdline.append("-t") |
| 404 |
self._cmdline.append(str(self.timeout)) |
| 405 |
if self.incoming_window is not None: |
| 406 |
self._cmdline.append("-W") |
| 407 |
self._cmdline.append(str(self.incoming_window)) |
| 408 |
if self.recv_count is not None: |
| 409 |
self._cmdline.append("-B") |
| 410 |
self._cmdline.append(str(self.recv_count)) |
| 411 |
if self.name is not None: |
| 412 |
self._cmdline.append("-N") |
| 413 |
self._cmdline.append(str(self.name)) |
| 414 |
|
| 415 |
def _ready(self): |
| 416 |
pass |
| 417 |
|
| 418 |
|
| 419 |
class MessengerReceiver(MessengerApp): |
| 420 |
""" Interface to configure a receiving MessengerApp """ |
| 421 |
|
| 422 |
def __init__(self): |
| 423 |
MessengerApp.__init__(self) |
| 424 |
self._command = None |
| 425 |
# @todo make these properties |
| 426 |
self.subscriptions = [] |
| 427 |
self.receive_count = None |
| 428 |
self.recv_count = None |
| 429 |
self.incoming_window = None |
| 430 |
self.timeout = None |
| 431 |
self.report_interval = None |
| 432 |
self.send_reply = False |
| 433 |
self.outgoing_window = None |
| 434 |
self.forwards = [] |
| 435 |
self.name = None |
| 436 |
|
| 437 |
# command string? |
| 438 |
def _build_command(self): |
| 439 |
self._cmdline = os.environ.get("TEST_EXE_PREFIX", "").split() |
| 440 |
self._cmdline += self._command |
| 441 |
self._do_common_options() |
| 442 |
self._cmdline += ["-X", "READY"] |
| 443 |
assert self.subscriptions, "Missing subscriptions, required for receiver!" |
| 444 |
self._cmdline.append("-a") |
| 445 |
self._cmdline.append(",".join(self.subscriptions)) |
| 446 |
if self.receive_count is not None: |
| 447 |
self._cmdline.append("-c") |
| 448 |
self._cmdline.append(str(self.receive_count)) |
| 449 |
if self.recv_count is not None: |
| 450 |
self._cmdline.append("-b") |
| 451 |
self._cmdline.append(str(self.recv_count)) |
| 452 |
if self.incoming_window is not None: |
| 453 |
self._cmdline.append("-w") |
| 454 |
self._cmdline.append(str(self.incoming_window)) |
| 455 |
if self.timeout is not None: |
| 456 |
self._cmdline.append("-t") |
| 457 |
self._cmdline.append(str(self.timeout)) |
| 458 |
if self.report_interval is not None: |
| 459 |
self._cmdline.append("-e") |
| 460 |
self._cmdline.append(str(self.report_interval)) |
| 461 |
if self.send_reply: |
| 462 |
self._cmdline.append("-R") |
| 463 |
if self.outgoing_window is not None: |
| 464 |
self._cmdline.append("-W") |
| 465 |
self._cmdline.append(str(self.outgoing_window)) |
| 466 |
if self.forwards: |
| 467 |
self._cmdline.append("-F") |
| 468 |
self._cmdline.append(",".join(self.forwards)) |
| 469 |
if self.name is not None: |
| 470 |
self._cmdline.append("-N") |
| 471 |
self._cmdline.append(str(self.name)) |
| 472 |
|
| 473 |
def _ready(self): |
| 474 |
""" wait for subscriptions to complete setup. """ |
| 475 |
r = self._process.stdout.readline() |
| 476 |
assert r.strip() == "READY", "Unexpected input while waiting for receiver to initialize: %s" % r |
| 477 |
|
| 478 |
|
| 479 |
class MessengerSenderC(MessengerSender): |
| 480 |
def __init__(self): |
| 481 |
MessengerSender.__init__(self) |
| 482 |
self._command = ["msgr-send"] |
| 483 |
|
| 484 |
|
| 485 |
class MessengerReceiverC(MessengerReceiver): |
| 486 |
def __init__(self): |
| 487 |
MessengerReceiver.__init__(self) |
| 488 |
self._command = ["msgr-recv"] |
| 489 |
|
| 490 |
|
| 491 |
class ReactorSenderC(MessengerSender): |
| 492 |
def __init__(self): |
| 493 |
MessengerSender.__init__(self) |
| 494 |
self._command = ["reactor-send"] |
| 495 |
|
| 496 |
|
| 497 |
class ReactorReceiverC(MessengerReceiver): |
| 498 |
def __init__(self): |
| 499 |
MessengerReceiver.__init__(self) |
| 500 |
self._command = ["reactor-recv"] |