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

The following examples show how to use io.fabric8.kubernetes.api.model.extensions.IngressRule. 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: 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 #2
Source File: KubernetesInternalRuntimeTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private static Ingress mockIngress() {
  final Ingress ingress = mock(Ingress.class);
  mockName(INGRESS_NAME, ingress);
  final IngressSpec spec = mock(IngressSpec.class);

  final IngressBackend backend = mock(IngressBackend.class);
  when(backend.getServiceName()).thenReturn(SERVICE_NAME);
  when(backend.getServicePort()).thenReturn(new IntOrString(EXPOSED_PORT_1));
  when(spec.getBackend()).thenReturn(backend);

  final IngressRule rule = mock(IngressRule.class);
  when(rule.getHost()).thenReturn(INGRESS_HOST);
  when(spec.getRules()).thenReturn(singletonList(rule));

  when(ingress.getSpec()).thenReturn(spec);
  when(ingress.getMetadata().getLabels())
      .thenReturn(ImmutableMap.of(CHE_ORIGINAL_NAME_LABEL, INGRESS_NAME));
  return ingress;
}
 
Example #3
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 #4
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 #5
Source File: IngressesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void emptyWhenPortByIntAndNotFound() {
  final String SERVER_PORT_NAME = "server-8080";
  final int PORT = 8080;

  Service service = createService(SERVER_PORT_NAME, PORT);
  Ingress ingress = createIngress(new IngressBackend("servicename", new IntOrString(666)));

  Optional<IngressRule> foundRule =
      Ingresses.findIngressRuleForServicePort(singletonList(ingress), service, PORT);
  assertFalse(foundRule.isPresent());
}
 
Example #6
Source File: IngressesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void emptyWhenPortByStringAndNotFound() {
  final String SERVER_PORT_NAME = "server-8080";
  final int PORT = 8080;

  Service service = createService(SERVER_PORT_NAME, PORT);
  Ingress ingress =
      createIngress(new IngressBackend("servicename", new IntOrString("does not exist")));

  Optional<IngressRule> foundRule =
      Ingresses.findIngressRuleForServicePort(singletonList(ingress), service, PORT);
  assertFalse(foundRule.isPresent());
}
 
Example #7
Source File: IngressesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void findHostWhenPortDefinedByInt() {
  final String SERVER_PORT_NAME = "server-8080";
  final int PORT = 8080;

  Service service = createService(SERVER_PORT_NAME, PORT);
  Ingress ingress =
      createIngress(new IngressBackend("servicename", new IntOrString(SERVER_PORT_NAME)));

  Optional<IngressRule> foundRule =
      Ingresses.findIngressRuleForServicePort(singletonList(ingress), service, PORT);
  assertTrue(foundRule.isPresent());
  assertEquals(foundRule.get().getHost(), "ingresshost");
}
 
Example #8
Source File: IngressesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void findHostWhenPortDefinedByString() {
  final String SERVER_PORT_NAME = "server-8080";
  final int PORT = 8080;

  Service service = createService(SERVER_PORT_NAME, PORT);
  Ingress ingress = createIngress(new IngressBackend("servicename", new IntOrString(PORT)));

  Optional<IngressRule> foundRule =
      Ingresses.findIngressRuleForServicePort(singletonList(ingress), service, PORT);
  assertTrue(foundRule.isPresent());
  assertEquals(foundRule.get().getHost(), "ingresshost");
}
 
Example #9
Source File: MultiHostExternalServiceExposureStrategyTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void assertThatExternalServerIsExposed(
    String machineName,
    String serviceName,
    String serverNameRegex,
    String portProtocol,
    Integer port,
    ServicePort servicePort,
    ServerConfigImpl expected) {

  // ensure that required ingress is created
  String ingressName =
      serviceName + "-" + (expected.isUnique() ? serverNameRegex : servicePort.getName());
  Ingress ingress = kubernetesEnvironment.getIngresses().get(ingressName);
  IngressRule ingressRule = ingress.getSpec().getRules().get(0);
  assertEquals(ingressRule.getHost(), ingressName + "." + DOMAIN);
  assertEquals(ingressRule.getHttp().getPaths().get(0).getPath(), "/");
  IngressBackend backend = ingressRule.getHttp().getPaths().get(0).getBackend();
  assertEquals(backend.getServiceName(), serviceName);
  assertEquals(backend.getServicePort().getStrVal(), servicePort.getName());

  Annotations.Deserializer ingressAnnotations =
      Annotations.newDeserializer(ingress.getMetadata().getAnnotations());
  Map<String, ServerConfigImpl> servers = ingressAnnotations.servers();
  ServerConfig serverConfig = servers.get(serverNameRegex);
  assertEquals(serverConfig, expected);

  assertEquals(ingressAnnotations.machineName(), machineName);
}
 
Example #10
Source File: DefaultHostExternalServiceExposureStrategyTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private void assertThatExternalServerIsExposed(
    String machineName,
    String serviceName,
    String serverNameRegex,
    ServicePort servicePort,
    ServerConfigImpl expected) {

  // ensure that required ingress is created
  for (Ingress ingress : kubernetesEnvironment.getIngresses().values()) {
    IngressRule ingressRule = ingress.getSpec().getRules().get(0);
    IngressBackend backend = ingressRule.getHttp().getPaths().get(0).getBackend();
    if (serviceName.equals(backend.getServiceName())) {
      assertEquals(backend.getServicePort().getStrVal(), servicePort.getName());

      Annotations.Deserializer ingressAnnotations =
          Annotations.newDeserializer(ingress.getMetadata().getAnnotations());
      Map<String, ServerConfigImpl> servers = ingressAnnotations.servers();
      ServerConfig serverConfig = servers.get(serverNameRegex);

      if (serverConfig == null) {
        // ok, this ingress is not for this particular server
        continue;
      }

      assertEquals(serverConfig, expected);

      assertEquals(ingressAnnotations.machineName(), machineName);
      return;
    }
  }

  Assert.fail(
      format(
          "Could not find an ingress for machine '%s' and service '%s'",
          machineName, serviceName));
}
 
Example #11
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 #12
Source File: KubernetesServerResolver.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void fillIngressServers(Ingress ingress, Map<String, ServerImpl> servers) {
  IngressRule ingressRule = ingress.getSpec().getRules().get(0);

  // host either set by rule, or determined by LB ip
  final String host =
      ingressRule.getHost() != null
          ? ingressRule.getHost()
          : ingress.getStatus().getLoadBalancer().getIngress().get(0).getIp();

  Annotations.newDeserializer(ingress.getMetadata().getAnnotations())
      .servers()
      .forEach(
          (name, config) -> {
            String path =
                buildPath(
                    pathTransformInverter.undoPathTransformation(
                        ingressRule.getHttp().getPaths().get(0).getPath()),
                    config.getPath());
            servers.put(
                name,
                new RuntimeServerBuilder()
                    .protocol(config.getProtocol())
                    .host(host)
                    .path(path)
                    .attributes(config.getAttributes())
                    .targetPort(config.getPort())
                    .build());
          });
}
 
Example #13
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);
}
 
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: 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 #16
Source File: KubernetesPreviewUrlCommandProvisioner.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Optional<String> findHostForServicePort(
    List<Ingress> ingresses, Service service, int port) {
  return Ingresses.findIngressRuleForServicePort(ingresses, service, port)
      .map(IngressRule::getHost);
}
 
Example #17
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;
}