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

The following examples show how to use io.fabric8.kubernetes.api.model.extensions.IngressBackend. 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: 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 #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: PreviewUrlExposerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldProvisionServiceAndIngressWhenNotFound()
    throws InternalInfrastructureException {
  Mockito.when(
          externalServiceExposureStrategy.getExternalPath(Mockito.anyString(), Mockito.any()))
      .thenReturn("some-server-path");

  final int PORT = 8080;
  final String SERVER_PORT_NAME = "server-" + PORT;

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

  KubernetesEnvironment env =
      KubernetesEnvironment.builder()
          .setCommands(singletonList(new CommandImpl(command)))
          .setIngresses(new HashMap<>())
          .setServices(new HashMap<>())
          .build();

  previewUrlExposer.expose(env);

  assertEquals(env.getIngresses().size(), 1);
  assertEquals(env.getServices().size(), 1);

  Service provisionedService = env.getServices().values().iterator().next();
  ServicePort provisionedServicePort = provisionedService.getSpec().getPorts().get(0);
  assertEquals(provisionedServicePort.getName(), SERVER_PORT_NAME);
  assertEquals(provisionedServicePort.getPort().intValue(), PORT);

  Ingress provisionedIngress = env.getIngresses().values().iterator().next();
  IngressBackend provisionedIngressBackend =
      provisionedIngress.getSpec().getRules().get(0).getHttp().getPaths().get(0).getBackend();
  assertEquals(provisionedIngressBackend.getServicePort().getStrVal(), SERVER_PORT_NAME);
  assertEquals(
      provisionedIngressBackend.getServiceName(), provisionedService.getMetadata().getName());
}
 
Example #12
Source File: PreviewUrlExposerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldProvisionIngressWhenNotFound() throws InternalInfrastructureException {
  Mockito.when(
          externalServiceExposureStrategy.getExternalPath(Mockito.anyString(), Mockito.any()))
      .thenReturn("some-server-path");

  final int PORT = 8080;
  final String SERVER_PORT_NAME = "server-" + PORT;
  final String SERVICE_NAME = "servicename";

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

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

  Map<String, Service> services = new HashMap<>();
  services.put(SERVICE_NAME, service);

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

  previewUrlExposer.expose(env);
  assertEquals(env.getIngresses().size(), 1);
  Ingress provisionedIngress = env.getIngresses().values().iterator().next();
  IngressBackend provisionedIngressBackend =
      provisionedIngress.getSpec().getRules().get(0).getHttp().getPaths().get(0).getBackend();
  assertEquals(provisionedIngressBackend.getServicePort().getStrVal(), SERVER_PORT_NAME);
  assertEquals(provisionedIngressBackend.getServiceName(), SERVICE_NAME);
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
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);
    }
}