-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Add new CassandraContainer implementation #8616
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
eddumelendez
merged 17 commits into
testcontainers:main
from
maximevw:upgrade-cassandra-driver
Aug 13, 2024
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
5479ced
Upgrade Java driver for Cassandra to latest version
maximevw 437abf6
Fix documentation for Cassandra module
maximevw 10a64b4
Merge branch 'testcontainers:main' into upgrade-cassandra-driver
maximevw 2e9e295
Add CassandraContainer implementation without dependency on Java driver
maximevw 16a644b
Using -f argument to execute init script in Cassandra container
maximevw d39cef2
Reformat code
maximevw ff8648b
Apply changes following code review
maximevw 23d98f4
Fix tests formatting
maximevw a054714
Cleanup the tests following review
maximevw 9fc9ff4
Merge branch 'main' into upgrade-cassandra-driver
eddumelendez 0f1cc35
Improve init script documentation and tests when authentication is re…
maximevw 9cd6625
Merge branch 'testcontainers:main' into upgrade-cassandra-driver
maximevw cd0e35f
Improve documentation
maximevw 01790ae
Update modules/cassandra/src/main/java/org/testcontainers/cassandra/C…
maximevw ebeffab
Set CassandraQueryWaitStrategy by default
maximevw e5db72d
Update docs/modules/databases/cassandra.md
eddumelendez 2314621
Fix format
eddumelendez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
176 changes: 176 additions & 0 deletions
176
modules/cassandra/src/main/java/org/testcontainers/cassandra/CassandraContainer.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,176 @@ | ||
package org.testcontainers.cassandra; | ||
|
||
import com.github.dockerjava.api.command.InspectContainerResponse; | ||
import org.testcontainers.cassandra.delegate.CassandraDatabaseDelegate; | ||
import org.testcontainers.cassandra.wait.CassandraQueryWaitStrategy; | ||
import org.testcontainers.containers.GenericContainer; | ||
import org.testcontainers.ext.ScriptUtils; | ||
import org.testcontainers.ext.ScriptUtils.ScriptLoadException; | ||
import org.testcontainers.utility.DockerImageName; | ||
import org.testcontainers.utility.MountableFile; | ||
|
||
import java.io.File; | ||
import java.net.InetSocketAddress; | ||
import java.net.URISyntaxException; | ||
import java.net.URL; | ||
import java.util.Optional; | ||
|
||
/** | ||
* Testcontainers implementation for Apache Cassandra. | ||
* <p> | ||
* Supported image: {@code cassandra} | ||
* <p> | ||
* Exposed ports: 9042 | ||
*/ | ||
public class CassandraContainer extends GenericContainer<CassandraContainer> { | ||
|
||
private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("cassandra"); | ||
|
||
private static final Integer CQL_PORT = 9042; | ||
|
||
private static final String DEFAULT_LOCAL_DATACENTER = "datacenter1"; | ||
|
||
private static final String CONTAINER_CONFIG_LOCATION = "/etc/cassandra"; | ||
|
||
private static final String USERNAME = "cassandra"; | ||
|
||
private static final String PASSWORD = "cassandra"; | ||
|
||
private String configLocation; | ||
|
||
private String initScriptPath; | ||
|
||
public CassandraContainer(String dockerImageName) { | ||
this(DockerImageName.parse(dockerImageName)); | ||
} | ||
|
||
public CassandraContainer(DockerImageName dockerImageName) { | ||
super(dockerImageName); | ||
dockerImageName.assertCompatibleWith(DEFAULT_IMAGE_NAME); | ||
|
||
addExposedPort(CQL_PORT); | ||
|
||
withEnv("CASSANDRA_SNITCH", "GossipingPropertyFileSnitch"); | ||
withEnv("JVM_OPTS", "-Dcassandra.skip_wait_for_gossip_to_settle=0 -Dcassandra.initial_token=0"); | ||
withEnv("HEAP_NEWSIZE", "128M"); | ||
withEnv("MAX_HEAP_SIZE", "1024M"); | ||
withEnv("CASSANDRA_ENDPOINT_SNITCH", "GossipingPropertyFileSnitch"); | ||
withEnv("CASSANDRA_DC", DEFAULT_LOCAL_DATACENTER); | ||
|
||
// Use the CassandraQueryWaitStrategy by default to avoid potential issues when the authentication is enabled. | ||
waitingFor(new CassandraQueryWaitStrategy()); | ||
} | ||
|
||
@Override | ||
protected void configure() { | ||
// Map (effectively replace) directory in Docker with the content of resourceLocation if resource location is | ||
// not null. | ||
Optional | ||
.ofNullable(configLocation) | ||
.map(MountableFile::forClasspathResource) | ||
.ifPresent(mountableFile -> withCopyFileToContainer(mountableFile, CONTAINER_CONFIG_LOCATION)); | ||
} | ||
|
||
@Override | ||
protected void containerIsStarted(InspectContainerResponse containerInfo) { | ||
runInitScriptIfRequired(); | ||
} | ||
|
||
/** | ||
* Load init script content and apply it to the database if initScriptPath is set | ||
*/ | ||
private void runInitScriptIfRequired() { | ||
if (initScriptPath != null) { | ||
try { | ||
URL resource = Thread.currentThread().getContextClassLoader().getResource(initScriptPath); | ||
if (resource == null) { | ||
logger().warn("Could not load classpath init script: {}", initScriptPath); | ||
throw new ScriptLoadException( | ||
"Could not load classpath init script: " + initScriptPath + ". Resource not found." | ||
); | ||
} | ||
// The init script is executed as is by the cqlsh command, so copy it into the container. | ||
String targetInitScriptName = new File(resource.toURI()).getName(); | ||
copyFileToContainer(MountableFile.forClasspathResource(initScriptPath), targetInitScriptName); | ||
new CassandraDatabaseDelegate(this).execute(null, targetInitScriptName, -1, false, false); | ||
} catch (URISyntaxException e) { | ||
logger().warn("Could not copy init script into container: {}", initScriptPath); | ||
throw new ScriptLoadException("Could not copy init script into container: " + initScriptPath, e); | ||
} catch (ScriptUtils.ScriptStatementFailedException e) { | ||
logger().error("Error while executing init script: {}", initScriptPath, e); | ||
throw new ScriptUtils.UncategorizedScriptException( | ||
"Error while executing init script: " + initScriptPath, | ||
e | ||
); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Initialize Cassandra with the custom overridden Cassandra configuration | ||
* <p> | ||
* Be aware, that Docker effectively replaces all /etc/cassandra content with the content of config location, so if | ||
* Cassandra.yaml in configLocation is absent or corrupted, then Cassandra just won't launch | ||
* | ||
* @param configLocation relative classpath with the directory that contains cassandra.yaml and other configuration files | ||
*/ | ||
public CassandraContainer withConfigurationOverride(String configLocation) { | ||
this.configLocation = configLocation; | ||
return self(); | ||
} | ||
|
||
/** | ||
* Initialize Cassandra with init CQL script | ||
* <p> | ||
* CQL script will be applied after container is started (see using WaitStrategy). | ||
* </p> | ||
* | ||
* @param initScriptPath relative classpath resource | ||
*/ | ||
public CassandraContainer withInitScript(String initScriptPath) { | ||
this.initScriptPath = initScriptPath; | ||
return self(); | ||
} | ||
|
||
/** | ||
* Get username | ||
* | ||
* By default, Cassandra has authenticator: AllowAllAuthenticator in cassandra.yaml | ||
* If username and password need to be used, then authenticator should be set as PasswordAuthenticator | ||
* (through custom Cassandra configuration) and through CQL with default cassandra-cassandra credentials | ||
* user management should be modified | ||
*/ | ||
public String getUsername() { | ||
return USERNAME; | ||
} | ||
|
||
/** | ||
* Get password | ||
* | ||
* By default, Cassandra has authenticator: AllowAllAuthenticator in cassandra.yaml | ||
* If username and password need to be used, then authenticator should be set as PasswordAuthenticator | ||
* (through custom Cassandra configuration) and through CQL with default cassandra-cassandra credentials | ||
* user management should be modified | ||
*/ | ||
public String getPassword() { | ||
return PASSWORD; | ||
} | ||
eddumelendez marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Retrieve an {@link InetSocketAddress} for connecting to the Cassandra container via the driver. | ||
* | ||
* @return A InetSocketAddrss representation of this Cassandra container's host and port. | ||
*/ | ||
public InetSocketAddress getContactPoint() { | ||
return new InetSocketAddress(getHost(), getMappedPort(CQL_PORT)); | ||
} | ||
|
||
/** | ||
* Retrieve the Local Datacenter for connecting to the Cassandra container via the driver. | ||
* | ||
* @return The configured local Datacenter name. | ||
*/ | ||
public String getLocalDatacenter() { | ||
return getEnvMap().getOrDefault("CASSANDRA_DC", DEFAULT_LOCAL_DATACENTER); | ||
} | ||
} |
83 changes: 83 additions & 0 deletions
83
...sandra/src/main/java/org/testcontainers/cassandra/delegate/CassandraDatabaseDelegate.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
package org.testcontainers.cassandra.delegate; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.apache.commons.lang3.ArrayUtils; | ||
import org.apache.commons.lang3.StringUtils; | ||
import org.testcontainers.cassandra.CassandraContainer; | ||
import org.testcontainers.containers.Container; | ||
import org.testcontainers.containers.ContainerState; | ||
import org.testcontainers.containers.ExecConfig; | ||
import org.testcontainers.delegate.AbstractDatabaseDelegate; | ||
import org.testcontainers.ext.ScriptUtils.ScriptStatementFailedException; | ||
|
||
import java.io.IOException; | ||
|
||
/** | ||
* Cassandra database delegate | ||
*/ | ||
@Slf4j | ||
@RequiredArgsConstructor | ||
public class CassandraDatabaseDelegate extends AbstractDatabaseDelegate<Void> { | ||
|
||
private final ContainerState container; | ||
|
||
@Override | ||
protected Void createNewConnection() { | ||
// Return null here, because we run scripts using cqlsh command directly in the container. | ||
// So, we don't use connection object in the execute() method. | ||
return null; | ||
} | ||
|
||
@Override | ||
public void execute( | ||
String statement, | ||
String scriptPath, | ||
int lineNumber, | ||
boolean continueOnError, | ||
boolean ignoreFailedDrops | ||
) { | ||
try { | ||
// Use cqlsh command directly inside the container to execute statements | ||
// See documentation here: https://cassandra.apache.org/doc/stable/cassandra/tools/cqlsh.html | ||
String[] cqlshCommand = new String[] { "cqlsh" }; | ||
|
||
if (this.container instanceof CassandraContainer) { | ||
CassandraContainer cassandraContainer = (CassandraContainer) this.container; | ||
String username = cassandraContainer.getUsername(); | ||
String password = cassandraContainer.getPassword(); | ||
cqlshCommand = ArrayUtils.addAll(cqlshCommand, "-u", username, "-p", password); | ||
maximevw marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
// If no statement specified, directly execute the script specified into scriptPath (using -f argument), | ||
// otherwise execute the given statement (using -e argument). | ||
String executeArg = "-e"; | ||
String executeArgValue = statement; | ||
if (StringUtils.isBlank(statement)) { | ||
executeArg = "-f"; | ||
executeArgValue = scriptPath; | ||
} | ||
cqlshCommand = ArrayUtils.addAll(cqlshCommand, executeArg, executeArgValue); | ||
|
||
Container.ExecResult result = | ||
this.container.execInContainer(ExecConfig.builder().command(cqlshCommand).build()); | ||
if (result.getExitCode() == 0) { | ||
if (StringUtils.isBlank(statement)) { | ||
log.info("CQL script {} successfully executed", scriptPath); | ||
} else { | ||
log.info("CQL statement {} was applied", statement); | ||
} | ||
} else { | ||
log.error("CQL script execution failed with error: \n{}", result.getStderr()); | ||
throw new ScriptStatementFailedException(statement, lineNumber, scriptPath); | ||
} | ||
} catch (IOException | InterruptedException e) { | ||
throw new ScriptStatementFailedException(statement, lineNumber, scriptPath, e); | ||
} | ||
} | ||
|
||
@Override | ||
protected void closeConnectionQuietly(Void session) { | ||
// Nothing to do here, because we run scripts using cqlsh command directly in the container. | ||
} | ||
} |
47 changes: 47 additions & 0 deletions
47
...cassandra/src/main/java/org/testcontainers/cassandra/wait/CassandraQueryWaitStrategy.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package org.testcontainers.cassandra.wait; | ||
|
||
import org.rnorth.ducttape.TimeoutException; | ||
import org.testcontainers.cassandra.delegate.CassandraDatabaseDelegate; | ||
import org.testcontainers.containers.ContainerLaunchException; | ||
import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy; | ||
import org.testcontainers.delegate.DatabaseDelegate; | ||
|
||
import java.util.concurrent.TimeUnit; | ||
|
||
import static org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess; | ||
|
||
/** | ||
* Waits until Cassandra returns its version | ||
*/ | ||
public class CassandraQueryWaitStrategy extends AbstractWaitStrategy { | ||
|
||
private static final String SELECT_VERSION_QUERY = "SELECT release_version FROM system.local"; | ||
|
||
private static final String TIMEOUT_ERROR = "Timed out waiting for Cassandra to be accessible for query execution"; | ||
|
||
@Override | ||
protected void waitUntilReady() { | ||
// execute select version query until success or timeout | ||
try { | ||
retryUntilSuccess( | ||
(int) startupTimeout.getSeconds(), | ||
TimeUnit.SECONDS, | ||
() -> { | ||
getRateLimiter() | ||
.doWhenReady(() -> { | ||
try (DatabaseDelegate databaseDelegate = getDatabaseDelegate()) { | ||
databaseDelegate.execute(SELECT_VERSION_QUERY, "", 1, false, false); | ||
} | ||
}); | ||
return true; | ||
} | ||
); | ||
} catch (TimeoutException e) { | ||
throw new ContainerLaunchException(TIMEOUT_ERROR); | ||
} | ||
} | ||
|
||
private DatabaseDelegate getDatabaseDelegate() { | ||
return new CassandraDatabaseDelegate(waitStrategyTarget); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.