private static Map<String, String> getData(KubernetesClient client, String name, String namespace, String[] profiles) { try { ConfigMap map = StringUtils.isEmpty(namespace) ? client.configMaps().withName(name).get() : client.configMaps().inNamespace(namespace).withName(name).get(); if (map != null) { return processAllEntries(map.getData(), profiles); } } catch (Exception e) { LOG.warn("Can't read configMap with name: [" + name + "] in namespace:[" + namespace + "]. Ignoring"); } return new HashMap<>(); }
@Scheduled(fixedDelayString = "${spring.cloud.kubernetes.discovery.catalogServicesWatchDelay:30000}") public void catalogServicesWatch() { try { List<String> previousState = catalogEndpointsState.get(); //not all pods participate in the service discovery. only those that have endpoints. List<Endpoints> endpoints = kubernetesClient.endpoints().list().getItems(); List<String> endpointsPodNames = endpoints.stream() .map(Endpoints::getSubsets) .filter(Objects::nonNull) .flatMap(Collection::stream) .map(EndpointSubset::getAddresses) .filter(Objects::nonNull) .flatMap(Collection::stream) .map(EndpointAddress::getTargetRef) .filter(Objects::nonNull) .map(ObjectReference::getName) // pod name unique in namespace .sorted(String::compareTo).collect(Collectors.toList()); catalogEndpointsState.set(endpointsPodNames); if (!endpointsPodNames.equals(previousState)) { logger.trace("Received endpoints update from kubernetesClient: {}", endpointsPodNames); publisher.publishEvent(new HeartbeatEvent(this, endpointsPodNames)); } } catch (Exception e) { logger.error("Error watching Kubernetes Services", e); } }
secret = client.secrets().withName(name).get(); secret = client.secrets().inNamespace(namespace).withName(name).get(); client.secrets().withLabels(config.getLabels()).list().getItems() .forEach(s -> putAll(s, result)); client.secrets().inNamespace(namespace) .withLabels(config.getLabels()).list().getItems() .forEach(s -> putAll(s, result));
try (Watch watch = client.replicationControllers().inNamespace("thisisatest").withResourceVersion("0").watch(new Watcher<ReplicationController>() { @Override public void eventReceived(Action action, ReplicationController resource) { log("Create resource quota", client.resourceQuotas().inNamespace("thisisatest").create(quota)); log("Get jobs in namespace", client.batch().jobs().inNamespace("thisisatest").list()); } catch (APIGroupNotAvailableException e) { log("Skipping jobs example - extensions API group not available"); log("Created RC", client.replicationControllers().inNamespace("thisisatest").create(rc)); client.replicationControllers().inNamespace("thisisatest").createNew() .withNewMetadata().withName("nginx2-controller").addToLabels("server", "nginx").endMetadata() .withNewSpec().withReplicas(0) ReplicationController gotRc = client.replicationControllers().inNamespace("thisisatest").withName("nginx-controller").get(); log("Get RC by name in namespace", gotRc); log("Get RC by label", client.replicationControllers().withLabel("server", "nginx").list()); log("Get RC without label", client.replicationControllers().withoutLabel("server", "apache").list()); log("Get RC with label in", client.replicationControllers().withLabelIn("server", "nginx").list()); log("Get RC with label not in", client.replicationControllers().withLabelNotIn("server", "apache").list()); log("Get RC by label in namespace", client.replicationControllers().inNamespace("thisisatest").withLabel("server", "nginx").list());
OpenShiftClient openShiftClient = new Controller(client).getOpenShiftClientOrNull(); if (openShiftClient != null) { try { openShiftClient.deploymentConfigs().inNamespace(sessionNamespace).delete(); } catch (KubernetesClientException e) { errors.add(e); openShiftClient.routes().inNamespace(sessionNamespace).delete(); } catch (KubernetesClientException e) { errors.add(e); client.extensions().deployments().inNamespace(sessionNamespace).delete(); } catch (KubernetesClientException e) { errors.add(e); client.extensions().replicaSets().inNamespace(sessionNamespace).delete(); } catch (KubernetesClientException e) { errors.add(e); client.replicationControllers().inNamespace(sessionNamespace).delete(); } catch (KubernetesClientException e) { errors.add(e); client.pods().inNamespace(sessionNamespace).delete(); } catch (KubernetesClientException e) { errors.add(e); client.extensions().ingresses().inNamespace(sessionNamespace).delete(); } catch (KubernetesClientException e) {
private ConfigMap getConfigMap() { return kubernetesClient.configMaps() .inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) .withName(leaderProperties.getConfigMapName()) .get(); }
Controller controller = new Controller(kubernetes); controller.setThrowExceptionOnError(true); controller.setRecreateMode(false); controller.setAllowCreate(step.getCreateNewResources()); controller.setServicesOnlyMode(step.getServicesOnly()); dto = KubernetesHelper.loadJson(resources); } else { dto = KubernetesHelper.loadYaml(resources.getBytes(), KubernetesResource.class); entities.addAll(KubernetesHelper.toItemList(dto)); answer = kubernetes.resourceList(items).accept(new TypedVisitor<ObjectMetaBuilder>() { String yaml = KubernetesHelper.toYaml(environmentRollout); OpenShiftClient oClient = openShiftClient(); BuildResource<Build, DoneableBuild, String, LogWatch> resource = oClient.builds().inNamespace(this.buildConfigNamespace).withName(buildName); try { Build build = resource.get();
@Override public String getURL(Service service, String portName, String namespace, KubernetesClient client) { String serviceName = service.getMetadata().getName(); ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName); if(port != null && port.getName() != null && isOpenShift(client)) { try { String serviceProtocol = port.getProtocol(); OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class); Route route = openShiftClient.routes().inNamespace(namespace).withName(service.getMetadata().getName()).get(); if (route != null) { return (serviceProtocol + "://" + route.getSpec().getHost()).toLowerCase(); } } catch (KubernetesClientException e) { if(e.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { logger.warn("Could not lookup route:" + serviceName + " in namespace:"+ namespace +", due to: " + e.getMessage()); } } } return null; }
public static void main(String[] args) throws InterruptedException { String namespace = "myproject"; String master = "CLUSTER_URL"; Config config = new ConfigBuilder().withMasterUrl(master).build(); OpenShiftClient client = new DefaultOpenShiftClient(config); try { ImageStreamTag istag = new ImageStreamTagBuilder().withNewMetadata().withName("bar1:1.0.12").endMetadata() .withNewTag().withNewFrom().withKind("DockerImage").withName("openshift/wildfly-81-centos7:latest").endFrom().endTag() .build(); log("Created istag", client.imageStreamTags().inNamespace(namespace).create(istag)); Thread.sleep(30000); }finally { log("ImageStreamTags are :"); log(client.imageStreamTags().inNamespace(namespace).withName("bar1:1.0.12").get().toString()); log("ImageStreamTags using list are :"); log(client.imageStreamTags().list().getItems().get(0).toString()); log("Deleted istag",client.imageStreamTags().withName("bar1:1.0.12").delete()); client.close(); } }
private String loadKubernetesExposeControllerCommandLine(KubernetesClient kubernetes, String commands) throws Exception { String namespace = System.getenv("KUBERNETES_NAMESPACE"); if (Strings.isNullOrBlank(namespace)) { namespace = KubernetesHelper.getNamespace(kubernetes); } ConfigMap configMap = kubernetes.configMaps().inNamespace(namespace).withName("exposecontroller").get(); if (configMap == null) { listener.getLogger().println("WARNING: no ConfigMap in namespace " + namespace + " called: exposecontroller so cannot run exposecontroller to expose Service URLs"); return null; } String configYaml = null; Map<String, String> data = configMap.getData(); if (data != null) { configYaml = data.get("config.yml"); } if (Strings.isNullOrBlank(configYaml)) { throw new Exception("ConfigMap " + namespace + "/exposecontroller does not have a `config.yml` data entry"); } Map map; try { map = KubernetesHelper.loadYaml(configYaml, Map.class); } catch (IOException e) { throw new Exception("Could not parse YAML in ConfigMap " + namespace + "/exposecontroller entry `config.yml`: " + e, e); } StringBuilder builder = new StringBuilder(commands); appendCliArgument(builder, "--http", map.get("http")); appendCliArgument(builder, "--exposer", map.get("exposer")); appendCliArgument(builder, "--domain", map.get("domain")); return builder.toString(); }
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(); System.out.println(services); } catch (KubernetesClientException e) {
/** * Returns a client for the first working pod for the given service */ public J4pClient clientForService(String serviceName, String namespace) { List<Pod> pods = KubernetesHelper.getPodsForService(requireService(serviceName, namespace), kubernetes.pods().inNamespace(namespace).list().getItems()); return clientForPod(pods); }
public static void main(String[] args) { String master = "https://localhost:8443/"; if (args.length == 1) { master = args[0]; } Config config = new ConfigBuilder().withMasterUrl(master).build(); KubernetesClient client = new DefaultKubernetesClient(config); try { log("Create namespace:", client.namespaces().create(new NamespaceBuilder().withNewMetadata().withName("thisisatest").endMetadata().build())); log("Deleted namespace:", client.namespaces().withName("test").delete()); log("Deleted testPod:", client.pods().inNamespace("thisisatest").withName("testpod").delete()); log("Deleted pod by label:", client.pods().withLabel("this", "works").delete()); } catch (KubernetesClientException e) { logger.error(e.getMessage(), e); } finally { client.namespaces().withName("thisisatest").delete(); client.close(); } }
try { KubernetesClient kubernetes = getKubernetes(); String ns = kubernetes.getNamespace(); if (Strings.isNullOrBlank(ns)) { ns = getNamespace(); Service service = kubernetes.services().inNamespace(ns).withName(serviceName).get(); return service != null ? KubernetesHelper.getServiceURL(kubernetes, serviceName, ns, protocol, true) : null; } catch (Throwable e) {
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()); List<Service> svcs = client.services().inNamespace(session.getNamespace()).list().getItems(); if (svcs == null) { throw new MultiException("No services found in namespace" + session.getNamespace());
public void start() { if (watch == null) { synchronized (lock) { if (watch == null) { LOGGER.debug("Starting leader record watcher"); watch = kubernetesClient .configMaps() .inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) .withName(leaderProperties.getConfigMapName()) .watch(this); } } } }
client.serviceAccounts().inNamespace("thisisatest").create(fabric8); log("Created image stream", client.imageStreams().inNamespace("thisisatest").createNew() .withNewMetadata() .withName("example-camel-cdi") log("Created image stream", client.imageStreams().inNamespace("thisisatest").createNew() .withNewMetadata() .withName("java-sti") log("Created build config", client.buildConfigs().inNamespace("thisisatest").createNew() .withNewMetadata() .withName("custom-build-config") Build build = client.buildConfigs().inNamespace("thisisatest").withName("custom-build-config").instantiate(new BuildRequestBuilder() .withNewMetadata().withName("custom-build-config").endMetadata() .build()); log("Build:", build.getMetadata().getName()); client.buildConfigs().inNamespace("thisisatest").withName("custom-build-config") .withSecret("secret101") .withType("github") for (Build b: client.builds().inNamespace("thisisatest").list().getItems()) { log("\t\t\t"+b.getMetadata().getName()); log("\t\t\t\t\t Log:");client.builds().inNamespace("thisisatest").withName(b.getMetadata().getName()).watchLog(System.out);
/** * Returns all the clients for the first working pod for the given replication controller */ public List<J4pClient> clientsForReplicationController(String replicationControllerName, String namespace) { ReplicationController replicationController = requireReplicationController(replicationControllerName, namespace); List<Pod> pods = KubernetesHelper.getPodsForReplicationController(replicationController, kubernetes.pods().inNamespace(namespace).list().getItems()); return clientsForPod(pods); }