How to use register method of org.testcontainers.utility.ResourceReaper class

Best Testcontainers-java code snippet using org.testcontainers.utility.ResourceReaper.register

Source:ResourceReaper.java Github

copy

Full Screen

...44 private static final Logger LOGGER = LoggerFactory.getLogger(ResourceReaper.class);45 private static final List<List<Map.Entry<String, String>>> DEATH_NOTE = new ArrayList<>();46 private static ResourceReaper instance;47 private final DockerClient dockerClient;48 private Map<String, String> registeredContainers = new ConcurrentHashMap<>();49 private Set<String> registeredNetworks = Collections.newSetFromMap(new ConcurrentHashMap<>());50 private AtomicBoolean hookIsSet = new AtomicBoolean(false);51 private ResourceReaper() {52 dockerClient = DockerClientFactory.instance().client();53 }54 public static String start(String hostIpAddress, DockerClient client) {55 return start(hostIpAddress, client, false);56 }57 @SneakyThrows(InterruptedException.class)58 public static String start(String hostIpAddress, DockerClient client, boolean withDummyMount) {59 String ryukImage = TestcontainersConfiguration.getInstance().getRyukImage();60 DockerClientFactory.instance().checkAndPullImage(client, ryukImage);61 MountableFile mountableFile = MountableFile.forClasspathResource(ResourceReaper.class.getName().replace(".", "/") + ".class");62 List<Bind> binds = new ArrayList<>();63 binds.add(new Bind("//var/run/docker.sock", new Volume("/var/run/docker.sock")));64 if (withDummyMount) {65 // Not needed for Ryuk, but we perform pre-flight checks with it (micro optimization)66 binds.add(new Bind(mountableFile.getResolvedPath(), new Volume("/dummy"), AccessMode.ro));67 }68 String ryukContainerId = client.createContainerCmd(ryukImage)69 .withHostConfig(new HostConfig() {70 @JsonProperty("AutoRemove")71 boolean autoRemove = true;72 })73 .withExposedPorts(new ExposedPort(8080))74 .withPublishAllPorts(true)75 .withName("testcontainers-ryuk-" + DockerClientFactory.SESSION_ID)76 .withLabels(Collections.singletonMap(DockerClientFactory.TESTCONTAINERS_LABEL, "true"))77 .withBinds(binds)78 .exec()79 .getId();80 client.startContainerCmd(ryukContainerId).exec();81 InspectContainerResponse inspectedContainer = client.inspectContainerCmd(ryukContainerId).exec();82 Integer ryukPort = inspectedContainer.getNetworkSettings().getPorts().getBindings().values().stream()83 .flatMap(Stream::of)84 .findFirst()85 .map(Ports.Binding::getHostPortSpec)86 .map(Integer::parseInt)87 .get();88 CountDownLatch ryukScheduledLatch = new CountDownLatch(1);89 synchronized (DEATH_NOTE) {90 DEATH_NOTE.add(91 DockerClientFactory.DEFAULT_LABELS.entrySet().stream()92 .<Map.Entry<String, String>>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue()))93 .collect(Collectors.toList())94 );95 }96 Thread kiraThread = new Thread(97 DockerClientFactory.TESTCONTAINERS_THREAD_GROUP,98 () -> {99 while (true) {100 int index = 0;101 try(Socket clientSocket = new Socket(hostIpAddress, ryukPort)) {102 OutputStream out = clientSocket.getOutputStream();103 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));104 synchronized (DEATH_NOTE) {105 while (true) {106 if (DEATH_NOTE.size() <= index) {107 try {108 DEATH_NOTE.wait(1_000);109 continue;110 } catch (InterruptedException e) {111 throw new RuntimeException(e);112 }113 }114 List<Map.Entry<String, String>> filters = DEATH_NOTE.get(index);115 String query = URLEncodedUtils.format(116 filters.stream()117 .map(it -> new BasicNameValuePair(it.getKey(), it.getValue()))118 .collect(Collectors.toList()),119 (String) null120 );121 log.debug("Sending '{}' to Ryuk", query);122 out.write(query.getBytes());123 out.write('\n');124 out.flush();125 while (!"ACK".equalsIgnoreCase(in.readLine())) {126 }127 ryukScheduledLatch.countDown();128 index++;129 }130 }131 } catch (IOException e) {132 log.warn("Can not connect to Ryuk at {}:{}", hostIpAddress, ryukPort, e);133 }134 }135 },136 "testcontainers-ryuk"137 );138 kiraThread.setDaemon(true);139 kiraThread.start();140 // We need to wait before we can start any containers to make sure that we delete them141 if (!ryukScheduledLatch.await(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) {142 throw new IllegalStateException("Can not connect to Ryuk");143 }144 return ryukContainerId;145 }146 public synchronized static ResourceReaper instance() {147 if (instance == null) {148 instance = new ResourceReaper();149 }150 return instance;151 }152 /**153 * Perform a cleanup.154 *155 */156 public synchronized void performCleanup() {157 registeredContainers.forEach(this::stopContainer);158 registeredNetworks.forEach(this::removeNetwork);159 }160 /**161 * Register a filter to be cleaned up.162 *163 * @param filter the filter164 */165 public void registerFilterForCleanup(List<Map.Entry<String, String>> filter) {166 synchronized (DEATH_NOTE) {167 DEATH_NOTE.add(filter);168 DEATH_NOTE.notifyAll();169 }170 }171 /**172 * Register a container to be cleaned up, either on explicit call to stopAndRemoveContainer, or at JVM shutdown.173 *174 * @param containerId the ID of the container175 * @param imageName the image name of the container (used for logging)176 */177 public void registerContainerForCleanup(String containerId, String imageName) {178 setHook();179 registeredContainers.put(containerId, imageName);180 }181 /**182 * Stop a potentially running container and remove it, including associated volumes.183 *184 * @param containerId the ID of the container185 */186 public void stopAndRemoveContainer(String containerId) {187 stopContainer(containerId, registeredContainers.get(containerId));188 registeredContainers.remove(containerId);189 }190 /**191 * Stop a potentially running container and remove it, including associated volumes.192 *193 * @param containerId the ID of the container194 * @param imageName the image name of the container (used for logging)195 */196 public void stopAndRemoveContainer(String containerId, String imageName) {197 stopContainer(containerId, imageName);198 registeredContainers.remove(containerId);199 }200 private void stopContainer(String containerId, String imageName) {201 boolean running;202 try {203 InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();204 running = containerInfo.getState().getRunning();205 } catch (NotFoundException e) {206 LOGGER.trace("Was going to stop container but it apparently no longer exists: {}");207 return;208 } catch (DockerException e) {209 LOGGER.trace("Error encountered when checking container for shutdown (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());210 return;211 }212 if (running) {213 try {214 LOGGER.trace("Stopping container: {}", containerId);215 dockerClient.killContainerCmd(containerId).exec();216 LOGGER.trace("Stopped container: {}", imageName);217 } catch (DockerException e) {218 LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());219 }220 }221 try {222 dockerClient.inspectContainerCmd(containerId).exec();223 } catch (NotFoundException e) {224 LOGGER.trace("Was going to remove container but it apparently no longer exists: {}");225 return;226 }227 try {228 LOGGER.trace("Removing container: {}", containerId);229 try {230 dockerClient.removeContainerCmd(containerId).withRemoveVolumes(true).withForce(true).exec();231 LOGGER.debug("Removed container and associated volume(s): {}", imageName);232 } catch (InternalServerErrorException e) {233 LOGGER.trace("Exception when removing container with associated volume(s): {} (due to {})", imageName, e.getMessage());234 }235 } catch (DockerException e) {236 LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());237 }238 }239 /**240 * Register a network to be cleaned up at JVM shutdown.241 *242 * @param id the ID of the network243 */244 public void registerNetworkIdForCleanup(String id) {245 setHook();246 registeredNetworks.add(id);247 }248 /**249 * @param networkName the name of the network250 * @deprecated see {@link ResourceReaper#registerNetworkIdForCleanup(String)}251 */252 @Deprecated253 public void registerNetworkForCleanup(String networkName) {254 try {255 // Try to find the network by name, so that we can register its ID for later deletion256 dockerClient.listNetworksCmd()257 .withNameFilter(networkName)258 .exec()259 .forEach(network -> registerNetworkIdForCleanup(network.getId()));260 } catch (Exception e) {261 LOGGER.trace("Error encountered when looking up network (name: {})", networkName);262 }263 }264 /**265 * Removes a network by ID.266 * @param id267 */268 public void removeNetworkById(String id) {269 removeNetwork(id);270 }271 /**272 * Removes a network by ID.273 * @param identifier274 * @deprecated see {@link ResourceReaper#removeNetworkById(String)}275 */276 @Deprecated277 public void removeNetworks(String identifier) {278 removeNetworkById(identifier);279 }280 private void removeNetwork(String id) {281 try {282 List<Network> networks;283 try {284 // Try to find the network if it still exists285 // Listing by ID first prevents docker-java logging an error if we just go blindly into removeNetworkCmd286 networks = dockerClient.listNetworksCmd().withIdFilter(id).exec();287 } catch (Exception e) {288 LOGGER.trace("Error encountered when looking up network for removal (name: {}) - it may not have been removed", id);289 return;290 }291 // at this point networks should contain either 0 or 1 entries, depending on whether the network exists292 // using a for loop we essentially treat the network like an optional, only applying the removal if it exists293 for (Network network : networks) {294 try {295 dockerClient.removeNetworkCmd(network.getId()).exec();296 registeredNetworks.remove(network.getId());297 LOGGER.debug("Removed network: {}", id);298 } catch (Exception e) {299 LOGGER.trace("Error encountered removing network (name: {}) - it may not have been removed", network.getName());300 }301 }302 } finally {303 registeredNetworks.remove(id);304 }305 }306 public void unregisterNetwork(String identifier) {307 registeredNetworks.remove(identifier);308 }309 public void unregisterContainer(String identifier) {310 registeredContainers.remove(identifier);311 }312 private void setHook() {313 if (hookIsSet.compareAndSet(false, true)) {314 // If the JVM stops without containers being stopped, try and stop the container.315 Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, this::performCleanup));316 }317 }318}...

Full Screen

Full Screen

Source:EtcdClusterImpl.java Github

copy

Full Screen

...57 @Override58 public void start() {59 final CountDownLatch latch = new CountDownLatch(containers.size());60 final AtomicReference<Exception> failedToStart = new AtomicReference<>();61 ResourceReaper.instance().registerNetworkIdForCleanup(this.network.getId());62 for (EtcdContainer container : containers) {63 new Thread(() -> {64 try {65 container.start();66 ResourceReaper.instance().registerContainerForCleanup(67 container.getContainerId(),68 container.getDockerImageName());69 } catch (Exception e) {70 failedToStart.set(e);71 } finally {72 latch.countDown();73 }74 }).start();75 }76 try {77 latch.await(1, TimeUnit.MINUTES);78 } catch (InterruptedException e) {79 throw new RuntimeException(e);80 }...

Full Screen

Full Screen

Source:BaseTest.java Github

copy

Full Screen

...19 protected static final ToxiproxyContainer.ContainerProxy PROXY;20 @LocalServerPort21 protected int localServerPort;22 static {23 ResourceReaper.instance().registerNetworkIdForCleanup(NETWORK.getId());24 POSTGRESQL_CONTAINER = R2dbcDemoPostgresqlContainer.getInstance()25 .withExposedPorts(5432)26 .withNetwork(NETWORK);27 POSTGRESQL_CONTAINER.start();28 log.info("Postgresql container started. Address: {}, port: {}",29 POSTGRESQL_CONTAINER.getHost(),30 POSTGRESQL_CONTAINER.getFirstMappedPort());31 TOXIPROXY_CONTAINER = new ToxiproxyContainer(DockerImageName.parse("shopify/toxiproxy:2.1.0"))32 .withNetwork(NETWORK)33 .withNetworkAliases(TOXIPROXY_NETWORK_ALIAS);34 TOXIPROXY_CONTAINER.start();35 PROXY = TOXIPROXY_CONTAINER.getProxy(POSTGRESQL_CONTAINER, 5432);36 var r2dbcUrl = POSTGRESQL_CONTAINER.getR2dbcUrl(PROXY.getContainerIpAddress(), PROXY.getProxyPort());37 System.setProperty("DB_URL", r2dbcUrl);...

Full Screen

Full Screen

register

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.utility.ResourceReaper;2public class 1 {3 public static void main(String[] args) {4 ResourceReaper.registerShutdownHook();5 }6}7import org.testcontainers.utility.ResourceReaper;8public class 2 {9 public static void main(String[] args) {10 ResourceReaper.registerShutdownHook();11 }12}13import org.testcontainers.utility.ResourceReaper;14public class 3 {15 public static void main(String[] args) {16 ResourceReaper.registerShutdownHook();17 }18}19import org.testcontainers.utility.ResourceReaper;20public class 4 {21 public static void main(String[] args) {22 ResourceReaper.registerShutdownHook();23 }24}25import org.testcontainers.utility.ResourceReaper;26public class 5 {27 public static void main(String[] args) {28 ResourceReaper.registerShutdownHook();29 }30}31import org.testcontainers.utility.ResourceReaper;32public class 6 {33 public static void main(String[] args) {34 ResourceReaper.registerShutdownHook();35 }36}37import org.testcontainers.utility.ResourceReaper;38public class 7 {39 public static void main(String[] args) {40 ResourceReaper.registerShutdownHook();41 }42}43import org.testcontainers.utility.ResourceReaper;44public class 8 {45 public static void main(String[] args) {46 ResourceReaper.registerShutdownHook();47 }48}

Full Screen

Full Screen

register

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.utility.ResourceReaper;2public class TestContainerReaper {3 public static void main(String[] args) {4 ResourceReaper.register();5 }6}7import org.testcontainers.utility.ResourceReaper;8public class TestContainerReaper {9 public static void main(String[] args) {10 ResourceReaper.register();11 }12}13import org.testcontainers.utility.ResourceReaper;14public class TestContainerReaper {15 public static void main(String[] args) {16 ResourceReaper.register();17 }18}19import org.testcontainers.utility.ResourceReaper;20public class TestContainerReaper {21 public static void main(String[] args) {22 ResourceReaper.register();23 }24}25import org.testcontainers.utility.ResourceReaper;26public class TestContainerReaper {27 public static void main(String[] args) {28 ResourceReaper.register();29 }30}31import org.testcontainers.utility.ResourceReaper;32public class TestContainerReaper {33 public static void main(String[] args) {34 ResourceReaper.register();35 }36}37import org.testcontainers.utility.ResourceReaper;38public class TestContainerReaper {39 public static void main(String[] args) {40 ResourceReaper.register();41 }42}43import org.testcontainers.utility.ResourceReaper;44public class TestContainerReaper {45 public static void main(String[] args) {46 ResourceReaper.register();47 }48}49import org.testcontainers.utility.ResourceReaper;50public class TestContainerReaper {51 public static void main(String[] args) {52 ResourceReaper.register();53 }

Full Screen

Full Screen

register

Using AI Code Generation

copy

Full Screen

1import java.io.IOException;2import java.lang.reflect.InvocationTargetException;3import java.lang.reflect.Method;4import java.util.UUID;5import org.testcontainers.utility.ResourceReaper;6public class 1 {7 public static void main(String[] args) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {8 Method m = ResourceReaper.class.getDeclaredMethod("register", String.class);9 m.setAccessible(true);10 m.invoke(null, UUID.randomUUID().toString());11 }12}13import java.io.IOException;14import java.lang.reflect.InvocationTargetException;15import java.lang.reflect.Method;16import java.util.UUID;17import org.testcontainers.utility.ResourceReaper;18public class 2 {19 public static void main(String[] args) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {20 Method m = ResourceReaper.class.getDeclaredMethod("register", String.class);21 m.setAccessible(true);22 m.invoke(null, UUID.randomUUID().toString());23 }24}25import java.io.IOException;26import java.lang.reflect.InvocationTargetException;27import java.lang.reflect.Method;28import java.util.UUID;29import org.testcontainers.utility.ResourceReaper;30public class 3 {31 public static void main(String[] args) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {32 Method m = ResourceReaper.class.getDeclaredMethod("register", String.class);33 m.setAccessible(true);34 m.invoke(null, UUID.randomUUID().toString());35 }36}37import java.io.IOException;38import java.lang.reflect.InvocationTargetException;39import java.lang.reflect.Method;40import java.util.UUID;41import org.testcontainers.utility.ResourceReaper;42public class 4 {43 public static void main(String[] args) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {44 Method m = ResourceReaper.class.getDeclaredMethod("register", String.class);45 m.setAccessible(true);46 m.invoke(null, UUID.randomUUID().toString());47 }48}49import java.io.IOException;50import java.lang.reflect.InvocationTargetException;

Full Screen

Full Screen

register

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.utility;2import java.io.IOException;3public class ResourceReaper {4 public static void main(String[] args) throws IOException {5 ResourceReaper.register("a");6 }7}8public class ResourceReaper {9 public static void main(String[] args) throws IOException {10 ResourceReaper.register("a");11 }12}13public class ResourceReaper {14 public static void main(String[] args) throws IOException {15 ResourceReaper.register("a");16 }17}18public class ResourceReaper {19 public static void main(String[] args) throws IOException {20 ResourceReaper.register("a");21 }22}23public class ResourceReaper {24 public static void main(String[] args) throws IOException {25 ResourceReaper.register("a");26 }27}28public class ResourceReaper {29 public static void main(String[] args) throws IOException {30 ResourceReaper.register("a");31 }32}33public class ResourceReaper {34 public static void main(String[] args) throws IOException {35 ResourceReaper.register("a");36 }37}38public class ResourceReaper {39 public static void main(String[] args) throws IOException {40 ResourceReaper.register("a");41 }42}43public class ResourceReaper {44 public static void main(String[] args) throws IOException {45 ResourceReaper.register("a");46 }47}48public class ResourceReaper {49 public static void main(String[] args) throws IOException {50 ResourceReaper.register("a");51 }52}53public class ResourceReaper {54 public static void main(String[] args) throws IOException {55 ResourceReaper.register("a");56 }57}

Full Screen

Full Screen

register

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.utility.ResourceReaper;2public class Test {3public static void main(String[] args) {4ResourceReaper.registerFile("test.txt");5}6}7import org.testcontainers.utility.ResourceReaper;8public class Test {9public static void main(String[] args) {10ResourceReaper.registerFile("test2.txt");11}12}

Full Screen

Full Screen

register

Using AI Code Generation

copy

Full Screen

1import java.io.IOException;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.utility.ResourceReaper;4public class 1 {5 public static void main(String[] args) throws IOException, InterruptedException {6 GenericContainer container = new GenericContainer("alpine:latest").withCommand("sleep 1000");7 container.start();8 ResourceReaper.registerJVMShutDownHook(container);9 Thread.sleep(10000);10 }11}12import java.io.IOException;13import org.testcontainers.containers.GenericContainer;14import org.testcontainers.utility.ResourceReaper;15public class 2 {16 public static void main(String[] args) throws IOException, InterruptedException {17 GenericContainer container = new GenericContainer("alpine:latest").withCommand("sleep 1000");18 container.start();19 ResourceReaper.registerJVMShutDownHook(container);20 Thread.sleep(10000);21 }22}23import java.io.IOException;24import org.testcontainers.containers.GenericContainer;25import org.testcontainers.utility.ResourceReaper;26public class 3 {27 public static void main(String[] args) throws IOException, InterruptedException {28 GenericContainer container = new GenericContainer("alpine:latest").withCommand("sleep 1000");29 container.start();30 ResourceReaper.registerJVMShutDownHook(container);31 Thread.sleep(10000);32 }33}

Full Screen

Full Screen

register

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.utility.ResourceReaper;2public class 1 {3 public static void main(String[] args) {4 ResourceReaper.registerShutdownHook();5 }6}7import org.testcontainers.utility.ResourceReaper;8public class 2 {9 public static void main(String[] args) {10 ResourceReaper.unregisterShutdownHook();11 }12}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful