diff --git a/.github/workflows/run-s3-rustfs-integration-tests.yml b/.github/workflows/run-s3-rustfs-integration-tests.yml new file mode 100644 index 00000000..b1946157 --- /dev/null +++ b/.github/workflows/run-s3-rustfs-integration-tests.yml @@ -0,0 +1,23 @@ +name: Run S3-RustFS integration tests + +on: + workflow_dispatch: + push: + branches: [ develop ] + paths: + - 'src/s3-rustfs/**' + pull_request: + branches: [ develop ] + paths: + - 'src/s3-rustfs/**' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + s3-rustfs: + uses: ./.github/workflows/run-module-integration-tests.yml + with: + module: s3-rustfs + secrets: inherit diff --git a/CHANGELOG.md b/CHANGELOG.md index dde7ae59..1a9620aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ * The last states/errors of strategies are now stored * If a strategy times out the last state is collected and attached to the corresponding timeout * Renamed and moved `JDBCWaitStrategy` → `JDBCAbortableWaitStrategy` +* Added `s3-rustfs` module #762 * Update dependencies # 4.8.1 diff --git a/README.md b/README.md index 1d2be053..e737778a 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ Modules for XDEV's Testcontainer Infrastructure Framework * Predefined implementation for [Mockserver](https://github.com/xdev-software/mockserver-neolight) * [oidc-server-mock](./src/oidc-server-mock/) * Predefined implementation for [OIDC Server Mock](https://github.com/xdev-software/oidc-server-mock) +* [s3-rustfs](./src/s3-rustfs/) + * Predefined implementation for using S3 with [RustFS](https://github.com/rustfs/rustfs) * [selenium](./src/selenium/) * Predefined implementation for [Selenium](https://github.com/SeleniumHQ/selenium) * Includes improvements from [xdev-software/testcontainers-selenium](https://github.com/xdev-software/testcontainers-selenium/) diff --git a/demos/advanced-demo/integration-tests/tci-webapp/src/main/java/software/xdev/tci/demo/tci/webapp/WebAppTCI.java b/demos/advanced-demo/integration-tests/tci-webapp/src/main/java/software/xdev/tci/demo/tci/webapp/WebAppTCI.java index ee96147b..b9edf15f 100644 --- a/demos/advanced-demo/integration-tests/tci-webapp/src/main/java/software/xdev/tci/demo/tci/webapp/WebAppTCI.java +++ b/demos/advanced-demo/integration-tests/tci-webapp/src/main/java/software/xdev/tci/demo/tci/webapp/WebAppTCI.java @@ -27,11 +27,13 @@ public String getActuatorPassword() public String getInternalHTTPEndpoint() { + // noinspection HttpUrlsUsage return "http://" + this.getNetworkAlias() + ":" + WebAppContainer.DEFAULT_HTTP_PORT; } public String getExternalHTTPEndpoint() { + // noinspection HttpUrlsUsage return "http://" + this.getContainer().getHost() + ":" + this.getContainer().getMappedPort(WebAppContainer.DEFAULT_HTTP_PORT); } diff --git a/src/base/src/main/java/software/xdev/tci/TCI.java b/src/base/src/main/java/software/xdev/tci/TCI.java index c295e9d8..4bf21f4a 100644 --- a/src/base/src/main/java/software/xdev/tci/TCI.java +++ b/src/base/src/main/java/software/xdev/tci/TCI.java @@ -15,12 +15,19 @@ */ package software.xdev.tci; +import java.util.Map; import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; import org.rnorth.ducttape.unreliables.Unreliables; +import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; +import software.xdev.tci.concurrent.LazyConstantSuppliers; import software.xdev.tci.safestart.SafeNamedContainerStarter; @@ -37,6 +44,10 @@ @SuppressWarnings("java:S119") public class TCI> { + protected static final Map, Logger> LOGGER_CACHE = new ConcurrentHashMap<>(); + + private final Supplier loggerSupplier; + private C container; private String networkAlias; private Runnable onStopped; @@ -45,6 +56,12 @@ protected TCI(final C container, final String networkAlias) { this.container = Objects.requireNonNull(container); this.networkAlias = networkAlias; + this.loggerSupplier = LazyConstantSuppliers.of(this::createLogger); + } + + protected Logger createLogger() + { + return LOGGER_CACHE.computeIfAbsent(this.getClass(), LoggerFactory::getLogger); } public void setOnStopped(final Runnable onStopped) @@ -104,4 +121,38 @@ public String getNetworkAlias() { return this.networkAlias; } + + protected Logger logger() + { + return this.loggerSupplier.get(); + } + + protected void closeAndFree(@Nullable final AutoCloseable closeable, final String name, final Runnable freeUp) + { + if(closeable != null) + { + this.closeNonNull(closeable, name); + freeUp.run(); + } + } + + protected void close(@Nullable final AutoCloseable closeable, final String name) + { + if(closeable != null) + { + this.closeNonNull(closeable, name); + } + } + + protected void closeNonNull(@NonNull final AutoCloseable closeable, final String name) + { + try + { + closeable.close(); + } + catch(final Exception ex) + { + this.logger().warn("Failed to close {}", name, ex); + } + } } diff --git a/src/db-jdbc/src/main/java/software/xdev/tci/db/BaseDBTCI.java b/src/db-jdbc/src/main/java/software/xdev/tci/db/BaseDBTCI.java index 427e23a9..b12d6b17 100644 --- a/src/db-jdbc/src/main/java/software/xdev/tci/db/BaseDBTCI.java +++ b/src/db-jdbc/src/main/java/software/xdev/tci/db/BaseDBTCI.java @@ -17,8 +17,6 @@ import java.sql.Driver; import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Supplier; @@ -27,8 +25,6 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.testcontainers.containers.JdbcDatabaseContainer; import software.xdev.tci.TCI; @@ -38,8 +34,6 @@ public abstract class BaseDBTCI> extends TCI { - protected static final Map, Logger> LOGGER_CACHE = new ConcurrentHashMap<>(); - public static final String DEFAULT_DATABASE = "testdb"; public static final String DEFAULT_USERNAME = "testuser"; @SuppressWarnings("java:S2068") // This is only for tests @@ -47,7 +41,6 @@ public abstract class BaseDBTCI> extends TCI< protected final boolean migrateAndInitializeEMC; protected final Supplier> emcFactorySupplier; - protected final Logger logger; protected String database = DEFAULT_DATABASE; protected String username = DEFAULT_USERNAME; @@ -65,8 +58,6 @@ protected BaseDBTCI( super(container, networkAlias); this.migrateAndInitializeEMC = migrateAndInitializeEMC; this.emcFactorySupplier = emcFactorySupplier; - - this.logger = LOGGER_CACHE.computeIfAbsent(this.getClass(), LoggerFactory::getLogger); } @Override @@ -76,32 +67,21 @@ public void start(final String containerName) if(this.migrateAndInitializeEMC) { // Do basic migrations async - this.log().debug("Running migration to basic structure"); + this.logger().debug("Running migration to basic structure"); this.execInitialDatabaseMigration(); - this.log().info("Migration executed"); + this.logger().info("Migration executed"); // Create EMC in background to improve performance (~5s) - this.log().debug("Initializing EntityManagerController..."); + this.logger().debug("Initializing EntityManagerController..."); this.getEMC(); - this.log().info("Initialized EntityManagerController"); + this.logger().info("Initialized EntityManagerController"); } } @Override public void stop() { - if(this.emc != null) - { - try - { - this.emc.close(); - } - catch(final Exception ex) - { - this.log().warn("Failed to close EntityManagerController", ex); - } - this.emc = null; - } + this.closeAndFree(this.emc, "EntityManagerController", () -> this.emc = null); super.stop(); } @@ -180,11 +160,6 @@ public void migrateDatabase(final Collection locations) public abstract void migrateDatabase(final String... locations); - protected Logger log() - { - return this.logger; - } - // region Configure public BaseDBTCI withDatabase(final String database) diff --git a/src/mailpit/src/main/java/software/xdev/tci/mailpit/MailpitTCI.java b/src/mailpit/src/main/java/software/xdev/tci/mailpit/MailpitTCI.java index ead979a5..879e9304 100644 --- a/src/mailpit/src/main/java/software/xdev/tci/mailpit/MailpitTCI.java +++ b/src/mailpit/src/main/java/software/xdev/tci/mailpit/MailpitTCI.java @@ -21,7 +21,6 @@ import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; import org.apache.hc.core5.util.Timeout; -import org.slf4j.LoggerFactory; import software.xdev.mailpit.client.ApiClient; import software.xdev.tci.TCI; @@ -39,6 +38,7 @@ public MailpitTCI(final MailpitContainer container, final String networkAlias) public String getExternalHTTPEndpoint() { + // noinspection HttpUrlsUsage return "http://" + this.getContainer().getHost() + ":" @@ -54,16 +54,15 @@ public ApiClient apiClient() final Duration defaultTimeout = Duration.ofSeconds(30); - this.apiClient = new ApiClient(); - this.apiClient.setHttpClient(HttpClientBuilder.create() + this.apiClient = new ApiClient(HttpClientBuilder.create() .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create() .setDefaultConnectionConfig(ConnectionConfig.custom() .setConnectTimeout(Timeout.of(defaultTimeout)) .setSocketTimeout(Timeout.of(defaultTimeout)) .build()) .build()) - .build()); - this.apiClient.setBasePath(this.getExternalHTTPEndpoint()); + .build()) + .setBasePath(this.getExternalHTTPEndpoint()); return this.apiClient; } @@ -73,14 +72,7 @@ public void stop() { if(this.apiClient != null) { - try - { - this.apiClient.getHttpClient().close(); - } - catch(final Exception e) - { - LoggerFactory.getLogger(this.getClass()).warn("Failed to close API client", e); - } + this.closeNonNull(this.apiClient.getHttpClient(), "API client"); } super.stop(); } diff --git a/src/mailpit/src/main/java/software/xdev/tci/mailpit/containers/MailpitContainer.java b/src/mailpit/src/main/java/software/xdev/tci/mailpit/containers/MailpitContainer.java index 98f25a03..0a6318d4 100644 --- a/src/mailpit/src/main/java/software/xdev/tci/mailpit/containers/MailpitContainer.java +++ b/src/mailpit/src/main/java/software/xdev/tci/mailpit/containers/MailpitContainer.java @@ -31,7 +31,12 @@ public class MailpitContainer extends GenericContainer public MailpitContainer() { - super(DEFAULT_IMAGE); + this(DEFAULT_IMAGE); + } + + public MailpitContainer(final DockerImageName dockerImageName) + { + super(dockerImageName); // Version check is not needed in tests this.addEnv("MP_DISABLE_VERSION_CHECK", "true"); diff --git a/src/mailpit/src/test/java/software/xdev/tci/mailpit/SimpleMailpitTest.java b/src/mailpit/src/test/java/software/xdev/tci/mailpit/SimpleMailpitTest.java index f3468ce9..684e49f3 100644 --- a/src/mailpit/src/test/java/software/xdev/tci/mailpit/SimpleMailpitTest.java +++ b/src/mailpit/src/test/java/software/xdev/tci/mailpit/SimpleMailpitTest.java @@ -40,8 +40,6 @@ import software.xdev.tci.factory.registry.TCIFactoryRegistry; import software.xdev.tci.mailpit.containers.MailpitContainer; import software.xdev.tci.mailpit.factory.MailpitTCIFactory; -import software.xdev.tci.network.LazyNetwork; -import software.xdev.tci.network.LazyNetworkPool; class SimpleMailpitTest @@ -52,16 +50,12 @@ class SimpleMailpitTest container.addExposedPort(MailpitTCIFactory.SMTP_PORT); return container; }); - protected static final LazyNetworkPool LAZY_NETWORK_POOL = new LazyNetworkPool(); - protected LazyNetwork network; protected MailpitTCI mailpitInfra; @BeforeAll static void beforeAll() { - LAZY_NETWORK_POOL.managePoolAsync(); - TCIFactoryRegistry.instance().warmUp(); // Preload classes @@ -71,8 +65,7 @@ static void beforeAll() @BeforeEach void beforeEach() { - this.network = LAZY_NETWORK_POOL.getNew(); - this.mailpitInfra = FACTORY.getNew(this.network); + this.mailpitInfra = FACTORY.getNew(null); } @Test @@ -129,17 +122,11 @@ void afterEach() this.mailpitInfra.stop(); this.mailpitInfra = null; } - if(this.network != null) - { - this.network.close(); - this.network = null; - } } @AfterAll static void afterAll() { FACTORY.close(); - LAZY_NETWORK_POOL.close(); } } diff --git a/src/oidc-server-mock/src/main/java/software/xdev/tci/oidc/BaseOIDCTCI.java b/src/oidc-server-mock/src/main/java/software/xdev/tci/oidc/BaseOIDCTCI.java index d8a6d040..86884604 100644 --- a/src/oidc-server-mock/src/main/java/software/xdev/tci/oidc/BaseOIDCTCI.java +++ b/src/oidc-server-mock/src/main/java/software/xdev/tci/oidc/BaseOIDCTCI.java @@ -24,8 +24,6 @@ import java.util.function.Function; import org.rnorth.ducttape.unreliables.Unreliables; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import software.xdev.tci.TCI; import software.xdev.tci.envperf.EnvironmentPerformance; @@ -40,8 +38,6 @@ public abstract class BaseOIDCTCI< A extends OIDCServerMockApi> extends TCI { - private static final Logger LOG = LoggerFactory.getLogger(BaseOIDCTCI.class); - public static final String CLIENT_ID = BaseOIDCServerContainer.DEFAULT_CLIENT_ID; public static final String CLIENT_SECRET = BaseOIDCServerContainer.DEFAULT_CLIENT_SECRET; @@ -102,14 +98,7 @@ protected void closeAndFreeAPI() { if(this.api instanceof final AutoCloseable autoCloseableApi) { - try - { - autoCloseableApi.close(); - } - catch(final Exception ex) - { - LOG.warn("Failed to close API", ex); - } + this.closeNonNull(autoCloseableApi, "API"); } this.api = null; } diff --git a/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/ApiTest.java b/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/ApiTest.java index a093e9d0..c30f4bb8 100644 --- a/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/ApiTest.java +++ b/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/ApiTest.java @@ -15,30 +15,14 @@ */ package software.xdev.tci.oidc.api; -import org.junit.jupiter.api.BeforeAll; - -import software.xdev.tci.network.LazyNetwork; -import software.xdev.tci.network.LazyNetworkPool; import software.xdev.tci.oidc.BaseOIDCTCI; public abstract class ApiTest> { - private static final LazyNetworkPool LAZY_NETWORK_POOL = new LazyNetworkPool(); - - protected LazyNetwork network; protected T oidcInfra; - @BeforeAll - static void beforeAll() - { - LAZY_NETWORK_POOL.managePoolAsync(); - } - - protected void beforeEach() - { - this.network = LAZY_NETWORK_POOL.getNew(); - } + protected abstract void beforeEach(); protected void afterEach() { @@ -47,10 +31,5 @@ protected void afterEach() this.oidcInfra.stop(); this.oidcInfra = null; } - if(this.network != null) - { - this.network.close(); - this.network = null; - } } } diff --git a/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/jackson/JacksonApiTest.java b/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/jackson/JacksonApiTest.java index ee1118ae..6b058a4c 100644 --- a/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/jackson/JacksonApiTest.java +++ b/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/jackson/JacksonApiTest.java @@ -32,8 +32,7 @@ class JacksonApiTest extends ApiTest @BeforeEach protected void beforeEach() { - super.beforeEach(); - this.oidcInfra = FACTORY.getNew(this.network); + this.oidcInfra = FACTORY.getNew(null); } @Test diff --git a/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/simple/SimpleApiTest.java b/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/simple/SimpleApiTest.java index 1d00cbc9..8f1500e6 100644 --- a/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/simple/SimpleApiTest.java +++ b/src/oidc-server-mock/src/test/java/software/xdev/tci/oidc/api/simple/SimpleApiTest.java @@ -34,8 +34,7 @@ class SimpleApiTest extends ApiTest @BeforeEach protected void beforeEach() { - super.beforeEach(); - this.oidcInfra = FACTORY.getNew(this.network); + this.oidcInfra = FACTORY.getNew(null); } @Test diff --git a/src/pom.xml b/src/pom.xml index 95f973e9..df1e18b4 100644 --- a/src/pom.xml +++ b/src/pom.xml @@ -28,6 +28,7 @@ mailpit mockserver oidc-server-mock + s3-rustfs selenium spring-dao-support diff --git a/src/s3-rustfs/Dockerfile b/src/s3-rustfs/Dockerfile new file mode 100644 index 00000000..c6ec7816 --- /dev/null +++ b/src/s3-rustfs/Dockerfile @@ -0,0 +1,3 @@ +# This file is just used as a reminder to update the latest minor version in +# RustFSContainer.java from time to time +FROM rustfs/rustfs:1.0.5 diff --git a/src/s3-rustfs/README.md b/src/s3-rustfs/README.md new file mode 100644 index 00000000..90f9bf78 --- /dev/null +++ b/src/s3-rustfs/README.md @@ -0,0 +1,3 @@ +# S3-RustFS + +TCI for [RustFS](https://github.com/rustfs/rustfs). diff --git a/src/s3-rustfs/pom.xml b/src/s3-rustfs/pom.xml new file mode 100644 index 00000000..5e4160f1 --- /dev/null +++ b/src/s3-rustfs/pom.xml @@ -0,0 +1,92 @@ + + + 4.0.0 + + + software.xdev.tci + src + 4.9.0-SNAPSHOT + + + s3-rustfs + jar + + s3-rustfs + TCI - s3-rustfs + + + + true + + 2.26.1 + + + + + software.xdev.tci + base + 4.9.0-SNAPSHOT + + + + software.amazon.awssdk + s3 + 2.57.11 + + + + software.amazon.awssdk + crt-core + + + + software.amazon.awssdk + netty-nio-client + + + + + + + org.junit.jupiter + junit-jupiter + 6.1.3 + test + + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + test + + + org.apache.logging.log4j + log4j-slf4j2-impl + ${log4j.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${skipTests} + + + + + + + run-it + + false + + + + diff --git a/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/RustFSTCI.java b/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/RustFSTCI.java new file mode 100644 index 00000000..722d881c --- /dev/null +++ b/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/RustFSTCI.java @@ -0,0 +1,150 @@ +/* + * Copyright © 2024 XDEV Software (https://xdev.software) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package software.xdev.tci.s3.rustfs; + +import java.net.URI; +import java.util.List; + +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3Configuration; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.xdev.tci.TCI; +import software.xdev.tci.s3.rustfs.containers.RustFSContainer; + + +public class RustFSTCI extends TCI +{ + private final List initialBucketsToCreate; + + private S3Client s3Client; + private S3Presigner s3Presigner; + + public RustFSTCI( + final RustFSContainer container, + final String networkAlias, + final List initialBucketsToCreate) + { + super(container, networkAlias); + this.initialBucketsToCreate = initialBucketsToCreate; + } + + public S3Client s3Client() + { + if(this.s3Client == null) + { + this.initS3Client(); + } + + return this.s3Client; + } + + protected synchronized void initS3Client() + { + if(this.s3Client == null) + { + this.s3Client = this.createS3Client(); + } + } + + protected S3Client createS3Client() + { + return S3Client.builder() + .credentialsProvider(this.createCredentialsProvider()) + .region(Region.US_EAST_1) // Just here so that it doesn't crash + .endpointOverride(URI.create(this.getContainer().gets3Url())) + .forcePathStyle(true) + .build(); + } + + public S3Presigner s3Presigner() + { + if(this.s3Presigner == null) + { + this.initS3Presigner(); + } + return this.s3Presigner; + } + + protected synchronized void initS3Presigner() + { + if(this.s3Presigner == null) + { + this.s3Presigner = this.createS3Presigner(); + } + } + + protected S3Presigner createS3Presigner() + { + return S3Presigner.builder() + .credentialsProvider(this.createCredentialsProvider()) + .region(Region.US_EAST_1) // Just here so that it doesn't crash + .endpointOverride(URI.create(this.getExternalS3Url())) + .serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build()) + .build(); + } + + protected AwsCredentialsProvider createCredentialsProvider() + { + return StaticCredentialsProvider.create(AwsBasicCredentials.create( + this.getContainer().getUsername(), + this.getContainer().getPassword())); + } + + @SuppressWarnings("resource") + public RustFSTCI createBucket(final String bucket) + { + try + { + this.s3Client().createBucket(b -> b.bucket(bucket)); + } + catch(final Exception e) + { + throw new IllegalStateException("Failed to create bucket " + bucket, e); + } + return this; + } + + @Override + public void start(final String containerName) + { + super.start(containerName); + + this.initialBucketsToCreate.forEach(this::createBucket); + } + + @Override + public void stop() + { + this.closeAndFree(this.s3Client, "s3Client", () -> this.s3Client = null); + this.closeAndFree(this.s3Presigner, "s3Presigner", () -> this.s3Presigner = null); + super.stop(); + } + + public String getExternalS3Url() + { + return this.getContainer().gets3Url(); + } + + public static String getInternalS3URL(final String dnsName) + { + // noinspection HttpUrlsUsage + return "http://" + dnsName + ":" + RustFSContainer.S3_PORT; + } +} diff --git a/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/containers/RustFSContainer.java b/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/containers/RustFSContainer.java new file mode 100644 index 00000000..cc76c86b --- /dev/null +++ b/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/containers/RustFSContainer.java @@ -0,0 +1,94 @@ +/* + * Copyright © 2024 XDEV Software (https://xdev.software) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package software.xdev.tci.s3.rustfs.containers; + +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.images.RemoteDockerImage; +import org.testcontainers.utility.DockerImageName; + + +@SuppressWarnings("java:S2068") +public class RustFSContainer extends GenericContainer +{ + public static final DockerImageName DEFAULT_IMAGE = DockerImageName.parse("rustfs/rustfs:1.0.5"); + + public static final int S3_PORT = 9000; + + public static final String DEFAULT_USERNAME = "rustfs"; + public static final String DEFAULT_PASSWORD = "rustfs"; + + protected String username = DEFAULT_USERNAME; + protected String password = DEFAULT_PASSWORD; + + public RustFSContainer(final DockerImageName dockerImageName) + { + super(dockerImageName); + } + + public RustFSContainer(final RemoteDockerImage image) + { + super(image); + } + + public RustFSContainer() + { + this(DEFAULT_IMAGE); + + this.withCommand("server", "/data"); + this.addExposedPort(S3_PORT); + } + + public RustFSContainer withUsername(final String username) + { + this.username = username; + return this; + } + + public RustFSContainer withPassword(final String password) + { + this.password = password; + return this; + } + + @Override + protected void configure() + { + if(this.username != null) + { + this.addEnv("RUSTFS_ACCESS_KEY", this.username); + } + if(this.password != null) + { + this.addEnv("RUSTFS_SECRET_KEY", this.password); + } + } + + public String gets3Url() + { + // noinspection HttpUrlsUsage + return "http://" + this.getHost() + ":" + this.getMappedPort(S3_PORT); + } + + public String getUsername() + { + return this.username; + } + + public String getPassword() + { + return this.password; + } +} diff --git a/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/factory/RustFSTCIFactory.java b/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/factory/RustFSTCIFactory.java new file mode 100644 index 00000000..9ddde04b --- /dev/null +++ b/src/s3-rustfs/src/main/java/software/xdev/tci/s3/rustfs/factory/RustFSTCIFactory.java @@ -0,0 +1,52 @@ +/* + * Copyright © 2024 XDEV Software (https://xdev.software) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package software.xdev.tci.s3.rustfs.factory; + +import static software.xdev.tci.envperf.EnvironmentPerformance.cpuSlownessFactor; + +import java.time.Duration; +import java.util.List; + +import software.xdev.tci.factory.prestart.PreStartableTCIFactory; +import software.xdev.tci.misc.ContainerMemory; +import software.xdev.tci.s3.rustfs.RustFSTCI; +import software.xdev.tci.s3.rustfs.containers.RustFSContainer; +import software.xdev.tci.startup.wait.FastAbortOnContainerDeathWaitStrategy; +import software.xdev.tci.startup.wait.strategy.HostPortWaitAbortableStrategy; +import software.xdev.tci.startup.wait.strategy.HttpWaitAbortableStrategy; + + +public class RustFSTCIFactory extends PreStartableTCIFactory +{ + @SuppressWarnings("checkstyle:MagicNumber") + public RustFSTCIFactory(final String... bucketsToCreate) + { + super( + (c, na) -> new RustFSTCI(c, na, List.of(bucketsToCreate)), + () -> new RustFSContainer() + .withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withMemory(ContainerMemory.M512M)) + .waitingFor(FastAbortOnContainerDeathWaitStrategy.waitAll(s -> s + .withStartupTimeout(Duration.ofSeconds(30 + 20L * cpuSlownessFactor())) + .withStrategy(new HostPortWaitAbortableStrategy()) + .withStrategy(new HttpWaitAbortableStrategy() + .forPath("/health/ready") + .forPort(RustFSContainer.S3_PORT) + ))), + "s3-rustfs", + "container.s3.rustfs", + "S3-RustFS"); + } +} diff --git a/src/s3-rustfs/src/test/java/software/xdev/tci/s3/rustfs/SimpleS3RustFSTest.java b/src/s3-rustfs/src/test/java/software/xdev/tci/s3/rustfs/SimpleS3RustFSTest.java new file mode 100644 index 00000000..6e226e14 --- /dev/null +++ b/src/s3-rustfs/src/test/java/software/xdev/tci/s3/rustfs/SimpleS3RustFSTest.java @@ -0,0 +1,106 @@ +/* + * Copyright © 2024 XDEV Software (https://xdev.software) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package software.xdev.tci.s3.rustfs; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.Bucket; +import software.amazon.awssdk.services.s3.model.S3Object; +import software.xdev.tci.factory.registry.TCIFactoryRegistry; +import software.xdev.tci.s3.rustfs.factory.RustFSTCIFactory; + + +class SimpleS3RustFSTest +{ + protected static final String BUCKET = "test"; + protected static final RustFSTCIFactory FACTORY = new RustFSTCIFactory(BUCKET); + + protected RustFSTCI rustFSInfra; + + @BeforeAll + static void beforeAll() + { + TCIFactoryRegistry.instance().warmUp(); + } + + @BeforeEach + void beforeEach() + { + this.rustFSInfra = FACTORY.getNew(null); + } + + @Test + void check() + { + final S3Client s3Client = this.rustFSInfra.s3Client(); + final List buckets = s3Client.listBuckets().buckets(); + assertEquals(1, buckets.size()); + assertEquals(BUCKET, buckets.getFirst().name()); + + final String fileName = "test-file.txt"; + s3Client.putObject( + b -> b + .bucket(BUCKET) + .key(fileName), + RequestBody.fromString("THIS_IS_A_TEST")); + + final List contents = s3Client.listObjects(b -> b.bucket(BUCKET)) + .contents(); + + assertEquals(1, contents.size()); + assertEquals(fileName, contents.getFirst().key()); + + final String presignedUrl = this.rustFSInfra.s3Presigner().presignGetObject(b -> b + .getObjectRequest(br -> br + .bucket(BUCKET) + .key(fileName) + .build()) + .signatureDuration(Duration.ofMinutes(10))) + .url() + .toString(); + + Assertions.assertTrue(presignedUrl.startsWith( + this.rustFSInfra.getExternalS3Url() + "/" + BUCKET + "/" + fileName)); + } + + @AfterEach + void afterEach() + { + if(this.rustFSInfra != null) + { + this.rustFSInfra.stop(); + this.rustFSInfra = null; + } + } + + @AfterAll + static void afterAll() + { + FACTORY.close(); + } +} diff --git a/src/s3-rustfs/src/test/resources/log4j2-test.xml b/src/s3-rustfs/src/test/resources/log4j2-test.xml new file mode 100644 index 00000000..f30d015b --- /dev/null +++ b/src/s3-rustfs/src/test/resources/log4j2-test.xml @@ -0,0 +1,28 @@ + + + + + + %d{HH:mm:ss} %-5p [%t] [%-25.25c] %m %n + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/selenium/src/main/java/software/xdev/tci/selenium/BrowserTCI.java b/src/selenium/src/main/java/software/xdev/tci/selenium/BrowserTCI.java index c4abf012..3ab91b86 100644 --- a/src/selenium/src/main/java/software/xdev/tci/selenium/BrowserTCI.java +++ b/src/selenium/src/main/java/software/xdev/tci/selenium/BrowserTCI.java @@ -35,8 +35,6 @@ import org.openqa.selenium.remote.http.HttpClient; import org.rnorth.ducttape.timeouts.Timeouts; import org.rnorth.ducttape.unreliables.Unreliables; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.testcontainers.lifecycle.TestDescription; import software.xdev.tci.TCI; @@ -48,8 +46,6 @@ public class BrowserTCI extends TCI { - private static final Logger LOG = LoggerFactory.getLogger(BrowserTCI.class); - protected static final Supplier DEFAULT_HTTP_CLIENT_FACTORY_PROVIDER = LazyConstantSuppliers.of(HttpClient.Factory::createDefault); @@ -133,7 +129,7 @@ public void start(final String containerName) @SuppressWarnings("checkstyle:MagicNumber") protected void initWebDriver() { - LOG.debug("Initializing WebDriver"); + this.logger().debug("Initializing WebDriver"); final HttpClient.Factory factory = this.httpClientFactoryProvider.get(); final AtomicInteger retryCounter = new AtomicInteger(1); this.webDriver = Unreliables.retryUntilSuccess( @@ -156,7 +152,7 @@ protected RemoteWebDriver tryCreateWebDriver(final HttpClient.Factory factory, f final ClientConfig config = this.clientConfig.baseUri(this.getContainer().getSeleniumAddressURI()); final int tryCount = retryCounter.getAndIncrement(); - LOG.info( + this.logger().info( "Creating new WebDriver [retryCount={},retrySec={},clientConfig={}] Try #{}", this.webDriverRetryCount, this.webDriverRetrySec, @@ -188,12 +184,12 @@ protected RemoteWebDriver tryCreateWebDriver(final HttpClient.Factory factory, f // Cancel further communication and abort all connections try { - LOG.warn("Encounter problem in try #{} - Terminating communication", tryCount, rex); + this.logger().warn("Encounter problem in try #{} - Terminating communication", tryCount, rex); client.close(); } catch(final Exception ex) { - LOG.warn("Failed to cleanup try #{}", tryCount, ex); + this.logger().warn("Failed to cleanup try #{}", tryCount, ex); } throw rex; @@ -219,7 +215,7 @@ protected void installBrowserLogInspector() return; } - LOG.info("Installing Log Inspector"); + this.logger().info("Installing Log Inspector"); this.logInspector = new LogInspector(this.webDriver); final String name = this.getContainer().getContainerNameCleaned(); @@ -273,18 +269,8 @@ public void stop() if(this.logInspector != null) { final long startMs = System.currentTimeMillis(); - try - { - this.logInspector.close(); - } - catch(final Exception e) - { - LOG.warn("Failed to stop logInspector", e); - } - finally - { - LOG.debug("Stopping logInspector took {}ms", System.currentTimeMillis() - startMs); - } + this.closeNonNull(this.logInspector, "logInspector"); + this.logger().debug("Stopping logInspector took {}ms", System.currentTimeMillis() - startMs); this.logInspector = null; } if(this.webDriver != null) @@ -296,11 +282,11 @@ public void stop() } catch(final Exception e) { - LOG.warn("Failed to quit webdriver", e); + this.logger().warn("Failed to quit webdriver", e); } finally { - LOG.debug("Quiting driver took {}ms", System.currentTimeMillis() - startMs); + this.logger().debug("Quiting driver took {}ms", System.currentTimeMillis() - startMs); } this.webDriver = null; }