io.fabric8.kubernetes.api.model.ServicePort Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.ServicePort. 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: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
protected Service createService(String name, String type, List<ServicePort> ports, Labels labels, Labels selector, Map<String, String> annotations, String loadBalancerIP) {
    Service service = new ServiceBuilder()
            .withNewMetadata()
                .withName(name)
                .withLabels(labels.toMap())
                .withNamespace(namespace)
                .withAnnotations(annotations)
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withType(type)
                .withSelector(selector.toMap())
                .withPorts(ports)
                .withLoadBalancerIP(loadBalancerIP)
            .endSpec()
            .build();
    log.trace("Created service {}", service);
    return service;
}
 
Example #2
Source File: SidecarServicesProvisionerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Service createService(ChePluginEndpoint endpoint) {
  ServicePort servicePort =
      new ServicePortBuilder()
          .withPort(endpoint.getTargetPort())
          .withProtocol("TCP")
          .withNewTargetPort(endpoint.getTargetPort())
          .build();
  return new ServiceBuilder()
      .withNewMetadata()
      .withName(endpoint.getName())
      .endMetadata()
      .withNewSpec()
      .withSelector(singletonMap(CHE_ORIGINAL_NAME_LABEL, POD_NAME))
      .withPorts(singletonList(servicePort))
      .endSpec()
      .build();
}
 
Example #3
Source File: IngressEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Should we try to create an external URL for the given service?
 * <p>
 * By default lets ignore the kubernetes services and any service which does not expose ports 80 and 443
 *
 * @return true if we should create an Ingress for this service.
 */
private static boolean shouldCreateExternalURLForService(ServiceBuilder service, KitLogger log) {
    String serviceName = service.buildMetadata().getName();
    ServiceSpec spec = service.buildSpec();
    if (spec != null && !isKuberentesSystemService(serviceName)) {
        List<ServicePort> ports = spec.getPorts();
        log.debug("Service " + serviceName + " has ports: " + ports);
        if (ports.size() == 1) {
            String type = spec.getType();
            if (Objects.equals(type, "LoadBalancer")) {
                return true;
            }
            log.info("Not generating Ingress for service " + serviceName + " type is not LoadBalancer: " + type);
        } else {
            log.info("Not generating Ingress for service " + serviceName + " as only single port services are supported. Has ports: " + ports);
        }
    }
    return false;
}
 
Example #4
Source File: OpenShiftExternalServerExposer.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void expose(
    OpenShiftEnvironment env,
    String machineName,
    String serviceName,
    String serverId,
    ServicePort servicePort,
    Map<String, ServerConfig> externalServers) {
  Route commonRoute =
      new RouteBuilder()
          .withName(Names.generateName("route"))
          .withMachineName(machineName)
          .withTargetPort(servicePort.getName())
          .withServers(externalServers)
          .withTo(serviceName)
          .build();
  env.getRoutes().put(commonRoute.getMetadata().getName(), commonRoute);
}
 
Example #5
Source File: KubernetesServerExposer.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Exposes specified servers.
 *
 * <p>Note that created Kubernetes objects will select the corresponding pods by {@link
 * Constants#CHE_ORIGINAL_NAME_LABEL} label. That should be added by {@link
 * UniqueNamesProvisioner}.
 *
 * @param servers servers to expose
 * @see ConfigurationProvisioner#provision(KubernetesEnvironment, RuntimeIdentity)
 */
public void expose(Map<String, ? extends ServerConfig> servers) throws InfrastructureException {
  Map<String, ServerConfig> internalServers = new HashMap<>();
  Map<String, ServerConfig> externalServers = new HashMap<>();
  Map<String, ServerConfig> secureServers = new HashMap<>();
  Map<String, ServicePort> unsecuredPorts = new HashMap<>();
  Map<String, ServicePort> securedPorts = new HashMap<>();

  splitServersAndPortsByExposureType(
      servers, internalServers, externalServers, secureServers, unsecuredPorts, securedPorts);

  provisionServicesForDiscoverableServers(servers);

  Optional<Service> serviceOpt = createService(internalServers, unsecuredPorts);

  if (serviceOpt.isPresent()) {
    Service service = serviceOpt.get();
    String serviceName = service.getMetadata().getName();
    k8sEnv.getServices().put(serviceName, service);
    exposeNonSecureServers(serviceName, externalServers, unsecuredPorts);
  }

  exposeSecureServers(secureServers, securedPorts);
}
 
Example #6
Source File: ExternalServerExposer.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Exposes service port on given service externally (outside kubernetes cluster). The exposed
 * service port is associated with a specific Server configuration. Server configuration should be
 * encoded in the exposing object's annotations, to be used by {@link KubernetesServerResolver}.
 *
 * @param k8sEnv Kubernetes environment
 * @param machineName machine containing servers
 * @param serviceName service associated with machine, mapping all machine server ports
 * @param serverId non-null for a unique server, null for a compound set of servers that should be
 *     exposed together.
 * @param servicePort specific service port to be exposed externally
 * @param externalServers server configs of servers to be exposed externally
 */
public void expose(
    T k8sEnv,
    @Nullable String machineName,
    String serviceName,
    String serverId,
    ServicePort servicePort,
    Map<String, ServerConfig> externalServers) {

  if (serverId == null) {
    // this is the ID for non-unique servers
    serverId = servicePort.getName();
  }

  Ingress ingress =
      generateIngress(machineName, serviceName, serverId, servicePort, externalServers);

  k8sEnv.getIngresses().put(ingress.getMetadata().getName(), ingress);
}
 
Example #7
Source File: KubernetesServerExposer.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void exposeInContainerIfNeeded(ServicePort servicePort) {
  if (container
      .getPorts()
      .stream()
      .noneMatch(
          p ->
              p.getContainerPort().equals(servicePort.getPort())
                  && servicePort.getProtocol().equals(p.getProtocol()))) {
    ContainerPort containerPort =
        new ContainerPortBuilder()
            .withContainerPort(servicePort.getPort())
            .withProtocol(servicePort.getProtocol())
            .build();
    container.getPorts().add(containerPort);
  }
}
 
Example #8
Source File: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a headless service
 *
 * Uses Alpha annotation service.alpha.kubernetes.io/tolerate-unready-endpoints for older versions of Kubernetes still supported by Strimzi,
 * replaced by the publishNotReadyAddresses field in the spec,  annotation is ignored in later versions of Kubernetes
 */
protected Service createHeadlessService(List<ServicePort> ports) {
    Map<String, String> annotations = Collections.singletonMap("service.alpha.kubernetes.io/tolerate-unready-endpoints", "true");
    Service service = new ServiceBuilder()
            .withNewMetadata()
                .withName(headlessServiceName)
                .withLabels(getLabelsWithStrimziName(headlessServiceName, templateHeadlessServiceLabels).toMap())
                .withNamespace(namespace)
                .withAnnotations(mergeLabelsOrAnnotations(annotations, templateHeadlessServiceAnnotations))
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withType("ClusterIP")
                .withClusterIP("None")
                .withSelector(getSelectorLabels().toMap())
                .withPorts(ports)
                .withPublishNotReadyAddresses(true)
            .endSpec()
            .build();
    log.trace("Created headless service {}", service);
    return service;
}
 
Example #9
Source File: KubernetesClientTestBase.java    From flink with Apache License 2.0 6 votes vote down vote up
protected Service buildExternalServiceWithNodePort() {
	final ServicePort servicePort = new ServicePortBuilder()
		.withName(Constants.REST_PORT_NAME)
		.withPort(REST_PORT)
		.withNodePort(NODE_PORT)
		.withNewTargetPort(REST_PORT)
		.build();

	final ServiceStatus serviceStatus = new ServiceStatusBuilder()
		.withLoadBalancer(new LoadBalancerStatus(Collections.emptyList()))
		.build();

	return buildExternalService(
		KubernetesConfigOptions.ServiceExposedType.NodePort,
		servicePort,
		serviceStatus);
}
 
Example #10
Source File: KubernetesDiscoveredServiceWorkItemHandlerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGivenServiceExists() {
    final ServiceSpec serviceSpec = new ServiceSpec();
    serviceSpec.setPorts(Collections.singletonList(new ServicePort("http", 0, 8080, "http", new IntOrString(8080))));
    serviceSpec.setClusterIP("172.30.158.31");
    serviceSpec.setType("ClusterIP");
    serviceSpec.setSessionAffinity("ClientIP");

    final ObjectMeta metadata = new ObjectMeta();
    metadata.setName("test-kieserver");
    metadata.setNamespace(MOCK_NAMESPACE);
    metadata.setLabels(Collections.singletonMap("test-kieserver", "service"));

    final Service service = new Service("v1", "Service", metadata, serviceSpec, new ServiceStatus(new LoadBalancerStatus()));
    getClient().services().create(service);

    final DiscoveredServiceWorkItemHandler handler = new TestDiscoveredServiceWorkItemHandler(this);
    final ServiceInfo serviceInfo = handler.findEndpoint(MOCK_NAMESPACE, "test-kieserver");
    assertThat(serviceInfo, notNullValue());
    assertThat(serviceInfo.getUrl(), is("http://172.30.158.31:8080/test-kieserver"));
}
 
Example #11
Source File: DefaultServiceEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private ServicePort extractPortsFromImageSpec(String imageName, String portSpec, ServicePort portOverride, String targetPortFromImageLabel) {

        Matcher portMatcher = PORT_PROTOCOL_PATTERN.matcher(portSpec);
        if (!portMatcher.matches()) {
            log.warn("Invalid port specification '%s' for image %s. Must match \\d+(/(tcp|udp))?. Ignoring for now for service generation",
                     portSpec, imageName);
            return null;
        }

        Integer targetPort = Integer.parseInt(targetPortFromImageLabel != null ? targetPortFromImageLabel : portMatcher.group(1));
        String protocol = getProtocol(portMatcher.group(2));
        Integer port = checkForLegacyMapping(targetPort);

        // With a port override you can override the detected ports
        if (portOverride != null) {
            return updateMissingTargetPort(portOverride, targetPort);
        }

        return new ServicePortBuilder()
            .withPort(port)
            .withNewTargetPort(targetPort)
            .withProtocol(protocol)
            .withName(getDefaultPortName(port, protocol))
            .build();
    }
 
Example #12
Source File: DefaultServiceEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private ServicePort parsePortMapping(String port) {
    Matcher matcher = PORT_MAPPING_PATTERN.matcher(port);
    if (!matcher.matches()) {
        log.error("Invalid 'port' configuration '%s'. Must match <port>(:<targetPort>)?,<port2>?,...", port);
        throw new IllegalArgumentException("Invalid port mapping specification " + port);
    }

    int servicePort = Integer.parseInt(matcher.group("port"));
    String optionalTargetPort = matcher.group("targetPort");
    String protocol = getProtocol(matcher.group("protocol"));

    ServicePortBuilder builder = new ServicePortBuilder()
        .withPort(servicePort)
        .withProtocol(protocol)
        .withName(getDefaultPortName(servicePort, protocol));

    // leave empty if not set. will be filled up with the port from the image config
    if (optionalTargetPort != null) {
        builder.withNewTargetPort(Integer.parseInt(optionalTargetPort));
    }
    return builder.build();
}
 
Example #13
Source File: URLFromOpenshiftRouteImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@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(Locale.ROOT);
      }
    } 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;
}
 
Example #14
Source File: KafkaBridgeCluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public Service generateService() {
    List<ServicePort> ports = new ArrayList<>(3);

    int port = DEFAULT_REST_API_PORT;
    if (http != null) {
        port = http.getPort();
    }

    ports.add(createServicePort(REST_API_PORT_NAME, port, port, "TCP"));

    if (isMetricsEnabled()) {
        ports.add(createServicePort(METRICS_PORT_NAME, METRICS_PORT, METRICS_PORT, "TCP"));
    }

    return createDiscoverableService("ClusterIP", ports, mergeLabelsOrAnnotations(getDiscoveryAnnotation(port), templateServiceAnnotations, ModelUtils.getCustomLabelsOrAnnotations(CO_ENV_VAR_CUSTOM_ANNOTATIONS)));
}
 
Example #15
Source File: KubeDiscovery.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static String getHostString(
    Service serviceEntry, JsonObject env, Field serviceNameField) {
  final String clusterIP = serviceEntry.getSpec().getClusterIP();
  final List<ServicePort> ports = serviceEntry.getSpec().getPorts();
  return serviceNameField.isAnnotationPresent(PortName.class)
      ? resolveServiceWithPortName(env, serviceNameField, clusterIP, ports)
      : resolveService("", clusterIP, ports);
}
 
Example #16
Source File: JwtProxyProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldFalseValueAsDefaultForCookiesAuthEnabledAttribute() throws Exception {
  // given
  JwtProxyConfigBuilder configBuilder = mock(JwtProxyConfigBuilder.class);
  when(configBuilderFactory.create(any())).thenReturn(configBuilder);

  jwtProxyProvisioner =
      new JwtProxyProvisioner(
          signatureKeyManager,
          configBuilderFactory,
          externalServiceExposureStrategy,
          cookiePathStrategy,
          "eclipse/che-jwtproxy",
          "128mb",
          "0.5",
          "Always",
          runtimeId);

  ServerConfigImpl server1 = new ServerConfigImpl("4401/tcp", "http", "/", emptyMap());

  ServicePort port = new ServicePort();
  port.setTargetPort(new IntOrString(4401));

  // when
  jwtProxyProvisioner.expose(
      k8sEnv,
      podWithName(),
      "machine",
      "terminal",
      port,
      "TCP",
      ImmutableMap.of("server1", server1));

  // then
  verify(configBuilder)
      .addVerifierProxy(
          eq(4400), eq("http://terminal:4401"), eq(emptySet()), eq(false), eq("/"), isNull());
}
 
Example #17
Source File: SidecarServicesProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Service createService(String name, String podName, int port) {
  ServicePort servicePort =
      new ServicePortBuilder().withPort(port).withProtocol("TCP").withNewTargetPort(port).build();
  return new ServiceBuilder()
      .withNewMetadata()
      .withName(name)
      .endMetadata()
      .withNewSpec()
      .withSelector(singletonMap(CHE_ORIGINAL_NAME_LABEL, podName))
      .withPorts(singletonList(servicePort))
      .endSpec()
      .build();
}
 
Example #18
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 #19
Source File: ResolveServicesByNameTest.java    From vxms with Apache License 2.0 5 votes vote down vote up
public void initService() {
  final ObjectMeta buildmyTestService =
      new ObjectMetaBuilder().addToLabels("test", "test").withName("myTestService").build();
  final ServicePort portmyTestService =
      new ServicePortBuilder().withPort(8080).withProtocol("http").build();
  final ServiceSpec specmyTestService =
      new ServiceSpecBuilder()
          .addNewPort()
          .and()
          .withClusterIP("192.168.1.1")
          .withPorts(portmyTestService)
          .build();

  final ObjectMeta buildmyTestService2 =
      new ObjectMetaBuilder().addToLabels("test", "test2").withName("myTestService2").build();
  final ServicePort portmyTestService2 =
      new ServicePortBuilder().withPort(9080).withProtocol("http").build();
  final ServiceSpec specmyTestService2 =
      new ServiceSpecBuilder()
          .addNewPort()
          .and()
          .withClusterIP("192.168.1.2")
          .withPorts(portmyTestService2)
          .build();

  final Service servicemyTestService =
      new ServiceBuilder().withMetadata(buildmyTestService).withSpec(specmyTestService).build();
  final Service servicemyTestService2 =
      new ServiceBuilder().withMetadata(buildmyTestService2).withSpec(specmyTestService2).build();
  server
      .expect()
      .withPath("/api/v1/namespaces/default/services")
      .andReturn(
          200,
          new ServiceListBuilder()
              .addToItems(servicemyTestService, servicemyTestService2)
              .build())
      .times(2);
}
 
Example #20
Source File: KubernetesServerExposer.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private ServicePort getServicePort(ServerConfig serverConfig) {
  String[] portProtocol = serverConfig.getPort().split("/");
  int port = parseInt(portProtocol[0]);
  String protocol = portProtocol.length > 1 ? portProtocol[1].toUpperCase() : "TCP";
  return new ServicePortBuilder()
      .withName("server-" + port)
      .withPort(port)
      .withProtocol(protocol)
      .withNewTargetPort(port)
      .build();
}
 
Example #21
Source File: JwtProxyProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldBindToLocalhostWhenNoServiceForServerExists() throws Exception {
  // given
  JwtProxyConfigBuilder configBuilder = mock(JwtProxyConfigBuilder.class);
  when(configBuilderFactory.create(any())).thenReturn(configBuilder);

  jwtProxyProvisioner =
      new JwtProxyProvisioner(
          signatureKeyManager,
          configBuilderFactory,
          externalServiceExposureStrategy,
          cookiePathStrategy,
          "eclipse/che-jwtproxy",
          "128mb",
          "0.5",
          "Always",
          runtimeId);

  ServerConfigImpl server1 = new ServerConfigImpl("4401/tcp", "http", "/", emptyMap());

  ServicePort port = new ServicePort();
  port.setTargetPort(new IntOrString(4401));

  // when
  jwtProxyProvisioner.expose(
      k8sEnv, podWithName(), "machine", null, port, "TCP", ImmutableMap.of("server1", server1));

  // then
  verify(configBuilder)
      .addVerifierProxy(
          eq(4400), eq("http://127.0.0.1:4401"), eq(emptySet()), eq(false), eq("/"), isNull());
}
 
Example #22
Source File: ServiceOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Finds out if corresponding port from desired service also exists in current service.
 * If it exists, it will copy the node port.
 * That will make sure the node port doesn't change with every reconciliation.
 *
 * @param current   Current Service
 * @param desired   Desired Service
 */
protected void patchNodePorts(Service current, Service desired) {
    for (ServicePort desiredPort : desired.getSpec().getPorts())    {
        String portName = desiredPort.getName();

        for (ServicePort currentPort : current.getSpec().getPorts())    {
            if (desiredPort.getNodePort() == null && portName.equals(currentPort.getName()) && currentPort.getNodePort() != null) {
                desiredPort.setNodePort(currentPort.getNodePort());
            }
        }
    }
}
 
Example #23
Source File: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
protected ServicePort createServicePort(String name, int port, int targetPort, Integer nodePort, String protocol) {
    ServicePortBuilder builder = new ServicePortBuilder()
        .withName(name)
        .withProtocol(protocol)
        .withPort(port)
        .withNewTargetPort(targetPort);
    if (nodePort != null) {
        builder.withNodePort(nodePort);
    }
    ServicePort servicePort = builder.build();
    log.trace("Created service port {}", servicePort);
    return servicePort;
}
 
Example #24
Source File: MultiHostExternalServiceExposureStrategyTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateIngressForServer() {
  // given
  ServerConfigImpl httpServerConfig =
      new ServerConfigImpl("8080/tcp", "http", "/api", ATTRIBUTES_MAP);
  IntOrString targetPort = new IntOrString(8080);
  ServicePort servicePort =
      new ServicePortBuilder()
          .withName("server-8080")
          .withPort(8080)
          .withProtocol("TCP")
          .withTargetPort(targetPort)
          .build();
  Map<String, ServerConfig> serversToExpose = ImmutableMap.of("http-server", httpServerConfig);

  // when
  externalServerExposer.expose(
      kubernetesEnvironment, MACHINE_NAME, SERVICE_NAME, null, servicePort, serversToExpose);

  // then
  assertThatExternalServerIsExposed(
      MACHINE_NAME,
      SERVICE_NAME,
      "http-server",
      "tcp",
      8080,
      servicePort,
      new ServerConfigImpl(httpServerConfig).withAttributes(ATTRIBUTES_MAP));
}
 
Example #25
Source File: Ingresses.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean matchesServicePort(IntOrString backendPort, ServicePort servicePort) {
  if (backendPort.getStrVal() != null && backendPort.getStrVal().equals(servicePort.getName())) {
    return true;
  }
  if (backendPort.getIntVal() != null && backendPort.getIntVal().equals(servicePort.getPort())) {
    return true;
  }
  return false;
}
 
Example #26
Source File: OpenShiftPreviewUrlCommandProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldDoNothingWhenCantFindRouteForPreviewUrl() throws InfrastructureException {
  int port = 8080;
  List<CommandImpl> commands =
      Collections.singletonList(
          new CommandImpl("a", "a", "a", new PreviewUrlImpl(port, null), Collections.emptyMap()));
  OpenShiftEnvironment env =
      OpenShiftEnvironment.builder().setCommands(new ArrayList<>(commands)).build();

  Mockito.when(mockProject.services()).thenReturn(mockServices);
  Service service = new Service();
  ServiceSpec spec = new ServiceSpec();
  spec.setPorts(
      Collections.singletonList(new ServicePort("a", null, port, "TCP", new IntOrString(port))));
  service.setSpec(spec);
  Mockito.when(mockServices.get()).thenReturn(Collections.singletonList(service));

  Mockito.when(mockProject.routes()).thenReturn(mockRoutes);
  Mockito.when(mockRoutes.get()).thenReturn(Collections.emptyList());

  previewUrlCommandProvisioner.provision(env, mockProject);

  assertTrue(commands.containsAll(env.getCommands()));
  assertTrue(env.getCommands().containsAll(commands));
  assertEquals(
      env.getWarnings().get(0).getCode(), Warnings.NOT_ABLE_TO_PROVISION_OBJECTS_FOR_PREVIEW_URL);
}
 
Example #27
Source File: OpenShiftPreviewUrlCommandProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateCommandWhenServiceAndIngressFound() throws InfrastructureException {
  int port = 8080;
  List<CommandImpl> commands =
      Collections.singletonList(
          new CommandImpl("a", "a", "a", new PreviewUrlImpl(port, null), Collections.emptyMap()));
  OpenShiftEnvironment env =
      OpenShiftEnvironment.builder().setCommands(new ArrayList<>(commands)).build();

  Mockito.when(mockProject.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("8080", null, port, "TCP", new IntOrString(port))));
  service.setSpec(spec);
  Mockito.when(mockServices.get()).thenReturn(Collections.singletonList(service));

  Route route = new Route();
  RouteSpec routeSpec = new RouteSpec();
  routeSpec.setPort(new RoutePort(new IntOrString("8080")));
  routeSpec.setTo(new RouteTargetReference("a", "servicename", 1));
  routeSpec.setHost("testhost");
  route.setSpec(routeSpec);

  Mockito.when(mockProject.routes()).thenReturn(mockRoutes);
  Mockito.when(mockRoutes.get()).thenReturn(Collections.singletonList(route));

  previewUrlCommandProvisioner.provision(env, mockProject);

  assertTrue(env.getCommands().get(0).getAttributes().containsKey("previewUrl"));
  assertEquals(env.getCommands().get(0).getAttributes().get("previewUrl"), "testhost");
  assertTrue(env.getWarnings().isEmpty());
}
 
Example #28
Source File: ZookeeperCluster.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private List<ServicePort> getServicePortList() {
    List<ServicePort> portList = new ArrayList<>(3);
    portList.add(createServicePort(CLIENT_TLS_PORT_NAME, CLIENT_TLS_PORT, CLIENT_TLS_PORT, "TCP"));
    portList.add(createServicePort(CLUSTERING_PORT_NAME, CLUSTERING_PORT, CLUSTERING_PORT, "TCP"));
    portList.add(createServicePort(LEADER_ELECTION_PORT_NAME, LEADER_ELECTION_PORT, LEADER_ELECTION_PORT, "TCP"));

    return portList;
}
 
Example #29
Source File: ServicesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testFindPortWhenExists() {
  final int PORT = 1234;

  Service service = new Service();
  ServiceSpec spec = new ServiceSpec();
  ServicePort port = new ServicePort();
  port.setPort(PORT);
  spec.setPorts(Arrays.asList(port, new ServicePort()));
  service.setSpec(spec);

  assertEquals(Services.findPort(service, PORT).get(), port);
}
 
Example #30
Source File: KubernetesAppDeployerIntegrationTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceWithMultiplePorts() {
	log.info("Testing {}...", "ServiceWithMultiplePorts");
	KubernetesAppDeployer kubernetesAppDeployer = new KubernetesAppDeployer(new KubernetesDeployerProperties(), kubernetesClient);

	AppDefinition definition = new AppDefinition(randomName(), null);
	Resource resource = testApplication();
	AppDeploymentRequest request = new AppDeploymentRequest(definition, resource,
			Collections.singletonMap("spring.cloud.deployer.kubernetes.servicePorts", "8080,9090"));

	log.info("Deploying {}...", request.getDefinition().getName());
	String deploymentId = kubernetesAppDeployer.deploy(request);
	Timeout timeout = deploymentTimeout();
	assertThat(deploymentId, eventually(hasStatusThat(
			Matchers.hasProperty("state", is(deployed))), timeout.maxAttempts, timeout.pause));

	List<ServicePort> servicePorts = kubernetesClient.services().withName(request.getDefinition().getName()).get()
			.getSpec().getPorts();

	assertThat(servicePorts, is(notNullValue()));
	assertThat(servicePorts.size(), is(2));
	assertTrue(servicePorts.stream().anyMatch(o -> o.getPort().equals(8080)));
	assertTrue(servicePorts.stream().anyMatch(o -> o.getName().equals("port-8080")));
	assertTrue(servicePorts.stream().anyMatch(o -> o.getPort().equals(9090)));
	assertTrue(servicePorts.stream().anyMatch(o -> o.getName().equals("port-9090")));

	log.info("Undeploying {}...", deploymentId);
	timeout = undeploymentTimeout();
	kubernetesAppDeployer.undeploy(deploymentId);
	assertThat(deploymentId, eventually(hasStatusThat(
			Matchers.hasProperty("state", is(unknown))), timeout.maxAttempts, timeout.pause));
}