Java Code Examples for io.fabric8.kubernetes.api.model.Service

The following examples show how to use io.fabric8.kubernetes.api.model.Service. These examples are extracted from open source projects. 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 Project: flink   Author: apache   File: Fabric8FlinkKubeClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Endpoint> getRestEndpoint(String clusterId) {
	Optional<KubernetesService> restService = getRestService(clusterId);
	if (!restService.isPresent()) {
		return Optional.empty();
	}
	final Service service = restService.get().getInternalResource();
	final int restPort = getRestPortFromExternalService(service);

	final KubernetesConfigOptions.ServiceExposedType serviceExposedType =
		KubernetesConfigOptions.ServiceExposedType.valueOf(service.getSpec().getType());

	// Return the external service.namespace directly when using ClusterIP.
	if (serviceExposedType == KubernetesConfigOptions.ServiceExposedType.ClusterIP) {
		return Optional.of(
			new Endpoint(ExternalServiceDecorator.getNamespacedExternalServiceName(clusterId, namespace), restPort));
	}

	return getRestEndPointFromService(service, restPort);
}
 
Example #2
Source Project: spring-cloud-kubernetes   Author: spring-cloud   File: KubernetesDiscoveryClientFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFilteredServices() {
	List<String> springBootServiceNames = Arrays.asList("serviceA", "serviceB");
	List<Service> services = createSpringBootServiceByName(springBootServiceNames);

	// Add non spring boot service
	Service service = new Service();
	ObjectMeta objectMeta = new ObjectMeta();
	objectMeta.setName("ServiceNonSpringBoot");
	service.setMetadata(objectMeta);
	services.add(service);

	ServiceList serviceList = new ServiceList();
	serviceList.setItems(services);
	when(this.serviceOperation.list()).thenReturn(serviceList);
	when(this.kubernetesClient.services()).thenReturn(this.serviceOperation);

	when(this.properties.getFilter())
			.thenReturn("metadata.additionalProperties['spring-boot']");

	List<String> filteredServices = this.underTest.getServices();

	System.out.println("Filtered Services: " + filteredServices);
	assertThat(filteredServices).isEqualTo(springBootServiceNames);

}
 
Example #3
Source Project: strimzi-kafka-operator   Author: strimzi   File: KubernetesResource.java    License: Apache License 2.0 6 votes vote down vote up
public static Service deployKeycloakNodePortService(String namespace) {
    String keycloakName = "keycloak";

    Map<String, String> keycloakLabels = new HashMap<>();
    keycloakLabels.put("app", keycloakName);

    return getSystemtestsServiceResource(keycloakName + "service-https",
        Constants.HTTPS_KEYCLOAK_DEFAULT_PORT, namespace, "TCP")
        .editSpec()
            .withType("NodePort")
            .withSelector(keycloakLabels)
            .editFirstPort()
                .withNodePort(Constants.HTTPS_KEYCLOAK_DEFAULT_NODE_PORT)
            .endPort()
        .endSpec().build();
}
 
Example #4
Source Project: jkube   Author: eclipse   File: DefaultServiceEnricher.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void create(PlatformMode platformMode, KubernetesListBuilder builder) {

    final ResourceConfig xmlConfig = getConfiguration().getResource();
    if (xmlConfig != null && xmlConfig.getServices() != null) {
        // Add Services configured via XML
        addServices(builder, xmlConfig.getServices());

    } else {
        final Service defaultService = getDefaultService();

        if (hasServices(builder)) {
            mergeInDefaultServiceParameters(builder, defaultService);
        } else {
            addDefaultService(builder, defaultService);
        }

        if (Configs.asBoolean(getConfig(Config.normalizePort))) {
            normalizeServicePorts(builder);
        }
    }


}
 
Example #5
Source Project: flink   Author: apache   File: Fabric8FlinkKubeClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Optional<KubernetesService> getRestService(String clusterId) {
	final String serviceName = ExternalServiceDecorator.getExternalServiceName(clusterId);

	final Service service = this.internalClient
		.services()
		.inNamespace(namespace)
		.withName(serviceName)
		.fromServer()
		.get();

	if (service == null) {
		LOG.debug("Service {} does not exist", serviceName);
		return Optional.empty();
	}

	return Optional.of(new KubernetesService(service));
}
 
Example #6
Source Project: kubernetes-pipeline-plugin   Author: jenkinsci   File: ServiceResourceUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void patchServiceNameAndRoute() throws Exception {
    // GIVEN
    envVars.set(ServiceResourceUtil.K8S_PIPELINE_SERVICE_PATCH, "enabled");
    Set<HasMetadata> entities = getEntitiesFromResource("/services/invalidservice1.yaml");
    ServiceResourceUtil util = new ServiceResourceUtil();

    // WHEN
    util.patchServiceName(entities);

    // THEN
    HasMetadata service = getKind(entities, "Service");
    Route route = (Route) getKind(entities, "Route");
    assertEquals(2, entities.size());
    assertFalse(util.hasInvalidDNS((Service) service));
    assertEquals(service.getMetadata().getName(), route.getSpec().getTo().getName());
}
 
Example #7
Source Project: jkube   Author: eclipse   File: DefaultServiceEnricher.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void addMissingServiceParts(ServiceBuilder service, Service defaultService) {

        // If service has no spec -> take over the complete spec from default service
        if (!service.hasSpec()) {
            service.withNewSpecLike(defaultService.getSpec()).endSpec();
            return;
        }

        // If service has no ports -> take over ports from default service
        List<ServicePort> ports = service.buildSpec().getPorts();
        if (ports == null || ports.isEmpty()) {
            service.editSpec().withPorts(defaultService.getSpec().getPorts()).endSpec();
            return;
        }

        // Complete missing parts:
        service.editSpec()
               .withPorts(addMissingDefaultPorts(ports, defaultService))
               .endSpec();
    }
 
Example #8
Source Project: jkube   Author: eclipse   File: IngressEnricherTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCreate() {
    // Given
    new Expectations() {{
        // Enable creation of Ingress for Service of type LoadBalancer
        context.getProperty(CREATE_EXTERNAL_URLS);
        result = "true";
    }};

    Service providedService = getTestService().build();
    KubernetesListBuilder kubernetesListBuilder = new KubernetesListBuilder().addToItems(providedService);
    IngressEnricher ingressEnricher = new IngressEnricher(context);

    // When
    ingressEnricher.create(PlatformMode.kubernetes, kubernetesListBuilder);

    // Then
    Ingress ingress = (Ingress) kubernetesListBuilder.buildLastItem();
    assertEquals(2, kubernetesListBuilder.buildItems().size());
    assertNotNull(ingress);
    assertEquals(providedService.getMetadata().getName(), ingress.getMetadata().getName());
    assertNotNull(ingress.getSpec());
    assertEquals(providedService.getMetadata().getName(), ingress.getSpec().getBackend().getServiceName());
    assertEquals(providedService.getSpec().getPorts().get(0).getTargetPort(), ingress.getSpec().getBackend().getServicePort());
}
 
Example #9
Source Project: flink   Author: apache   File: KubernetesJobManagerFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAdditionalResourcesSize() {
	final List<HasMetadata> resultAdditionalResources = this.kubernetesJobManagerSpecification.getAccompanyingResources();
	assertEquals(3, resultAdditionalResources.size());

	final List<HasMetadata> resultServices = resultAdditionalResources
		.stream()
		.filter(x -> x instanceof Service)
		.collect(Collectors.toList());
	assertEquals(2, resultServices.size());

	final List<HasMetadata> resultConfigMaps = resultAdditionalResources
		.stream()
		.filter(x -> x instanceof ConfigMap)
		.collect(Collectors.toList());
	assertEquals(1, resultConfigMaps.size());
}
 
Example #10
Source Project: jkube   Author: eclipse   File: PatchService.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static EntityPatcher<Service> servicePatcher() {
    return (KubernetesClient client, String namespace, Service newObj, Service oldObj) -> {
        if (UserConfigurationCompare.configEqual(newObj, oldObj)) {
            return oldObj;
        }

        DoneableService entity =
            client.services()
                  .inNamespace(namespace)
                  .withName(newObj.getMetadata().getName())
                  .edit();

        if (!UserConfigurationCompare.configEqual(newObj.getMetadata(), oldObj.getMetadata())) {
            entity.withMetadata(newObj.getMetadata());
        }

        if(!UserConfigurationCompare.configEqual(newObj.getSpec(), oldObj.getSpec())) {
            entity.withSpec(newObj.getSpec());
        }
        return entity.done();
    };
}
 
Example #11
Source Project: kogito-runtimes   Author: kiegroup   File: MockKubernetesServerSupport.java    License: Apache License 2.0 6 votes vote down vote up
protected void createMockService(final String serviceName, final String ip, final Map<String, String> labels, final String namespace) {
    final ServiceSpec serviceSpec = new ServiceSpec();
    serviceSpec.setPorts(Collections.singletonList(new ServicePort("http", 0, 8080, "http", new IntOrString(8080))));
    serviceSpec.setClusterIP(ip);
    serviceSpec.setType("ClusterIP");
    serviceSpec.setSessionAffinity("ClientIP");

    final ObjectMeta metadata = new ObjectMeta();
    metadata.setName(serviceName);
    metadata.setNamespace(MOCK_NAMESPACE);
    metadata.setLabels(labels);

    final Service service = new Service("v1", "Service", metadata, serviceSpec, new ServiceStatus(new LoadBalancerStatus()));
    if (namespace != null) {
        this.server.getClient().inNamespace(namespace).services().create(service);
    } else {
        this.server.getClient().services().create(service);
    }

}
 
Example #12
Source Project: kogito-runtimes   Author: kiegroup   File: KubernetesDiscoveredServiceWorkItemHandlerTest.java    License: 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 #13
Source Project: kubernetes-client   Author: fabric8io   File: URLFromEnvVarsImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getURL(Service service, String portName, String namespace, KubernetesClient client) {
  String serviceHost     = URLFromServiceUtil.resolveHostFromEnvVarOrSystemProperty(service.getMetadata().getName());
  String servicePort     = URLFromServiceUtil.resolvePortFromEnvVarOrSystemProperty(service.getMetadata().getName(), "");
  String serviceProtocol = URLFromServiceUtil.resolveProtocolFromEnvVarOrSystemProperty(service.getSpec().getPorts().iterator().next().getProtocol(), "");

  if(!serviceHost.isEmpty() && !servicePort.isEmpty() && !serviceProtocol.isEmpty()) {
    return serviceProtocol + "://" + serviceHost + ":" + servicePort;
  } else {
    String answer = URLFromServiceUtil.getOrCreateAnnotations(service).get(ANNOTATION_EXPOSE_URL);
    if(answer != null && !answer.isEmpty()) {
      return answer;
    }
  }
  return null;
}
 
Example #14
Source Project: kubernetes-client   Author: fabric8io   File: TemplateIT.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
  currentNamespace = session.getNamespace();
  Service aService = new ServiceBuilder()
    .withNewMetadata().withName("bar").endMetadata()
    .withNewSpec()
    .addNewPort()
    .withPort(80).endPort()
    .addToSelector("cheese", "edam")
    .withType("ExternalName")
    .endSpec()
    .build();

  template1 = new TemplateBuilder()
    .withApiVersion("template.openshift.io/v1")
    .withNewMetadata().withName("foo").endMetadata()
    .addToObjects(aService)
    .build();

  client.templates().inNamespace(currentNamespace).create(template1);
}
 
Example #15
Source Project: kubernetes-pipeline-plugin   Author: jenkinsci   File: ServiceResourceUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void dontPatchValidServiceAndRoute() throws Exception {
    // GIVEN
    envVars.set(ServiceResourceUtil.K8S_PIPELINE_SERVICE_PATCH, "enabled");
    Set<HasMetadata> entities = getEntitiesFromResource("/services/validservice3.yaml");
    ServiceResourceUtil util = new ServiceResourceUtil();

    // WHEN
    util.patchServiceName(entities);

    // THEN
    HasMetadata service = getKind(entities, "Service");
    Route route = (Route) getKind(entities, "Route");
    assertEquals(4, entities.size());
    assertFalse(util.hasInvalidDNS((Service) service));
    assertEquals("nodejs-rest-http", service.getMetadata().getName());
    assertEquals("nodejs-rest-http", route.getSpec().getTo().getName());
}
 
Example #16
Source Project: module-ballerina-kubernetes   Author: ballerina-platform   File: Sample1Test.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_k8s.bal"), 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("hello_world_k8s.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Deployment":
                deployment = (Deployment) data;
                break;
            case "Service":
                service = (Service) data;
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}
 
Example #17
Source Project: che   Author: eclipse   File: KubernetesPluginsToolingApplierTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = InfrastructureException.class,
    expectedExceptionsMessageRegExp =
        "Applying of sidecar tooling failed. Kubernetes service with name '"
            + CHE_PLUGIN_ENDPOINT_NAME
            + "' already exists in the workspace environment.")
public void throwsExceptionOnAddingChePluginEndpointServiceIfServiceExists() throws Exception {
  // given
  ChePluginEndpoint endpoint1 =
      new ChePluginEndpoint().name(CHE_PLUGIN_ENDPOINT_NAME).targetPort(101010).setPublic(true);
  CheContainerPort cheContainerPort1 = new CheContainerPort().exposedPort(101010);
  ChePlugin chePlugin = createChePlugin();
  chePlugin.setEndpoints(singletonList(endpoint1));
  chePlugin.getContainers().get(0).setPorts(singletonList(cheContainerPort1));

  // make collision of service names
  internalEnvironment.getServices().put(CHE_PLUGIN_ENDPOINT_NAME, new Service());

  // when
  applier.apply(runtimeIdentity, internalEnvironment, singletonList(chePlugin));
}
 
Example #18
Source Project: che   Author: eclipse   File: OpenShiftEnvironmentFactoryTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldCreateOpenShiftEnvironmentWithServicesFromRecipe() throws Exception {
  // given
  Service service1 =
      new ServiceBuilder().withNewMetadata().withName("service1").endMetadata().build();
  Service service2 =
      new ServiceBuilder().withNewMetadata().withName("service2").endMetadata().build();
  when(k8sRecipeParser.parse(any(InternalRecipe.class))).thenReturn(asList(service1, service2));

  // when
  KubernetesEnvironment osEnv = osEnvFactory.doCreate(internalRecipe, emptyMap(), emptyList());

  // then
  assertEquals(osEnv.getServices().size(), 2);
  assertEquals(osEnv.getServices().get("service1"), service1);
  assertEquals(osEnv.getServices().get("service2"), service2);
}
 
Example #19
Source Project: dekorate   Author: dekorateio   File: ServicePresentCondition.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
 Optional<OnServicePresentCondition> annotation = context.getElement().map(e -> e.getAnnotation(OnServicePresentCondition.class));
 if (!annotation.isPresent()) {
  return ConditionEvaluationResult.enabled("Condition not found!");
 }
 OnServicePresentCondition condition = annotation.get();
  try {
    KubernetesClient client = getKubernetesClient(context);
    String namespace = Strings.isNotNullOrEmpty(condition.namespace()) ? condition.namespace() :  client.getNamespace();
    Service service = getKubernetesClient(context).services().inNamespace(namespace).withName(condition.value()).get();
    if (service != null) {
      return ConditionEvaluationResult.enabled("Found service:" + condition.value() + " in namespace:" + namespace + " .");
    } else {
      return ConditionEvaluationResult.disabled("Could not find service:" + condition.value() + " in namespace:" + namespace + " .");
    }
  } catch (Throwable t) {
    return ConditionEvaluationResult.disabled("Could not lookup for service.");
  }
}
 
Example #20
Source Project: apollo   Author: logzio   File: ApolloToKubernetes.java    License: Apache License 2.0 5 votes vote down vote up
private static String getApolloUniqueIdentifierWithPrefix(io.logz.apollo.models.Environment apolloEnvironment,
                                                          io.logz.apollo.models.Service apolloService,
                                                          Optional<String> groupName,
                                                          String prefix) {
    String naiveUniqueIdentofier = "apollo_" + prefix + "_env_" + apolloEnvironment.getId() + "_service_" + apolloService.getId();
    if (groupName.isPresent()) {
        naiveUniqueIdentofier += "_group_" + groupName.get();
    }
    return Encryptor.encryptString(LabelsNormalizer.normalize(naiveUniqueIdentofier));
}
 
Example #21
Source Project: che   Author: eclipse   File: ServicesTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@DataProvider
public Object[][] nullService() {
  List<Service> nullServices = createNullServices();
  Object[][] returnObjects = new Object[nullServices.size()][1];
  for (int i = 0; i < nullServices.size(); i++) {
    returnObjects[i][0] = nullServices.get(i);
  }

  return returnObjects;
}
 
Example #22
Source Project: kubernetes-client   Author: fabric8io   File: ServiceOperationsImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Service waitUntilReady(long amount, TimeUnit timeUnit) throws InterruptedException {
  long started = System.nanoTime();
  super.waitUntilReady(amount, timeUnit);
  long alreadySpent = System.nanoTime() - started;

  // if awaiting existence took very long, let's give at least 10 seconds to awaiting readiness
  long remaining = Math.max(10_000, timeUnit.toNanos(amount) - alreadySpent);

  EndpointsOperationsImpl endpointsOperation = new EndpointsOperationsImpl(context);
  endpointsOperation.waitUntilReady(remaining, TimeUnit.MILLISECONDS);

  return get();
}
 
Example #23
Source Project: che   Author: eclipse   File: Services.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Go through all given services and finds one that has given port.
 *
 * @return {@link Optional} of found {@link Service}, or {@link Optional#empty()} when not found.
 */
public static Optional<Service> findServiceWithPort(Collection<Service> services, int port) {
  if (services == null) {
    return Optional.empty();
  }
  return services.stream().filter(s -> Services.findPort(s, port).isPresent()).findFirst();
}
 
Example #24
Source Project: spring-cloud-deployer-kubernetes   Author: spring-cloud   File: KubernetesAppInstanceStatus.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated
public KubernetesAppInstanceStatus(Pod pod, Service service, KubernetesDeployerProperties properties) {
	this.pod = pod;
	this.service = service;
	this.properties = properties;
	// we assume one container per pod
	if (pod != null && pod.getStatus().getContainerStatuses().size() == 1) {
		this.containerStatus = pod.getStatus().getContainerStatuses().get(0);
	}
	else {
		this.containerStatus = null;
	}
	this.runningPhaseDeploymentStateResolver = new DefaultRunningPhaseDeploymentStateResolver(properties);
}
 
Example #25
Source Project: flink   Author: apache   File: InternalServiceDecorator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<HasMetadata> buildAccompanyingKubernetesResources() throws IOException {
	if (!kubernetesJobManagerParameters.isInternalServiceEnabled()) {
		return Collections.emptyList();
	}

	final String serviceName = getInternalServiceName(kubernetesJobManagerParameters.getClusterId());

	final Service headlessService = new ServiceBuilder()
		.withApiVersion(Constants.API_VERSION)
		.withNewMetadata()
			.withName(serviceName)
			.withLabels(kubernetesJobManagerParameters.getCommonLabels())
			.endMetadata()
		.withNewSpec()
			.withClusterIP(Constants.HEADLESS_SERVICE_CLUSTER_IP)
			.withSelector(kubernetesJobManagerParameters.getLabels())
			.addNewPort()
				.withName(Constants.JOB_MANAGER_RPC_PORT_NAME)
				.withPort(kubernetesJobManagerParameters.getRPCPort())
				.endPort()
			.addNewPort()
				.withName(Constants.BLOB_SERVER_PORT_NAME)
				.withPort(kubernetesJobManagerParameters.getBlobServerPort())
				.endPort()
			.endSpec()
		.build();

	// Set job manager address to namespaced service name
	final String namespace = kubernetesJobManagerParameters.getNamespace();
	kubernetesJobManagerParameters.getFlinkConfiguration().setString(
		JobManagerOptions.ADDRESS,
		getNamespacedInternalServiceName(serviceName, namespace));

	return Collections.singletonList(headlessService);
}
 
Example #26
Source Project: strimzi-kafka-operator   Author: strimzi   File: KafkaExporter.java    License: Apache License 2.0 5 votes vote down vote up
public Service generateService() {
    if (!isDeployed()) {
        return null;
    }

    List<ServicePort> ports = new ArrayList<>(1);

    ports.add(createServicePort(METRICS_PORT_NAME, METRICS_PORT, METRICS_PORT, "TCP"));
    return createService("ClusterIP", ports, mergeLabelsOrAnnotations(prometheusAnnotations(), templateServiceAnnotations));
}
 
Example #27
Source Project: che   Author: eclipse   File: KubernetesServerExposer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void exposeSecureServers(
    Map<String, ServerConfig> securedServers, Map<String, ServicePort> securedPorts)
    throws InfrastructureException {

  if (securedPorts.isEmpty()) {
    return;
  }

  Optional<Service> secureService =
      secureServerExposer.createService(securedPorts.values(), pod, machineName, securedServers);

  String secureServiceName =
      secureService
          .map(
              s -> {
                String n = s.getMetadata().getName();
                k8sEnv.getServices().put(n, s);
                return n;
              })
          .orElse(null);

  for (ServicePort servicePort : securedPorts.values()) {
    // expose service port related secure servers if exist
    Map<String, ServerConfig> matchedSecureServers = match(securedServers, servicePort);
    if (!matchedSecureServers.isEmpty()) {
      onEachExposableServerSet(
          matchedSecureServers,
          (serverId, srvrs) -> {
            secureServerExposer.expose(
                k8sEnv, pod, machineName, secureServiceName, serverId, servicePort, srvrs);
          });
    }
  }
}
 
Example #28
Source Project: kubernetes-client   Author: fabric8io   File: ServiceOperationsImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Service replace(Service item) {
    try {
      Service old = fromServer().get();
      return super.replace(new ServiceBuilder(item)
        .editSpec()
        .withClusterIP(old.getSpec().getClusterIP())
        .endSpec()
        .build());
    } catch (Exception e) {
      throw KubernetesClientException.launderThrowable(forOperationType("replace"), e);
    }
}
 
Example #29
Source Project: kubernetes-client   Author: fabric8io   File: ServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGetUrlFromClusterIPService() {
  // Given
  Service service = new ServiceBuilder()
    .withNewMetadata().withName("svc1").endMetadata()
    .withNewSpec()
    .withClusterIP("187.30.14.32")
    .addNewPort()
    .withName("http")
    .withPort(8080)
    .withProtocol("TCP")
    .withNewTargetPort().withIntVal(8080).endTargetPort()
    .endPort()
    .withType("ClusterIP")
    .endSpec()
    .build();
  server.expect().get().withPath("/api/v1/namespaces/ns1/services/svc1")
    .andReturn(HttpURLConnection.HTTP_OK, service).always();
  server.expect().get().withPath("/apis/extensions/v1beta1/namespaces/ns1/ingresses")
    .andReturn(HttpURLConnection.HTTP_OK, new IngressListBuilder().build()).always();
  KubernetesClient client = server.getClient();

  // When
  String url = client.services().inNamespace("ns1").withName("svc1").getURL("http");

  // Then
  assertEquals("tcp://187.30.14.32:8080", url);
}
 
Example #30
Source Project: che   Author: eclipse   File: Services.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Try to find port in given service.
 *
 * @return {@link Optional} of found {@link ServicePort}, or {@link Optional#empty()} when not
 *     found.
 */
public static Optional<ServicePort> findPort(Service service, int port) {
  if (service == null || service.getSpec() == null || service.getSpec().getPorts() == null) {
    return Optional.empty();
  }
  return service
      .getSpec()
      .getPorts()
      .stream()
      .filter(p -> p.getPort() != null && p.getPort() == port)
      .findFirst();
}