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

The following examples show how to use io.fabric8.kubernetes.api.model.Service. 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: KubernetesJobManagerFactoryTest.java    From flink with 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 #2
Source File: ServiceResourceUtilTest.java    From kubernetes-pipeline-plugin with 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 #3
Source File: DefaultServiceEnricher.java    From jkube with 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 #4
Source File: TemplateIT.java    From kubernetes-client with 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 #5
Source File: Fabric8FlinkKubeClient.java    From flink with 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 File: DefaultServiceEnricher.java    From jkube with 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 #7
Source File: URLFromEnvVarsImpl.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 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 #8
Source File: ServiceResourceUtilTest.java    From kubernetes-pipeline-plugin with 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 #9
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 #10
Source File: Sample1Test.java    From module-ballerina-kubernetes with 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 #11
Source File: IngressEnricherTest.java    From jkube with 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 #12
Source File: KubernetesPluginsToolingApplierTest.java    From che with 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 #13
Source File: KubernetesResource.java    From strimzi-kafka-operator with 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 #14
Source File: PatchService.java    From jkube with 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 #15
Source File: OpenShiftEnvironmentFactoryTest.java    From che with 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 #16
Source File: MockKubernetesServerSupport.java    From kogito-runtimes with 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 #17
Source File: ServicePresentCondition.java    From dekorate with 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 #18
Source File: KubernetesDiscoveryClientFilterTest.java    From spring-cloud-kubernetes with 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 #19
Source File: Fabric8FlinkKubeClient.java    From flink with 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 #20
Source File: SpringBootOnOpenshiftTest.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainService() {
  KubernetesList list = Serialization.unmarshalAsList(SpringBootOnOpenshiftTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/openshift.yml"));
  assertNotNull(list);
  Service s = findFirst(list, Service.class).orElseThrow(()-> new IllegalStateException());
  assertNotNull(s);
}
 
Example #21
Source File: K8sServiceWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processDeletion(Service service) {
    if (!isMaster()) {
        return;
    }

    log.trace("Process service {} removal event from API server.",
            service.getMetadata().getName());

    k8sServiceAdminService.removeService(service.getMetadata().getUid());
}
 
Example #22
Source File: KubernetesClientTestBase.java    From flink with Apache License 2.0 5 votes vote down vote up
protected Service buildExternalServiceWithClusterIP() {
	final ServicePort servicePort = new ServicePortBuilder()
		.withName(Constants.REST_PORT_NAME)
		.withPort(REST_PORT)
		.withNewTargetPort(REST_PORT)
		.build();

	return buildExternalService(
		KubernetesConfigOptions.ServiceExposedType.ClusterIP,
		servicePort,
		null);
}
 
Example #23
Source File: DemoApplicationTests.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainService() {
  KubernetesList list = Serialization.unmarshalAsList(getClass().getClassLoader().getResourceAsStream("META-INF/dekorate/kubernetes.yml"));
  assertNotNull(list);
  Service service = findFirst(list, Service.class).orElseThrow(IllegalStateException::new);
  assertNotNull(service);
  assertEquals(1, list.getItems().stream().filter(i -> Service.class.isInstance(i)).count());
}
 
Example #24
Source File: RoutesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Service createService(String portString, int portInt) {
  Service service = new Service();
  ObjectMeta metadata = new ObjectMeta();
  metadata.setName("servicename");
  service.setMetadata(metadata);
  ServiceSpec spec = new ServiceSpec();
  spec.setPorts(
      Collections.singletonList(new ServicePort(portString, null, portInt, "TCP", null)));
  service.setSpec(spec);
  return service;
}
 
Example #25
Source File: KafkaClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testSourceRangeOnNodePort() {
    List<String> sourceRanges = new ArrayList();
    sourceRanges.add("10.0.0.0/8");
    sourceRanges.add("130.211.204.1/32");

    Kafka kafkaAssembly = new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas,
            image, healthDelay, healthTimeout, metricsCm, configuration, emptyMap()))
            .editSpec()
                .editKafka()
                    .withNewListeners()
                        .withNewKafkaListenerExternalNodePort()
                        .endKafkaListenerExternalNodePort()
                    .endListeners()
                    .withNewTemplate()
                        .withNewExternalBootstrapService()
                            .withLoadBalancerSourceRanges(sourceRanges)
                        .endExternalBootstrapService()
                        .withNewPerPodService()
                            .withLoadBalancerSourceRanges(sourceRanges)
                        .endPerPodService()
                    .endTemplate()
                .endKafka()
            .endSpec()
            .build();
    KafkaCluster kc = KafkaCluster.fromCrd(kafkaAssembly, VERSIONS);

    // Check external bootstrap service
    Service ext = kc.generateExternalBootstrapService();
    assertThat(ext.getSpec().getLoadBalancerSourceRanges(), is(emptyList()));

    // Check per pod services
    for (int i = 0; i < replicas; i++)  {
        Service srv = kc.generateExternalService(i);
        assertThat(srv.getSpec().getLoadBalancerSourceRanges(), is(emptyList()));
    }
}
 
Example #26
Source File: KubernetesServerExposerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private void assertThatExternalServersAreExposed(
    String machineName,
    String portProtocol,
    Integer port,
    Map<String, ServerConfig> expectedServers) {
  // then
  assertThatContainerPortIsExposed(portProtocol, port);
  // ensure that service is created

  Service service = findContainerRelatedService();
  assertNotNull(service);

  // ensure that required service port is exposed
  ServicePort servicePort = assertThatServicePortIsExposed(port, service);

  Annotations.Deserializer serviceAnnotations =
      Annotations.newDeserializer(service.getMetadata().getAnnotations());
  assertEquals(serviceAnnotations.machineName(), machineName);
  // check that we did not create servers for public endpoints
  assertFalse(
      serviceAnnotations
          .servers()
          .keySet()
          .stream()
          .anyMatch(key -> expectedServers.containsKey(key)));

  verify(externalServerExposer)
      .expose(
          eq(kubernetesEnvironment),
          eq(machineName),
          eq(service.getMetadata().getName()),
          any(),
          eq(servicePort),
          eq(expectedServers));
}
 
Example #27
Source File: KafkaClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadBalancerSourceRange() {
    List<String> sourceRanges = new ArrayList();
    sourceRanges.add("10.0.0.0/8");
    sourceRanges.add("130.211.204.1/32");

    Kafka kafkaAssembly = new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas,
            image, healthDelay, healthTimeout, metricsCm, configuration, emptyMap()))
            .editSpec()
                .editKafka()
                    .withNewListeners()
                        .withNewKafkaListenerExternalLoadBalancer()
                        .endKafkaListenerExternalLoadBalancer()
                    .endListeners()
                    .withNewTemplate()
                        .withNewExternalBootstrapService()
                            .withLoadBalancerSourceRanges(sourceRanges)
                        .endExternalBootstrapService()
                        .withNewPerPodService()
                            .withLoadBalancerSourceRanges(sourceRanges)
                        .endPerPodService()
                    .endTemplate()
                .endKafka()
            .endSpec()
            .build();
    KafkaCluster kc = KafkaCluster.fromCrd(kafkaAssembly, VERSIONS);

    // Check external bootstrap service
    Service ext = kc.generateExternalBootstrapService();
    assertThat(ext.getSpec().getLoadBalancerSourceRanges(), is(sourceRanges));

    // Check per pod services
    for (int i = 0; i < replicas; i++)  {
        Service srv = kc.generateExternalService(i);
        assertThat(srv.getSpec().getLoadBalancerSourceRanges(), is(sourceRanges));
    }
}
 
Example #28
Source File: URLFromClusterIPImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public String getURL(Service service, String portName, String namespace, KubernetesClient client) {
  ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName);
  if (port != null && service.getSpec().getType().equals("ClusterIP")) {
    return port.getProtocol().toLowerCase() + "://" + service.getSpec().getClusterIP() + ":" + port.getPort();
  }
  return null;
}
 
Example #29
Source File: ServiceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testHealthCheckPortPatching()  {
    KubernetesClient client = mock(KubernetesClient.class);

    Service current = new ServiceBuilder()
            .withNewMetadata()
                .withNamespace(NAMESPACE)
                .withName(RESOURCE_NAME)
            .endMetadata()
            .withNewSpec()
                .withType("Loadbalancer")
                .withHealthCheckNodePort(34321)
            .endSpec()
            .build();

    Service desired = new ServiceBuilder()
            .withNewMetadata()
            .withNamespace(NAMESPACE)
            .withName(RESOURCE_NAME)
            .endMetadata()
            .withNewSpec()
            .withType("Loadbalancer")
            .endSpec()
            .build();

    ServiceOperator op = new ServiceOperator(vertx, client);
    op.patchHealthCheckPorts(current, desired);

    assertThat(current.getSpec().getHealthCheckNodePort(), is(desired.getSpec().getHealthCheckNodePort()));
}
 
Example #30
Source File: PatchServiceTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testResourcePatching() {
    Service oldService = new ServiceBuilder()
            .withNewMetadata().withName("service1").endMetadata()
            .withNewSpec()
            .withClusterIP("192.168.1.3")
            .withSelector(Collections.singletonMap("app", "MyApp"))
            .addNewPort()
            .withProtocol("TCP")
            .withTargetPort(new IntOrString("9376"))
            .withPort(80)
            .endPort()
            .endSpec()
            .build();
    Service newService = new ServiceBuilder()
            .withNewMetadata().withName("service1").addToAnnotations(Collections.singletonMap("app", "org.eclipse.jkube")).endMetadata()
            .withSpec(oldService.getSpec())
            .build();

    mockServer.expect().get().withPath("/api/v1/namespaces/test/services/service1").andReturn(200, oldService).always();
    mockServer.expect().patch().withPath("/api/v1/namespaces/test/services/service1").andReturn(200, new ServiceBuilder().withMetadata(newService.getMetadata()).withSpec(oldService.getSpec()).build()).once();

    OpenShiftClient client = mockServer.createOpenShiftClient();
    PatchService patchService = new PatchService(client, log);

    Service patchedService = patchService.compareAndPatchEntity("test", newService, oldService);

    assertTrue(UserConfigurationCompare.configEqual(patchedService.getMetadata(), newService.getMetadata()));
}