io.fabric8.kubernetes.api.model.extensions.IngressBuilder Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.extensions.IngressBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IngressTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteMulti() {
  Ingress ingress1 = new IngressBuilder().withNewMetadata().withName("ingress1").withNamespace("test").and().build();
  Ingress ingress2 = new IngressBuilder().withNewMetadata().withName("ingress2").withNamespace("ns1").and().build();
  Ingress ingress3 = new IngressBuilder().withNewMetadata().withName("ingress3").withNamespace("any").and().build();

 server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/ingresses/ingress1").andReturn(200, ingress1).once();
 server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/ingresses/ingress2").andReturn(200, ingress2).once();

  KubernetesClient client = server.getClient();

  Boolean deleted = client.extensions().ingress().inAnyNamespace().delete(ingress1, ingress2);
  assertTrue(deleted);

  deleted = client.extensions().ingress().inAnyNamespace().delete(ingress3);
  assertFalse(deleted);
}
 
Example #2
Source File: IngressTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
 server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/ingresses/ingress1").andReturn(200, new IngressBuilder().build()).once();
 server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/ingresses/ingress2").andReturn(200, new IngressBuilder().build()).once();

  KubernetesClient client = server.getClient();

  Boolean deleted = client.extensions().ingress().withName("ingress1").delete();
  assertTrue(deleted);

  deleted = client.extensions().ingress().withName("ingress2").delete();
  assertFalse(deleted);

  deleted = client.extensions().ingress().inNamespace("ns1").withName("ingress2").delete();
  assertTrue(deleted);
}
 
Example #3
Source File: IngressTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/ingresses/ingress1").andReturn(200, new IngressBuilder().build()).once();
 server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/ingresses/ingress2").andReturn(200, new IngressBuilder().build()).once();

  KubernetesClient client = server.getClient();

  Ingress ingress = client.extensions().ingress().withName("ingress1").get();
  assertNotNull(ingress);

  ingress = client.extensions().ingress().withName("ingress2").get();
  assertNull(ingress);

  ingress = client.extensions().ingress().inNamespace("ns1").withName("ingress2").get();
  assertNotNull(ingress);
}
 
Example #4
Source File: KubernetesEnvironmentFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void ignoreIgressesWhenRecipeContainsThem() throws Exception {
  when(k8sRecipeParser.parse(any(InternalRecipe.class)))
      .thenReturn(
          asList(
              new IngressBuilder().withNewMetadata().withName("ingress1").endMetadata().build(),
              new IngressBuilder().withNewMetadata().withName("ingress2").endMetadata().build()));

  final KubernetesEnvironment parsed =
      k8sEnvFactory.doCreate(internalRecipe, emptyMap(), emptyList());

  assertTrue(parsed.getIngresses().isEmpty());
  assertEquals(parsed.getWarnings().size(), 1);
  assertEquals(
      parsed.getWarnings().get(0),
      new WarningImpl(INGRESSES_IGNORED_WARNING_CODE, INGRESSES_IGNORED_WARNING_MESSAGE));
}
 
Example #5
Source File: SystemtestsKubernetesApps.java    From enmasse with Apache License 2.0 6 votes vote down vote up
private static Ingress getSystemtestsIngressResource(String appName, int port) throws Exception {
    IngressBackend backend = new IngressBackend();
    backend.setServiceName(appName);
    backend.setServicePort(new IntOrString(port));
    HTTPIngressPath path = new HTTPIngressPath();
    path.setPath("/");
    path.setBackend(backend);

    return new IngressBuilder()
            .withNewMetadata()
            .withName(appName)
            .addToLabels("route", appName)
            .endMetadata()
            .withNewSpec()
            .withRules(new IngressRuleBuilder()
                    .withHost(appName + "."
                            + (env.kubernetesDomain().equals("nip.io") ? new URL(env.getApiUrl()).getHost() + ".nip.io" : env.kubernetesDomain()))
                    .withNewHttp()
                    .withPaths(path)
                    .endHttp()
                    .build())
            .endSpec()
            .build();
}
 
Example #6
Source File: IngressTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithNameMismatch() {
  Assertions.assertThrows(KubernetesClientException.class, () -> {
    Ingress ingress1 = new IngressBuilder().withNewMetadata().withName("ingress1").withNamespace("test").and().build();
    Ingress ingress2 = new IngressBuilder().withNewMetadata().withName("ingress2").withNamespace("ns1").and().build();
    KubernetesClient client = server.getClient();

    client.extensions().ingress().inNamespace("test1").withName("myingress1").create(ingress1);
  });
}
 
Example #7
Source File: IngressTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWithNamespaceMismatch() {
  Assertions.assertThrows(KubernetesClientException.class, () -> {
    Ingress ingress1 = new IngressBuilder().withNewMetadata().withName("ingress1").withNamespace("test").and().build();
    Ingress ingress2 = new IngressBuilder().withNewMetadata().withName("ingress2").withNamespace("ns1").and().build();
    KubernetesClient client = server.getClient();

    Boolean deleted = client.extensions().ingress().inNamespace("test1").delete(ingress1);
    assertTrue(deleted);
  });
}
 
Example #8
Source File: KubernetesServerResolverTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Ingress createIngress(
    String name, String machineName, Pair<String, ServerConfig> server) {
  Serializer serializer = Annotations.newSerializer();
  serializer.machineName(machineName);
  serializer.server(server.first, server.second);

  return new IngressBuilder()
      .withNewMetadata()
      .withName(name)
      .withAnnotations(serializer.annotations())
      .endMetadata()
      .withNewSpec()
      .withRules(
          new IngressRule(
              null,
              new HTTPIngressRuleValue(
                  singletonList(
                      new HTTPIngressPath(
                          new IngressBackend(name, new IntOrString("8080")),
                          INGRESS_PATH_PREFIX)))))
      .endSpec()
      .withNewStatus()
      .withNewLoadBalancer()
      .addNewIngress()
      .withIp("127.0.0.1")
      .endIngress()
      .endLoadBalancer()
      .endStatus()
      .build();
}
 
Example #9
Source File: IngressOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
protected Ingress resource() {
    return new IngressBuilder()
            .withNewMetadata()
                .withName(RESOURCE_NAME)
                .withNamespace(NAMESPACE)
                .withLabels(singletonMap("foo", "bar"))
            .endMetadata()
            .build();
}
 
Example #10
Source File: SparkOperatorEntrypoint.java    From spark-operator with Apache License 2.0 5 votes vote down vote up
private Ingress createIngressForMetrics() {
        Ingress ingress = new IngressBuilder().withNewMetadata().withName("spark-operator-metrics")
                .withLabels(Collections.singletonMap("type", "operator-metrics")).endMetadata()
                .withNewSpec().withRules(new IngressRuleBuilder().withNewHttp()
                        .withPaths(new HTTPIngressPathBuilder().withNewBackend().withServiceName("spark-operator-metrics")
                                .withNewServicePort(entrypoint.getConfig().getMetricsPort()).endBackend().build()).endHttp().build())
                .endSpec().build();
        return ingress;
}
 
Example #11
Source File: IngressEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns true if we already have a route created for the given name
 */
private static boolean hasIngress(final KubernetesListBuilder listBuilder, final String name) {
    final AtomicBoolean answer = new AtomicBoolean(false);
    listBuilder.accept(new TypedVisitor<IngressBuilder>() {

        @Override
        public void visit(IngressBuilder builder) {
            ObjectMeta metadata = builder.buildMetadata();
            if (metadata != null && name.equals(metadata.getName())) {
                answer.set(true);
            }
        }
    });
    return answer.get();
}
 
Example #12
Source File: KafkaCluster.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a bootstrap ingress which can be used to bootstrap clients outside of Kubernetes.
 *
 * @return The generated Ingress
 */
public Ingress generateExternalBootstrapIngress() {
    if (isExposedWithIngress()) {
        KafkaListenerExternalIngress listener = (KafkaListenerExternalIngress) listeners.getExternal();
        Map<String, String> dnsAnnotations;
        String host;

        if (listener.getConfiguration() != null && listener.getConfiguration().getBootstrap() != null && listener.getConfiguration().getBootstrap().getHost() != null) {
            host = listener.getConfiguration().getBootstrap().getHost();
            dnsAnnotations = listener.getConfiguration().getBootstrap().getDnsAnnotations();
        } else {
            throw new InvalidResourceException("Bootstrap hostname is required for exposing Kafka cluster using Ingress");
        }

        HTTPIngressPath path = new HTTPIngressPathBuilder()
                .withPath("/")
                .withNewBackend()
                    .withNewServicePort(EXTERNAL_PORT)
                    .withServiceName(externalBootstrapServiceName(cluster))
                .endBackend()
                .build();

        IngressRule rule = new IngressRuleBuilder()
                .withHost(host)
                .withNewHttp()
                    .withPaths(path)
                .endHttp()
                .build();

        IngressTLS tls = new IngressTLSBuilder()
                .withHosts(host)
                .build();

        Ingress ingress = new IngressBuilder()
                .withNewMetadata()
                    .withName(serviceName)
                    .withLabels(getLabelsWithStrimziName(serviceName, templateExternalBootstrapIngressLabels).toMap())
                    .withAnnotations(mergeLabelsOrAnnotations(generateInternalIngressAnnotations(listener), templateExternalBootstrapIngressAnnotations, dnsAnnotations))
                    .withNamespace(namespace)
                    .withOwnerReferences(createOwnerReference())
                .endMetadata()
                .withNewSpec()
                    .withRules(rule)
                    .withTls(tls)
                .endSpec()
                .build();

        return ingress;
    }

    return null;
}
 
Example #13
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
private static Ingress newIngress() {
  return new IngressBuilder()
      .withMetadata(new ObjectMetaBuilder().withName(INGRESS_NAME).build())
      .build();
}
 
Example #14
Source File: KafkaCluster.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Generates ingress for pod. This ingress is used for exposing it externally using Nginx Ingress.
 *
 * @param pod Number of the pod for which this ingress should be generated
 * @return The generated Ingress
 */
public Ingress generateExternalIngress(int pod) {
    if (isExposedWithIngress()) {
        KafkaListenerExternalIngress listener = (KafkaListenerExternalIngress) listeners.getExternal();
        Map<String, String> dnsAnnotations = null;
        String host = null;

        if (listener.getConfiguration() != null && listener.getConfiguration().getBrokers() != null) {
            host = listener.getConfiguration().getBrokers().stream()
                    .filter(broker -> broker != null && broker.getBroker() == pod
                            && broker.getHost() != null)
                    .map(IngressListenerBrokerConfiguration::getHost)
                    .findAny()
                    .orElseThrow(() -> new InvalidResourceException("Hostname for broker with id " + pod + " is required for exposing Kafka cluster using Ingress"));

            dnsAnnotations = listener.getConfiguration().getBrokers().stream()
                    .filter(broker -> broker != null && broker.getBroker() == pod)
                    .map(IngressListenerBrokerConfiguration::getDnsAnnotations)
                    .findAny()
                    .orElse(null);
        }

        String perPodServiceName = externalServiceName(cluster, pod);

        HTTPIngressPath path = new HTTPIngressPathBuilder()
                .withPath("/")
                .withNewBackend()
                    .withNewServicePort(EXTERNAL_PORT)
                    .withServiceName(perPodServiceName)
                .endBackend()
                .build();

        IngressRule rule = new IngressRuleBuilder()
                .withHost(host)
                .withNewHttp()
                    .withPaths(path)
                .endHttp()
                .build();

        IngressTLS tls = new IngressTLSBuilder()
                .withHosts(host)
                .build();

        Ingress ingress = new IngressBuilder()
                .withNewMetadata()
                    .withName(perPodServiceName)
                    .withLabels(getLabelsWithStrimziName(perPodServiceName, templatePerPodIngressLabels).toMap())
                    .withAnnotations(mergeLabelsOrAnnotations(generateInternalIngressAnnotations(listener), templatePerPodIngressAnnotations, dnsAnnotations))
                    .withNamespace(namespace)
                    .withOwnerReferences(createOwnerReference())
                .endMetadata()
                .withNewSpec()
                    .withRules(rule)
                    .withTls(tls)
                .endSpec()
                .build();

        return ingress;
    }

    return null;
}
 
Example #15
Source File: IngressHandler.java    From module-ballerina-kubernetes with Apache License 2.0 4 votes vote down vote up
/**
 * Generate kubernetes ingress definition from annotation.
 *
 * @param ingressModel IngressModel object
 * @throws KubernetesPluginException If an error occurs while generating artifact.
 */
private void generate(IngressModel ingressModel) throws KubernetesPluginException {
    //generate ingress backend
    IngressBackend ingressBackend = new IngressBackendBuilder()
            .withServiceName(ingressModel.getServiceName())
            .withNewServicePort(ingressModel.getServicePort())
            .build();

    //generate ingress path
    HTTPIngressPath ingressPath = new HTTPIngressPathBuilder()
            .withBackend(ingressBackend)
            .withPath(ingressModel
                    .getPath()).build();

    //generate TLS
    List<IngressTLS> ingressTLS = new ArrayList<>();
    if (ingressModel.isEnableTLS()) {
        ingressTLS.add(new IngressTLSBuilder()
                .withHosts(ingressModel.getHostname())
                .build());
    }

    //generate annotationMap
    Map<String, String> annotationMap = new HashMap<>();
    annotationMap.put("kubernetes.io/ingress.class", ingressModel.getIngressClass());
    if (NGINX.equals(ingressModel.getIngressClass())) {
        annotationMap.put("nginx.ingress.kubernetes.io/ssl-passthrough", String.valueOf(ingressModel.isEnableTLS
                ()));
        if (ingressModel.getTargetPath() != null) {
            annotationMap.put("nginx.ingress.kubernetes.io/rewrite-target", ingressModel.getTargetPath());
        }
    }
    //Add user defined ingress annotations to yaml.
    Map<String, String> userDefinedAnnotationMap = ingressModel.getAnnotations();
    if (userDefinedAnnotationMap != null) {
        userDefinedAnnotationMap.forEach(annotationMap::putIfAbsent);
    }

    //generate ingress
    Ingress ingress = new IngressBuilder()
            .withNewMetadata()
            .withName(ingressModel.getName())
            .withNamespace(dataHolder.getNamespace())
            .addToLabels(ingressModel.getLabels())
            .addToAnnotations(annotationMap)
            .endMetadata()
            .withNewSpec()
            .withTls(ingressTLS)
            .addNewRule()
            .withHost(ingressModel.getHostname())
            .withNewHttp()
            .withPaths(ingressPath)
            .endHttp()
            .endRule()
            .endSpec()
            .build();
    String ingressYAML;
    try {
        ingressYAML = SerializationUtils.dumpWithoutRuntimeStateAsYaml(ingress);
        KubernetesUtils.writeToFile(ingressYAML, INGRESS_FILE_POSTFIX + YAML);
    } catch (IOException e) {
        String errorMessage = "error while generating yaml file for ingress: " + ingressModel.getName();
        throw new KubernetesPluginException(errorMessage, e);
    }
}
 
Example #16
Source File: KubernetesHistoryServerDeployer.java    From spark-operator with Apache License 2.0 4 votes vote down vote up
public KubernetesResourceList getResourceList(SparkHistoryServer hs, String namespace, boolean isOpenshift) {
    checkForInjectionVulnerabilities(hs, namespace);
    List<HasMetadata> resources = new ArrayList<>();

    Map<String, String> defaultLabels = getDefaultLabels(hs.getName());
    int uiPort = hs.getInternalPort();

    Deployment deployment = getDeployment(hs, defaultLabels);
    resources.add(deployment);

    if (HistoryServerHelper.needsVolume(hs) && null != hs.getSharedVolume()) {
        PersistentVolumeClaim pvc = getPersistentVolumeClaim(hs, defaultLabels);
        resources.add(pvc);
    }

    // expose the service using Ingress or Route
    if (hs.getExpose()) {
        Service service = new ServiceBuilder().withNewMetadata().withLabels(defaultLabels).withName(hs.getName())
                .endMetadata().withNewSpec().withSelector(defaultLabels)
                .withPorts(new ServicePortBuilder().withName("web-ui").withPort(uiPort).build()).endSpec().build();
        resources.add(service);
        if (isOpenshift) {
            Route route = new RouteBuilder().withNewMetadata().withName(hs.getName())
                    .withLabels(defaultLabels).endMetadata()
                    .withNewSpec().withHost(hs.getHost())
                    .withNewTo("Service", hs.getName(), 100)
                    .endSpec().build();
            resources.add(route);
        } else {
            Ingress ingress = new IngressBuilder().withNewMetadata().withName(hs.getName())
                    .withLabels(defaultLabels).endMetadata()
                    .withNewSpec().withRules(new IngressRuleBuilder().withHost(hs.getHost()).withNewHttp()
                            .withPaths(new HTTPIngressPathBuilder().withNewBackend().withServiceName(hs.getName()).withNewServicePort(uiPort).endBackend().build()).endHttp().build())
                    .endSpec().build();
            resources.add(ingress);
        }
    }

    KubernetesList k8sResources = new KubernetesListBuilder().withItems(resources).build();
    return k8sResources;
}
 
Example #17
Source File: IngressEnricher.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
protected static Ingress addIngress(KubernetesListBuilder listBuilder, ServiceBuilder serviceBuilder, String routeDomainPostfix, KitLogger log) {
    ObjectMeta serviceMetadata = serviceBuilder.buildMetadata();
    if (serviceMetadata == null) {
        log.info("No Metadata for service! ");
    }
    if (isExposedService(serviceMetadata) && shouldCreateExternalURLForService(serviceBuilder, log)) {
        Objects.requireNonNull(serviceMetadata);
        String serviceName = serviceMetadata.getName();
        if (!hasIngress(listBuilder, serviceName)) {
            Integer servicePort = getServicePort(serviceBuilder);
            if (servicePort != null) {

                IngressBuilder ingressBuilder = new IngressBuilder().
                        withMetadata(serviceMetadata).
                        withNewSpec().
                        endSpec();

                // removing `expose : true` label from metadata.
                removeLabel(ingressBuilder.buildMetadata(), EXPOSE_LABEL, "true");
                removeLabel(ingressBuilder.buildMetadata(), JKubeAnnotations.SERVICE_EXPOSE_URL.value(), "true");
                ingressBuilder.withNewMetadataLike(ingressBuilder.buildMetadata());

                if (StringUtils.isNotBlank(routeDomainPostfix)) {
                    routeDomainPostfix = serviceName + "." + FileUtil.stripPrefix(routeDomainPostfix, ".");
                    ingressBuilder = ingressBuilder.withSpec(new IngressSpecBuilder().addNewRule().
                            withHost(routeDomainPostfix).
                            withNewHttp().
                            withPaths(new HTTPIngressPathBuilder()
                                    .withNewBackend()
                                    .withServiceName(serviceName)
                                    .withServicePort(KubernetesHelper.createIntOrString(getServicePort(serviceBuilder)))
                                    .endBackend()
                                    .build())
                            .endHttp().
                                    endRule().build());
                } else {
                    ingressBuilder.withSpec(new IngressSpecBuilder().withBackend(new IngressBackendBuilder().
                            withNewServiceName(serviceName)
                            .withNewServicePort(getServicePort(serviceBuilder))
                            .build()).build());
                }

                return ingressBuilder.build();
            }
        }
    }
    return null;
}
 
Example #18
Source File: MetadataVisitor.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected ObjectMeta getOrCreateMetadata(IngressBuilder item) {
    return addEmptyLabelsAndAnnotations(item::hasMetadata, item::withNewMetadata, item::editMetadata, item::buildMetadata)
            .endMetadata().buildMetadata();
}