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

The following examples show how to use io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath. 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: 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 #2
Source File: Ingresses.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * In given {@code ingresses} finds {@link IngressRule} for given {@code service} and {@code
 * port}.
 *
 * @return found {@link IngressRule} or {@link Optional#empty()}
 */
public static Optional<IngressRule> findIngressRuleForServicePort(
    Collection<Ingress> ingresses, Service service, int port) {
  Optional<ServicePort> foundPort = Services.findPort(service, port);
  if (!foundPort.isPresent()) {
    return Optional.empty();
  }

  for (Ingress ingress : ingresses) {
    for (IngressRule rule : ingress.getSpec().getRules()) {
      for (HTTPIngressPath path : rule.getHttp().getPaths()) {
        IngressBackend backend = path.getBackend();
        if (backend.getServiceName().equals(service.getMetadata().getName())
            && matchesServicePort(backend.getServicePort(), foundPort.get())) {
          return Optional.of(rule);
        }
      }
    }
  }
  return Optional.empty();
}
 
Example #3
Source File: ExternalServerIngressBuilderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void assertIngressSpec(String path, String host, Ingress ingress) {
  assertEquals(ingress.getSpec().getRules().get(0).getHost(), host);
  HTTPIngressPath httpIngressPath =
      ingress.getSpec().getRules().get(0).getHttp().getPaths().get(0);
  assertEquals(httpIngressPath.getPath(), path);
  assertEquals(httpIngressPath.getBackend().getServiceName(), SERVICE_NAME);
  assertEquals(httpIngressPath.getBackend().getServicePort().getStrVal(), SERVICE_PORT);

  assertEquals(ingress.getMetadata().getName(), NAME);
  assertTrue(ingress.getMetadata().getAnnotations().containsKey("annotation-key"));
  assertEquals(ingress.getMetadata().getAnnotations().get("annotation-key"), "annotation-value");

  Annotations.Deserializer ingressAnnotations =
      Annotations.newDeserializer(ingress.getMetadata().getAnnotations());
  Map<String, ServerConfigImpl> servers = ingressAnnotations.servers();
  ServerConfig serverConfig = servers.get("http-server");
  assertEquals(serverConfig, SERVER_CONFIG);

  assertEquals(ingressAnnotations.machineName(), MACHINE_NAME);
}
 
Example #4
Source File: ExternalServerIngressBuilder.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public Ingress build() {

    IngressBackend ingressBackend =
        new IngressBackendBuilder()
            .withServiceName(serviceName)
            .withNewServicePort(servicePort.getStrVal())
            .build();

    HTTPIngressPathBuilder httpIngressPathBuilder =
        new HTTPIngressPathBuilder().withBackend(ingressBackend);

    if (!isNullOrEmpty(path)) {
      httpIngressPathBuilder.withPath(path);
    }

    HTTPIngressPath httpIngressPath = httpIngressPathBuilder.build();

    HTTPIngressRuleValue httpIngressRuleValue =
        new HTTPIngressRuleValueBuilder().withPaths(httpIngressPath).build();
    IngressRuleBuilder ingressRuleBuilder = new IngressRuleBuilder().withHttp(httpIngressRuleValue);

    if (!isNullOrEmpty(host)) {
      ingressRuleBuilder.withHost(host);
    }

    IngressRule ingressRule = ingressRuleBuilder.build();

    IngressSpec ingressSpec = new IngressSpecBuilder().withRules(ingressRule).build();

    Map<String, String> ingressAnnotations = new HashMap<>(annotations);
    ingressAnnotations.putAll(
        Annotations.newSerializer().servers(serversConfigs).machineName(machineName).annotations());

    return new io.fabric8.kubernetes.api.model.extensions.IngressBuilder()
        .withSpec(ingressSpec)
        .withMetadata(
            new ObjectMetaBuilder().withName(name).withAnnotations(ingressAnnotations).build())
        .build();
  }
 
Example #5
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 #6
Source File: IngressesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Ingress createIngress(IngressBackend backend) {
  Ingress ingress = new Ingress();
  ObjectMeta ingressMeta = new ObjectMeta();
  ingressMeta.setName("ingressname");
  ingress.setMetadata(ingressMeta);
  IngressSpec ingressSpec = new IngressSpec();
  IngressRule ingressRule = new IngressRule();
  ingressRule.setHost("ingresshost");
  ingressRule.setHttp(
      new HTTPIngressRuleValue(singletonList(new HTTPIngressPath(backend, null))));
  ingressSpec.setRules(singletonList(ingressRule));
  ingress.setSpec(ingressSpec);
  return ingress;
}
 
Example #7
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 #8
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 #9
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 #10
Source File: KubernetesPreviewUrlCommandProvisionerTest.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void shouldUpdateCommandWhenServiceAndIngressFound() throws InfrastructureException {
  final int PORT = 8080;
  final String SERVICE_PORT_NAME = "service-" + PORT;
  List<CommandImpl> commands =
      Collections.singletonList(
          new CommandImpl("a", "a", "a", new PreviewUrlImpl(PORT, null), Collections.emptyMap()));
  KubernetesEnvironment env =
      KubernetesEnvironment.builder().setCommands(new ArrayList<>(commands)).build();

  Mockito.when(mockNamespace.services()).thenReturn(mockServices);
  Service service = new Service();
  ObjectMeta metadata = new ObjectMeta();
  metadata.setName("servicename");
  service.setMetadata(metadata);
  ServiceSpec spec = new ServiceSpec();
  spec.setPorts(
      Collections.singletonList(
          new ServicePort(SERVICE_PORT_NAME, null, PORT, "TCP", new IntOrString(PORT))));
  service.setSpec(spec);
  Mockito.when(mockServices.get()).thenReturn(Collections.singletonList(service));

  Ingress ingress = new Ingress();
  IngressSpec ingressSpec = new IngressSpec();
  IngressRule rule =
      new IngressRule(
          "testhost",
          new HTTPIngressRuleValue(
              Collections.singletonList(
                  new HTTPIngressPath(
                      new IngressBackend("servicename", new IntOrString(SERVICE_PORT_NAME)),
                      null))));
  ingressSpec.setRules(Collections.singletonList(rule));
  ingress.setSpec(ingressSpec);
  Mockito.when(mockNamespace.ingresses()).thenReturn(mockIngresses);
  Mockito.when(mockIngresses.get()).thenReturn(Collections.singletonList(ingress));

  previewUrlCommandProvisioner.provision(env, mockNamespace);

  assertTrue(env.getCommands().get(0).getAttributes().containsKey("previewUrl"));
  assertEquals(env.getCommands().get(0).getAttributes().get("previewUrl"), "testhost");
  assertTrue(env.getWarnings().isEmpty());
}
 
Example #11
Source File: PreviewUrlExposerTest.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void shouldNotProvisionWhenServiceAndIngressFound()
    throws InternalInfrastructureException {
  final int PORT = 8080;
  final String SERVER_PORT_NAME = "server-" + PORT;

  CommandImpl command =
      new CommandImpl("a", "a", "a", new PreviewUrlImpl(PORT, null), Collections.emptyMap());

  Service service = new Service();
  ObjectMeta serviceMeta = new ObjectMeta();
  serviceMeta.setName("servicename");
  service.setMetadata(serviceMeta);
  ServiceSpec serviceSpec = new ServiceSpec();
  serviceSpec.setPorts(
      singletonList(new ServicePort(SERVER_PORT_NAME, null, PORT, "TCP", new IntOrString(PORT))));
  service.setSpec(serviceSpec);

  Ingress ingress = new Ingress();
  ObjectMeta ingressMeta = new ObjectMeta();
  ingressMeta.setName("ingressname");
  ingress.setMetadata(ingressMeta);
  IngressSpec ingressSpec = new IngressSpec();
  IngressRule ingressRule = new IngressRule();
  ingressRule.setHost("ingresshost");
  IngressBackend ingressBackend =
      new IngressBackend("servicename", new IntOrString(SERVER_PORT_NAME));
  ingressRule.setHttp(
      new HTTPIngressRuleValue(singletonList(new HTTPIngressPath(ingressBackend, null))));
  ingressSpec.setRules(singletonList(ingressRule));
  ingress.setSpec(ingressSpec);

  Map<String, Service> services = new HashMap<>();
  services.put("servicename", service);
  Map<String, Ingress> ingresses = new HashMap<>();
  ingresses.put("ingressname", ingress);

  KubernetesEnvironment env =
      KubernetesEnvironment.builder()
          .setCommands(singletonList(new CommandImpl(command)))
          .setServices(services)
          .setIngresses(ingresses)
          .build();

  assertEquals(env.getIngresses().size(), 1);
  previewUrlExposer.expose(env);
  assertEquals(env.getIngresses().size(), 1);
}