in log4j-kubernetes/src/main/java/org/apache/logging/log4j/kubernetes/KubernetesLookup.java [78:161]
private boolean initialize() {
if (kubernetesInfo == null || (isSpringIncluded && !kubernetesInfo.isSpringActive)) {
initLock.lock();
try {
final boolean isSpringActive = isSpringActive();
if (kubernetesInfo == null || (!kubernetesInfo.isSpringActive && isSpringActive)) {
final KubernetesInfo info = new KubernetesInfo();
KubernetesClient client = null;
info.isSpringActive = isSpringActive;
if (pod == null) {
client = new KubernetesClientBuilder().createClient();
if (client != null) {
pod = getCurrentPod(System.getenv(HOSTNAME), client);
info.masterUrl = client.getMasterUrl();
if (pod != null) {
info.namespace = pod.getMetadata().getNamespace();
namespace = client.namespaces().withName(info.namespace).get();
}
} else {
LOGGER.warn("Kubernetes is not available for access");
}
} else {
info.masterUrl = masterUrl;
}
if (pod != null) {
if (namespace != null) {
info.namespaceId = namespace.getMetadata().getUid();
info.namespaceAnnotations = namespace.getMetadata().getAnnotations();
info.namespaceLabels = namespace.getMetadata().getLabels();
}
info.app = pod.getMetadata().getLabels().get("app");
info.hostName = pod.getSpec().getNodeName();
info.annotations = pod.getMetadata().getAnnotations();
final String app = info.app != null ? info.app : "";
info.podTemplateHash = pod.getMetadata().getLabels().get("pod-template-hash");
info.accountName = pod.getSpec().getServiceAccountName();
info.clusterName = pod.getMetadata().getClusterName();
info.hostIp = pod.getStatus().getHostIP();
info.labels = pod.getMetadata().getLabels();
info.podId = pod.getMetadata().getUid();
info.podIp = pod.getStatus().getPodIP();
info.podName = pod.getMetadata().getName();
ContainerStatus containerStatus = null;
final List<ContainerStatus> statuses = pod.getStatus().getContainerStatuses();
if (statuses.size() == 1) {
containerStatus = statuses.get(0);
} else if (statuses.size() > 1) {
final String containerId = ContainerUtil.getContainerId();
if (containerId != null) {
containerStatus = statuses.stream()
.filter(cs -> cs.getContainerID().contains(containerId))
.findFirst().orElse(null);
}
}
final String containerName;
if (containerStatus != null) {
info.containerId = containerStatus.getContainerID();
info.imageId = containerStatus.getImageID();
containerName = containerStatus.getName();
} else {
containerName = null;
}
Container container = null;
final List<Container> containers = pod.getSpec().getContainers();
if (containers.size() == 1) {
container = containers.get(0);
} else if (containers.size() > 1 && containerName != null) {
container = containers.stream().filter(c -> c.getName().equals(containerName))
.findFirst().orElse(null);
}
if (container != null) {
info.containerName = container.getName();
info.imageName = container.getImage();
}
kubernetesInfo = info;
}
}
} finally {
initLock.unlock();
}
}
return kubernetesInfo != null;
}