/
DockerResource.java
executable file
·86 lines (74 loc) · 2.5 KB
/
DockerResource.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* Copyright (c) 2017 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.internal.utils.test.docker;
import java.io.IOException;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import org.junit.rules.ExternalResource;
/**
* External docker resource for utilization within tests.
* If the environment variable "HOSTING_ENVIRONMENT" is set to "IDE", then the resource will use localhost:{PORT}
* instead of starting its own container.
*/
@NotThreadSafe
public abstract class DockerResource extends ExternalResource {
private static final String CONTAINER_ALREADY_STARTED = "Container has already been started.";
private static final String HOSTING_ENVIRONMENT_ENV_VARIABLE_NAME = "HOSTING_ENVIRONMENT";
private static final String IDE_HOSTING_ENVIRONMENT = "IDE";
private final ContainerFactory containerFactory;
@Nullable private DockerContainer container;
public DockerResource(ContainerFactory containerFactory) {
this.containerFactory = containerFactory;
}
@Override
protected void before() {
if (container != null) {
throw new IllegalStateException(CONTAINER_ALREADY_STARTED);
}
if (!IDE_HOSTING_ENVIRONMENT.equals(System.getenv(HOSTING_ENVIRONMENT_ENV_VARIABLE_NAME))) {
container = containerFactory.createContainer();
container.start();
}
}
@Override
protected void after() {
if (container != null) {
container.stop();
container.remove();
container = null;
}
try {
containerFactory.close();
} catch (final IOException e) {
throw new AssertionError(e);
}
}
/**
* @return the port on which the container listens.
*/
protected int getPort(final int port) {
if (container == null) {
return port;
}
return container.getPort(port);
}
/**
* @return the IP on which the container was bound.
*/
public String getBindIp() {
if (container == null) {
return "localhost";
}
return container.getHostname();
}
}