diff --git a/.github/scripts/ExternalEurekaProbe.java b/.github/scripts/ExternalEurekaProbe.java new file mode 100644 index 000000000000..785b2eb12ba7 --- /dev/null +++ b/.github/scripts/ExternalEurekaProbe.java @@ -0,0 +1,79 @@ +/* + * 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 com.sun.net.httpserver.HttpServer; +import org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository; +import org.apache.shenyu.registry.api.config.RegisterConfig; +import org.apache.shenyu.spi.ExtensionLoader; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.concurrent.atomic.AtomicInteger; + +/** Tests the packaged external provider with the actual Admin dependency order. */ +public final class ExternalEurekaProbe { + + private ExternalEurekaProbe() { + } + + public static void main(final String[] args) throws Exception { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + AtomicInteger requests = new AtomicInteger(); + byte[] applications = """ + {"applications":{"versions__delta":"1","apps__hashcode":"UP_1_","application":[ + {"name":"CI-PROBE","instance":[{"instanceId":"ci-probe","hostName":"127.0.0.1", + "app":"CI-PROBE","ipAddr":"127.0.0.1","status":"UP", + "port":{"$":18081,"@enabled":"true"},"vipAddress":"CI-PROBE", + "secureVipAddress":"CI-PROBE","metadata":{"weight":"100"}, + "dataCenterInfo":{"@class":"com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo","name":"MyOwn"}}]} + ]}} + """.getBytes(StandardCharsets.UTF_8); + server.createContext("/eureka/", exchange -> { + requests.incrementAndGet(); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, applications.length); + try (var body = exchange.getResponseBody()) { + body.write(applications); + } + }); + server.start(); + ShenyuInstanceRegisterRepository repository = null; + try { + repository = ExtensionLoader.getExtensionLoader(ShenyuInstanceRegisterRepository.class).getJoin("eureka"); + Path actual = Path.of(repository.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).toRealPath(); + if (!actual.equals(Path.of(args[0]).toRealPath())) { + throw new IllegalStateException("Eureka provider did not load from the external runtime: " + actual); + } + RegisterConfig config = new RegisterConfig(); + config.setServerLists("http://127.0.0.1:" + server.getAddress().getPort() + "/eureka/"); + repository.init(config); + if (requests.get() == 0 || repository.selectInstances("CI-PROBE").size() != 1) { + throw new IllegalStateException("Packaged Eureka provider did not discover the loopback fixture"); + } + System.out.println("Packaged external Eureka SPI and HTTP discovery probe passed"); + } finally { + try { + if (repository != null) { + repository.close(); + } + } finally { + server.stop(0); + } + } + } +} diff --git a/.github/scripts/check-registry-dependencies.py b/.github/scripts/check-registry-dependencies.py index ff233ff0c332..74bfea85ad86 100644 --- a/.github/scripts/check-registry-dependencies.py +++ b/.github/scripts/check-registry-dependencies.py @@ -18,7 +18,7 @@ import sys from pathlib import Path -PROVIDERS = ("zookeeper", "etcd", "nacos", "apollo", "eureka", "kubernetes") +PROVIDERS = ("zookeeper", "etcd", "nacos", "apollo", "kubernetes") COMPATIBILITY_PROVIDERS = set(PROVIDERS) - {"apollo"} LEAN_MODULES = ( "shenyu-registry/shenyu-registry-api", diff --git a/.github/scripts/external-eureka-runtime.py b/.github/scripts/external-eureka-runtime.py new file mode 100644 index 000000000000..ed1a47ea4073 --- /dev/null +++ b/.github/scripts/external-eureka-runtime.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +# 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. + +"""Build and install the pinned external provider for Spring Cloud CI fixtures.""" + +import argparse +import fnmatch +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import xml.etree.ElementTree as ET +import zipfile + +RECEIVER_COMMIT = "be07c121085f219f46578515156e7a0bb20befdf" +MODULE = "shenyu-extension/shenyu-extension-eureka/shenyu-registry-eureka" +SPI = "META-INF/shenyu/org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository" +PROVIDER = "org.apache.shenyu.registry.eureka.EurekaInstanceRegisterRepository" +NS = {"m": "http://maven.apache.org/POM/4.0.0"} + + +def capture(command, cwd): + return subprocess.check_output(command, cwd=cwd, text=True).strip() + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def classpath(path): + return [Path(item).resolve() for item in path.read_text().strip().split(os.pathsep) if item] + + +def coordinate(path, repository): + parts = path.relative_to(repository).parts + if len(parts) < 4: + raise ValueError("Not a Maven repository artifact: " + str(path)) + group, artifact, version = ".".join(parts[:-3]), parts[-3], parts[-2] + prefix = artifact + "-" + version + if not path.name.startswith(prefix) or path.suffix != ".jar": + raise ValueError("Unexpected Maven artifact filename: " + str(path)) + classifier = path.name[len(prefix):-4] + return group, artifact, classifier + + +def select_dependencies(paths, admin_paths, repository, shaded): + # Keep the version already supplied by Admin; do not introduce a second core + # API or transport implementation into the container's extension classpath. + owned = {coordinate(path, repository): path for path in admin_paths} + selected = [] + reused = [] + seen = set() + for path in paths: + key = coordinate(path, repository) + ga = key[0] + ":" + key[1] + if key in owned: + reused.append({"artifact": ga, "requested_version": path.parent.name, + "admin_version": owned[key].parent.name}) + continue + if key[0] == "org.apache.shenyu" or any(fnmatch.fnmatchcase(ga, pattern) for pattern in shaded): + continue + if key in seen: + raise ValueError("Duplicate external dependency: " + ga) + seen.add(key) + selected.append(path) + return selected, reused + + +def verify_provider(path): + with zipfile.ZipFile(path) as archive: + entries = [line.strip() for line in archive.read(SPI).decode().splitlines() + if line.strip() and not line.lstrip().startswith("#")] + if entries != ["eureka=" + PROVIDER]: + raise ValueError("The external JAR does not register the expected Eureka SPI") + if PROVIDER.replace(".", "/") + ".class" not in archive.namelist(): + raise ValueError("The external JAR is missing the provider class") + if "org/apache/shenyu/registry/api/ShenyuInstanceRegisterRepository.class" in archive.namelist(): + raise ValueError("The external JAR must not bundle the retained registry API") + + +def prepare(core, store, output): + if output.exists(): + raise ValueError("Use a new output directory: " + str(output)) + if capture(["git", "rev-parse", "HEAD"], store) != RECEIVER_COMMIT: + raise ValueError("The receiver checkout must match the pinned commit") + if capture(["git", "status", "--porcelain", "--untracked-files=no"], store): + raise ValueError("The receiver checkout has tracked modifications") + version = ET.parse(core / "pom.xml").findtext("m:version", namespaces=NS) + wrapper = str(core / "mvnw") + common = ["-B", "-ntp", "-Dmaven.javadoc.skip=true", "-Djacoco.skip=true", "-DskipRemoteResources=true"] + subprocess.run([wrapper, *common, "-f", str(store / "pom.xml"), "-pl", MODULE, "-am", + "clean", "verify", "dependency:build-classpath", "-Dshenyu.version=" + version, + "-Dmdep.outputFile=target/eureka-runtime-classpath.txt", "-DincludeScope=runtime"], cwd=core, check=True) + subprocess.run([wrapper, *common, "-f", str(core / "shenyu-admin/pom.xml"), + "dependency:build-classpath", "-Dmdep.outputFile=target/eureka-runtime-classpath.txt", + "-DincludeScope=runtime"], cwd=core, check=True) + # The wrapper can print a JAVA_HOME warning before Maven's evaluated value. + repository_value = re.sub(r"\x1b\[[0-9;]*m", "", capture( + [wrapper, "-q", "-N", "help:evaluate", "-Dexpression=settings.localRepository", "-DforceStdout"], core)) + repository = Path(repository_value.splitlines()[-1]).resolve() + module = store / MODULE + pom = ET.parse(module / "pom.xml") + shaded = [item.text for item in pom.findall(".//m:artifactSet/m:includes/m:include", NS)] + jars = [path for path in (module / "target").glob("shenyu-registry-eureka-*.jar") + if not path.name.endswith(("-sources.jar", "-javadoc.jar"))] + if len(jars) != 1: + raise ValueError("Expected one packaged external provider") + provider = jars[0] + verify_provider(provider) + admin_paths = classpath(core / "shenyu-admin/target/eureka-runtime-classpath.txt") + dependencies, reused = select_dependencies(classpath(module / "target/eureka-runtime-classpath.txt"), + admin_paths, repository, shaded) + output.mkdir(parents=True) + output.chmod(0o755) + records = [] + for path in [provider, *dependencies]: + destination = output / path.name + if destination.exists(): + raise ValueError("External dependency filename collision: " + path.name) + shutil.copyfile(path, destination) + destination.chmod(0o644) + records.append({"file": path.name, "sha256": digest(destination)}) + # Unit tests run before shading. Exercise the packaged, reduced classpath as + # well, including discovery over a real loopback HTTP connection. + java = str(Path(os.environ["JAVA_HOME"]) / "bin/java") if os.environ.get("JAVA_HOME") else "java" + cp = os.pathsep.join(str(path) for path in [*admin_paths, output / provider.name, + *(output / path.name for path in dependencies)]) + subprocess.run([java, "-cp", cp, str(Path(__file__).with_name("ExternalEurekaProbe.java")), + str(output / provider.name)], check=True, timeout=45) + manifest = {"receiver_commit": RECEIVER_COMMIT, "core_commit": capture(["git", "rev-parse", "HEAD"], core), + "core_version": version, "provider": provider.name, "files": records, + "reused_admin_dependencies": reused, "packaged_spi_http_probe": "passed"} + (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + print("Prepared external Eureka runtime: " + str(output), flush=True) + + +def install(source, destination, core_commit, core_version): + manifest = json.loads((source / "manifest.json").read_text()) + if manifest["receiver_commit"] != RECEIVER_COMMIT: + raise ValueError("External runtime uses an unexpected receiver commit") + if manifest["core_commit"] != core_commit or manifest["core_version"] != core_version: + raise ValueError("External runtime was prepared for a different core checkout") + if manifest.get("packaged_spi_http_probe") != "passed": + raise ValueError("External runtime has no passing packaged SPI/HTTP probe") + files = manifest["files"] + names = [item["file"] for item in files] + if len(names) != len(set(names)) or any(Path(name).name != name or not name.endswith(".jar") for name in names): + raise ValueError("Invalid external runtime file inventory") + if set(path.name for path in source.glob("*.jar")) != set(names) or manifest["provider"] not in names: + raise ValueError("External runtime inventory is incomplete") + for item in files: + path = source / item["file"] + if path.is_symlink() or digest(path) != item["sha256"]: + raise ValueError("External runtime checksum mismatch: " + item["file"]) + existing = destination / item["file"] + if existing.exists() and digest(existing) != item["sha256"]: + raise ValueError("Refusing to replace a different runtime dependency: " + item["file"]) + verify_provider(source / manifest["provider"]) + destination.mkdir(parents=True, exist_ok=True) + destination.chmod(0o755) + for item in files: + target = destination / item["file"] + shutil.copyfile(source / item["file"], target) + target.chmod(0o644) + print("Installed external Eureka runtime into " + str(destination), flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + build = commands.add_parser("prepare") + build.add_argument("store", type=Path) + build.add_argument("output", type=Path) + copy = commands.add_parser("install") + copy.add_argument("source", type=Path) + copy.add_argument("destination", type=Path) + args = parser.parse_args() + if args.command == "prepare": + prepare(Path(__file__).resolve().parents[2], args.store.resolve(), args.output.resolve()) + else: + core = Path(__file__).resolve().parents[2] + install(args.source.resolve(), args.destination.resolve(), capture(["git", "rev-parse", "HEAD"], core), + ET.parse(core / "pom.xml").findtext("m:version", namespaces=NS)) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test-external-eureka-runtime.py b/.github/scripts/test-external-eureka-runtime.py new file mode 100644 index 000000000000..ef3e52a61071 --- /dev/null +++ b/.github/scripts/test-external-eureka-runtime.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +# 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 importlib.util +import json +from pathlib import Path +import tempfile +import unittest +import zipfile + +SPEC = importlib.util.spec_from_file_location("runtime", Path(__file__).with_name("external-eureka-runtime.py")) +RUNTIME = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(RUNTIME) + + +class ExternalRuntimeTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.source = self.root / "source" + self.destination = self.root / "driver" + self.source.mkdir() + self.destination.mkdir() + self.provider = self.source / "shenyu-registry-eureka-2.7.1-SNAPSHOT.jar" + self.make_provider() + self.manifest = {"receiver_commit": RUNTIME.RECEIVER_COMMIT, "core_commit": "core-sha", + "core_version": "2.7.3-SNAPSHOT", "packaged_spi_http_probe": "passed", + "provider": self.provider.name, + "files": [{"file": self.provider.name, "sha256": RUNTIME.digest(self.provider)}]} + self.save_manifest() + + def make_provider(self, spi=None, include_core=False): + with zipfile.ZipFile(self.provider, "w") as archive: + archive.writestr(RUNTIME.SPI, spi or "# license comment\n\neureka=" + RUNTIME.PROVIDER + "\n") + archive.writestr(RUNTIME.PROVIDER.replace(".", "/") + ".class", b"fixture") + if include_core: + archive.writestr("org/apache/shenyu/registry/api/ShenyuInstanceRegisterRepository.class", b"duplicate") + + def save_manifest(self): + (self.source / "manifest.json").write_text(json.dumps(self.manifest)) + + def install(self): + RUNTIME.install(self.source, self.destination, "core-sha", "2.7.3-SNAPSHOT") + + def test_install_preserves_mysql_driver_and_is_idempotent(self): + driver = self.destination / "mysql-connector.jar" + driver.write_bytes(b"existing driver") + self.install() + self.install() + self.assertEqual(b"existing driver", driver.read_bytes()) + self.assertEqual(self.provider.read_bytes(), (self.destination / self.provider.name).read_bytes()) + + def test_checksum_failure_does_not_change_driver_directory(self): + self.provider.write_bytes(b"truncated artifact") + with self.assertRaisesRegex(ValueError, "checksum mismatch"): + self.install() + self.assertEqual([], list(self.destination.iterdir())) + + def test_existing_different_jar_is_not_overwritten(self): + target = self.destination / self.provider.name + target.write_bytes(b"another version") + with self.assertRaisesRegex(ValueError, "Refusing to replace"): + self.install() + self.assertEqual(b"another version", target.read_bytes()) + + def test_unlisted_jar_is_rejected(self): + (self.source / "unexpected.jar").write_bytes(b"unlisted") + with self.assertRaisesRegex(ValueError, "inventory is incomplete"): + self.install() + + def test_wrong_source_pair_is_rejected(self): + for field in ["receiver_commit", "core_commit", "core_version"]: + with self.subTest(field=field): + original = self.manifest[field] + self.manifest[field] = "wrong" + self.save_manifest() + with self.assertRaisesRegex(ValueError, "unexpected receiver|different core"): + self.install() + self.manifest[field] = original + + def test_missing_packaged_probe_is_rejected(self): + self.manifest.pop("packaged_spi_http_probe") + self.save_manifest() + with self.assertRaisesRegex(ValueError, "no passing"): + self.install() + + def test_manifest_cannot_escape_source_directory(self): + self.manifest["files"][0]["file"] = "../outside.jar" + self.save_manifest() + with self.assertRaisesRegex(ValueError, "Invalid external runtime"): + self.install() + + def test_missing_provider_is_rejected(self): + self.manifest["provider"] = "missing.jar" + self.save_manifest() + with self.assertRaisesRegex(ValueError, "inventory is incomplete"): + self.install() + + def test_bundled_core_api_is_rejected(self): + self.make_provider(include_core=True) + with self.assertRaisesRegex(ValueError, "must not bundle"): + RUNTIME.verify_provider(self.provider) + + def test_wrong_spi_key_is_rejected(self): + self.make_provider(spi="different=" + RUNTIME.PROVIDER) + with self.assertRaisesRegex(ValueError, "expected Eureka SPI"): + RUNTIME.verify_provider(self.provider) + + def test_dependency_selection_keeps_core_versions_and_excludes_shaded_closure(self): + repo = self.root / "repository" + + def artifact(group, name, version): + return repo.joinpath(*group.split("."), name, version, name + "-" + version + ".jar") + + core = artifact("com.example", "shared", "2") + old = artifact("com.example", "shared", "1") + distinct_group = artifact("other.example", "shared", "1") + shaded = artifact("org.glassfish.jersey.core", "jersey-client", "3") + api = artifact("org.apache.shenyu", "shenyu-common", "2.7.3-SNAPSHOT") + selected, reused = RUNTIME.select_dependencies([old, distinct_group, shaded, api], [core], repo, + ["org.glassfish.jersey.*:*"]) + self.assertEqual([distinct_group], selected) + self.assertEqual([{"artifact": "com.example:shared", "requested_version": "1", "admin_version": "2"}], reused) + + def test_duplicate_external_coordinate_is_rejected(self): + repo = self.root / "repository" + first = repo / "example/dependency/1/dependency-1.jar" + second = repo / "example/dependency/2/dependency-2.jar" + with self.assertRaisesRegex(ValueError, "Duplicate external"): + RUNTIME.select_dependencies([first, second], [], repo, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 23e437cd94b5..06b056a49f83 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,6 +89,8 @@ jobs: run: python3 script/performance/http-pool/test_report.py - name: Test HTTP pool Java argument files run: python3 script/performance/http-pool/test_runner.py + - name: Test external Eureka runtime assembly + run: python3 -B .github/scripts/test-external-eureka-runtime.py - name: Test Maven transfer retries run: bash .github/scripts/maven-with-retry-test.sh - name: Test storage Compose healthchecks diff --git a/.github/workflows/e2e-k8s.yml b/.github/workflows/e2e-k8s.yml index 9f360afce43c..1cf1ccb49a8c 100644 --- a/.github/workflows/e2e-k8s.yml +++ b/.github/workflows/e2e-k8s.yml @@ -117,6 +117,25 @@ jobs: run: | exec bash .github/scripts/maven-with-retry.sh ./mvnw -B clean install -Prelease,docker -Dmaven.javadoc.skip=true -Drat.skip=true -Dmaven.test.skip=true -Djacoco.skip=true -DskipITs -DskipTests -T1C + - name: Check out the pinned external Eureka candidate + if: contains(needs.changes.outputs.e2e_matrix, 'e2e-springcloud-sync-compose') + uses: actions/checkout@v4 + with: + repository: apache/shenyu-plugin-store + ref: be07c121085f219f46578515156e7a0bb20befdf + path: target/external-eureka-store + - name: Prepare the external Eureka runtime for Spring Cloud + if: contains(needs.changes.outputs.e2e_matrix, 'e2e-springcloud-sync-compose') + run: python3 .github/scripts/external-eureka-runtime.py prepare target/external-eureka-store target/external-eureka-runtime + - name: Upload the external Eureka runtime + if: contains(needs.changes.outputs.e2e_matrix, 'e2e-springcloud-sync-compose') + uses: actions/upload-artifact@v4 + with: + name: external-eureka-runtime + path: target/external-eureka-runtime/ + retention-days: 1 + if-no-files-found: error + - name: Prepare selected example and E2E Maven inputs env: E2E_MATRIX: ${{ needs.changes.outputs.e2e_matrix }} @@ -280,6 +299,13 @@ jobs: name: shenyu-local-maven-repository path: /tmp/shenyu-m2 + - name: Download the external Eureka runtime + if: matrix.script == 'e2e-springcloud-sync-compose' + uses: actions/download-artifact@v4 + with: + name: external-eureka-runtime + path: /tmp/shenyu-eureka-runtime + - name: Verify the image artifacts are present run: | missing=() @@ -327,6 +353,7 @@ jobs: - name: Run E2E Tests env: SHENYU_E2E_SYNC: ${{ matrix.sync }} + SHENYU_EUREKA_RUNTIME: /tmp/shenyu-eureka-runtime run: | bash ./shenyu-e2e/shenyu-e2e-case/${{ matrix.case }}/compose/script/${{ matrix.script }}.sh diff --git a/.github/workflows/integrated-test.yml b/.github/workflows/integrated-test.yml index 58247d5a739c..64c98f239915 100644 --- a/.github/workflows/integrated-test.yml +++ b/.github/workflows/integrated-test.yml @@ -111,6 +111,18 @@ jobs: shell: bash run: | exec bash .github/scripts/maven-with-retry.sh ./mvnw -B -T 1C clean install -Prelease,docker -Dmaven.javadoc.skip=true -Dmaven.test.skip=true + - name: Check out the pinned external Eureka candidate + if: matrix.case == 'shenyu-integrated-test-spring-cloud' + uses: actions/checkout@v4 + with: + repository: apache/shenyu-plugin-store + ref: be07c121085f219f46578515156e7a0bb20befdf + path: target/external-eureka-store + - name: Prepare the external Eureka runtime for Spring Cloud + if: matrix.case == 'shenyu-integrated-test-spring-cloud' + run: | + python3 .github/scripts/external-eureka-runtime.py prepare target/external-eureka-store target/external-eureka-runtime + echo "SHENYU_EUREKA_RUNTIME=$GITHUB_WORKSPACE/target/external-eureka-runtime" >> "$GITHUB_ENV" - name: Resolve required example projects id: examples env: diff --git a/README.md b/README.md index 408278893cd9..7aaaa6fd72a4 100644 --- a/README.md +++ b/README.md @@ -156,3 +156,5 @@ Organizations using Apache ShenYu are welcome to [register through GitHub issue ## License Apache ShenYu is licensed under the [Apache License, Version 2.0](LICENSE). + +Eureka registry externalization: see [the staged migration and rollback guide](docs/plugin-store-eureka.md). diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index dcd272092b30..03b50dcdaff6 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -46,6 +46,11 @@ ### API Changes +- The planned Eureka registry cutover retains the `eureka` type and transfers + `shenyu-registry-eureka` and its starter to plugin-store (#7596). + Merge requires compatible artifact publication and announced release/rollback + coordination. See [the migration guide](docs/plugin-store-eureka.md). + - WASM loaders support opt-in startup execution deadlines and per-instance linear-memory ceilings. Defaults remain disabled. Timed execution owns bounded workers, propagates interruption and replaces interrupted instances after physical exit. See diff --git a/docs/plugin-store-eureka.md b/docs/plugin-store-eureka.md new file mode 100644 index 000000000000..d4710c3e9a25 --- /dev/null +++ b/docs/plugin-store-eureka.md @@ -0,0 +1,219 @@ + + +# Eureka plugin-store migration + +Prepared cutover for apache/shenyu#7596. The receiving extension owns +shenyu-registry-eureka and shenyu-spring-boot-starter-registry-eureka. +The main-repository removal can be reviewed before publication, but must not merge until compatible artifacts are +published and the complete Admin/gateway deployment gate below passes. +Source preparation, local snapshot installation and this guide are not publication. + +## Compatibility and ownership + +Development validation uses store 2.7.1-SNAPSHOT, core 2.7.2-SNAPSHOT at cutover commit cfc267c8b (base 87c22dde7), +Microsoft OpenJDK 17.0.18 and Netflix eureka-client/eureka-client-jersey3 2.0.2. +The disposable server uses ShenYu's Spring Cloud Eureka example (4.1.2). +These are development coordinates and test scope, not a released compatibility matrix. + +The provider keeps its packages, non-singleton @Join annotation, eureka type key, +SPI resource and existing lease/registration behavior. Runtime parity testing also +corrects identity-only update comparison: changed upstream payloads produce updates; +an IP/port change removes the old URL before adding its replacement. Polling-failure +recovery remains covered. +No core factory dispatch or enum/SQL key changes are needed. It resolves through +ShenyuInstanceRegisterRepositoryFactory with an external provider JAR. +This transfer does not redesign Eureka instance identity, authentication or refresh policy. +In particular, current identity is derived by Eureka's configured instance builder; +do not treat the single-identity update test as certification for multiple replicas +using an identical default identity. + +The registry adapter is independent of Spring Cloud backend service discovery. +The generic main-repository Eureka server example and Spring Cloud transport E2E +fixtures remain usable while their broader test ownership is reviewed. They are not +default Admin/bootstrap registry dependencies and do not justify retaining the in-tree +registry provider. + +## Install + +Use a published store version explicitly announced compatible with the selected +core release. Keep one owner per Maven group/artifact/version. The same provider +coordinates/packages cannot coexist from both repositories on a runtime classpath. + +For gateway instance registration, add: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry-eureka + ${store.version} + +``` + +The external starter retains bound-port registration and owns provider cleanup on +application-context shutdown. It explicitly excludes +the core starter's old transitive Eureka provider. It contributes its external +provider instead. Other retained compatibility providers may remain on that +starter's classpath; exclude those explicitly if building a minimal assembly. + +Admin discovery and SDK deployments that already own their registration/discovery +wiring need the provider rather than the gateway starter: + +```xml + + org.apache.shenyu + shenyu-registry-eureka + ${store.version} + +``` + +The provider JAR isolates Jersey 3 transport, HK2 and JAX-RS classes under private +packages. This avoids the older Jersey providers found on the full Bootstrap +classpath while retaining shared ShenYu API/SPI class identity. Resolve the complete +runtime dependency closure when installing into lib/ distributions. Do not copy only the provider +JAR or replace retained core API/SPI classes with bundled duplicates. +The source remains ASF/Apache-2.0. Preserve Netflix/Jersey and resolved third-party +licenses/notices in custom binary distributions. + +## Enable and verify + +Gateway configuration retains its keys: + +```yaml +shenyu: + register: + enabled: true + registerType: eureka + serverLists: http://eureka:8761/eureka/ + props: + name: shenyu-gateway + host: gateway +``` + +The listener uses the actually bound server port unless props.port explicitly +overrides it. Existing SDK register-type=eureka and server-list settings retain +their current meaning; HTTP annotation registration to Admin is a separate flow. +Do not change Admin's HTTP client-registration transport to eureka merely to +enable the instance/discovery adapter. + +The starter tests cover disabled-by-default wiring, external SPI construction, +configuration binding and one registration at the bound port. Unit tests retain +the source module's polling and shutdown checks. The opt-in eureka-live Maven +profile launches no fake service: it requires -Deureka.test.url pointing at a +real disposable server and verifies registration, initial discovery, an instance +update/refresh, deregistration and watch shutdown. + +Example verification from a checkout with the core Maven wrapper available: + +```text +core/mvnw -f store/pom.xml -pl shenyu-extension/shenyu-extension-eureka/shenyu-spring-boot-starter-registry-eureka -am test +core/mvnw -f store/pom.xml -pl shenyu-extension/shenyu-extension-eureka/shenyu-registry-eureka -am verify -Peureka-live -Deureka.test.url=http://127.0.0.1:8761/eureka/ +``` + +The live profile must fail if its server URL is missing/unreachable; ordinary unit +tests do not silently substitute for it. Its CI lane builds the server and core +API artifacts from a pinned main commit, then runs the receiving provider. + +## Spring Cloud CI assembly + +The retained Spring Cloud integration and E2E fixtures use Eureka discovery in +Admin. After removing the in-tree provider, these fixtures explicitly install the +external candidate into Admin's `ext-lib` directory. The default Admin and +bootstrap images remain independent of the external provider. + +The workflows build receiver commit +`be07c121085f219f46578515156e7a0bb20befdf` against the current core checkout's +installed artifacts and version. The helper runs the receiver's unit/SPI tests, +Checkstyle and RAT, then assembles its shaded provider and remaining runtime +dependencies. It reuses dependencies already supplied by Admin by Maven +group/artifact/classifier, records both versions, and excludes classes already +shaded into the provider. Before accepting this reduced classpath, a Java probe +loads the external provider through the real ShenYu SPI and discovers an instance +through its shaded HTTP client against a loopback Eureka response fixture. +This probe checks packaged dependency compatibility; the subsequent Docker +integration/E2E jobs still have to pass their real server and gateway assertions. + +To reproduce the preparation after installing the core Admin reactor, check out +that exact receiver commit in a separate directory and run from the core checkout: + +```bash +python3 .github/scripts/external-eureka-runtime.py prepare /path/to/store /tmp/shenyu-eureka-runtime +export SHENYU_EUREKA_RUNTIME=/tmp/shenyu-eureka-runtime +``` + +Use a new output directory. `MAVEN_CONFIG` can supply local Maven settings. The +integration compose file mounts this directory read-only. The Spring Cloud E2E +script verifies the downloaded manifest's core/receiver commits and JAR hashes, +then merges the candidate into the existing MySQL driver mount without removing +the driver. A mismatched or incomplete candidate fails before containers start. +Changing either checkout requires preparing a new candidate. + +This fixed source candidate makes the cutover's existing CI fixtures executable +before publication. It is not a released compatibility matrix and does not waive +the coordinated publication or full deployment gates below. + +## Cutover gates + +1. Merge/review the receiving code and confirm published artifact ownership and + compatible core/store versions without duplicate coordinates. +2. Run the live provider lane and a complete disposable Eureka + Admin + bootstrap + environment using only the external runtime provider. Verify gateway instance + registration at its bound address, discovery, config refresh, deregistration, + healthy sibling behavior and restart/rollback. Record image/JAR digests and logs. +3. Package main Admin/bootstrap after removal and inspect dependency trees and + release licenses. Keep other registry implementations and SDK boundary tests green. +4. Publish external artifacts first, then merge the main removal in the coordinated + release and announce migration/rollback versions. Do not close #7596 before the + complete deployment and publication evidence exists. + +Local evidence on 2026-10-21: seven unit/SPI/starter tests pass with Checkstyle +and RAT, and a separate real-server provider lifecycle test passes. The complete +local process E2E passes 13 checkpoints using actual Eureka, H2 Admin and bootstrap +JVMs with the external provider JAR. It verifies class origins in both server +processes, bound-port registration, discovery/proxying, endpoint refresh and old +endpoint removal, graceful gateway deregistration, gateway restart, healthy sibling +preservation and final route removal. The harness uses a stdin-controlled Spring +context for graceful shutdown on Windows as well as Linux. + +The runtime source pair is core cfc267c8b and extension 8bf73dd; the tested registry +JAR SHA-256 is e5fefda48d00b17cf505549e100479b87c04a5d83ca7c0ef6c3547225fc8fc31. +The receiving repository retains the machine-readable process result under its +Eureka e2e/results directory. The CI lane is configured to repeat the live provider +and complete process tests; its configuration alone is not a passing CI result. +Docker image/container execution was not run. + +To reproduce the full process harness, first package core Admin, bootstrap and the +retained registry starter with dependency:build-classpath, setting +-Dmdep.outputFile=target/eureka-classpath.txt -DincludeScope=runtime. Package the +external Eureka starter reactor with the same classpath goal. Start the real Eureka +example server, then run e2e/run-local.py with --core, --store, --java, --eureka and +--output paths. The workflow records the complete wrapper commands and retains +redacted process/class-origin logs plus result.json. + +## Upgrade and rollback + +Back up the Admin database, registry configuration and exact old images/JARs. +Install the complete external closure in staging, remove the in-tree provider +version, and keep the eureka key and application/instance configuration unchanged. +Confirm discovery refresh and route/instance removal after a process dies; do not +infer success from a Maven build or an HTTP registration acknowledgement alone. + +For rollback, stop/drain the new processes and restore the last core distribution +that included the provider, removing the external copy. Preserve database/type +keys and Eureka applications. Clean up or expire obsolete instance records using +the deployment's existing lease/identity procedure. Do not clear the whole registry +or run two versions with identical classes in the same JVM. diff --git a/pom.xml b/pom.xml index 230113de8d1a..d6ed92b099c7 100644 --- a/pom.xml +++ b/pom.xml @@ -202,7 +202,6 @@ 2.0.1 8.2.3 3.9.2 - 2.0.2 1.2 19.0.3 1.14.11 @@ -802,12 +801,6 @@ ${caffeine.version} - - com.netflix.eureka - eureka-client - ${eureka.version} - - io.kubernetes client-java-spring-integration diff --git a/shenyu-admin/pom.xml b/shenyu-admin/pom.xml index 0ddc0693a0a4..0d39895c9271 100644 --- a/shenyu-admin/pom.xml +++ b/shenyu-admin/pom.xml @@ -384,12 +384,6 @@ ${project.version} runtime - - org.apache.shenyu - shenyu-registry-eureka - ${project.version} - runtime - org.apache.shenyu shenyu-registry-kubernetes diff --git a/shenyu-dist/shenyu-admin-dist/src/main/release-docs/LICENSE b/shenyu-dist/shenyu-admin-dist/src/main/release-docs/LICENSE index 23ca00901ba8..e1bf52698351 100644 --- a/shenyu-dist/shenyu-admin-dist/src/main/release-docs/LICENSE +++ b/shenyu-dist/shenyu-admin-dist/src/main/release-docs/LICENSE @@ -230,7 +230,6 @@ The text of each license is the standard Apache 2.0 license. client-java-api 19.0.3: https://mvnrepository.com/artifact/io.kubernetes/client-java-api, Apache 2.0 client-java 19.0.3: https://mvnrepository.com/artifact/io.kubernetes/client-java, Apache 2.0 client-java-proto 19.0.3: https://mvnrepository.com/artifact/io.kubernetes/client-java-proto, Apache 2.0 - eureka-client-jersey3 2.0.6: https://github.com/Netflix/eureka, Apache 2.0 annotations 13.0: http://source.android.com, Apache 2.0 annotations 4.1.1.4: http://source.android.com, Apache 2.0 attoparser 2.0.7.RELEASE: http://www.attoparser.org, Apache 2.0 @@ -434,10 +433,9 @@ The text of each license is the standard Apache 2.0 license. commons-jxpath 1.3: https://github.com/apache/commons-jxpath, Apache 2.0 commons-lang 2.6: https://github.com/apache/commons-lang, Apache 2.0 commons-logging 1.2: https://github.com/apache/commons-logging, Apache 2.0 - eureka-client 2.0.2 https://github.com/Netflix/eureka, Apache 2.0 j2objc-annotations 3.1 https://github.com/google/j2objc, Apache 2.0 jettison 1.5.4: https://github.com/jettison-json/jettison, Apache 2.0 - joda-time 2.3 https://www.joda.org/joda-time/, Apache 2.0 + joda-time 2.10.5 https://www.joda.org/joda-time/, Apache 2.0 netflix-eventbus 0.3.0: https://github.com/Netflix/netflix-commons, Apache 2.0 netflix-infix 0.3.0: https://github.com/Netflix/netflix-commons, Apache 2.0 servo-core 0.12.21: https://github.com/Netflix/servo, Apache 2.0 diff --git a/shenyu-dist/shenyu-admin-dist/src/main/release-docs/NOTICE b/shenyu-dist/shenyu-admin-dist/src/main/release-docs/NOTICE index 2372a66656ca..f1e934296a7f 100644 --- a/shenyu-dist/shenyu-admin-dist/src/main/release-docs/NOTICE +++ b/shenyu-dist/shenyu-admin-dist/src/main/release-docs/NOTICE @@ -1049,14 +1049,14 @@ W3.org documents ======================================================================== Bundled resources: - joda-time-2.3.jar / META-INF/NOTICE.txt + joda-time-2.10.5.jar / META-INF/NOTICE.txt ======================================================================== ============================================================================= = NOTICE file corresponding to section 4d of the Apache License Version 2.0 = ============================================================================= This product includes software developed by -Joda.org (http://www.joda.org/). +Joda.org (https://www.joda.org/). ======================================================================== Bundled resources: diff --git a/shenyu-dist/shenyu-admin-dist/src/main/release-docs/licenses/LICENSE-bundled-dependencies.txt b/shenyu-dist/shenyu-admin-dist/src/main/release-docs/licenses/LICENSE-bundled-dependencies.txt index 67da31a999b1..d89ff6feb982 100644 --- a/shenyu-dist/shenyu-admin-dist/src/main/release-docs/licenses/LICENSE-bundled-dependencies.txt +++ b/shenyu-dist/shenyu-admin-dist/src/main/release-docs/licenses/LICENSE-bundled-dependencies.txt @@ -1275,7 +1275,7 @@ Bundled resources: jackson-core-2.21.7.jar / META-INF/LICENSE jackson-databind-2.21.7.jar / META-INF/LICENSE jakarta.inject-api-2.0.1.jar / META-INF/LICENSE.txt - joda-time-2.3.jar / META-INF/LICENSE.txt + joda-time-2.10.5.jar / META-INF/LICENSE.txt log4j-api-2.25.5.jar / META-INF/LICENSE log4j-to-slf4j-2.25.5.jar / META-INF/LICENSE nacos-client-2.2.4.jar / META-INF/LICENSE.txt diff --git a/shenyu-e2e/shenyu-e2e-case/shenyu-e2e-case-spring-cloud/compose/script/e2e-springcloud-sync-compose.sh b/shenyu-e2e/shenyu-e2e-case/shenyu-e2e-case-spring-cloud/compose/script/e2e-springcloud-sync-compose.sh index a569860fc2a8..6de46ecf741a 100644 --- a/shenyu-e2e/shenyu-e2e-case/shenyu-e2e-case-spring-cloud/compose/script/e2e-springcloud-sync-compose.sh +++ b/shenyu-e2e/shenyu-e2e-case/shenyu-e2e-case-spring-cloud/compose/script/e2e-springcloud-sync-compose.sh @@ -23,6 +23,10 @@ source "$(dirname "$0")/../../../../../.github/scripts/select-e2e-sync.sh" SHENYU_TESTCASE_DIR=$(dirname "$(dirname "$(dirname "$(dirname "$0")")")") bash "${SHENYU_TESTCASE_DIR}"/k8s/script/storage/storage_init_mysql.sh +# Merge the verified external provider into the existing MySQL driver mount. +python3 .github/scripts/external-eureka-runtime.py install \ + "${SHENYU_EUREKA_RUNTIME:?Prepare the external Eureka runtime first}" /tmp/shenyu-e2e/mysql/driver || exit 1 + # init register center CUR_PATH=$(readlink -f "$(dirname "$0")") PRGDIR=$(dirname "$CUR_PATH") diff --git a/shenyu-examples/shenyu-examples-sdk/shenyu-examples-sdk-springcloud/shenyu-examples-sdk-springcloud-consumer/pom.xml b/shenyu-examples/shenyu-examples-sdk/shenyu-examples-sdk-springcloud/shenyu-examples-sdk-springcloud-consumer/pom.xml index 8ff4e584535f..f3af03b0c4c6 100644 --- a/shenyu-examples/shenyu-examples-sdk/shenyu-examples-sdk-springcloud/shenyu-examples-sdk-springcloud-consumer/pom.xml +++ b/shenyu-examples/shenyu-examples-sdk/shenyu-examples-sdk-springcloud/shenyu-examples-sdk-springcloud-consumer/pom.xml @@ -29,6 +29,8 @@ shenyu-examples-sdk-springcloud-consumer + + 2.7.1-SNAPSHOT 4.3.3 @@ -88,7 +90,7 @@ org.apache.shenyu shenyu-registry-eureka - ${project.version} + ${shenyu-plugin-store.version} servlet-api diff --git a/shenyu-integrated-test/shenyu-integrated-test-sdk-apache-dubbo/pom.xml b/shenyu-integrated-test/shenyu-integrated-test-sdk-apache-dubbo/pom.xml index 4a87214573ea..5a0ba54a4d67 100644 --- a/shenyu-integrated-test/shenyu-integrated-test-sdk-apache-dubbo/pom.xml +++ b/shenyu-integrated-test/shenyu-integrated-test-sdk-apache-dubbo/pom.xml @@ -62,10 +62,6 @@ org.apache.shenyu shenyu-registry-nacos - - org.apache.shenyu - shenyu-registry-eureka - org.apache.shenyu shenyu-registry-kubernetes diff --git a/shenyu-integrated-test/shenyu-integrated-test-sdk-http/pom.xml b/shenyu-integrated-test/shenyu-integrated-test-sdk-http/pom.xml index c6abfed027ef..b31ba765dba3 100644 --- a/shenyu-integrated-test/shenyu-integrated-test-sdk-http/pom.xml +++ b/shenyu-integrated-test/shenyu-integrated-test-sdk-http/pom.xml @@ -54,10 +54,6 @@ org.apache.shenyu shenyu-registry-nacos - - org.apache.shenyu - shenyu-registry-eureka - org.apache.shenyu shenyu-registry-kubernetes diff --git a/shenyu-integrated-test/shenyu-integrated-test-spring-cloud/docker-compose.yml b/shenyu-integrated-test/shenyu-integrated-test-spring-cloud/docker-compose.yml index 9cf83296c623..7ab53a0a2872 100644 --- a/shenyu-integrated-test/shenyu-integrated-test-spring-cloud/docker-compose.yml +++ b/shenyu-integrated-test/shenyu-integrated-test-spring-cloud/docker-compose.yml @@ -23,6 +23,8 @@ services: - shenyu ports: - "9095:9095" + volumes: + - "${SHENYU_EUREKA_RUNTIME:?Prepare the external Eureka runtime first}:/opt/shenyu-admin/ext-lib:ro" environment: - SPRING_PROFILES_ACTIVE=h2 - shenyu.sync.websocket.token=shenyu-sync-token diff --git a/shenyu-registry/README.md b/shenyu-registry/README.md index 66ea84e1b5c2..290cfc5c0cb7 100644 --- a/shenyu-registry/README.md +++ b/shenyu-registry/README.md @@ -41,7 +41,7 @@ runtime classpath, using the same ShenYu version as the application: | `etcd` | `shenyu-registry-etcd` | | `nacos` | `shenyu-registry-nacos` | | `apollo` | `shenyu-registry-apollo`; in-tree deprecation and planned external ownership: [migration guide](../docs/plugin-store-apollo.md) | -| `eureka` | `shenyu-registry-eureka` | +| `eureka` | External `shenyu-registry-eureka`; see [migration guide](../docs/plugin-store-eureka.md) | | `kubernetes` | `shenyu-registry-kubernetes` | Multiple implementation dependencies may coexist. The configured key selects the @@ -59,9 +59,9 @@ example selects Eureka, and the gRPC example selects no registry implementation. ## Compatibility and migration -For the 2.7.2 transition, `shenyu-spring-boot-starter-registry` retains the five providers -previously supplied by core: ZooKeeper, etcd, Nacos, Eureka and Kubernetes. Existing users -of that starter keep the same classpath and configuration keys. Apollo was not part of +For the 2.7.2 transition, `shenyu-spring-boot-starter-registry` retains four providers +previously supplied by core: ZooKeeper, etcd, Nacos and Kubernetes. Existing users +of that starter retain these providers; Eureka requires the external starter/provider. Configuration keys remain unchanged. Apollo was not part of the previous aggregate and remains an explicit choice. Removing the compatibility aggregate is deferred to a separately announced change. @@ -98,17 +98,16 @@ without any built-in provider dependency. | Consumer | Registry implementation inventory | | --- | --- | | Registry API/core, SDK libraries and SDK starters | None | -| Compatibility registry starter | ZooKeeper, etcd, Nacos, Eureka, Kubernetes | -| Admin distribution | ZooKeeper, etcd, Nacos, Eureka, Kubernetes, explicitly declared | +| Compatibility registry starter | ZooKeeper, etcd, Nacos, Kubernetes | +| Admin distribution | ZooKeeper, etcd, Nacos, Kubernetes, explicitly declared | | Bootstrap distribution | Registry API only; client libraries also arrive through sync/register/plugin modules | | SDK HTTP/Dubbo integration gateways | ZooKeeper | | Upload-plugin integration gateway | None; registry registration is not enabled | The packaged Admin client inventory includes Curator 5.7.0, ZooKeeper 3.9.5, jetcd -0.7.3, Nacos 2.2.4, Eureka 2.0.2, and Kubernetes Java client 17.0.2. Bootstrap still +0.7.3, Nacos 2.2.4 and Kubernetes Java client 17.0.2. Bootstrap still packages Curator, ZooKeeper, jetcd and Nacos through its other selected modules. Both -release archives include their LICENSE/NOTICE files. No registry client license entry -is removed by this change. +release archives include their LICENSE/NOTICE files. Eureka client licensing follows the external runtime closure; review the release inventory at cutover. Admin retains the same client libraries, so its existing distribution LICENSE/NOTICE entries still apply. Bootstrap distribution client libraries also come from selected diff --git a/shenyu-registry/pom.xml b/shenyu-registry/pom.xml index edaf5ce05294..9f27a9dbf921 100644 --- a/shenyu-registry/pom.xml +++ b/shenyu-registry/pom.xml @@ -33,7 +33,6 @@ shenyu-registry-etcd shenyu-registry-nacos shenyu-registry-apollo - shenyu-registry-eureka shenyu-registry-kubernetes diff --git a/shenyu-registry/shenyu-registry-eureka/pom.xml b/shenyu-registry/shenyu-registry-eureka/pom.xml deleted file mode 100644 index 7ab34988440d..000000000000 --- a/shenyu-registry/shenyu-registry-eureka/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - org.apache.shenyu - shenyu-registry - 2.7.3-SNAPSHOT - - 4.0.0 - shenyu-registry-eureka - - - - org.apache.shenyu - shenyu-registry-api - ${project.version} - - - - com.netflix.eureka - eureka-client - - - - com.netflix.eureka - eureka-client-jersey3 - 2.0.2 - - - diff --git a/shenyu-registry/shenyu-registry-eureka/src/main/java/org/apache/shenyu/registry/eureka/EurekaInstanceRegisterRepository.java b/shenyu-registry/shenyu-registry-eureka/src/main/java/org/apache/shenyu/registry/eureka/EurekaInstanceRegisterRepository.java deleted file mode 100644 index 33122bc12502..000000000000 --- a/shenyu-registry/shenyu-registry-eureka/src/main/java/org/apache/shenyu/registry/eureka/EurekaInstanceRegisterRepository.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * 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. - */ - -package org.apache.shenyu.registry.eureka; - -import com.google.gson.JsonObject; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.LeaseInfo; -import com.netflix.appinfo.MyDataCenterInstanceConfig; -import com.netflix.appinfo.RefreshableInstanceConfig; -import com.netflix.appinfo.UniqueIdentifier; -import com.netflix.appinfo.providers.Archaius1VipAddressResolver; -import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; -import com.netflix.discovery.DefaultEurekaClientConfig; -import com.netflix.discovery.DiscoveryClient; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.shared.transport.jersey3.Jersey3TransportClientFactories; -import org.apache.commons.lang.StringUtils; -import org.apache.shenyu.common.concurrent.ShenyuThreadFactory; -import org.apache.shenyu.common.exception.ShenyuException; -import org.apache.shenyu.common.utils.GsonUtils; -import org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository; -import org.apache.shenyu.registry.api.config.RegisterConfig; -import org.apache.shenyu.registry.api.entity.InstanceEntity; -import org.apache.shenyu.registry.api.event.ChangedEventListener; -import org.apache.shenyu.spi.Join; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.URI; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -@Join(isSingleton = false) -public class EurekaInstanceRegisterRepository implements ShenyuInstanceRegisterRepository { - - private static final Logger LOGGER = LoggerFactory.getLogger(EurekaInstanceRegisterRepository.class); - - private EurekaClient eurekaClient; - - private EurekaClient registerDiscoveryClient; - - private DefaultEurekaClientConfig eurekaClientConfig; - - private EurekaInstanceConfig eurekaInstanceConfig; - - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10, ShenyuThreadFactory.create("scheduled-eureka-watcher", true)); - - private final ConcurrentMap> listenerThreadsMap = new ConcurrentHashMap<>(); - - private final ConcurrentMap> instanceListMap = new ConcurrentHashMap<>(); - - @Override - public void init(final RegisterConfig config) { - eurekaInstanceConfig = new MyDataCenterInstanceConfig(); - eurekaClientConfig = new DefaultEurekaClientConfig() { - @Override - public List getEurekaServerServiceUrls(final String zone) { - return Arrays.asList(config.getServerLists().split(",")); - } - - @Override - public boolean shouldFetchRegistry() { - return false; - } - }; - - DefaultEurekaClientConfig eurekaClientNotRegisterEurekaConfig = new DefaultEurekaClientConfig() { - @Override - public List getEurekaServerServiceUrls(final String zone) { - return Arrays.asList(config.getServerLists().split(",")); - } - - @Override - public boolean shouldRegisterWithEureka() { - return false; - } - }; - LOGGER.info("eureka registry init..."); - eurekaClient = new DiscoveryClient(new ApplicationInfoManager(eurekaInstanceConfig, - new EurekaConfigBasedInstanceInfoProvider(eurekaInstanceConfig).get()), eurekaClientNotRegisterEurekaConfig, - new Jersey3TransportClientFactories()); - } - - @Override - public void persistInstance(final InstanceEntity instance) { - - InstanceInfo.Builder instanceInfoBuilder = instanceInfoBuilder(); - InstanceInfo instanceInfo = instanceInfoBuilder - .setAppName(instance.getAppName()) - .setIPAddr(instance.getHost()) - .setHostName(instance.getHost()) - .setPort(instance.getPort()) - .setLastDirtyTimestamp(System.currentTimeMillis()) - .setStatus(InstanceInfo.InstanceStatus.UP) - .build(); - LeaseInfo.Builder leaseInfoBuilder = LeaseInfo.Builder.newBuilder() - .setRenewalIntervalInSecs(eurekaInstanceConfig.getLeaseRenewalIntervalInSeconds()) - .setDurationInSecs(eurekaInstanceConfig.getLeaseExpirationDurationInSeconds()); - instanceInfo.setLeaseInfo(leaseInfoBuilder.build()); - ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(eurekaInstanceConfig, instanceInfo); - registerDiscoveryClient = new DiscoveryClient(applicationInfoManager, eurekaClientConfig, new Jersey3TransportClientFactories()); - LOGGER.info("eureka registry persistInstance success: {}", instanceInfo); - } - - @Override - public List selectInstances(final String selectKey) { - return getInstances(selectKey); - } - - @Override - public boolean serviceExists(final String key) { - try { - List instances = eurekaClient.getInstancesByVipAddressAndAppName(null, key, true); - return !instances.isEmpty(); - } catch (Exception e) { - throw new ShenyuException(e); - } - } - - @Override - public void watchInstances(final String key, final ChangedEventListener listener) { - try { - List initialInstances = eurekaClient.getInstancesByVipAddressAndAppName(null, key, true); - instanceListMap.put(key, initialInstances); - for (InstanceInfo instance : initialInstances) { - listener.onEvent(key, buildUpstreamJsonFromInstance(instance), ChangedEventListener.Event.ADDED); - } - ScheduledFuture scheduledFuture = executorService.scheduleAtFixedRate(() -> { - try { - List previousInstances = instanceListMap.get(key); - List currentInstances = eurekaClient.getInstancesByVipAddressAndAppName(null, key, true); - compareInstances(new HashSet<>(previousInstances), new HashSet<>(currentInstances), listener); - instanceListMap.put(key, currentInstances); - } catch (Exception e) { - // an exception escaping a fixed-rate task suppresses all later executions, - // so a single polling failure must only be logged to keep the watch alive - LOGGER.error("eureka registry eurekaDiscoveryService watch key: {} error", key, e); - } - }, 0, 1, TimeUnit.SECONDS); - listenerThreadsMap.put(key, scheduledFuture); - LOGGER.info("eureka registry subscribed to eureka updates for key: {}", key); - } catch (Exception e) { - LOGGER.error("eureka registry error watching key: {}", key, e); - throw new ShenyuException(e); - } - } - - @Override - public void unWatchInstances(final String key) { - try { - ScheduledFuture scheduledFuture = listenerThreadsMap.get(key); - if (Objects.nonNull(scheduledFuture)) { - scheduledFuture.cancel(true); - listenerThreadsMap.remove(key); - LOGGER.info("eureka registry unwatch key {} successfully", key); - } - } catch (Exception e) { - LOGGER.error("eureka registry error removing eureka watch task for key {} {}", key, e.getMessage(), e); - throw new ShenyuException(e); - } - } - - private void compareInstances(final Set previousInstances, final Set currentInstances, final ChangedEventListener listener) { - Set addedInstances = currentInstances.stream() - .filter(item -> !previousInstances.contains(item)) - .collect(Collectors.toSet()); - if (!addedInstances.isEmpty()) { - for (InstanceInfo instance : addedInstances) { - listener.onEvent(instance.getAppName(), buildUpstreamJsonFromInstance(instance), ChangedEventListener.Event.ADDED); - } - } - - Set deletedInstances = previousInstances.stream() - .filter(item -> !currentInstances.contains(item)) - .collect(Collectors.toSet()); - if (!deletedInstances.isEmpty()) { - for (InstanceInfo instance : deletedInstances) { - instance.setStatus(InstanceInfo.InstanceStatus.DOWN); - listener.onEvent(instance.getAppName(), buildUpstreamJsonFromInstance(instance), ChangedEventListener.Event.DELETED); - } - } - - Set updatedInstances = currentInstances.stream() - .filter(currentInstance -> previousInstances.stream() - .anyMatch(previousInstance -> currentInstance.getInstanceId().equals(previousInstance.getInstanceId()) && !currentInstance.equals(previousInstance))) - .collect(Collectors.toSet()); - if (!updatedInstances.isEmpty()) { - for (InstanceInfo instance : updatedInstances) { - listener.onEvent(instance.getAppName(), buildUpstreamJsonFromInstance(instance), ChangedEventListener.Event.UPDATED); - } - } - } - - private String buildUpstreamJsonFromInstance(final InstanceInfo instanceInfo) { - JsonObject upstreamJson = new JsonObject(); - upstreamJson.addProperty("url", instanceInfo.getIPAddr() + ":" + instanceInfo.getPort()); - upstreamJson.addProperty("weight", instanceInfo.getMetadata().get("weight")); - boolean secure = instanceInfo.isPortEnabled(InstanceInfo.PortType.SECURE); - String scheme = secure ? "https://" : "http://"; - upstreamJson.addProperty("protocol", Optional.ofNullable(instanceInfo.getMetadata().get("protocol")).orElse(scheme)); - upstreamJson.addProperty("props", instanceInfo.getMetadata().get("props")); - if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP) { - upstreamJson.addProperty("status", 0); - } else if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.DOWN) { - upstreamJson.addProperty("status", 1); - } - return GsonUtils.getInstance().toJson(upstreamJson); - } - - private List getInstances(final String selectKey) { - List instances = eurekaClient.getInstancesByVipAddressAndAppName(null, selectKey, true); - return instances.stream() - .map(i -> InstanceEntity.builder() - .appName(i.getAppName()).host(i.getHostName()).port(i.getPort()).uri(getURI(i)) - .build() - ).collect(Collectors.toList()); - } - - private URI getURI(final InstanceInfo instance) { - boolean secure = instance.isPortEnabled(InstanceInfo.PortType.SECURE); - String scheme = secure ? "https" : "http"; - int port = instance.getPort(); - if (port <= 0) { - port = secure ? 443 : 80; - } - String uri = String.format("%s://%s:%s", scheme, instance.getIPAddr(), port); - return URI.create(uri); - } - - @Override - public void close() { - try { - for (ScheduledFuture scheduledFuture : listenerThreadsMap.values()) { - scheduledFuture.cancel(true); - } - listenerThreadsMap.clear(); - if (Objects.nonNull(eurekaClient)) { - eurekaClient.getApplicationInfoManager().setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); - eurekaClient.shutdown(); - } - if (Objects.nonNull(registerDiscoveryClient)) { - registerDiscoveryClient.getApplicationInfoManager().setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); - registerDiscoveryClient.shutdown(); - } - LOGGER.info("eureka registry shutting down..."); - } catch (Exception e) { - LOGGER.error("eureka registry shutting down error", e); - throw new ShenyuException(e); - } - } - - /** - * Gets the instance information from the config instance and returns it after setting the appropriate status. - * ref: com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider#get - * - * @return InstanceInfo instance to be registered with eureka server - */ - public InstanceInfo.Builder instanceInfoBuilder() { - // Builder the instance information to be registered with eureka server - final InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(new Archaius1VipAddressResolver()); - - // set the appropriate id for the InstanceInfo, falling back to datacenter Id if applicable, else hostname - String instanceId = eurekaInstanceConfig.getInstanceId(); - if (StringUtils.isEmpty(instanceId)) { - DataCenterInfo dataCenterInfo = eurekaInstanceConfig.getDataCenterInfo(); - if (dataCenterInfo instanceof UniqueIdentifier) { - instanceId = ((UniqueIdentifier) dataCenterInfo).getId(); - } else { - instanceId = eurekaInstanceConfig.getHostName(false); - } - } - - String defaultAddress; - if (eurekaInstanceConfig instanceof RefreshableInstanceConfig) { - // Refresh AWS data center info, and return up to date address - defaultAddress = ((RefreshableInstanceConfig) eurekaInstanceConfig).resolveDefaultAddress(false); - } else { - defaultAddress = eurekaInstanceConfig.getHostName(false); - } - - // fail safe - if (StringUtils.isEmpty(defaultAddress)) { - defaultAddress = eurekaInstanceConfig.getIpAddress(); - } - - builder.setNamespace(eurekaInstanceConfig.getNamespace()) - .setInstanceId(instanceId) - .setAppName(eurekaInstanceConfig.getAppname()) - .setAppGroupName(eurekaInstanceConfig.getAppGroupName()) - .setDataCenterInfo(eurekaInstanceConfig.getDataCenterInfo()) - .setIPAddr(eurekaInstanceConfig.getIpAddress()) - .setHostName(defaultAddress) - .setPort(eurekaInstanceConfig.getNonSecurePort()) - .enablePort(InstanceInfo.PortType.UNSECURE, eurekaInstanceConfig.isNonSecurePortEnabled()) - .setSecurePort(eurekaInstanceConfig.getSecurePort()) - .enablePort(InstanceInfo.PortType.SECURE, eurekaInstanceConfig.getSecurePortEnabled()) - .setVIPAddress(eurekaInstanceConfig.getVirtualHostName()) - .setSecureVIPAddress(eurekaInstanceConfig.getSecureVirtualHostName()) - .setHomePageUrl(eurekaInstanceConfig.getHomePageUrlPath(), eurekaInstanceConfig.getHomePageUrl()) - .setStatusPageUrl(eurekaInstanceConfig.getStatusPageUrlPath(), eurekaInstanceConfig.getStatusPageUrl()) - .setASGName(eurekaInstanceConfig.getASGName()) - .setHealthCheckUrls(eurekaInstanceConfig.getHealthCheckUrlPath(), - eurekaInstanceConfig.getHealthCheckUrl(), eurekaInstanceConfig.getSecureHealthCheckUrl()); - - // Start off with the STARTING state to avoid traffic - if (!eurekaInstanceConfig.isInstanceEnabledOnit()) { - InstanceInfo.InstanceStatus initialStatus = InstanceInfo.InstanceStatus.STARTING; - LOGGER.info("Setting initial instance status as: {}", initialStatus); - builder.setStatus(initialStatus); - } else { - LOGGER.info("Setting initial instance status as: {}. This may be too early for the instance to advertise " - + "itself as available. You would instead want to control this via a healthcheck handler.", - InstanceInfo.InstanceStatus.UP); - } - - // Add any user-specific metadata information - for (Map.Entry mapEntry : eurekaInstanceConfig.getMetadataMap().entrySet()) { - String key = mapEntry.getKey(); - String value = mapEntry.getValue(); - // only add the metadata if the value is present - if (StringUtils.isNotEmpty(value)) { - builder.add(key, value); - } - } - return builder; - } -} diff --git a/shenyu-registry/shenyu-registry-eureka/src/main/resources/META-INF/shenyu/org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository b/shenyu-registry/shenyu-registry-eureka/src/main/resources/META-INF/shenyu/org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository deleted file mode 100644 index a0bf57c670f2..000000000000 --- a/shenyu-registry/shenyu-registry-eureka/src/main/resources/META-INF/shenyu/org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository +++ /dev/null @@ -1,17 +0,0 @@ -# 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. - -eureka=org.apache.shenyu.registry.eureka.EurekaInstanceRegisterRepository diff --git a/shenyu-registry/shenyu-registry-eureka/src/test/java/org/apache/shenyu/registry/eureka/EurekaInstanceRegisterRepositoryTest.java b/shenyu-registry/shenyu-registry-eureka/src/test/java/org/apache/shenyu/registry/eureka/EurekaInstanceRegisterRepositoryTest.java deleted file mode 100644 index b6985af23767..000000000000 --- a/shenyu-registry/shenyu-registry-eureka/src/test/java/org/apache/shenyu/registry/eureka/EurekaInstanceRegisterRepositoryTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * 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. - */ - -package org.apache.shenyu.registry.eureka; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.DiscoveryClient; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaEventListener; -import org.apache.shenyu.registry.api.config.RegisterConfig; -import org.apache.shenyu.registry.api.entity.InstanceEntity; -import org.apache.shenyu.registry.api.event.ChangedEventListener; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.MockedConstruction; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockConstruction; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public final class EurekaInstanceRegisterRepositoryTest { - - private EurekaInstanceRegisterRepository repository; - - private final InstanceEntity instance = new InstanceEntity("shenyu-instances", "shenyu-host", 9195); - - private final Map instanceStorage = new HashMap<>(); - - private final Map eurekaEventStorage = new HashMap<>(); - - private MockedConstruction discoveryClientMockedConstruction; - - @BeforeEach - public void setUp() throws Exception { - repository = new EurekaInstanceRegisterRepository(); - Class clazz = repository.getClass(); - - Field eurekaClientField = clazz.getDeclaredField("eurekaClient"); - eurekaClientField.setAccessible(true); - eurekaClientField.set(repository, mockEurekaClient()); - - RegisterConfig registerConfig = new RegisterConfig(); - registerConfig.setServerLists(""); - repository.init(registerConfig); - - // mock the function discoveryClient#register(). - discoveryClientMockedConstruction = mockConstruction(DiscoveryClient.class, (mock, context) -> { - InstanceInfo.Builder builder = repository.instanceInfoBuilder(); - builder.setAppName(instance.getAppName()) - .setIPAddr(instance.getHost()) - .setHostName(instance.getHost()) - .setPort(instance.getPort()) - .setStatus(InstanceInfo.InstanceStatus.UP); - InstanceInfo instanceInfo = builder.build(); - instanceStorage.put(instanceInfo.getAppName(), instanceInfo); - }); - } - - private EurekaClient mockEurekaClient() { - DiscoveryClient discoveryClient = mock(DiscoveryClient.class); - - doAnswer(invocationOnMock -> { - eurekaEventStorage.clear(); - return null; - }).when(discoveryClient).shutdown(); - - return discoveryClient; - } - - @Test - public void persistInstance() { - repository.persistInstance(instance); - assertTrue(instanceStorage.containsKey(instance.getAppName().toUpperCase())); - InstanceInfo instanceInfo = instanceStorage.get(instance.getAppName().toUpperCase()); - assertEquals(instance.getHost(), instanceInfo.getHostName()); - assertEquals(instance.getPort(), instanceInfo.getPort()); - assertEquals(instance.getAppName().toUpperCase(), instanceInfo.getAppName()); - } - - @Test - public void testSelectInstancesAndWatcher() { - repository.selectInstances(instance.getAppName()); - repository.close(); - assertTrue(eurekaEventStorage.isEmpty()); - } - - @Test - public void testWatchInstancesKeepsPollingAfterFailure() throws Exception { - InstanceInfo info = mock(InstanceInfo.class); - when(info.getAppName()).thenReturn(instance.getAppName()); - when(info.getIPAddr()).thenReturn("10.0.0.1"); - when(info.getPort()).thenReturn(8080); - when(info.getInstanceId()).thenReturn("instance-1"); - when(info.getMetadata()).thenReturn(new HashMap<>()); - when(info.isPortEnabled(InstanceInfo.PortType.SECURE)).thenReturn(false); - when(info.getStatus()).thenReturn(InstanceInfo.InstanceStatus.UP); - - EurekaClient failingThenRecovering = mock(EurekaClient.class); - when(failingThenRecovering.getApplicationInfoManager()).thenReturn(mock(ApplicationInfoManager.class)); - when(failingThenRecovering.getInstancesByVipAddressAndAppName(nullable(String.class), eq(instance.getAppName()), anyBoolean())) - .thenReturn(new ArrayList<>()) - .thenThrow(new RuntimeException("eureka temporarily unavailable")) - .thenReturn(Collections.singletonList(info)); - - Field eurekaClientField = repository.getClass().getDeclaredField("eurekaClient"); - eurekaClientField.setAccessible(true); - eurekaClientField.set(repository, failingThenRecovering); - - ChangedEventListener listener = mock(ChangedEventListener.class); - repository.watchInstances(instance.getAppName(), listener); - - verify(listener, timeout(5000).atLeastOnce()) - .onEvent(eq(instance.getAppName()), anyString(), eq(ChangedEventListener.Event.ADDED)); - repository.close(); - } - - @AfterEach - public void clear() { - discoveryClientMockedConstruction.close(); - } -} diff --git a/shenyu-registry/shenyu-registry-eureka/src/test/java/org/apache/shenyu/registry/eureka/RegistrySpiTest.java b/shenyu-registry/shenyu-registry-eureka/src/test/java/org/apache/shenyu/registry/eureka/RegistrySpiTest.java deleted file mode 100644 index ea1f39c636e2..000000000000 --- a/shenyu-registry/shenyu-registry-eureka/src/test/java/org/apache/shenyu/registry/eureka/RegistrySpiTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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. - */ - -package org.apache.shenyu.registry.eureka; - -import org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository; -import org.apache.shenyu.spi.ExtensionLoader; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class RegistrySpiTest { - - @Test - void discoversPublishedRegistryKey() { - ShenyuInstanceRegisterRepository repository = ExtensionLoader.getExtensionLoader(ShenyuInstanceRegisterRepository.class).getJoin("eureka"); - assertEquals(EurekaInstanceRegisterRepository.class, repository.getClass()); - } -} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/pom.xml index a6949a4bb9ce..660a22e5051c 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/pom.xml @@ -48,11 +48,6 @@ shenyu-registry-nacos ${project.version} - - org.apache.shenyu - shenyu-registry-eureka - ${project.version} - org.apache.shenyu shenyu-registry-kubernetes diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/src/test/java/org/apache/shenyu/springboot/starter/registry/RegistryClasspathTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/src/test/java/org/apache/shenyu/springboot/starter/registry/RegistryClasspathTest.java index 52076875132e..d12151708301 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/src/test/java/org/apache/shenyu/springboot/starter/registry/RegistryClasspathTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-registry/src/test/java/org/apache/shenyu/springboot/starter/registry/RegistryClasspathTest.java @@ -51,9 +51,9 @@ void disabledRegistrationStartsWithoutARegistryConnection() { } @Test - void compatibilityStarterStillDiscoversItsOriginalProviders() { + void compatibilityStarterDiscoversRetainedProviders() { assertThat(ExtensionLoader.getExtensionLoader(ShenyuInstanceRegisterRepository.class).getExtensionClasses1()) - .containsKeys("zookeeper", "etcd", "nacos", "eureka", "kubernetes"); + .containsKeys("zookeeper", "etcd", "nacos", "kubernetes"); } @Test