Best Testcontainers-java code snippet using org.testcontainers.utility.RyukResourceReaper.register
Source:ResourceReaper.java
...49 )50 );51 private static ResourceReaper instance;52 final DockerClient dockerClient = DockerClientFactory.lazyClient();53 private Map<String, String> registeredContainers = new ConcurrentHashMap<>();54 private Set<String> registeredNetworks = Sets.newConcurrentHashSet();55 private Set<String> registeredImages = Sets.newConcurrentHashSet();56 private AtomicBoolean hookIsSet = new AtomicBoolean(false);57 /**58 * Internal constructor to avoid custom implementations59 */60 ResourceReaper() {}61 public static synchronized ResourceReaper instance() {62 if (instance == null) {63 boolean useRyuk = !Boolean.parseBoolean(System.getenv("TESTCONTAINERS_RYUK_DISABLED"));64 if (useRyuk) {65 //noinspection deprecation66 instance = new RyukResourceReaper();67 } else {68 String ryukDisabledMessage =69 "\n" +70 "********************************************************************************" +71 "\n" +72 "Ryuk has been disabled. This can cause unexpected behavior in your environment." +73 "\n" +74 "********************************************************************************";75 LOGGER.warn(ryukDisabledMessage);76 instance = new JVMHookResourceReaper();77 }78 }79 return instance;80 }81 /**82 * Perform a cleanup.83 * @deprecated no longer supported API, use {@link DockerClient} directly84 */85 @Deprecated86 public void performCleanup() {87 registeredContainers.forEach(this::removeContainer);88 registeredNetworks.forEach(this::removeNetwork);89 registeredImages.forEach(this::removeImage);90 }91 /**92 * Register a filter to be cleaned up.93 *94 * @param filter the filter95 * @deprecated only label filter is supported by the prune API, use {@link #registerLabelsFilterForCleanup(Map)}96 */97 @Deprecated98 public void registerFilterForCleanup(List<Map.Entry<String, String>> filter) {99 synchronized (DEATH_NOTE) {100 DEATH_NOTE.add(filter);101 DEATH_NOTE.notifyAll();102 }103 }104 /**105 * Register a label to be cleaned up.106 *107 * @param labels the filter108 */109 public void registerLabelsFilterForCleanup(Map<String, String> labels) {110 registerFilterForCleanup(111 labels112 .entrySet()113 .stream()114 .map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue()))115 .collect(Collectors.toList())116 );117 }118 /**119 * Register a container to be cleaned up, either on explicit call to stopAndRemoveContainer, or at JVM shutdown.120 *121 * @param containerId the ID of the container122 * @param imageName the image name of the container (used for logging)123 * @deprecated no longer supported API124 */125 @Deprecated126 public void registerContainerForCleanup(String containerId, String imageName) {127 setHook();128 registeredContainers.put(containerId, imageName);129 }130 /**131 * Stop a potentially running container and remove it, including associated volumes.132 *133 * @param containerId the ID of the container134 * @deprecated use {@link DockerClient} directly135 */136 @Deprecated137 public void stopAndRemoveContainer(String containerId) {138 removeContainer(containerId, registeredContainers.get(containerId));139 registeredContainers.remove(containerId);140 }141 /**142 * Stop a potentially running container and remove it, including associated volumes.143 *144 * @param containerId the ID of the container145 * @param imageName the image name of the container (used for logging)146 * @deprecated use {@link DockerClient} directly147 */148 @Deprecated149 public void stopAndRemoveContainer(String containerId, String imageName) {150 removeContainer(containerId, imageName);151 registeredContainers.remove(containerId);152 }153 private void removeContainer(String containerId, String imageName) {154 boolean running;155 try {156 InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();157 running = containerInfo.getState() != null && Boolean.TRUE.equals(containerInfo.getState().getRunning());158 } catch (NotFoundException e) {159 LOGGER.trace("Was going to stop container but it apparently no longer exists: {}", containerId);160 return;161 } catch (Exception e) {162 LOGGER.trace(163 "Error encountered when checking container for shutdown (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",164 containerId,165 Throwables.getRootCause(e).getMessage()166 );167 return;168 }169 if (running) {170 try {171 LOGGER.trace("Stopping container: {}", containerId);172 dockerClient.killContainerCmd(containerId).exec();173 LOGGER.trace("Stopped container: {}", imageName);174 } catch (Exception e) {175 LOGGER.trace(176 "Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",177 containerId,178 Throwables.getRootCause(e).getMessage()179 );180 }181 }182 try {183 dockerClient.inspectContainerCmd(containerId).exec();184 } catch (Exception e) {185 LOGGER.trace("Was going to remove container but it apparently no longer exists: {}", containerId);186 return;187 }188 try {189 LOGGER.trace("Removing container: {}", containerId);190 dockerClient.removeContainerCmd(containerId).withRemoveVolumes(true).withForce(true).exec();191 LOGGER.debug("Removed container and associated volume(s): {}", imageName);192 } catch (Exception e) {193 LOGGER.trace(194 "Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",195 containerId,196 Throwables.getRootCause(e).getMessage()197 );198 }199 }200 /**201 * Register a network to be cleaned up at JVM shutdown.202 *203 * @param id the ID of the network204 * @deprecated no longer supported API205 */206 @Deprecated207 public void registerNetworkIdForCleanup(String id) {208 setHook();209 registeredNetworks.add(id);210 }211 /**212 * Removes a network by ID.213 * @param id214 * @deprecated use {@link DockerClient} directly215 */216 @Deprecated217 public void removeNetworkById(String id) {218 removeNetwork(id);219 }220 private void removeNetwork(String id) {221 try {222 List<Network> networks;223 try {224 // Try to find the network if it still exists225 // Listing by ID first prevents docker-java logging an error if we just go blindly into removeNetworkCmd226 networks = dockerClient.listNetworksCmd().withIdFilter(id).exec();227 } catch (Exception e) {228 LOGGER.trace(229 "Error encountered when looking up network for removal (name: {}) - it may not have been removed",230 id231 );232 return;233 }234 // at this point networks should contain either 0 or 1 entries, depending on whether the network exists235 // using a for loop we essentially treat the network like an optional, only applying the removal if it exists236 for (Network network : networks) {237 try {238 dockerClient.removeNetworkCmd(network.getId()).exec();239 registeredNetworks.remove(network.getId());240 LOGGER.debug("Removed network: {}", id);241 } catch (Exception e) {242 LOGGER.trace(243 "Error encountered removing network (name: {}) - it may not have been removed",244 network.getName()245 );246 }247 }248 } finally {249 registeredNetworks.remove(id);250 }251 }252 /**253 * @deprecated no longer supported API254 */255 @Deprecated256 public void unregisterNetwork(String identifier) {257 registeredNetworks.remove(identifier);258 }259 /**260 * @deprecated no longer supported API261 */262 @Deprecated263 public void unregisterContainer(String identifier) {264 registeredContainers.remove(identifier);265 }266 /**267 * @deprecated no longer supported API268 */269 @Deprecated270 public void registerImageForCleanup(String dockerImageName) {271 setHook();272 registeredImages.add(dockerImageName);273 }274 private void removeImage(String dockerImageName) {275 LOGGER.trace("Removing image tagged {}", dockerImageName);276 try {277 dockerClient.removeImageCmd(dockerImageName).withForce(true).exec();278 } catch (Throwable e) {279 LOGGER.warn("Unable to delete image " + dockerImageName, e);280 }281 }282 void setHook() {283 if (hookIsSet.compareAndSet(false, true)) {284 // If the JVM stops without containers being stopped, try and stop the container.285 Runtime286 .getRuntime()287 .addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, this::performCleanup));288 }289 }290 /**291 *292 * @deprecated internal API293 */294 @Deprecated295 public Map<String, String> getLabels() {296 return MARKER_LABELS;297 }298 /**299 *300 * @deprecated internal API301 */302 @Deprecated303 public CreateContainerCmd register(GenericContainer<?> container, CreateContainerCmd cmd) {304 cmd.getLabels().putAll(getLabels());305 return cmd;306 }307 /**308 * @deprecated internal API309 */310 @Deprecated311 public void init() {}312 static class FilterRegistry {313 @VisibleForTesting314 static final String ACKNOWLEDGMENT = "ACK";315 private final BufferedReader in;316 private final OutputStream out;317 FilterRegistry(InputStream ryukInputStream, OutputStream ryukOutputStream) {318 this.in = new BufferedReader(new InputStreamReader(ryukInputStream));319 this.out = ryukOutputStream;320 }321 /**322 * Registers the given filters with Ryuk323 *324 * @param filters the filter to register325 * @return true if the filters have been registered successfuly, false otherwise326 * @throws IOException if communication with Ryuk fails327 */328 protected boolean register(List<Map.Entry<String, String>> filters) throws IOException {329 String query = filters330 .stream()331 .map(it -> {332 try {333 return (334 URLEncoder.encode(it.getKey(), "UTF-8") + "=" + URLEncoder.encode(it.getValue(), "UTF-8")335 );336 } catch (UnsupportedEncodingException e) {337 throw new RuntimeException(e);338 }339 })340 .collect(Collectors.joining("&"));341 log.debug("Sending '{}' to Ryuk", query);342 out.write(query.getBytes());...
Source:RyukResourceReaper.java
...38 log.debug("Ryuk is enabled but will be started on demand");39 }40 }41 @Override42 public void registerLabelsFilterForCleanup(Map<String, String> labels) {43 maybeStart();44 super.registerLabelsFilterForCleanup(labels);45 }46 @Override47 public Map<String, String> getLabels() {48 maybeStart();49 return super.getLabels();50 }51 @Override52 public CreateContainerCmd register(GenericContainer<?> container, CreateContainerCmd cmd) {53 if (container == ryukContainer) {54 // Do not register Ryuk container to avoid self-pruning55 return cmd;56 }57 maybeStart();58 return super.register(container, cmd);59 }60 @SneakyThrows(InterruptedException.class)61 private synchronized void maybeStart() {62 if (!started.compareAndSet(false, true)) {63 return;64 }65 ryukContainer.start();66 CountDownLatch ryukScheduledLatch = new CountDownLatch(1);67 String host = ryukContainer.getHost();68 Integer ryukPort = ryukContainer.getFirstMappedPort();69 Thread kiraThread = new Thread(70 DockerClientFactory.TESTCONTAINERS_THREAD_GROUP,71 () -> {72 while (true) {73 RYUK_ACK_RATE_LIMITER.doWhenReady(() -> {74 int index = 0;75 // not set the read timeout, as Ryuk would not send anything unless a new filter is submitted, meaning that we would get a timeout exception pretty quick76 try (Socket clientSocket = new Socket()) {77 clientSocket.connect(new InetSocketAddress(host, ryukPort), 5 * 1000);78 ResourceReaper.FilterRegistry registry = new ResourceReaper.FilterRegistry(79 clientSocket.getInputStream(),80 clientSocket.getOutputStream()81 );82 synchronized (ResourceReaper.DEATH_NOTE) {83 while (true) {84 if (ResourceReaper.DEATH_NOTE.size() <= index) {85 try {86 ResourceReaper.DEATH_NOTE.wait(1_000);87 continue;88 } catch (InterruptedException e) {89 throw new RuntimeException(e);90 }91 }92 List<Map.Entry<String, String>> filters = ResourceReaper.DEATH_NOTE.get(index);93 boolean isAcknowledged = registry.register(filters);94 if (isAcknowledged) {95 log.debug("Received 'ACK' from Ryuk");96 ryukScheduledLatch.countDown();97 index++;98 } else {99 log.debug("Didn't receive 'ACK' from Ryuk. Will retry to send filters.");100 }101 }102 }103 } catch (IOException e) {104 log.warn("Can not connect to Ryuk at {}:{}", host, ryukPort, e);105 }106 });107 }...
register
Using AI Code Generation
1import org.testcontainers.utility.RyukResourceReaper;2public class 1 {3 public static void main(String[] args) {4 RyukResourceReaper.register();5 }6}7import org.testcontainers.utility.RyukResourceReaper;8public class 2 {9 public static void main(String[] args) {10 RyukResourceReaper.register();11 }12}13import org.testcontainers.utility.RyukResourceReaper;14public class 3 {15 public static void main(String[] args) {16 RyukResourceReaper.register();17 }18}19import org.testcontainers.utility.RyukResourceReaper;20public class 4 {21 public static void main(String[] args) {22 RyukResourceReaper.register();23 }24}25import org.testcontainers.utility.RyukResourceReaper;26public class 5 {27 public static void main(String[] args) {28 RyukResourceReaper.register();29 }30}31import org.testcontainers.utility.RyukResourceReaper;32public class 6 {33 public static void main(String[] args) {34 RyukResourceReaper.register();35 }36}37import org.testcontainers.utility.RyukResourceReaper;38public class 7 {39 public static void main(String[] args) {40 RyukResourceReaper.register();41 }42}43import org.testcontainers.utility.RyukResourceReaper;44public class 8 {45 public static void main(String[] args) {46 RyukResourceReaper.register();47 }48}
register
Using AI Code Generation
1import org.testcontainers.utility.RyukResourceReaper;2public class 1 {3 public static void main(String[] args) {4 RyukResourceReaper.register();5 }6}
register
Using AI Code Generation
1import org.testcontainers.utility.RyukResourceReaper;2import java.util.concurrent.TimeUnit;3import java.util.concurrent.TimeoutException;4public class 1 {5 public static void main(String[] args) throws TimeoutException, InterruptedException {6 RyukResourceReaper.register(5, TimeUnit.SECONDS);7 }8}9import org.testcontainers.utility.RyukResourceReaper;10import java.util.concurrent.TimeUnit;11import java.util.concurrent.TimeoutException;12public class 2 {13 public static void main(String[] args) throws TimeoutException, InterruptedException {14 RyukResourceReaper.register(5, TimeUnit.SECONDS);15 }16}17import org.testcontainers.utility.RyukResourceReaper;18import java.util.concurrent.TimeUnit;19import java.util.concurrent.TimeoutException;20public class 3 {21 public static void main(String[] args) throws TimeoutException, InterruptedException {22 RyukResourceReaper.register(5, TimeUnit.SECONDS);23 }24}25import org.testcontainers.utility.RyukResourceReaper;26import java.util.concurrent.TimeUnit;27import java.util.concurrent.TimeoutException;28public class 4 {29 public static void main(String[] args) throws TimeoutException, InterruptedException {30 RyukResourceReaper.register(5, TimeUnit.SECONDS);31 }32}33import org.testcontainers.utility.RyukResourceReaper;34import java.util.concurrent.TimeUnit;35import java.util.concurrent.TimeoutException;36public class 5 {37 public static void main(String[] args) throws TimeoutException, InterruptedException {38 RyukResourceReaper.register(5, TimeUnit.SECONDS);39 }40}41import org.testcontainers.utility.RyukResourceReaper;42import java.util.concurrent.TimeUnit;43import java.util.concurrent.TimeoutException;44public class 6 {45 public static void main(String[] args) throws TimeoutException, InterruptedException {46 RyukResourceReaper.register(5, TimeUnit.SECONDS);47 }48}
register
Using AI Code Generation
1import org.testcontainers.utility.RyukResourceReaper;2public class 1 {3 public static void main(String[] args) {4 RyukResourceReaper.register(() -> {5 System.out.println("callback executed");6 });7 }8}9import org.testcontainers.utility.RyukResourceReaper;10public class 2 {11 public static void main(String[] args) {12 RyukResourceReaper.register(() -> {13 System.out.println("callback executed");14 });15 }16}17import org.testcontainers.utility.RyukResourceReaper;18public class 3 {19 public static void main(String[] args) {20 RyukResourceReaper.register(() -> {21 System.out.println("callback executed");22 });23 }24}25import org.testcontainers.utility.RyukResourceReaper;26public class 4 {27 public static void main(String[] args) {28 RyukResourceReaper.register(() -> {29 System.out.println("callback executed");30 });31 }32}33import org.testcontainers.utility.RyukResourceReaper;34public class 5 {35 public static void main(String[] args) {36 RyukResourceReaper.register(() -> {37 System.out.println("callback executed");38 });39 }40}41import org.testcontainers.utility.RyukResourceReaper;42public class 6 {43 public static void main(String[] args) {44 RyukResourceReaper.register(() -> {45 System.out.println("callback executed");46 });47 }48}
register
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.utility.RyukResourceReaper;3public class TestContainer {4 public static void main(String[] args) {5 GenericContainer redis = new GenericContainer("redis:3.2.8");6 redis.start();7 RyukResourceReaper.register(redis);8 }9}10import org.testcontainers.containers.GenericContainer;11import org.testcontainers.utility.RyukResourceReaper;12public class TestContainer {13 public static void main(String[] args) {14 GenericContainer redis = new GenericContainer("redis:3.2.8");15 redis.start();16 RyukResourceReaper.register(redis);17 }18}19import org.testcontainers.containers.GenericContainer;20import org.testcontainers.utility.RyukResourceReaper;21public class TestContainer {22 public static void main(String[] args) {23 GenericContainer redis = new GenericContainer("redis:3.2.8");24 redis.start();25 RyukResourceReaper.register(redis);26 }27}28import org.testcontainers.containers.GenericContainer;29import org.testcontainers.utility.RyukResourceReaper;30public class TestContainer {31 public static void main(String[] args) {32 GenericContainer redis = new GenericContainer("redis:3.2.8");33 redis.start();34 RyukResourceReaper.register(redis);35 }36}37import org.testcontainers.containers.GenericContainer;38import org.testcontainers.utility.RyukResourceReaper;39public class TestContainer {40 public static void main(String[] args) {41 GenericContainer redis = new GenericContainer("redis:3
register
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.utility.RyukResourceReaper;3public class TestContainers {4 public static void main(String[] args) {5 RyukResourceReaper.registerShutdownHook();6 GenericContainer container = new GenericContainer("ubuntu:16.04");7 container.start();8 container.stop();9 }10}11import org.testcontainers.containers.GenericContainer;12import org.testcontainers.utility.RyukResourceReaper;13public class TestContainers {14 public static void main(String[] args) {15 RyukResourceReaper.registerShutdownHook();16 GenericContainer container = new GenericContainer("ubuntu:16.04");17 container.start();18 container.stop();19 }20}21import org.testcontainers.containers.GenericContainer;22import org.testcontainers.utility.RyukResourceReaper;23public class TestContainers {24 public static void main(String[] args) {25 RyukResourceReaper.registerShutdownHook();26 GenericContainer container = new GenericContainer("ubuntu:16.04");27 container.start();28 container.stop();29 }30}31import org.testcontainers.containers.GenericContainer;32import org.testcontainers.utility.RyukResourceReaper;33public class TestContainers {34 public static void main(String[] args) {35 RyukResourceReaper.registerShutdownHook();36 GenericContainer container = new GenericContainer("ubuntu:16.04");37 container.start();
register
Using AI Code Generation
1package org.testcontainers.utility;2import java.util.UUID;3import org.testcontainers.DockerClientFactory;4import org.testcontainers.containers.GenericContainer;5import org.testcontainers.containers.output.Slf4jLogConsumer;6import org.testcontainers.containers.wait.strategy.Wait;7import org.testcontainers.utility.RyukResourceReaper;8public class RyukResourceReaperTest {9 public static void main(String[] args) {10 GenericContainer ryukContainer = new GenericContainer("quay.io/testcontainers/ryuk:0.3.0")11 .withExposedPorts(8080)12 .waitingFor(Wait.forHttp("/").forStatusCode(200))13 .withLogConsumer(new Slf4jLogConsumer(RyukResourceReaperTest.class))14 .withStartupTimeoutSeconds(0);15 try {16 ryukContainer.start();17 } catch (Exception e) {18 System.out.println("Exception: " + e);19 }20 RyukResourceReaper.register(ryukContainer);21 GenericContainer container = new GenericContainer("alpine:3.11.3")22 .withCommand("sleep", "999999")23 .withExposedPorts(8080)24 .withLogConsumer(new Slf4jLogConsumer(RyukResourceReaperTest.class))25 .withStartupTimeoutSeconds(0);26 try {27 container.start();28 } catch (Exception e) {29 System.out.println("Exception: " + e);30 }31 RyukResourceReaper.register(container);
register
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.utility.RyukResourceReaper;3public class 1 {4 public static void main(String[] args) {5 GenericContainer container = new GenericContainer("alpine:3.9");6 container.start();7 RyukResourceReaper.registerContainer(container);8 }9}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!