|
| 1 | +package com.gitblit.utils; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | + |
| 5 | +import java.io.File; |
| 6 | + |
| 7 | +/** |
| 8 | + * The ContainerDetector tries to detect if the Gitblit instance |
| 9 | + * is running in a container, or directly on the (virtualized) OS. |
| 10 | + */ |
| 11 | +public class ContainerDetector |
| 12 | +{ |
| 13 | + private static Boolean inContainer; |
| 14 | + private static String detectedType = ""; |
| 15 | + |
| 16 | + /** |
| 17 | + * Detect if this instance in running inside a container. |
| 18 | + * |
| 19 | + * @return true - if a container could be detected |
| 20 | + * false - otherwise |
| 21 | + */ |
| 22 | + public static boolean detect() |
| 23 | + { |
| 24 | + if (inContainer == null) { |
| 25 | + File proc = new File("/proc/1/cgroup"); |
| 26 | + if (! proc.exists()) inContainer = Boolean.FALSE; |
| 27 | + else { |
| 28 | + String cgroups = FileUtils.readContent(proc, null); |
| 29 | + if (cgroups.contains("/docker")) { |
| 30 | + inContainer = Boolean.TRUE; |
| 31 | + detectedType = "Docker container"; |
| 32 | + } |
| 33 | + else if (cgroups.contains("/ecs")) { |
| 34 | + inContainer = Boolean.TRUE; |
| 35 | + detectedType = "ECS container"; |
| 36 | + } |
| 37 | + else if (cgroups.contains("/kubepod") || cgroups.contains("/kubepods")) { |
| 38 | + inContainer = Boolean.TRUE; |
| 39 | + detectedType = "Kubernetes pod"; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + // Finally, if we still haven't found proof, it is probably not a container |
| 44 | + if (inContainer == null) inContainer = Boolean.FALSE; |
| 45 | + } |
| 46 | + |
| 47 | + return inContainer; |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + /** |
| 52 | + * Report to some output if a container was detected. |
| 53 | + * |
| 54 | + */ |
| 55 | + public static void report(Logger logger, boolean onlyIfInContainer) |
| 56 | + { |
| 57 | + if (detect()) { |
| 58 | + String msg = "Running in a " + detectedType; |
| 59 | + if (logger == null) { |
| 60 | + System.out.println(msg); |
| 61 | + } |
| 62 | + else logger.info(msg); |
| 63 | + } |
| 64 | + else if (!onlyIfInContainer) { |
| 65 | + String msg = "Not detected to be running in a container"; |
| 66 | + if (logger == null) { |
| 67 | + System.out.println(msg); |
| 68 | + } |
| 69 | + else logger.info(msg); |
| 70 | + |
| 71 | + } |
| 72 | + |
| 73 | + } |
| 74 | +} |
0 commit comments