Skip to content

Apache DataFusion SQL Query Engine

ARROW-6165: [Integration] Run integration tests on multiple cores

Antoine Pitrou978140f83bd9
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 2fd4bfac6d..623ee7493a 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -22,7 +22,9 @@ on:
paths:
- '.github/workflows/integration.yml'
- 'ci/**'
+ - 'dev/archery/**'
- 'go/**'
+ - 'integration/**'
- 'js/**'
- 'cpp/**'
- 'java/**'
@@ -31,7 +33,9 @@ on:
paths:
- '.github/workflows/integration.yml'
- 'ci/**'
+ - 'dev/archery/**'
- 'go/**'
+ - 'integration/**'
- 'js/**'
- 'cpp/**'
- 'java/**'
diff --git a/ci/docker/conda-integration.dockerfile b/ci/docker/conda-integration.dockerfile
index b29ae4ed04..ee970b6b22 100644
--- a/ci/docker/conda-integration.dockerfile
+++ b/ci/docker/conda-integration.dockerfile
@@ -39,6 +39,7 @@ ENV GOROOT=/opt/go \
RUN wget -nv -O - https://dl.google.com/go/go${go}.linux-${arch}.tar.gz | tar -xzf - -C /opt
ENV ARROW_BUILD_INTEGRATION=ON \
+ ARROW_BUILD_TESTS=OFF \
ARROW_FLIGHT=ON \
ARROW_ORC=OFF \
ARROW_DATASET=OFF \
diff --git a/dev/archery/archery/cli.py b/dev/archery/archery/cli.py
index f0156e4ee5..b470629a19 100644
--- a/dev/archery/archery/cli.py
+++ b/dev/archery/archery/cli.py
@@ -498,8 +498,10 @@ def _set_default(opt, default):
help='Generate test JSON to indicated path')
@click.option('--run-flight', is_flag=True, default=False,
help='Run Flight integration tests')
[email protected]('--debug', type=bool, default=False,
[email protected]('--debug', is_flag=True, default=False,
help='Run executables in debug mode as relevant')
[email protected]('--serial', is_flag=True, default=False,
+ help='Run tests serially, rather than in parallel')
@click.option('--tempdir', default=None,
help=('Directory to use for writing '
'integration test temporary files'))
diff --git a/dev/archery/archery/integration/runner.py b/dev/archery/archery/integration/runner.py
index 60ee8f3b85..bad7b16c22 100644
--- a/dev/archery/archery/integration/runner.py
+++ b/dev/archery/archery/integration/runner.py
@@ -15,6 +15,9 @@
# specific language governing permissions and limitations
# under the License.
+from collections import namedtuple
+from concurrent.futures import ThreadPoolExecutor
+from functools import partial
import glob
import gzip
import itertools
@@ -27,57 +30,74 @@ from .tester_cpp import CPPTester
from .tester_go import GoTester
from .tester_java import JavaTester
from .tester_js import JSTester
-from .util import ARROW_ROOT_DEFAULT, guid, SKIP_ARROW, SKIP_FLIGHT
+from .util import (ARROW_ROOT_DEFAULT, guid, SKIP_ARROW, SKIP_FLIGHT,
+ find_unused_port, printer)
from . import datagen
+Failure = namedtuple('Failure',
+ ('test_case', 'producer', 'consumer', 'exc_info'))
+
+log = printer.print
+
+
+class Outcome:
+ def __init__(self):
+ self.failure = None
+ self.skipped = False
+
+
class IntegrationRunner(object):
def __init__(self, json_files, testers, tempdir=None, debug=False,
- stop_on_error=True, gold_dirs=None, **unused_kwargs):
+ stop_on_error=True, gold_dirs=None, serial=False,
+ **unused_kwargs):
self.json_files = json_files
self.testers = testers
self.temp_dir = tempdir or tempfile.mkdtemp()
self.debug = debug
self.stop_on_error = stop_on_error
+ self.serial = serial
self.gold_dirs = gold_dirs
+ self.failures = []
def run(self):
- failures = []
-
+ """
+ Run Arrow IPC integration tests for the matrix of enabled
+ implementations.
+ """
for producer, consumer in itertools.product(
filter(lambda t: t.PRODUCER, self.testers),
filter(lambda t: t.CONSUMER, self.testers)):
- for failure in self._compare_implementations(
- producer, consumer, self._produce_consume, self.json_files):
- failures.append(failure)
+ self._compare_implementations(
+ producer, consumer, self._produce_consume,
+ self.json_files)
if self.gold_dirs:
for gold_dir, consumer in itertools.product(
self.gold_dirs,
filter(lambda t: t.CONSUMER, self.testers)):
- print('\n\n\n\n')
- print('******************************************************')
- print('Tests against golden files in {}'.format(gold_dir))
- print('******************************************************')
-
- def run_gold(producer, consumer, test_case):
- self._run_gold(gold_dir, producer, consumer, test_case)
- for failure in self._compare_implementations(
- consumer, consumer, run_gold, self._gold_tests(gold_dir)):
- failures.append(failure)
-
- return failures
+ log('\n\n\n\n')
+ log('******************************************************')
+ log('Tests against golden files in {}'.format(gold_dir))
+ log('******************************************************')
+
+ def run_gold(producer, consumer, outcome, test_case):
+ self._run_gold(gold_dir, producer, consumer, outcome,
+ test_case)
+ self._compare_implementations(
+ consumer, consumer, run_gold,
+ self._gold_tests(gold_dir))
def run_flight(self):
- failures = []
+ """
+ Run Arrow Flight integration tests for the matrix of enabled
+ implementations.
+ """
servers = filter(lambda t: t.FLIGHT_SERVER, self.testers)
clients = filter(lambda t: (t.FLIGHT_CLIENT and t.CONSUMER),
self.testers)
for server, client in itertools.product(servers, clients):
- for failure in self._compare_flight_implementations(server,
- client):
- failures.append(failure)
- return failures
+ self._compare_flight_implementations(server, client)
def _gold_tests(self, gold_dir):
prefix = os.path.basename(os.path.normpath(gold_dir))
@@ -98,45 +118,80 @@ class IntegrationRunner(object):
skip = set()
yield datagen.JsonFile(name, None, None, skip=skip, path=out_path)
+ def _run_test_cases(self, producer, consumer, case_runner,
+ test_cases):
+ def case_wrapper(test_case):
+ with printer.cork():
+ return case_runner(test_case)
+
+ if self.failures and self.stop_on_error:
+ return
+
+ if self.serial:
+ for outcome in map(case_wrapper, test_cases):
+ if outcome.failure is not None:
+ self.failures.append(outcome.failure)
+ if self.stop_on_error:
+ break
+
+ else:
+ with ThreadPoolExecutor() as executor:
+ for outcome in executor.map(case_wrapper, test_cases):
+ if outcome.failure is not None:
+ self.failures.append(outcome.failure)
+ if self.stop_on_error:
+ break
+
def _compare_implementations(
self, producer, consumer, run_binaries, test_cases):
- print('##########################################################')
- print(
- '{0} producing, {1} consuming'.format(producer.name, consumer.name)
- )
- print('##########################################################')
-
- for test_case in test_cases:
- json_path = test_case.path
- print('==========================================================')
- print('Testing file {0}'.format(json_path))
- print('==========================================================')
-
- if producer.name in test_case.skip:
- print('-- Skipping test because producer {0} does '
- 'not support'.format(producer.name))
- continue
-
- if consumer.name in test_case.skip:
- print('-- Skipping test because consumer {0} does '
- 'not support'.format(consumer.name))
- continue
-
- if SKIP_ARROW in test_case.skip:
- print('-- Skipping test')
- continue
+ """
+ Compare Arrow IPC for two implementations (one producer, one consumer).
+ """
+ log('##########################################################')
+ log('IPC: {0} producing, {1} consuming'
+ .format(producer.name, consumer.name))
+ log('##########################################################')
+
+ case_runner = partial(self._run_ipc_test_case,
+ producer, consumer, run_binaries)
+ self._run_test_cases(producer, consumer, case_runner, test_cases)
+
+ def _run_ipc_test_case(self, producer, consumer, run_binaries, test_case):
+ """
+ Run one IPC test case.
+ """
+ outcome = Outcome()
+
+ json_path = test_case.path
+ log('==========================================================')
+ log('Testing file {0}'.format(json_path))
+ log('==========================================================')
+
+ if producer.name in test_case.skip:
+ log('-- Skipping test because producer {0} does '
+ 'not support'.format(producer.name))
+ outcome.skipped = True
+
+ elif consumer.name in test_case.skip:
+ log('-- Skipping test because consumer {0} does '
+ 'not support'.format(consumer.name))
+ outcome.skipped = True
+ elif SKIP_ARROW in test_case.skip:
+ log('-- Skipping test')
+ outcome.skipped = True
+
+ else:
try:
- run_binaries(producer, consumer, test_case)
+ run_binaries(producer, consumer, outcome, test_case)
except Exception:
- traceback.print_exc()
- yield (test_case, producer, consumer, sys.exc_info())
- if self.stop_on_error:
- break
- else:
- continue
-
- def _produce_consume(self, producer, consumer, test_case):
+ traceback.print_exc(file=printer.stdout)
+ outcome.failure = Failure(test_case, producer, consumer,
+ sys.exc_info())
+
+ return outcome
+
+ def _produce_consume(self, producer, consumer, outcome, test_case):
# Make the random access file
json_path = test_case.path
file_id = guid()[:8]
@@ -149,28 +204,28 @@ class IntegrationRunner(object):
consumer_file_path = os.path.join(self.temp_dir, file_id + '_' +
name + '.consumer_stream_as_file')
- print('-- Creating binary inputs')
+ log('-- Creating binary inputs')
producer.json_to_file(json_path, producer_file_path)
# Validate the file
- print('-- Validating file')
+ log('-- Validating file')
consumer.validate(json_path, producer_file_path)
- print('-- Validating stream')
+ log('-- Validating stream')
producer.file_to_stream(producer_file_path, producer_stream_path)
consumer.stream_to_file(producer_stream_path, consumer_file_path)
consumer.validate(json_path, consumer_file_path)
- def _run_gold(self, gold_dir, producer, consumer, test_case):
+ def _run_gold(self, gold_dir, producer, consumer, outcome, test_case):
json_path = test_case.path
# Validate the file
- print('-- Validating file')
+ log('-- Validating file')
producer_file_path = os.path.join(
gold_dir, "generated_" + test_case.name + ".arrow_file")
consumer.validate(json_path, producer_file_path)
- print('-- Validating stream')
+ log('-- Validating stream')
consumer_stream_path = os.path.join(
gold_dir, "generated_" + test_case.name + ".stream")
file_id = guid()[:8]
@@ -183,38 +238,49 @@ class IntegrationRunner(object):
consumer.validate(json_path, consumer_file_path)
def _compare_flight_implementations(self, producer, consumer):
- print('##########################################################')
- print(
- '{0} serving, {1} requesting'.format(producer.name, consumer.name)
- )
- print('##########################################################')
-
- for test_case in self.json_files:
- json_path = test_case.path
- print('=' * 58)
- print('Testing file {0}'.format(json_path))
- print('=' * 58)
-
- if ('Java' in (producer.name, consumer.name) and
- "map" in test_case.name):
- print('TODO(ARROW-1279): Enable map tests ' +
- ' for Java and JS once Java supports them and JS\'' +
- ' are unbroken')
- continue
-
- if SKIP_FLIGHT in test_case.skip:
- print('-- Skipping test')
- continue
+ log('##########################################################')
+ log('Flight: {0} serving, {1} requesting'
+ .format(producer.name, consumer.name))
+ log('##########################################################')
+
+ case_runner = partial(self._run_flight_test_case, producer, consumer)
+ self._run_test_cases(producer, consumer, case_runner, self.json_files)
+
+ def _run_flight_test_case(self, producer, consumer, test_case):
+ """
+ Run one Flight test case.
+ """
+ outcome = Outcome()
+ json_path = test_case.path
+ log('=' * 58)
+ log('Testing file {0}'.format(json_path))
+ log('=' * 58)
+
+ if ('Java' in (producer.name, consumer.name) and
+ "map" in test_case.name):
+ log('TODO(ARROW-1279): Enable map tests ' +
+ ' for Java and JS once Java supports them and JS\'' +
+ ' are unbroken')
+ outcome.skipped = True
+
+ elif SKIP_FLIGHT in test_case.skip:
+ log('-- Skipping test')
+ outcome.skipped = True
+
+ else:
try:
- with producer.flight_server():
+ port = find_unused_port()
+ with producer.flight_server(port):
# Have the client upload the file, then download and
# compare
- consumer.flight_request(producer.FLIGHT_PORT, json_path)
+ consumer.flight_request(port, json_path)
except Exception:
- traceback.print_exc()
- yield (test_case, producer, consumer, sys.exc_info())
- continue
+ traceback.print_exc(file=printer.stdout)
+ outcome.failure = Failure(test_case, producer, consumer,
+ sys.exc_info())
+
+ return outcome
def get_static_json_files():
@@ -235,16 +301,16 @@ def run_all_tests(with_cpp=True, with_java=True, with_js=True,
testers = []
if with_cpp:
- testers.append(CPPTester(kwargs))
+ testers.append(CPPTester(**kwargs))
if with_java:
- testers.append(JavaTester(kwargs))
+ testers.append(JavaTester(**kwargs))
if with_js:
- testers.append(JSTester(kwargs))
+ testers.append(JSTester(**kwargs))
if with_go:
- testers.append(GoTester(kwargs))
+ testers.append(GoTester(**kwargs))
static_json_files = get_static_json_files()
generated_json_files = datagen.get_generated_json_files(
@@ -254,24 +320,23 @@ def run_all_tests(with_cpp=True, with_java=True, with_js=True,
json_files = static_json_files + generated_json_files
runner = IntegrationRunner(json_files, testers, **kwargs)
- failures = []
- failures.extend(runner.run())
+ runner.run()
if run_flight:
- failures.extend(runner.run_flight())
+ runner.run_flight()
fail_count = 0
- if failures:
- print("################# FAILURES #################")
- for test_case, producer, consumer, exc_info in failures:
+ if runner.failures:
+ log("################# FAILURES #################")
+ for test_case, producer, consumer, exc_info in runner.failures:
fail_count += 1
- print("FAILED TEST:", end=" ")
- print(test_case.name, producer.name, "producing, ",
- consumer.name, "consuming")
+ log("FAILED TEST:", end=" ")
+ log(test_case.name, producer.name, "producing, ",
+ consumer.name, "consuming")
if exc_info:
traceback.print_exception(*exc_info)
- print()
+ log()
- print(fail_count, "failures")
+ log(fail_count, "failures")
if fail_count > 0:
sys.exit(1)
diff --git a/dev/archery/archery/integration/tester.py b/dev/archery/archery/integration/tester.py
index e3f075a36c..85ed2214d4 100644
--- a/dev/archery/archery/integration/tester.py
+++ b/dev/archery/archery/integration/tester.py
@@ -19,13 +19,14 @@
import subprocess
+from .util import log
+
class Tester(object):
PRODUCER = False
CONSUMER = False
FLIGHT_SERVER = False
FLIGHT_CLIENT = False
- FLIGHT_PORT = 31337
def __init__(self, debug=False, **args):
self.args = args
@@ -34,7 +35,7 @@ class Tester(object):
def run_shell_command(self, cmd):
cmd = ' '.join(cmd)
if self.debug:
- print(cmd)
+ log(cmd)
subprocess.check_call(cmd, shell=True)
def json_to_file(self, json_path, arrow_path):
@@ -49,7 +50,7 @@ class Tester(object):
def validate(self, json_path, arrow_path):
raise NotImplementedError
- def flight_server(self):
+ def flight_server(self, port):
raise NotImplementedError
def flight_request(self, port, json_path):
diff --git a/dev/archery/archery/integration/tester_cpp.py b/dev/archery/archery/integration/tester_cpp.py
index 541aaf27ac..f0fd3fc286 100644
--- a/dev/archery/archery/integration/tester_cpp.py
+++ b/dev/archery/archery/integration/tester_cpp.py
@@ -20,7 +20,7 @@ import os
import subprocess
from .tester import Tester
-from .util import run_cmd, ARROW_ROOT_DEFAULT
+from .util import run_cmd, ARROW_ROOT_DEFAULT, log
class CPPTester(Tester):
@@ -37,11 +37,8 @@ class CPPTester(Tester):
STREAM_TO_FILE = os.path.join(EXE_PATH, 'arrow-stream-to-file')
FILE_TO_STREAM = os.path.join(EXE_PATH, 'arrow-file-to-stream')
- FLIGHT_PORT = 31337
-
FLIGHT_SERVER_CMD = [
- os.path.join(EXE_PATH, 'flight-test-integration-server'),
- "-port", str(FLIGHT_PORT)]
+ os.path.join(EXE_PATH, 'flight-test-integration-server')]
FLIGHT_CLIENT_CMD = [
os.path.join(EXE_PATH, 'flight-test-integration-client'),
"-host", "localhost"]
@@ -60,7 +57,7 @@ class CPPTester(Tester):
cmd.append('--mode=' + command)
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
@@ -71,7 +68,7 @@ class CPPTester(Tester):
return self._run(arrow_path, json_path, 'JSON_TO_ARROW')
def stream_to_file(self, stream_path, file_path):
- cmd = ['cat', stream_path, '|', self.STREAM_TO_FILE, '>', file_path]
+ cmd = [self.STREAM_TO_FILE, '<', stream_path, '>', file_path]
self.run_shell_command(cmd)
def file_to_stream(self, file_path, stream_path):
@@ -79,17 +76,22 @@ class CPPTester(Tester):
self.run_shell_command(cmd)
@contextlib.contextmanager
- def flight_server(self):
+ def flight_server(self, port):
+ cmd = self.FLIGHT_SERVER_CMD + ['-port=' + str(port)]
if self.debug:
- print(' '.join(self.FLIGHT_SERVER_CMD))
- server = subprocess.Popen(self.FLIGHT_SERVER_CMD,
- stdout=subprocess.PIPE)
+ log(' '.join(cmd))
+ server = subprocess.Popen(cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
try:
output = server.stdout.readline().decode()
if not output.startswith("Server listening on localhost"):
+ server.kill()
+ out, err = server.communicate()
raise RuntimeError(
- "Flight-C++ server did not start properly, output: " +
- output)
+ "Flight-C++ server did not start properly, "
+ "stdout:\n{}\n\nstderr:\n{}\n"
+ .format(output + out.decode(), err.decode()))
yield
finally:
server.kill()
@@ -101,5 +103,5 @@ class CPPTester(Tester):
'-path=' + json_path,
]
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
diff --git a/dev/archery/archery/integration/tester_go.py b/dev/archery/archery/integration/tester_go.py
index 27df4d1f5b..5dda81dfc2 100644
--- a/dev/archery/archery/integration/tester_go.py
+++ b/dev/archery/archery/integration/tester_go.py
@@ -18,7 +18,7 @@
import os
from .tester import Tester
-from .util import run_cmd
+from .util import run_cmd, log
class GoTester(Tester):
@@ -47,7 +47,7 @@ class GoTester(Tester):
cmd.extend(['-mode', command])
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
@@ -58,7 +58,7 @@ class GoTester(Tester):
return self._run(arrow_path, json_path, 'JSON_TO_ARROW')
def stream_to_file(self, stream_path, file_path):
- cmd = ['cat', stream_path, '|', self.STREAM_TO_FILE, '>', file_path]
+ cmd = [self.STREAM_TO_FILE, '<', stream_path, '>', file_path]
self.run_shell_command(cmd)
def file_to_stream(self, file_path, stream_path):
diff --git a/dev/archery/archery/integration/tester_java.py b/dev/archery/archery/integration/tester_java.py
index 43e8e311df..bdfe3429ce 100644
--- a/dev/archery/archery/integration/tester_java.py
+++ b/dev/archery/archery/integration/tester_java.py
@@ -20,7 +20,7 @@ import os
import subprocess
from .tester import Tester
-from .util import run_cmd, ARROW_ROOT_DEFAULT
+from .util import run_cmd, ARROW_ROOT_DEFAULT, log
def load_version_from_pom():
@@ -37,8 +37,6 @@ class JavaTester(Tester):
FLIGHT_SERVER = True
FLIGHT_CLIENT = True
- FLIGHT_PORT = 31338
-
JAVA_OPTS = ['-Dio.netty.tryReflectionSetAccessible=true']
_arrow_version = load_version_from_pom()
@@ -72,7 +70,7 @@ class JavaTester(Tester):
cmd.extend(['-c', command])
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
@@ -87,7 +85,7 @@ class JavaTester(Tester):
['-cp', self.ARROW_TOOLS_JAR,
'org.apache.arrow.tools.StreamToFile', stream_path, file_path]
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
def file_to_stream(self, file_path, stream_path):
@@ -95,7 +93,7 @@ class JavaTester(Tester):
['-cp', self.ARROW_TOOLS_JAR,
'org.apache.arrow.tools.FileToStream', file_path, stream_path]
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
def flight_request(self, port, json_path):
@@ -103,23 +101,27 @@ class JavaTester(Tester):
['-cp', self.ARROW_FLIGHT_JAR, self.ARROW_FLIGHT_CLIENT,
'-port', str(port), '-j', json_path]
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
@contextlib.contextmanager
- def flight_server(self):
+ def flight_server(self, port):
cmd = ['java'] + self.JAVA_OPTS + \
['-cp', self.ARROW_FLIGHT_JAR, self.ARROW_FLIGHT_SERVER,
- '-port', str(self.FLIGHT_PORT)]
+ '-port', str(port)]
if self.debug:
- print(' '.join(cmd))
- server = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ log(' '.join(cmd))
+ server = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
try:
output = server.stdout.readline().decode()
if not output.startswith("Server listening on localhost"):
+ server.kill()
+ out, err = server.communicate()
raise RuntimeError(
- "Flight-Java server did not start properly, output: " +
- output)
+ "Flight-Java server did not start properly, "
+ "stdout:\n{}\n\nstderr:\n{}\n"
+ .format(output + out.decode(), err.decode()))
yield
finally:
server.kill()
diff --git a/dev/archery/archery/integration/tester_js.py b/dev/archery/archery/integration/tester_js.py
index 34939d040e..e24eec0cad 100644
--- a/dev/archery/archery/integration/tester_js.py
+++ b/dev/archery/archery/integration/tester_js.py
@@ -18,7 +18,7 @@
import os
from .tester import Tester
-from .util import run_cmd, ARROW_ROOT_DEFAULT
+from .util import run_cmd, ARROW_ROOT_DEFAULT, log
class JSTester(Tester):
@@ -46,7 +46,7 @@ class JSTester(Tester):
cmd.extend(['--mode', command])
if self.debug:
- print(' '.join(cmd))
+ log(' '.join(cmd))
run_cmd(cmd)
@@ -61,13 +61,13 @@ class JSTester(Tester):
self.run_shell_command(cmd)
def stream_to_file(self, stream_path, file_path):
- cmd = ['cat', stream_path, '|',
- 'node', '--no-warnings', self.STREAM_TO_FILE, '>',
- file_path]
+ cmd = ['node', '--no-warnings', self.STREAM_TO_FILE,
+ '<', stream_path,
+ '>', file_path]
self.run_shell_command(cmd)
def file_to_stream(self, file_path, stream_path):
- cmd = ['cat', file_path, '|',
- 'node', '--no-warnings', self.FILE_TO_STREAM, '>',
- stream_path]
+ cmd = ['node', '--no-warnings', self.FILE_TO_STREAM,
+ '<', file_path,
+ '>', stream_path]
self.run_shell_command(cmd)
diff --git a/dev/archery/archery/integration/util.py b/dev/archery/archery/integration/util.py
index 98d648a514..75f6e9ac4f 100644
--- a/dev/archery/archery/integration/util.py
+++ b/dev/archery/archery/integration/util.py
@@ -15,9 +15,14 @@
# specific language governing permissions and limitations
# under the License.
+import contextlib
+import io
import os
+import socket
import string
import subprocess
+import sys
+import threading
import uuid
import numpy as np
@@ -40,6 +45,61 @@ ARROW_ROOT_DEFAULT = os.environ.get(
)
+class _Printer:
+ """
+ A print()-providing object that can override the stream output on
+ a per-thread basis.
+ """
+
+ def __init__(self):
+ self._tls = threading.local()
+
+ def _get_stdout(self):
+ try:
+ return self._tls.stdout
+ except AttributeError:
+ self._tls.stdout = sys.stdout
+ self._tls.corked = False
+ return self._tls.stdout
+
+ def print(self, *args, **kwargs):
+ """
+ A variant of print() that writes to a thread-local stream.
+ """
+ print(*args, file=self._get_stdout(), **kwargs)
+
+ @property
+ def stdout(self):
+ """
+ A thread-local stdout wrapper that may be temporarily buffered
+ using `cork()`.
+ """
+ return self._get_stdout()
+
+ @contextlib.contextmanager
+ def cork(self):
+ """
+ Temporarily buffer this thread's stream and write out its contents
+ at the end of the context manager. Useful to avoid interleaved
+ output when multiple threads output progress information.
+ """
+ outer_stdout = self._get_stdout()
+ assert not self._tls.corked, "reentrant call"
+ inner_stdout = self._tls.stdout = io.StringIO()
+ self._tls.corked = True
+ try:
+ yield
+ finally:
+ self._tls.stdout = outer_stdout
+ self._tls.corked = False
+ outer_stdout.write(inner_stdout.getvalue())
+ outer_stdout.flush()
+
+
+printer = _Printer()
+log = printer.print
+
+
def rands(nchars):
"""
Generate one random byte string.
@@ -70,11 +130,28 @@ def run_cmd(cmd):
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
# this avoids hiding the stdout / stderr of failed processes
- print('Command failed: %s' % ' '.join(cmd))
- print('With output:')
- print('--------------')
- print(frombytes(e.output))
- print('--------------')
- raise e
+ sio = io.StringIO()
+ print('Command failed:', cmd, file=sio)
+ print('With output:', file=sio)
+ print('--------------', file=sio)
+ print(frombytes(e.output), file=sio)
+ print('--------------', file=sio)
+ raise RuntimeError(sio.getvalue())
return frombytes(output)
+
+
+# Adapted from CPython
+def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
+ """Returns an unused port that should be suitable for binding. This is
+ achieved by creating a temporary socket with the same family and type as
+ the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
+ the specified host address (defaults to 0.0.0.0) with the port set to 0,
+ eliciting an unused ephemeral port from the OS. The temporary socket is
+ then closed and deleted, and the ephemeral port is returned.
+ """
+ with socket.socket(family, socktype) as tempsock:
+ tempsock.bind(('', 0))
+ port = tempsock.getsockname()[1]
+ del tempsock
+ return port