@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 { Config config = new ConfigBuilder().build(); KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); OpenShiftClient client = kubernetesClient.adapt(OpenShiftClient.class); log("Created project", client.projectrequests().create(projectRequest)); client.serviceAccounts().inNamespace("thisisatest").createOrReplace(fabric8); log("Created deployment", client.deploymentConfigs().inNamespace("thisisatest").createOrReplaceWithNew() .withNewMetadata() .withName("nginx") client.deploymentConfigs().inNamespace("thisisatest").withName("nginx").scale(2, true); log("Created pods:", client.pods().inNamespace("thisisatest").list().getItems()); client.deploymentConfigs().inNamespace("thisisatest").withName("nginx").delete(); log("Pods:", client.pods().inNamespace("thisisatest").list().getItems()); log("Replication Controllers:", client.replicationControllers().inNamespace("thisisatest").list().getItems()); client.close();
log("Created namespace", client.namespaces().create(ns)); 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);
public static void main(String[] args) { try { OpenShiftClient client = new DefaultOpenShiftClient(); String namespace = client.getNamespace(); System.out.println("Watching BuildConfigs in namespace " + namespace); try (Watch watchable = client.buildConfigs().inNamespace(namespace).watch(new Watcher<BuildConfig>() { @Override public void eventReceived(Action action, BuildConfig resource) { System.out.println(">> Action: " + action + " on BuildConfig " + resource.getMetadata().getName() + " with version: " + resource.getApiVersion()); } @Override public void onClose(KubernetesClientException cause) { System.out.println("Watch Closed: " + cause); if (cause != null) { cause.printStackTrace(); } } })) { System.out.println("Created watchable " + watchable); } } catch (KubernetesClientException e) { System.out.println("Failed: " + e); e.printStackTrace(); } }
public static void main(String[] args) { try { OpenShiftClient client = new DefaultOpenShiftClient(); if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.IMAGE)) { System.out.println("WARNING this cluster does not support the API Group " + OpenShiftAPIGroups.IMAGE); return; } ImageStreamList list = client.imageStreams().list(); if (list == null) { System.out.println("ERROR no list returned!"); return; } List<ImageStream> items = list.getItems(); for (ImageStream item : items) { System.out.println("ImageStream " + item.getMetadata().getName() + " has version: " + item.getApiVersion()); } System.out.println("Found " + items.size() + " ImageStream(s)"); } catch (KubernetesClientException e) { System.out.println("Failed: " + e); e.printStackTrace(); } }
public static void main(String[] args) { try { OpenShiftClient client = new DefaultOpenShiftClient(); if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.BUILD)) { System.out.println("WARNING this cluster does not support the API Group " + OpenShiftAPIGroups.BUILD); return; } BuildConfigList list = client.buildConfigs().list(); if (list == null) { System.out.println("ERROR no list returned!"); return; } List<BuildConfig> items = list.getItems(); for (BuildConfig item : items) { System.out.println("BuildConfig " + item.getMetadata().getName() + " has version: " + item.getApiVersion()); } } catch (KubernetesClientException e) { System.out.println("Failed: " + e); e.printStackTrace(); } }
@Override public Secret getCertSecret(String name) { return client.secrets().inNamespace(namespace).withName(name).get(); }
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.securityContextConstraints().withName(sessionNamespace).delete(); } catch (KubernetesClientException e) { errors.add(e);
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();
Service service = delegate.services().inNamespace(prjName).withName(svcName).get(); if (service != null) { appName = service.getMetadata().getLabels().get(APP_LABEL); delegate.deploymentConfigs().inNamespace(prjName).withName(svcName).cascading(true).delete(); if (appName != null) { delegate.services().inNamespace(prjName).withLabel(APP_LABEL, appName).delete(); delegate.routes().inNamespace(prjName).withLabel(APP_LABEL, appName).delete(); } else { delegate.services().inNamespace(prjName).delete(); delegate.routes().inNamespace(prjName).delete(); for (ImageStream item : delegate.imageStreams().inNamespace(prjName).list().getItems()) { if (isGuvnorAlaGenerated(item)) { delegate.imageStreams().inNamespace(prjName).delete(item); for (Secret item : delegate.secrets().inNamespace(prjName).list().getItems()) { if (isGuvnorAlaGenerated(item)) { delegate.secrets().inNamespace(prjName).delete(item); for (ServiceAccount item : delegate.serviceAccounts().inNamespace(prjName).list().getItems()) { if (isGuvnorAlaGenerated(item)) { delegate.serviceAccounts().inNamespace(prjName).delete(item); if (isGuvnorAlaGenerated(delegate.projects().withName(prjName).get())) { delegate.projects().withName(prjName).delete();
.build(); log("Created ImageStream", client.imageStreams().inNamespace(namespace).create(imageStream)); log("First Tag is " + client.imageStreams().inNamespace(namespace).withName("slave-jenkins").get().getSpec().getTags().get(0).getName()); log("Second Tag is " + client.imageStreams().inNamespace(namespace).withName("slave-jenkins").get().getSpec().getTags().get(1).getName()); client.imageStreams().inNamespace(namespace).withName("slave-jenkins").delete(); client.close();
private OpenShiftRuntimeState getRuntimeState(OpenShiftRuntimeId runtimeId) { String prjName = runtimeId.project(); String svcName = runtimeId.service(); String state; String startedAt; Service service = delegate.services().inNamespace(prjName).withName(svcName).get(); if (service != null) { Integer replicas = getReplicas(service); if (replicas != null && replicas.intValue() > 0) { state = OpenShiftRuntimeState.RUNNING; } else { state = OpenShiftRuntimeState.READY; } startedAt = service.getMetadata().getCreationTimestamp(); } else { state = OpenShiftRuntimeState.UNKNOWN; startedAt = new Date().toString(); } return new OpenShiftRuntimeState(state, startedAt); }
@Override public void provideCert(AddressSpace addressSpace, EndpointInfo endpointInfo) { Secret secret = client.secrets().inNamespace(namespace).withName(endpointInfo.getCertSpec().getSecretName()).get(); if (secret == null) { String serviceName = KubeUtil.getAddressSpaceServiceName(endpointInfo.getServiceName(), addressSpace); Service service = client.services().withName(serviceName).get(); if (service != null && (service.getMetadata().getAnnotations() == null || service.getMetadata().getAnnotations().get(AnnotationKeys.OPENSHIFT_SERVING_CERT_SECRET_NAME) == null)) { log.info("Adding service annotation to generate OpenShift cert"); client.services().withName(serviceName).edit() .editMetadata() .addToAnnotations(AnnotationKeys.OPENSHIFT_SERVING_CERT_SECRET_NAME, endpointInfo.getCertSpec().getSecretName()) .endMetadata() .done(); } } } }
public void applyRoute(Route entity, String sourceName) { OpenShiftClient openShiftClient = getOpenShiftClient(); if (openShiftClient != null) { String id = getName(entity); Objects.requireNonNull(id, "No name for " + entity + " " + sourceName); String namespace = KubernetesHelper.getNamespace(entity); if (StringUtils.isBlank(namespace)) { namespace = getNamespace(); } Route route = openShiftClient.routes().inNamespace(namespace).withName(id).get(); if (route == null) { try { log.info("Creating Route " + namespace + ":" + id + " " + (entity.getSpec() != null ? "host: " + entity.getSpec().getHost() : "No Spec !")); openShiftClient.routes().inNamespace(namespace).create(entity); } catch (Exception e) { onApplyError("Failed to create Route from " + sourceName + ". " + e + ". " + entity, e); } } } }
private void createFromUri(String prjName, String uri) throws OpenShiftClientException { URL url = toUrl(uri); if (url != null) { KubernetesList kubeList = delegate.lists().load(url).get(); List<HasMetadata> items = kubeList.getItems(); if (items.size() > 0) { for (HasMetadata item : items) { String name = item.getMetadata().getName(); if (item instanceof ServiceAccount) { if (delegate.serviceAccounts().inNamespace(prjName).withName(name).get() == null) { setGuvnorAlaGenerated(item); } } else if (item instanceof Secret) { if (delegate.secrets().inNamespace(prjName).withName(name).get() == null) { setGuvnorAlaGenerated(item); } } else if (item instanceof ImageStream) { if (delegate.imageStreams().inNamespace(prjName).withName(name).get() == null) { setGuvnorAlaGenerated(item); } } } delegate.lists().inNamespace(prjName).create(kubeList); } } }
public void applyImageStream(ImageStream entity, String sourceName) { OpenShiftClient openShiftClient = getOpenShiftClient(); if (openShiftClient != null) { String kind = getKind(entity); String name = getName(entity); String namespace = getNamespace(); try { Resource<ImageStream, DoneableImageStream> resource = openShiftClient.imageStreams().inNamespace(namespace).withName(name); ImageStream old = resource.get(); if (old == null) { log.info("Creating " + kind + " " + name + " from " + sourceName); resource.create(entity); } else { log.info("Updating " + kind + " " + name + " from " + sourceName); copyAllImageStreamTags(entity, old); patchService.compareAndPatchEntity(namespace, entity, old); } openShiftClient.resource(entity).inNamespace(namespace).createOrReplace(); } catch (Exception e) { onApplyError("Failed to create " + kind + " from " + sourceName + ". " + e, e); } } }
/** * {@inheritDoc} */ @Override public List<Endpoint> listServices() throws ServiceDiscoveryException { List<Endpoint> endpointList = new ArrayList<>(); if (client != null) { log.debug("Looking for services in all namespaces"); try { List<Service> serviceList = client.services().inNamespace(null).list().getItems(); addServicesToEndpointList(serviceList, endpointList); } catch (KubernetesClientException | MalformedURLException e) { String msg = "Error occurred while trying to list services using Kubernetes client"; throw new ServiceDiscoveryException(msg, e, ExceptionCodes.ERROR_WHILE_TRYING_TO_DISCOVER_SERVICES); } } return endpointList; }
public boolean checkNamespace(String namespaceName) { if (StringUtils.isBlank(namespaceName)) { return false; } OpenShiftClient openshiftClient = getOpenShiftClient(); if (openshiftClient != null) { // It is preferable to iterate on the list of projects as regular user with the 'basic-role' bound // are not granted permission get operation on non-existing project resource that returns 403 // instead of 404. Only more privileged roles like 'view' or 'cluster-reader' are granted this permission. List<Project> projects = openshiftClient.projects().list().getItems(); for (Project project : projects) { if (namespaceName.equals(project.getMetadata().getName())) { return true; } } return false; } else { return kubernetesClient.namespaces().withName(namespaceName).get() != null; } }
public static void resizeApp(KubernetesClient kubernetes, String namespace, Set<HasMetadata> entities, int replicas, Logger log) { for (HasMetadata entity : entities) { String name = KubernetesHelper.getName(entity); Scaleable<?> scalable = null; if (entity instanceof Deployment) { scalable = kubernetes.extensions().deployments().inNamespace(namespace).withName(name); } else if (entity instanceof ReplicaSet) { scalable = kubernetes.extensions().replicaSets().inNamespace(namespace).withName(name); } else if (entity instanceof ReplicationController) { scalable = kubernetes.replicationControllers().inNamespace(namespace).withName(name); } else if (entity instanceof DeploymentConfig) { OpenShiftClient openshiftClient = OpenshiftHelper.asOpenShiftClient(kubernetes); if (openshiftClient == null) { log.warn("Ignoring DeploymentConfig %s as not connected to an OpenShift cluster", name); continue; } scalable = openshiftClient.deploymentConfigs().inNamespace(namespace).withName(name); } if (scalable != null) { log.info("Scaling " + KubernetesHelper.getKind(entity) + " " + namespace + "/" + name + " to replicas: " + replicas); scalable.scale(replicas, true); } } }
protected void doGetBuildConfig(Exchange exchange, String operation) throws Exception { BuildConfig buildConfig = null; String buildConfigName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_BUILD_CONFIG_NAME, String.class); String namespaceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class); if (ObjectHelper.isEmpty(buildConfigName)) { LOG.error("Get a specific Build Config require specify a Build Config name"); throw new IllegalArgumentException("Get a specific Build Config require specify a Build Config name"); } if (ObjectHelper.isEmpty(namespaceName)) { LOG.error("Get a specific Build Config require specify a namespace name"); throw new IllegalArgumentException("Get a specific Build Config require specify a namespace name"); } buildConfig = getEndpoint().getKubernetesClient().adapt(OpenShiftClient.class).buildConfigs() .inNamespace(namespaceName).withName(buildConfigName).get(); MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true); exchange.getOut().setBody(buildConfig); } }