This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12858-31a99d99bb502fa69130f9e57c1e78307e96b4cb in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit e653ba556c00e18fae6848243049253c4988ae95 Author: Karthik Thota <[email protected]> AuthorDate: Sun Nov 22 12:51:25 2026 +0000 [Feature][Client] Add install-plugin helper to Python SDK (#12858) --- .../seatunnel/plugin_installer.py | 339 +++++++++++++ .../tests/test_plugin_installer.py | 528 +++++++++++++++++++++ 2 files changed, 867 insertions(+) diff --git a/tools/seatunnel-python-sdk/seatunnel/plugin_installer.py b/tools/seatunnel-python-sdk/seatunnel/plugin_installer.py new file mode 100644 index 00000000000..ea3a177265a --- /dev/null +++ b/tools/seatunnel-python-sdk/seatunnel/plugin_installer.py @@ -0,0 +1,339 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +"""Select connector plugins in ``config/plugin_config`` and run ``bin/install-plugin.sh``. + +Ownership boundary: these helpers rewrite ``config/plugin_config`` in place. Only pass them +a SeaTunnel copy that the caller owns and manages, such as the launcher's per-user, +per-version cache directory. Never point them at a source checkout or at a shared +installation, because the connector selection there would be changed for everyone using it. + +:func:`install_plugins` runs ``bin/install-plugin.sh`` with bash and is supported on Linux +and macOS only. It holds an exclusive lock on ``config/.plugin_config.lock`` for the whole +select / install / restore sequence, so concurrent calls on the same copy run one after +another. :func:`select_plugins` works on any platform but takes no lock itself. +""" + +import contextlib +import os +import re +import shutil +import subprocess +import sys +import tempfile +from typing import Iterable, Iterator, List + + +class PluginInstallError(Exception): + """Raised when connector plugins cannot be selected or installed.""" + + +# Same character set that bin/install-plugin.sh accepts for a connector artifact ID and for a +# release version. +_ARTIFACT_ID_RE = re.compile(r"[A-Za-z0-9._-]+") + +# A connector artifact ID. It cannot start with "-", which install-plugin.sh treats as a +# section header such as "--connectors-v2--". +_CONNECTOR_ID_RE = re.compile(r"[A-Za-z0-9._][A-Za-z0-9._-]*") + +# A connector disabled by a leading "#" ("#connector-jdbc"). License and description comments +# contain spaces, so they do not match. +_DISABLED_CONNECTOR_RE = re.compile(r"#(" + _CONNECTOR_ID_RE.pattern + r")") + +_CONNECTOR_PREFIX = "connector-" + +_LOCK_FILE_NAME = ".plugin_config.lock" + + +def _normalize_connectors(connectors: Iterable[str]) -> List[str]: + """Validate requested connector names and return artifact IDs in request order. + + Both short names ("jdbc") and artifact IDs ("connector-jdbc") are accepted. + """ + if isinstance(connectors, str): + connectors = [connectors] + try: + names = list(connectors) + except TypeError as exc: + raise PluginInstallError( + f"Connectors must be a name or an iterable of names, got {connectors!r}." + ) from exc + + artifact_ids = [] + for raw in names: + if not isinstance(raw, str): + raise PluginInstallError(f"Invalid connector name {raw!r}: expected a string.") + name = raw.strip() + if not _CONNECTOR_ID_RE.fullmatch(name): + raise PluginInstallError(f"Invalid connector name {raw!r}.") + if not name.startswith(_CONNECTOR_PREFIX): + name = _CONNECTOR_PREFIX + name + if name not in artifact_ids: + artifact_ids.append(name) + + if not artifact_ids: + raise PluginInstallError("No connectors requested.") + return artifact_ids + + +def select_plugins(plugin_config_path: str, connectors: Iterable[str]) -> List[str]: + """Rewrite *plugin_config_path* so that only *connectors* are enabled. + + Lines are classified the same way ``bin/install-plugin.sh`` reads them: blank lines and + lines starting with ``-`` (section headers) or ``#`` (comments) are skipped, and every + other line is a connector. Connector lines that were not requested are disabled with a + leading ``#`` instead of being removed, so a later call can enable them again. Stray + whitespace around a connector ID is dropped when its line is rewritten. Section headers, + comments, blank lines and line endings are kept as they are. Running it again with the + same connectors leaves the file unchanged. + + CRLF line endings are preserved, but ``bin/install-plugin.sh`` itself only accepts LF + endings: it rejects a connector line ending in ``\\r`` as an invalid artifact ID. Give + :func:`install_plugins` a ``plugin_config`` with LF endings, as shipped in the + distribution. + + :param plugin_config_path: Path to ``config/plugin_config`` in a caller-managed copy + (see the module docstring); never a source checkout or a shared installation. + :param connectors: Short names (``"jdbc"``) or artifact IDs (``"connector-jdbc"``). + :returns: The enabled artifact IDs, in request order. + :raises PluginInstallError: If a name is invalid, a connector is not listed in the + file, the file contains a line that ``install-plugin.sh`` would reject, or the file + cannot be read, decoded or written. The file is not modified then. + """ + artifact_ids = _normalize_connectors(connectors) + + try: + with open(plugin_config_path, encoding="utf-8", newline="") as f: + original = f.read() + except (OSError, UnicodeDecodeError) as exc: + raise PluginInstallError( + f"Cannot read plugin config '{plugin_config_path}': {exc}" + ) from exc + + wanted = set(artifact_ids) + found = set() + lines = [] + for number, line in enumerate(original.splitlines(keepends=True), start=1): + content = line.rstrip("\r\n") + ending = line[len(content):] + first_char = content[:1] + + if first_char in ("", "-"): + # Blank line or section header: install-plugin.sh skips it. + lines.append(line) + continue + if first_char == "#": + match = _DISABLED_CONNECTOR_RE.fullmatch(content.rstrip()) + if match is None: + # An ordinary comment. + lines.append(line) + continue + artifact_id = match.group(1) + else: + # install-plugin.sh downloads this line as a connector and exits if it is not a + # valid artifact ID, so reject such a line before anything is rewritten. + artifact_id = content.strip() + if not _CONNECTOR_ID_RE.fullmatch(artifact_id): + raise PluginInstallError( + f"Line {number} of '{plugin_config_path}' is not a valid connector " + f"artifact ID: {content!r}. bin/install-plugin.sh would reject it; " + f"fix the line or comment it out with '#'." + ) + + if artifact_id in wanted: + found.add(artifact_id) + lines.append(artifact_id + ending) + else: + lines.append("#" + artifact_id + ending) + + missing = [a for a in artifact_ids if a not in found] + if missing: + raise PluginInstallError( + f"Connector(s) not found in '{plugin_config_path}': {', '.join(missing)}." + ) + + updated = "".join(lines) + if updated != original: + _write_atomically(plugin_config_path, updated.encode("utf-8")) + return artifact_ids + + +def _write_atomically(path: str, content: bytes) -> None: + """Write *content* to *path* through a temporary file, so a failure never leaves it half written.""" + directory = os.path.dirname(os.path.abspath(path)) + try: + fd, temp_path = tempfile.mkstemp(dir=directory, prefix=".plugin_config.") + try: + with os.fdopen(fd, "wb") as f: + f.write(content) + shutil.copymode(path, temp_path) + os.replace(temp_path, path) + except BaseException: + if os.path.exists(temp_path): + os.remove(temp_path) + raise + except OSError as exc: + raise PluginInstallError(f"Cannot write plugin config '{path}': {exc}") from exc + + +def _restore_if_changed(path: str, original: bytes) -> None: + """Write *original* back to *path*, unless the file still holds exactly those bytes.""" + try: + with open(path, "rb") as f: + current = f.read() + except OSError: + current = None + if current != original: + _write_atomically(path, original) + + +def _is_windows() -> bool: + return sys.platform == "win32" + + [email protected] +def _exclusive_lock(config_dir: str) -> Iterator[None]: + """Hold an exclusive lock on ``<config_dir>/.plugin_config.lock`` while the block runs. + + The lock file is left in place: deleting it would let a waiting process lock an inode + that a new caller no longer sees. Closing the descriptor releases the lock. + """ + import fcntl # POSIX only; install_plugins rejects Windows before getting here. + + lock_path = os.path.join(config_dir, _LOCK_FILE_NAME) + try: + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644) + except OSError as exc: + raise PluginInstallError(f"Cannot open lock file '{lock_path}': {exc}") from exc + try: + try: + fcntl.flock(fd, fcntl.LOCK_EX) + except OSError as exc: + raise PluginInstallError(f"Cannot lock '{lock_path}': {exc}") from exc + yield + finally: + os.close(fd) + + +def install_plugins(seatunnel_home: str, connectors: Iterable[str], version: str) -> List[str]: + """Enable *connectors* in ``config/plugin_config`` and run ``bin/install-plugin.sh <version>``. + + Supported on Linux and macOS only; :func:`select_plugins` works on any platform. + ``bin/install-plugin.cmd`` does not report download failures through its exit code, so + it cannot be used with the rollback below, and a WSL or Git ``bash`` cannot run the + script from a Windows path. + + The script's output is not captured, so download progress is shown to the user. + Environment variables such as ``SEATUNNEL_PLUGIN_DOWNLOAD_METHOD`` and + ``SEATUNNEL_MAVEN_REPOSITORY`` are passed through to it. + + If the script fails, cannot be started or is interrupted, ``plugin_config`` is restored + to its exact content before the call, so a failed install leaves no changed selection. + The whole sequence runs under an exclusive lock on ``config/.plugin_config.lock``, so a + concurrent call on the same copy waits instead of installing another call's selection. + + :param seatunnel_home: Root of a caller-managed SeaTunnel distribution, such as the + launcher's per-user, per-version cache (see the module docstring); never a source + checkout or a shared installation. A relative path is resolved against the current + working directory. + :param connectors: Short names (``"jdbc"``) or artifact IDs (``"connector-jdbc"``). + :param version: Connector version to install; it should match the SeaTunnel engine + version of the distribution. It may only contain ``A-Z a-z 0-9 . _ -``, the same + characters ``install-plugin.sh`` accepts. ``LATEST``, ``RELEASE`` and ``*-SNAPSHOT`` + make the script download through Maven (``mvnw``) instead of over HTTPS. + :returns: The installed artifact IDs, in request order. + :raises PluginInstallError: If the platform is Windows, the version is invalid, the + distribution layout is incomplete, ``bash`` is not available, a connector is not + listed, ``plugin_config`` cannot be parsed, or the script fails. + """ + # Check everything that can fail before the script starts, so a doomed install does + # not leave plugin_config rewritten. + if _is_windows(): + raise PluginInstallError( + "install_plugins() is supported on Linux and macOS only: it runs " + "bin/install-plugin.sh with bash. select_plugins() works on any platform." + ) + + version = version.strip() if isinstance(version, str) else "" + if not version: + raise PluginInstallError( + "A connector version is required; it should match your SeaTunnel engine version." + ) + if not _ARTIFACT_ID_RE.fullmatch(version): + raise PluginInstallError( + f"Invalid connector version {version!r}: only letters, digits, '.', '_' and '-' " + f"are allowed. It should match your SeaTunnel engine version." + ) + + if not isinstance(seatunnel_home, (str, os.PathLike)) or not isinstance( + os.fspath(seatunnel_home), str + ): + raise PluginInstallError( + f"seatunnel_home must be a path to a SeaTunnel distribution, got {seatunnel_home!r}." + ) + # The script path is passed to bash while cwd is seatunnel_home, so it must be absolute. + seatunnel_home = os.path.abspath(os.path.expanduser(os.fspath(seatunnel_home))) + config_dir = os.path.join(seatunnel_home, "config") + plugin_config = os.path.join(config_dir, "plugin_config") + script = os.path.join(seatunnel_home, "bin", "install-plugin.sh") + for path in (plugin_config, script): + if not os.path.isfile(path): + raise PluginInstallError( + f"'{path}' not found. Is '{seatunnel_home}' a SeaTunnel distribution?" + ) + + bash = shutil.which("bash") + if bash is None: + raise PluginInstallError("bash is required to run 'bin/install-plugin.sh'.") + + with _exclusive_lock(config_dir): + try: + with open(plugin_config, "rb") as f: + original = f.read() + except OSError as exc: + raise PluginInstallError( + f"Cannot read plugin config '{plugin_config}': {exc}" + ) from exc + + try: + # Inside the try, so an interrupt right after the rewrite is rolled back too. + artifact_ids = select_plugins(plugin_config, connectors) + try: + result = subprocess.run( + [bash, script, version], cwd=seatunnel_home, check=False + ) + except OSError as exc: + raise PluginInstallError(f"Failed to run '{script}': {exc}") from exc + + if result.returncode != 0: + raise PluginInstallError( + f"'{script} {version}' exited with code {result.returncode} while " + f"installing {', '.join(artifact_ids)}. See the output above for details." + ) + except BaseException as exc: + # Also covers KeyboardInterrupt during a long download. + try: + _restore_if_changed(plugin_config, original) + except PluginInstallError as restore_error: + message = f"Restoring the original plugin config also failed: {restore_error}" + if not isinstance(exc, Exception): + # Keep KeyboardInterrupt / SystemExit as they are, so the caller still + # stops. Raising it here records the restore failure as its __context__. + if hasattr(exc, "add_note"): + exc.add_note(message) + raise exc + raise PluginInstallError(f"{exc} {message}") from exc + raise + return artifact_ids diff --git a/tools/seatunnel-python-sdk/tests/test_plugin_installer.py b/tools/seatunnel-python-sdk/tests/test_plugin_installer.py new file mode 100644 index 00000000000..ab082949053 --- /dev/null +++ b/tools/seatunnel-python-sdk/tests/test_plugin_installer.py @@ -0,0 +1,528 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + + +import contextlib +import os +import subprocess +import tempfile +import unittest +from unittest import mock + +from seatunnel import plugin_installer +from seatunnel.plugin_installer import PluginInstallError, install_plugins, select_plugins + +try: + import fcntl +except ImportError: # Windows + fcntl = None + + +# Same layout as config/plugin_config in the distribution: license header, a description +# comment, a section header and one connector artifact ID per line. +PLUGIN_CONFIG = ( + "#\n" + "# Licensed to the Apache Software Foundation (ASF) under one or more\n" + "# http://www.apache.org/licenses/LICENSE-2.0\n" + "#\n" + "# Don't modify the delimiter \" -- \", just select the plugin you need\n" + "--connectors-v2--\n" + "connector-fake\n" + "connector-console\n" + "connector-jdbc\n" + "connector-cdc-mysql\n" + "connector-kafka\n" +) + + +class _PluginConfigTestCase(unittest.TestCase): + + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.home = self._tmp.name + os.makedirs(os.path.join(self.home, "config")) + os.makedirs(os.path.join(self.home, "bin")) + self.config_path = os.path.join(self.home, "config", "plugin_config") + self.script_path = os.path.join(self.home, "bin", "install-plugin.sh") + self._write(PLUGIN_CONFIG) + with open(self.script_path, "w") as f: + f.write("#!/bin/bash\n") + + def tearDown(self): + self._tmp.cleanup() + + def _write(self, content): + with open(self.config_path, "w", encoding="utf-8", newline="") as f: + f.write(content) + + def _read(self): + with open(self.config_path, encoding="utf-8", newline="") as f: + return f.read() + + def _enabled(self): + """Connector lines that install-plugin.sh would install (not '#' or '-', not blank).""" + return [ + line for line in self._read().splitlines() + if line and line[0] not in "#-" + ] + + +class TestSelectPlugins(_PluginConfigTestCase): + + def test_only_requested_connectors_stay_enabled(self): + """Requested connectors stay enabled; the others are disabled with '#'.""" + selected = select_plugins(self.config_path, ["connector-jdbc", "connector-cdc-mysql"]) + + self.assertEqual(["connector-jdbc", "connector-cdc-mysql"], selected) + self.assertEqual(["connector-jdbc", "connector-cdc-mysql"], self._enabled()) + content = self._read() + for disabled in ("#connector-fake", "#connector-console", "#connector-kafka"): + self.assertIn(disabled + "\n", content) + + def test_header_comments_and_section_header_are_preserved(self): + """License header, description comment and section header are unchanged.""" + select_plugins(self.config_path, ["jdbc"]) + + lines = self._read().splitlines() + self.assertEqual(PLUGIN_CONFIG.splitlines()[:6], lines[:6]) + self.assertIn("--connectors-v2--", lines) + + def test_second_run_with_same_connectors_is_idempotent(self): + """Running twice with the same request produces byte-identical content.""" + select_plugins(self.config_path, ["jdbc", "cdc-mysql"]) + first = self._read() + + select_plugins(self.config_path, ["jdbc", "cdc-mysql"]) + self.assertEqual(first, self._read()) + + def test_unchanged_file_is_not_rewritten(self): + """When nothing changes, the file is not written again.""" + select_plugins(self.config_path, ["jdbc"]) + + with mock.patch("seatunnel.plugin_installer._write_atomically") as write: + select_plugins(self.config_path, ["jdbc"]) + write.assert_not_called() + + def test_previously_disabled_connector_can_be_enabled_again(self): + """A connector disabled by an earlier call can be selected by a later one.""" + select_plugins(self.config_path, ["jdbc"]) + select_plugins(self.config_path, ["kafka"]) + + self.assertEqual(["connector-kafka"], self._enabled()) + self.assertIn("#connector-jdbc\n", self._read()) + + def test_short_name_and_artifact_id_are_equivalent(self): + """'jdbc' and 'connector-jdbc' select the same connector.""" + self.assertEqual(["connector-jdbc"], select_plugins(self.config_path, ["jdbc"])) + short = self._read() + self._write(PLUGIN_CONFIG) + self.assertEqual(["connector-jdbc"], select_plugins(self.config_path, ["connector-jdbc"])) + self.assertEqual(short, self._read()) + + def test_duplicate_names_are_collapsed(self): + """Duplicates, including short and full forms of one name, appear once.""" + selected = select_plugins(self.config_path, ["jdbc", "connector-jdbc", "jdbc"]) + self.assertEqual(["connector-jdbc"], selected) + + def test_single_string_is_accepted(self): + """A single connector name may be passed as a plain string.""" + self.assertEqual(["connector-jdbc"], select_plugins(self.config_path, "jdbc")) + + def test_unknown_connector_raises_and_leaves_file_unchanged(self): + """A connector missing from plugin_config raises and does not modify the file.""" + with self.assertRaises(PluginInstallError) as ctx: + select_plugins(self.config_path, ["jdbc", "does-not-exist"]) + + self.assertIn("connector-does-not-exist", str(ctx.exception)) + self.assertNotIn("connector-jdbc,", str(ctx.exception)) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_empty_request_raises(self): + """An empty connector list raises instead of disabling every connector.""" + with self.assertRaises(PluginInstallError): + select_plugins(self.config_path, []) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_invalid_connector_names_raise(self): + """Names with characters install-plugin.sh rejects, or a leading '-', raise.""" + for name in ("", " ", "jdbc mysql", "../jdbc", "jdbc;rm", "--connectors-v2--"): + with self.subTest(name=name): + with self.assertRaises(PluginInstallError): + select_plugins(self.config_path, [name]) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_crlf_line_endings_are_preserved(self): + """A file with Windows line endings keeps them on every line.""" + self._write(PLUGIN_CONFIG.replace("\n", "\r\n")) + + select_plugins(self.config_path, ["jdbc"]) + + content = self._read() + self.assertNotIn("\n", content.replace("\r\n", "")) + self.assertIn("#connector-fake\r\n", content) + self.assertIn("connector-jdbc\r\n", content) + + def test_last_line_without_newline_is_handled(self): + """A final connector line with no trailing newline is still matched.""" + self._write(PLUGIN_CONFIG.rstrip("\n")) + + select_plugins(self.config_path, ["kafka"]) + + self.assertTrue(self._read().endswith("\nconnector-kafka")) + self.assertEqual(["connector-kafka"], self._enabled()) + + def test_missing_file_raises(self): + """A missing plugin_config raises PluginInstallError.""" + with self.assertRaises(PluginInstallError) as ctx: + select_plugins(os.path.join(self.home, "nope"), ["jdbc"]) + self.assertIn("Cannot read plugin config", str(ctx.exception)) + + def test_connector_lines_with_stray_whitespace_are_recognized(self): + """Connector lines with surrounding whitespace are matched and written without it.""" + self._write( + PLUGIN_CONFIG.replace("connector-jdbc\n", " connector-jdbc\n") + .replace("connector-kafka\n", "connector-kafka \n") + ) + + select_plugins(self.config_path, ["jdbc"]) + + content = self._read() + self.assertEqual(["connector-jdbc"], self._enabled()) + self.assertIn("\nconnector-jdbc\n", content) + self.assertIn("\n#connector-kafka\n", content) + + def test_disabled_connector_with_trailing_whitespace_can_be_enabled(self): + """'#connector-kafka ' is recognized as a disabled connector, not as a comment.""" + self._write(PLUGIN_CONFIG.replace("connector-kafka\n", "#connector-kafka \n")) + + self.assertEqual(["connector-kafka"], select_plugins(self.config_path, ["kafka"])) + self.assertEqual(["connector-kafka"], self._enabled()) + + def test_line_rejected_by_install_script_raises_and_leaves_file_unchanged(self): + """A line install-plugin.sh would reject as an artifact ID fails before any rewrite.""" + for bad_line in ("connector-kafka # keep", "connector kafka", " ", " # indented"): + with self.subTest(line=bad_line): + content = PLUGIN_CONFIG.replace("connector-kafka\n", bad_line + "\n") + self._write(content) + with self.assertRaises(PluginInstallError) as ctx: + select_plugins(self.config_path, ["jdbc"]) + self.assertIn("Line 11", str(ctx.exception)) + self.assertIn("would reject it", str(ctx.exception)) + self.assertEqual(content, self._read()) + + def test_non_utf8_file_raises_plugin_install_error(self): + """A plugin_config that is not valid UTF-8 raises PluginInstallError, not UnicodeDecodeError.""" + with open(self.config_path, "wb") as f: + f.write(b"connector-jdbc\n\xff\xfe\n") + + with self.assertRaises(PluginInstallError) as ctx: + select_plugins(self.config_path, ["jdbc"]) + self.assertIsInstance(ctx.exception.__cause__, UnicodeDecodeError) + + def test_invalid_connectors_argument_raises_plugin_install_error(self): + """None and non-string names raise PluginInstallError showing the offending value.""" + with self.assertRaises(PluginInstallError) as ctx: + select_plugins(self.config_path, None) + self.assertIn("None", str(ctx.exception)) + + with self.assertRaises(PluginInstallError) as ctx: + select_plugins(self.config_path, ["jdbc", 42]) + self.assertIn("42", str(ctx.exception)) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + +class TestInstallPlugins(_PluginConfigTestCase): + + def setUp(self): + super().setUp() + patcher = mock.patch.object(plugin_installer, "_is_windows", return_value=False) + patcher.start() + self.addCleanup(patcher.stop) + if fcntl is None: + # fcntl.flock is POSIX only; the real lock is exercised on Linux and macOS. + patcher = mock.patch.object( + plugin_installer, "_exclusive_lock", lambda config_dir: contextlib.nullcontext() + ) + patcher.start() + self.addCleanup(patcher.stop) + + def _patch_which(self, path="/usr/bin/bash"): + return mock.patch("seatunnel.plugin_installer.shutil.which", return_value=path) + + def _patch_run(self, returncode=0, side_effect=None): + return mock.patch( + "seatunnel.plugin_installer.subprocess.run", + return_value=subprocess.CompletedProcess(args=[], returncode=returncode), + side_effect=side_effect, + ) + + def test_runs_install_script_with_version_after_selecting(self): + """The config is rewritten first, then install-plugin.sh runs with the version.""" + observed = {} + + def fake_run(args, cwd, check): + observed["enabled"] = self._enabled() + return subprocess.CompletedProcess(args=args, returncode=0) + + with self._patch_which(), self._patch_run(side_effect=fake_run) as run: + installed = install_plugins(self.home, ["fake", "console"], "3.0.1") + + self.assertEqual(["connector-fake", "connector-console"], installed) + self.assertEqual(["connector-fake", "connector-console"], observed["enabled"]) + run.assert_called_once_with( + ["/usr/bin/bash", self.script_path, "3.0.1"], cwd=self.home, check=False + ) + + def test_successful_install_keeps_new_selection(self): + """After a successful install, plugin_config keeps the requested selection.""" + with self._patch_which(), self._patch_run(returncode=0): + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertEqual(["connector-jdbc"], self._enabled()) + + def test_nonzero_exit_raises_and_restores_plugin_config(self): + """A failing install script raises and plugin_config is restored byte for byte.""" + with self._patch_which(), self._patch_run(returncode=1): + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertIn("exited with code 1", str(ctx.exception)) + self.assertIn("connector-jdbc", str(ctx.exception)) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_failed_install_restores_previous_selection_and_line_endings(self): + """Restoring returns the file to its state before the call, not to the default list.""" + self._write(PLUGIN_CONFIG.replace("\n", "\r\n")) + select_plugins(self.config_path, ["kafka"]) + with open(self.config_path, "rb") as f: + before = f.read() + + with self._patch_which(), self._patch_run(returncode=1): + with self.assertRaises(PluginInstallError): + install_plugins(self.home, ["jdbc"], "3.0.1") + + with open(self.config_path, "rb") as f: + self.assertEqual(before, f.read()) + + def test_oserror_raises_and_restores_plugin_config(self): + """An OSError starting the script is wrapped and plugin_config is restored.""" + with self._patch_which(), self._patch_run(side_effect=OSError("exec format error")): + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertIn("exec format error", str(ctx.exception)) + self.assertIsInstance(ctx.exception.__cause__, OSError) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_interrupt_restores_plugin_config_and_propagates(self): + """Ctrl+C during the download restores plugin_config and still interrupts.""" + with self._patch_which(), self._patch_run(side_effect=KeyboardInterrupt): + with self.assertRaises(KeyboardInterrupt): + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_interrupt_right_after_the_rewrite_is_rolled_back(self): + """Ctrl+C between the rewrite and the script start still restores plugin_config.""" + real_select = plugin_installer.select_plugins + + def select_then_interrupt(path, connectors): + real_select(path, connectors) + raise KeyboardInterrupt + + with self._patch_which(), self._patch_run() as run: + with mock.patch.object(plugin_installer, "select_plugins", select_then_interrupt): + with self.assertRaises(KeyboardInterrupt): + install_plugins(self.home, ["jdbc"], "3.0.1") + run.assert_not_called() + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_invalid_seatunnel_home_raises_plugin_install_error(self): + """A seatunnel_home that is not a str path raises PluginInstallError, not TypeError.""" + for home in (None, 42, b"/opt/seatunnel"): + with self.subTest(home=home): + with self._patch_which(), self._patch_run() as run: + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(home, ["jdbc"], "3.0.0") + run.assert_not_called() + self.assertIn("seatunnel_home must be a path", str(ctx.exception)) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def _patch_failing_restore(self): + """Let the selection write succeed, then make the restore write fail.""" + real_write = plugin_installer._write_atomically + calls = [] + + def write_then_fail(path, content): + calls.append(path) + if len(calls) > 1: + raise PluginInstallError("disk full") + real_write(path, content) + + return mock.patch.object(plugin_installer, "_write_atomically", write_then_fail) + + def test_restore_failure_reports_both_errors(self): + """If restoring fails too, the error mentions the script failure and the restore failure.""" + with self._patch_which(), self._patch_run(returncode=1): + with self._patch_failing_restore(): + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertIn("exited with code 1", str(ctx.exception)) + self.assertIn("Restoring the original plugin config also failed: disk full", + str(ctx.exception)) + + def test_restore_failure_during_interrupt_keeps_the_interrupt(self): + """KeyboardInterrupt / SystemExit are re-raised, with the restore failure attached.""" + for interrupt in (KeyboardInterrupt, SystemExit): + with self.subTest(interrupt=interrupt.__name__): + with self._patch_which(), self._patch_run(side_effect=interrupt): + with self._patch_failing_restore(): + with self.assertRaises(interrupt) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.1") + + restore_error = ctx.exception.__context__ + self.assertIsInstance(restore_error, PluginInstallError) + self.assertIn("disk full", str(restore_error)) + if hasattr(ctx.exception, "add_note"): + self.assertIn( + "Restoring the original plugin config also failed: disk full", + ctx.exception.__notes__, + ) + self._write(PLUGIN_CONFIG) + + def test_missing_bash_raises_before_rewriting(self): + """Without bash, nothing is rewritten and nothing is run.""" + with self._patch_which(None), self._patch_run() as run: + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertIn("bash is required", str(ctx.exception)) + run.assert_not_called() + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_missing_script_raises_before_rewriting(self): + """A home without bin/install-plugin.sh is rejected before plugin_config changes.""" + os.remove(self.script_path) + with self._patch_which(), self._patch_run() as run: + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertIn("install-plugin.sh", str(ctx.exception)) + run.assert_not_called() + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_missing_plugin_config_raises(self): + """A home without config/plugin_config is rejected.""" + os.remove(self.config_path) + with self._patch_which(), self._patch_run() as run: + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.1") + self.assertIn("plugin_config", str(ctx.exception)) + run.assert_not_called() + + def test_unknown_connector_does_not_run_script(self): + """If a connector is not listed, the script is not run.""" + with self._patch_which(), self._patch_run() as run: + with self.assertRaises(PluginInstallError): + install_plugins(self.home, ["does-not-exist"], "3.0.1") + run.assert_not_called() + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_empty_version_raises(self): + """An empty version is rejected before anything is rewritten or run.""" + for version in ("", " ", None): + with self.subTest(version=version): + with self._patch_which(), self._patch_run() as run: + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], version) + run.assert_not_called() + self.assertIn("engine version", str(ctx.exception)) + self.assertNotIn("3.0.1", str(ctx.exception)) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_invalid_version_raises_before_rewriting(self): + """Versions install-plugin.sh rejects, or reads as a Maven range, fail up front.""" + for version in ("3.0.1 beta", "3.0/1", "[3.0,)", "3.0+1", "3.0;rm"): + with self.subTest(version=version): + with self._patch_which(), self._patch_run() as run: + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], version) + run.assert_not_called() + self.assertIn("Invalid connector version", str(ctx.exception)) + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_relative_home_is_resolved_to_an_absolute_script_path(self): + """A relative seatunnel_home still hands bash an absolute script path.""" + parent, name = os.path.split(self.home) + cwd = os.getcwd() + os.chdir(parent) + self.addCleanup(os.chdir, cwd) + + with self._patch_which(), self._patch_run() as run: + install_plugins(name, ["jdbc"], "3.0.0") + + run.assert_called_once_with( + ["/usr/bin/bash", self.script_path, "3.0.0"], cwd=self.home, check=False + ) + self.assertTrue(os.path.isabs(run.call_args[0][0][1])) + + def test_windows_is_rejected_before_rewriting(self): + """On Windows the call fails up front, without rewriting plugin_config or running bash.""" + with mock.patch.object(plugin_installer, "_is_windows", return_value=True): + with self._patch_which() as which, self._patch_run() as run: + with self.assertRaises(PluginInstallError) as ctx: + install_plugins(self.home, ["jdbc"], "3.0.0") + self.assertIn("Linux and macOS only", str(ctx.exception)) + which.assert_not_called() + run.assert_not_called() + self.assertEqual(PLUGIN_CONFIG, self._read()) + + def test_failed_install_does_not_rewrite_an_unchanged_file(self): + """If the selection was already in place, a failed install performs no write at all.""" + select_plugins(self.config_path, ["jdbc"]) + before = self._read() + + with self._patch_which(), self._patch_run(returncode=1): + with mock.patch.object( + plugin_installer, "_write_atomically", wraps=plugin_installer._write_atomically + ) as write: + with self.assertRaises(PluginInstallError): + install_plugins(self.home, ["jdbc"], "3.0.0") + write.assert_not_called() + self.assertEqual(before, self._read()) + + @unittest.skipIf(fcntl is None, "fcntl.flock is POSIX only") + def test_lock_is_held_while_the_script_runs(self): + """A second process cannot take the plugin_config lock until the install finishes.""" + lock_path = os.path.join(self.home, "config", ".plugin_config.lock") + observed = {} + + def try_lock(): + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + return True + except BlockingIOError: + return False + finally: + os.close(fd) + + def fake_run(args, cwd, check): + observed["lock_free_during_run"] = try_lock() + return subprocess.CompletedProcess(args=args, returncode=0) + + with self._patch_which(), self._patch_run(side_effect=fake_run): + install_plugins(self.home, ["jdbc"], "3.0.0") + + self.assertFalse(observed["lock_free_during_run"]) + self.assertTrue(try_lock()) + + +if __name__ == "__main__": + unittest.main()
