@Override public void contribute(Builder builder) { try { Pod current = utils.currentPod().get(); Map<String, Object> details = new HashMap<>(); if (current != null) { details.put("inside", true); details.put("namespace", current.getMetadata().getNamespace()); details.put("podName", current.getMetadata().getName()); details.put("podIp", current.getStatus().getPodIP()); details.put("serviceAccount", current.getSpec().getServiceAccountName()); details.put("nodeName", current.getSpec().getNodeName()); details.put("hostIp", current.getStatus().getHostIP()); } else { details.put("inside", false); } builder.withDetail("kubernetes", details); } catch (Exception e) { LOG.warn("Failed to get pod details", e); } } }
PodList list = client.pods().withLabels(createdByZaleniumMap).list(); for (Pod pod : list.getItems()) { if (podIpAddress.equals(pod.getStatus().getPodIP())) { containerId = pod.getMetadata().getName(); currentPod = pod; break; List<EnvVar> podEnvironmentVariables = currentPod.getSpec().getContainers().get(0).getEnv(); Optional<EnvVar> noVncPort = podEnvironmentVariables.stream().filter(env -> "NOVNC_PORT".equals(env.getName())).findFirst(); registration.setIpAddress(currentPod.getStatus().getPodIP()); registration.setContainerId(containerId);
@Override public void eventReceived(Action action, Pod aPod) { log(aPod.getMetadata().getName(), aPod.getStatus().getPhase()); if(aPod.getStatus().getPhase().equals("Succeeded")) { log("Logs -> ", client.pods().inNamespace(namespace).withName(aPod.getMetadata().getName()).getLog()); watchLatch.countDown(); } }
/** * Print name of all pods in list * * @param pods list of pods that should be printed * @return */ public static String printPods(List<Pod> pods) { return pods.stream() .map(pod -> "{" + pod.getMetadata().getName() + ", " + pod.getStatus().getPhase() + "}") .collect(Collectors.joining(",")); }
private Set<String> pullClusterMembers() { List<Pod> pods = kubernetesClient.pods() .inNamespace(this.lockConfiguration.getKubernetesResourcesNamespaceOrDefault(kubernetesClient)) .withLabels(this.lockConfiguration.getClusterLabels()) .list().getItems(); return pods.stream().map(pod -> pod.getMetadata().getName()).collect(Collectors.toSet()); }
protected AppStatus buildAppStatus(String id, PodList podList, ServiceList services) { AppStatus.Builder statusBuilder = AppStatus.of(id); Service service = null; if (podList != null && podList.getItems() != null) { for (Pod pod : podList.getItems()) { for (Service svc : services.getItems()) { if (svc.getMetadata().getName() .equals(pod.getMetadata().getLabels().get(SPRING_DEPLOYMENT_KEY))) { service = svc; break; } } statusBuilder.with(new KubernetesAppInstanceStatus(pod, service, properties)); } } return statusBuilder.build(); }
try (final KubernetesClient client = new DefaultKubernetesClient(config)) { if (namespace == null) { namespace = client.getNamespace(); List<HasMetadata> resources = client.load(new FileInputStream(fileName)).get(); if (resources.isEmpty()) { System.err.println("No resources loaded from file: " +fileName); Pod pod = (Pod) resource; System.out.println("Creating pod in namespace " + namespace); NonNamespaceOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> pods = client.pods().inNamespace(namespace); Pod result = pods.create(pod); System.out.println("Created pod " + result.getMetadata().getName()); } else { System.err.println("Loaded resource is not a Pod! " + resource);
@Override public Collection<Instance> getInstanceList() throws Exception { LOGGER.info("Starting Kubernetes instance discovery using master URL: {}", client.getMasterUrl()); return client.pods().inAnyNamespace() .list() .getItems().stream() .filter(pod -> pod.getMetadata().getAnnotations() != null) // Ignore pods without annotations .filter(pod -> pod.getMetadata().getAnnotations().containsKey(PORT_ANNOTATION_KEY)) .map(pod -> { String portString = pod.getMetadata().getAnnotations().get(PORT_ANNOTATION_KEY); if (!Pattern.compile("^[0-9]{2,5}$").matcher(portString).matches()) { LOGGER.warn("Invalid port annotation for pod '{}': {}", pod.getMetadata().getName(), portString); return null; } else { String host = String.format("%s:%s", pod.getStatus().getPodIP(), portString); boolean running = pod.getStatus().getPhase().equals("Running"); LOGGER.info("Found Kubernetes Pod {} at address {}", pod.getMetadata().getName(), host); return new Instance(host, extractClusterNameFor(pod), running); } }) .filter(Objects::nonNull) .collect(Collectors.toList()); }
private static EntityPatcher<Pod> podPatcher() { return (KubernetesClient client, String namespace, Pod newObj, Pod oldObj) -> { if (UserConfigurationCompare.configEqual(newObj, oldObj)) { return oldObj; } DoneablePod entity = client.pods() .inNamespace(namespace) .withName(oldObj.getMetadata().getName()) .edit(); if (!UserConfigurationCompare.configEqual(newObj.getMetadata(), oldObj.getMetadata())) { entity.withMetadata(newObj.getMetadata()); } if(!UserConfigurationCompare.configEqual(newObj.getSpec(), oldObj.getSpec())) { entity.withSpec(newObj.getSpec()); } return entity.done(); }; }
client.namespaces().list() ); client.namespaces().withLabel("this", "works").list() ); client.pods().withLabel("this", "works").list() ); client.pods().inNamespace("test").withLabel("this", "works").list() ); client.pods().inNamespace("test").withName("testing").get() ); PodList podList = client.pods().inNamespace("myproject").list(5, null); podList.getItems().forEach((obj) -> { System.out.println(obj.getMetadata().getName()); }); podList = client.pods().inNamespace("myproject").list(5, podList.getMetadata().getContinue()); podList.getItems().forEach((obj) -> { System.out.println(obj.getMetadata().getName()); }); Integer services = client.services().inNamespace("myproject").list(1, null).getItems().size();
public HashMap<String, String> getLogsOfTerminatedPods(String namespace) { HashMap<String, String> terminatedPodsLogs = new HashMap<>(); try { client.pods().inNamespace(namespace).list().getItems().forEach(pod -> { pod.getStatus().getContainerStatuses().forEach(containerStatus -> { log.info("pod:'{}' : restart count '{}'", pod.getMetadata().getName(), containerStatus.getRestartCount()); if (containerStatus.getRestartCount() > 0) { terminatedPodsLogs.put( pod.getMetadata().getName(), client.pods().inNamespace(namespace) .withName(pod.getMetadata().getName()) .inContainer(containerStatus.getName()) .terminated().getLog()); } }); }); } catch (Exception allExceptions) { log.warn("Searching in terminated pods failed! No logs of terminated pods will be stored."); allExceptions.printStackTrace(); } return terminatedPodsLogs; }
public PodFluentImpl(Pod instance){ this.withApiVersion(instance.getApiVersion()); this.withKind(instance.getKind()); this.withMetadata(instance.getMetadata()); this.withSpec(instance.getSpec()); this.withStatus(instance.getStatus()); }
public Pod(io.fabric8.kubernetes.api.model.Pod pod) { this.name = pod.getMetadata().getName(); if (pod.getMetadata().getAnnotations() != null) { this.annotations.putAll(pod.getMetadata().getAnnotations()); } this.kind = pod.getKind(); this.host = pod.getStatus().getPodIP(); this.phase = pod.getStatus().getPhase(); this.ready = getReadyCondition(pod.getStatus().getConditions()); this.portMap = getPortMap(pod.getSpec().getContainers()); }
@Override public AppStatus status(String appId) { Map<String, String> selector = new HashMap<>(); ServiceList services = client.services().withLabel(SPRING_APP_KEY, appId).list(); selector.put(SPRING_APP_KEY, appId); PodList podList = client.pods().withLabels(selector).list(); if (logger.isDebugEnabled()) { logger.debug(String.format("Building AppStatus for app: %s", appId)); if (podList != null && podList.getItems() != null) { logger.debug(String.format("Pods for appId %s: %d", appId, podList.getItems().size())); for (Pod pod : podList.getItems()) { logger.debug(String.format("Pod: %s", pod.getMetadata().getName())); } } } AppStatus status = buildAppStatus(appId, podList, services); logger.debug(String.format("Status for app: %s is %s", appId, status)); return status; }
return; if (client.isAdaptable(OpenShiftClient.class)){ OpenShiftClient oClient = client.adapt(OpenShiftClient.class); List<DeploymentConfig> deploymentConfigs = oClient.deploymentConfigs().inNamespace(session.getNamespace()).list().getItems(); if (deploymentConfigs == null) { throw new MultiException("No deployment configs found in namespace" + session.getNamespace()); session.getLogger().info("Deployment config:" + KubernetesHelper.getName(deploymentConfig)); List<Deployment> deployments = client.extensions().deployments().inNamespace(session.getNamespace()).list().getItems(); if (deployments == null) { throw new MultiException("No deployments found in namespace" + session.getNamespace()); session.getLogger().info("Deployment:" + KubernetesHelper.getName(deployment)); List<Pod> pods = client.pods().inNamespace(session.getNamespace()).list().getItems(); if (pods == null) { throw new MultiException("No pods found in namespace" + session.getNamespace()); session.getLogger().info("Pod:" + KubernetesHelper.getName(pod) + " Status:" + pod.getStatus());
@Override public Boolean call() throws Exception { boolean result = true; List<Pod> pods = notNullList(kubernetesClient.pods().inNamespace(session.getNamespace()).list().getItems()); if (!KubernetesHelper.isPodReady(pod)) { PodStatus podStatus = pod.getStatus(); int restartCount = 0; if( "Succeeded".equals(podStatus.getPhase()) ) { List<ContainerStatus> containerStatuses = podStatus.getContainerStatuses(); for (ContainerStatus containerStatus : containerStatuses) { if (restartCount == 0) { String name = KubernetesHelper.getName(pod); File yamlFile = new File(session.getBaseDir(), "target/test-pod-status/" + name + ".yml"); yamlFile.getParentFile().mkdirs(); try { KubernetesHelper.saveYaml(pod, yamlFile); } catch (IOException e) { session.getLogger().warn("Failed to write " + yamlFile + ". " + e); if (KubernetesHelper.isPodRunning(pod)) { List<Container> containers = pod.getSpec().getContainers(); for (Container container : containers) { File logFile = LogHelpers.getLogFileName(session.getBaseDir(), name, container, restartCount); String log = kubernetesClient.pods().inNamespace(session.getNamespace()).withName(name).inContainer(container.getName()).getLog(); IOHelpers.writeFully(logFile, log);
public Optional<Reader> getLogs(String label, String integrationName) { return client.pods().list().getItems().stream() .filter(pod -> integrationName.equals(pod.getMetadata().getLabels().get(label))) .findAny() .map(pod -> pod.getMetadata().getName()) .flatMap(podName -> { PodOperationsImpl pod = (PodOperationsImpl) client.pods().withName(podName); try { Request request = new Request.Builder() .url(pod.getResourceUrl().toString() + "/log?pretty=false×tamps=true") .build(); Response response = null; try { response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected response from /log endpoint: " + response); } return Optional.of(new RegexBasedMasqueradeReader(new BufferedReader(response.body().charStream()), MASKING_REGEXP)); } catch (IOException e) { // NOPMD LOG.error("Error downloading log file for integration {}" , integrationName, e ); if (response != null){ response.close(); } } } catch (MalformedURLException e) { LOG.error("Error downloading log file for integration {}" , integrationName, e ); } return Optional.empty(); }); }
public Optional<String> getServiceLatestCreatedPodName(Service service, Optional<String> groupName) { PodList podList = kubernetesClient .pods() .inNamespace(environment.getKubernetesNamespace()) .withLabel(ApolloToKubernetes.getApolloDeploymentUniqueIdentifierKey(), ApolloToKubernetes.getApolloPodUniqueIdentifier(environment, service, groupName)) .list(); if (podList == null) { return Optional.empty(); } Optional<Pod> newestPod = podList.getItems() .stream() .sorted((o1, o2) -> { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); LocalDateTime pod1 = LocalDateTime.parse(o1.getStatus().getStartTime(), formatter); LocalDateTime pod2 = LocalDateTime.parse(o2.getStatus().getStartTime(), formatter); return pod1.compareTo(pod2); }).findFirst(); return newestPod.map(pod -> pod .getMetadata() .getName()); }
if (containerPort == 8778 || (Objects.equals("jolokia", name) && containerPort.intValue() > 0)) { if (useKubeProxy) { URL masterUrl = getKubernetes().getMasterUrl(); ObjectMeta metadata = pod.getMetadata(); String namespace = metadata.getNamespace(); String podName = metadata.getName(); String jolokiaUrl = URLUtils.join(masterUrl.toString(), "/api/v1/namespaces/" + namespace + "/pods/" + locateJolokiaProtocol() + ":" + podName + ":8778/proxy/jolokia/"); LOG.info("Using jolokia URL: " + jolokiaUrl); return createJolokiaClient(container, jolokiaUrl); PodStatus currentState = pod.getStatus(); String podIP = currentState.getPodIP(); if (Strings.isNotBlank(podIP)) { return createJolokiaClientFromHostAndPort(container, podIP, containerPort); String dockerIp = getDockerIp(); if (Strings.isNotBlank(dockerIp)) { host = dockerIp;
@Override public Set<String> discoverMembers() { LOGGER.debug("CELLAR KUBERNETES: query pods with labeled with [{}={}]", kubernetesPodLabelKey, kubernetesPodLabelValue); Set<String> members = new HashSet<String>(); try { PodList podList = kubernetesClient.pods().list(); for (Pod pod : podList.getItems()) { String value = pod.getMetadata().getLabels().get(kubernetesPodLabelKey); if (value != null && !value.isEmpty() && value.equals(kubernetesPodLabelValue)) { members.add(pod.getStatus().getPodIP()); } } } catch (Exception e) { LOGGER.error("CELLAR KUBERNETES: can't get pods", e); } return members; }