Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ package grails.gorm.tests
import java.time.Duration

import groovy.transform.CompileStatic
import groovy.transform.PackageScope
import org.testcontainers.containers.ContainerFetchException
import org.testcontainers.containers.GenericContainer
import org.testcontainers.db2.Db2Container
import org.testcontainers.mariadb.MariaDBContainer
import org.testcontainers.mysql.MySQLContainer
Expand Down Expand Up @@ -52,14 +55,90 @@ final class DatabaseContainers {
static final OracleContainer ORACLE = new OracleContainer('gvenzl/oracle-free:slim-faststart')
.withStartupTimeout(Duration.ofMinutes(3))

static final String DB2_IMAGE = 'icr.io/db2_community/db2:11.5.9.0'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Optional) DB2_IMAGE is only used inside DatabaseContainers, so this can be private static final.


/**
* Db2 for Linux, UNIX and Windows. IBM publishes the image for amd64 only, so the Db2 rows run on the amd64 CI
* runners and are skipped on arm64 machines. It starts in one to three minutes.
*/
static final Db2Container DB2 = new Db2Container('icr.io/db2_community/db2:11.5.9.0')
static final Db2Container DB2 = new Db2Container(DB2_IMAGE)
.acceptLicense()
.withStartupTimeout(Duration.ofMinutes(10))

private static final ImageFetch DB2_IMAGE_FETCH = new ImageFetch(DB2, DB2_IMAGE)

private DatabaseContainers() {
}

/**
* Starts the container of a row unless it is running already. A row without a container runs on H2.
* <p>
* The Db2 image comes from IBM's registry, icr.io, which the Docker daemon of some GitHub-hosted runners cannot
* reach at all, for as long as the job runs. {@code start()} retries a failing fetch for two minutes, and then once
* more while it builds its error message, so every Db2 row waited that long before it failed, about 20 minutes for a
* job. The image is therefore fetched once per test JVM, before the container is started, and when that fails, the
* first Db2 row fails with the failure and every later one fails with it at once.
*
* @param container the container of the row, or {@code null} for H2
* @throws ContainerFetchException if the container is Db2 and its image cannot be fetched
*/
static void start(GenericContainer container) {
start(container, DB2, DB2_IMAGE_FETCH)
}

/**
* Starts the container of a row as {@link #start(GenericContainer)} does, with the Db2 container and the fetch of
* its image given, so that a test can give its own.
*/
@PackageScope
static void start(GenericContainer container, GenericContainer db2, ImageFetch db2ImageFetch) {
if (container == null || container.running) {
return
}
if (container.is(db2)) {
db2ImageFetch.fetch()
}
container.start()
}

/**
* The image of a container, fetched once. A failure is remembered, so every later row that needs the image fails at
* once instead of fetching it again.
*/
@CompileStatic
static final class ImageFetch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Optional) ImageFetch is only referenced within grails.gorm.tests; marking it @PackageScope matches the package-private start overload.


private final GenericContainer container
private final String image
private boolean attempted
private ContainerFetchException failure

ImageFetch(GenericContainer container, String image) {
this.container = container
this.image = image
}

/**
* Fetches the image unless that was tried before.
*
* @throws ContainerFetchException if the image cannot be fetched
*/
synchronized void fetch() {
if (!attempted) {
try {
// Pulls the image unless Docker has it; the container keeps the name, so start() does not pull again
container.dockerImageName

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Optional) container.getDockerImageName() reads more clearly than bare property access container.dockerImageName when the call is made solely for its side effect.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd keep the property: the Groovy in this module reads getters as properties, and the comment above the line says it's read for the pull.

} catch (ContainerFetchException e) {
failure = e
}
// Not set when an error ends the fetch, so the next row fetches the image again
attempted = true
}
if (failure != null) {
// The message of the exception only names the image; its cause says what went wrong
throw new ContainerFetchException(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A row that needs a database image runs when that image cannot be fetched. The suite fails, because the failed fetch is thrown instead of skipping that row. Skip the row.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's on purpose: a missing image has to fail the suite. The first version of this PR skipped the row, and codeconsole's review showed what that hides. A tag that isn't there gets a 404 on every runner, so a typo or a retired tag would have skipped the Db2 rows in every job, and a local run would have skipped them without a word. Since f061141 the rows fail instead, but after one round of attempts, about 3.5 minutes instead of about 20, and with a message that names the image and the cause. On a westus3 runner, a rerun of the job usually lands in another region and passes.

"Pulling ${image} failed: ${failure.cause?.message ?: failure.message}", failure)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
/*
* 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
*
* https://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 grails.gorm.tests

import com.github.dockerjava.api.exception.NotFoundException
import org.testcontainers.containers.ContainerFetchException
import org.testcontainers.containers.ContainerLaunchException
import org.testcontainers.containers.GenericContainer
import org.testcontainers.shaded.org.awaitility.core.ConditionTimeoutException

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Optional) ImageFetch.fetch() only reads failure.cause?.message ?: failure.message and does not branch on the cause type. Importing Testcontainers' internal shaded ConditionTimeoutException (and transitive docker-java NotFoundException) couples this test to Testcontainers' shading layout while timeout() and notFound() exercise the same branch. Using plain new RuntimeException('...') avoids those imports, and adding a new RuntimeException() case (non-null cause with null message) covers the ?: fallback branch too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the row for a cause without a message. I'd keep the two exception types, though. They are what Testcontainers and the Docker daemon throw for the two failures we've seen, a registry that doesn't answer and a tag that isn't there, and the 404 row shows the Status 404: that docker-java puts before the message, as the Db2 rows show it. If Testcontainers stops shading Awaitility, the spec stops compiling, so it can't go stale unnoticed.


import spock.lang.Specification

class DatabaseContainersSpec extends Specification {

private static final String IMAGE = 'registry.example/db:1'

void 'a row without a container, or with one that is running, starts nothing'() {
given:
final GenericContainer running = Mock()

when:
DatabaseContainers.start(null)
DatabaseContainers.start(running)

then:
1 * running.isRunning() >> true
0 * running._
}

void 'the container of a row other than Db2 is started without fetching an image first'() {
given:
final GenericContainer db2 = Mock()
final GenericContainer container = Mock()

when:
DatabaseContainers.start(container, db2, new DatabaseContainers.ImageFetch(db2, IMAGE))

then:
1 * container.isRunning() >> false

then:
1 * container.start()
0 * container._
0 * db2._
}

void 'the image of the Db2 container is fetched before the container is started'() {
given:
final GenericContainer db2 = Mock()
final fetch = new DatabaseContainers.ImageFetch(db2, IMAGE)

when:
DatabaseContainers.start(db2, db2, fetch)

then:
1 * db2.isRunning() >> false

then:
1 * db2.getDockerImageName() >> IMAGE

then:
1 * db2.start()
0 * db2._
}

void 'the Db2 container is not started when its image cannot be fetched, by that row or a later one'() {
given:
final GenericContainer db2 = Mock()
final fetch = new DatabaseContainers.ImageFetch(db2, IMAGE)

when:
DatabaseContainers.start(db2, db2, fetch)

then:
1 * db2.isRunning() >> false
1 * db2.getDockerImageName() >> { throw new ContainerFetchException("Can't get Docker image", timeout()) }
0 * db2.start()
thrown(ContainerFetchException)

when:
DatabaseContainers.start(db2, db2, fetch)

then:
1 * db2.isRunning() >> false
0 * db2.getDockerImageName()
0 * db2.start()
thrown(ContainerFetchException)
}

void 'a Db2 container that failed to start is started again by the next row without fetching its image again'() {
given:
final GenericContainer db2 = Mock()
final fetch = new DatabaseContainers.ImageFetch(db2, IMAGE)

when:
DatabaseContainers.start(db2, db2, fetch)

then:
1 * db2.isRunning() >> false
1 * db2.getDockerImageName() >> IMAGE
1 * db2.start() >> { throw new ContainerLaunchException('Container startup failed') }
thrown(ContainerLaunchException)

when:
DatabaseContainers.start(db2, db2, fetch)

then:
1 * db2.isRunning() >> false
0 * db2.getDockerImageName()
1 * db2.start()
}

void 'a container that fails to start fails the row'() {
given:
final GenericContainer container = Mock()

when:
DatabaseContainers.start(container)

then:
1 * container.isRunning() >> false
1 * container.start() >> { throw new ContainerLaunchException('Container startup failed') }
thrown(ContainerLaunchException)
}

void 'an image that is fetched is not fetched again'() {
given:
final GenericContainer container = Mock()
final fetch = new DatabaseContainers.ImageFetch(container, IMAGE)

when:
fetch.fetch()
fetch.fetch()

then:
1 * container.getDockerImageName() >> IMAGE
noExceptionThrown()
}

void 'when the fetch fails, every later row fails with that failure without fetching again'() {
given:
final GenericContainer container = Mock()
final fetch = new DatabaseContainers.ImageFetch(container, IMAGE)
final failure = new ContainerFetchException("Can't get Docker image", timeout())

when:
fetch.fetch()

then:
1 * container.getDockerImageName() >> { throw failure }
final first = thrown(ContainerFetchException)
first.cause.is(failure)

when:
fetch.fetch()

then:
0 * container.getDockerImageName()
final later = thrown(ContainerFetchException)
later.cause.is(failure)
}

void 'when an error ends the fetch, the next row fetches the image again'() {
given:
final GenericContainer container = Mock()
final fetch = new DatabaseContainers.ImageFetch(container, IMAGE)

when:
fetch.fetch()

then:
1 * container.getDockerImageName() >> {
throw new NoClassDefFoundError('Could not initialize class org.testcontainers.DockerClientFactory')
}
thrown(NoClassDefFoundError)

when:
fetch.fetch()

then:
1 * container.getDockerImageName() >> IMAGE
noExceptionThrown()
}

void 'a failed fetch names the image and #what'() {
given:
final failure = new ContainerFetchException("Can't get Docker image", cause)
final GenericContainer container = Stub() {
getDockerImageName() >> { throw failure }
}
final fetch = new DatabaseContainers.ImageFetch(container, IMAGE)

when:
fetch.fetch()

then:
final e = thrown(ContainerFetchException)
e.message == message
e.cause.is(failure)

where:
what | cause || message
'that the registry did not answer' | timeout() || "Pulling ${IMAGE} failed: not fulfilled within 2 minutes"
'that the image is not there' | notFound() || "Pulling ${IMAGE} failed: Status 404: not found"
'the failure itself when it has no cause' | null || "Pulling ${IMAGE} failed: Can't get Docker image"
'the failure itself when its cause has no message' | new RuntimeException() || "Pulling ${IMAGE} failed: Can't get Docker image"
}

/**
* How Testcontainers gives up on a registry that does not answer: it retries the pull for two minutes.
*/
private static Exception timeout() {
new ConditionTimeoutException('not fulfilled within 2 minutes')
}

/**
* How the Docker daemon reports a registry that answers that the image is not there. The exception puts the status
* before the message.
*/
private static Exception notFound() {
new NotFoundException('not found')
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,7 @@ class NativeIdGeneratorHibernate7Spec extends Specification {

void "default id mapping generates distinct ids and creates the sequence it needs with #db"() {
given:
if (container != null && !container.isRunning()) {
container.start()
}
DatabaseContainers.start(container)
Map config = [
'dataSource.url' : container?.jdbcUrl ?: "jdbc:h2:mem:nativeIdDB;LOCK_TIMEOUT=10000",
'dataSource.driverClassName': container?.driverClassName ?: "org.h2.Driver",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ class RLikeHibernate7Spec extends HibernateGormDatastoreSpec {
@IgnoreIf({ data.db == 'DB2' && System.getProperty('os.arch') in ['aarch64', 'arm64'] })
void "test rlike works with #db"() {
given:
if (container != null && !container.isRunning()) {
container.start()
}
DatabaseContainers.start(container)

// Reconfigure manager for this specific database
manager.destroy() // Ensure a completely fresh state for each DB
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ class SharedJoinTableHibernate7Spec extends HibernateGormDatastoreSpec {
@IgnoreIf({ data.db == 'DB2' && System.getProperty('os.arch') in ['aarch64', 'arm64'] })
void "on #db a shared join table is unique per association"() {
given: 'the datastore on this database, with the schema created for it'
if (container != null && !container.isRunning()) {
container.start()
}
DatabaseContainers.start(container)
manager.destroy()
manager.grailsConfig = [
'dataSource.url' : container?.jdbcUrl ?: 'jdbc:h2:mem:sharedJoinTableDB;LOCK_TIMEOUT=10000',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,9 +262,7 @@ class SharedJoinTableListHibernate7Spec extends HibernateGormDatastoreSpec {
@IgnoreIf({ data.db == 'DB2' && System.getProperty('os.arch') in ['aarch64', 'arm64'] })
void "on #db two lists sharing a join table are written, read and kept unique by position"() {
given: 'the datastore on this database'
if (container != null && !container.isRunning()) {
container.start()
}
DatabaseContainers.start(container)
manager.destroy()
manager.grailsConfig = [
'dataSource.url' : container?.jdbcUrl ?: 'jdbc:h2:mem:sharedJoinTableListDB;LOCK_TIMEOUT=10000',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ class SharedKeyColumnHibernate7Spec extends HibernateGormDatastoreSpec {
@IgnoreIf({ data.db == 'DB2' && System.getProperty('os.arch') in ['aarch64', 'arm64'] })
void "on #db several rows in each association of a join table with a shared key column are accepted"() {
given: 'the datastore on this database, with the schema created for it'
if (container != null && !container.isRunning()) {
container.start()
}
DatabaseContainers.start(container)
manager.destroy()
manager.grailsConfig = [
'dataSource.url' : container?.jdbcUrl ?: 'jdbc:h2:mem:sharedKeyColumnDB;LOCK_TIMEOUT=10000',
Expand Down
Loading
Loading