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

The following examples show how to use io.fabric8.kubernetes.api.model.ServicePortBuilder. 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: KubernetesServerResolverTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Service createService(
    String name, String machineName, Integer port, Map<String, ServerConfigImpl> servers) {
  Serializer serializer = Annotations.newSerializer();
  serializer.machineName(machineName);
  if (servers != null) {
    serializer.servers(servers);
  }

  return new ServiceBuilder()
      .withNewMetadata()
      .withName(name)
      .withAnnotations(serializer.annotations())
      .endMetadata()
      .withNewSpec()
      .withPorts(
          new ServicePortBuilder()
              .withPort(port)
              .withNewTargetPort()
              .withIntVal(port)
              .endTargetPort()
              .build())
      .endSpec()
      .build();
}
 
Example #2
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 #3
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 #4
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 #5
Source File: OpenShiftServerResolverTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Service createService(
    String name, String machineName, Integer port, Map<String, ServerConfigImpl> servers) {
  Serializer serializer = Annotations.newSerializer();
  serializer.machineName(machineName);
  if (servers != null) {
    serializer.servers(servers);
  }

  return new ServiceBuilder()
      .withNewMetadata()
      .withName(name)
      .withAnnotations(serializer.annotations())
      .endMetadata()
      .withNewSpec()
      .withPorts(
          new ServicePortBuilder()
              .withPort(port)
              .withNewTargetPort()
              .withIntVal(port)
              .endTargetPort()
              .build())
      .endSpec()
      .build();
}
 
Example #6
Source File: DefaultHostExternalServiceExposureStrategyTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldCreateIngressForServer() {
  // given
  ServerConfigImpl httpServerConfig =
      new ServerConfigImpl("8080/tcp", "http", "/api", ATTRIBUTES_MAP);
  ServicePort servicePort =
      new ServicePortBuilder()
          .withName("server-8080")
          .withPort(8080)
          .withProtocol("TCP")
          .withTargetPort(new IntOrString(8080))
          .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",
      servicePort,
      new ServerConfigImpl(httpServerConfig).withAttributes(ATTRIBUTES_MAP));
}
 
Example #7
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 #8
Source File: KubernetesInternalRuntimeTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private static Service mockService() {
  final Service service = mock(Service.class);
  final ServiceSpec spec = mock(ServiceSpec.class);
  mockName(SERVICE_NAME, service);
  when(service.getSpec()).thenReturn(spec);
  when(spec.getSelector()).thenReturn(ImmutableMap.of(POD_SELECTOR, WORKSPACE_POD_NAME));
  final ServicePort sp1 =
      new ServicePortBuilder().withTargetPort(intOrString(EXPOSED_PORT_1)).build();
  final ServicePort sp2 =
      new ServicePortBuilder().withTargetPort(intOrString(EXPOSED_PORT_2)).build();
  when(spec.getPorts()).thenReturn(ImmutableList.of(sp1, sp2));
  return service;
}
 
Example #9
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 #10
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 #11
Source File: OpenShiftInternalRuntimeTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private static Service mockService() {
  final Service service = mock(Service.class);
  final ServiceSpec spec = mock(ServiceSpec.class);
  mockName(SERVICE_NAME, service);
  when(service.getSpec()).thenReturn(spec);
  when(spec.getSelector()).thenReturn(ImmutableMap.of(POD_SELECTOR, POD_NAME));
  final ServicePort sp1 =
      new ServicePortBuilder().withTargetPort(intOrString(EXPOSED_PORT_1)).build();
  final ServicePort sp2 =
      new ServicePortBuilder().withTargetPort(intOrString(EXPOSED_PORT_2)).build();
  when(spec.getPorts()).thenReturn(ImmutableList.of(sp1, sp2));
  return service;
}
 
Example #12
Source File: KubernetesServerExposerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateIngressPerUniqueServerWithTheSamePort() throws Exception {
  // given
  ServerConfigImpl httpServerConfig =
      new ServerConfigImpl("8080/tcp", "http", "/api", UNIQUE_SERVER_ATTRIBUTES);
  ServerConfigImpl wsServerConfig =
      new ServerConfigImpl("8080/tcp", "ws", "/connect", UNIQUE_SERVER_ATTRIBUTES);
  ServicePort servicePort =
      new ServicePortBuilder()
          .withName("server-8080")
          .withPort(8080)
          .withProtocol("TCP")
          .withTargetPort(new IntOrString(8080))
          .build();

  Map<String, ServerConfig> serversToExpose =
      ImmutableMap.of(
          "http-server", httpServerConfig,
          "ws-server", wsServerConfig);

  // when
  serverExposer.expose(serversToExpose);

  // then
  assertThatExternalServerIsExposed(
      MACHINE_NAME,
      "tcp",
      8080,
      "http-server",
      new ServerConfigImpl(httpServerConfig).withAttributes(UNIQUE_SERVER_ATTRIBUTES));
  assertThatExternalServerIsExposed(
      MACHINE_NAME,
      "tcp",
      8080,
      "ws-server",
      new ServerConfigImpl(wsServerConfig).withAttributes(UNIQUE_SERVER_ATTRIBUTES));
}
 
Example #13
Source File: ServicesController.java    From rabbitmq-operator with Apache License 2.0 5 votes vote down vote up
private List<ServicePort> getUpdatedServicePorts(final Service current, final Service desired) {
    final List<ServicePort> finalPorts = Lists.newArrayList();
    for (final ServicePort desiredPort : desired.getSpec().getPorts())    {
        for (final ServicePort currentPort : current.getSpec().getPorts())    {
            if (desiredPort.getNodePort() == null && desiredPort.getName().equals(currentPort.getName()) && currentPort.getNodePort() != null) {
                finalPorts.add(new ServicePortBuilder(desiredPort).withNodePort(currentPort.getNodePort()).build());
            }
        }
    }

    return finalPorts;
}
 
Example #14
Source File: KubernetesServerExposerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateIngressForServerWhenTwoServersHasTheSamePort()
    throws InfrastructureException {
  // given
  ServerConfigImpl httpServerConfig =
      new ServerConfigImpl("8080/tcp", "http", "/api", ATTRIBUTES_MAP);
  ServerConfigImpl wsServerConfig =
      new ServerConfigImpl("8080/tcp", "ws", "/connect", 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,
          "ws-server", wsServerConfig);

  // when
  serverExposer.expose(serversToExpose);

  // then
  assertThatExternalServersAreExposed(
      MACHINE_NAME,
      "tcp",
      8080,
      ImmutableMap.of(
          "http-server", new ServerConfigImpl(httpServerConfig).withAttributes(ATTRIBUTES_MAP),
          "ws-server", new ServerConfigImpl(wsServerConfig).withAttributes(ATTRIBUTES_MAP)));
}
 
Example #15
Source File: DefaultHostExternalServiceExposureStrategyTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateSingleIngressForTwoNonUniqueServersWithTheSamePort() {
  // given
  ServerConfigImpl httpServerConfig =
      new ServerConfigImpl("8080/tcp", "http", "/api", ATTRIBUTES_MAP);
  ServerConfigImpl wsServerConfig =
      new ServerConfigImpl("8080/tcp", "ws", "/connect", ATTRIBUTES_MAP);
  ServicePort servicePort =
      new ServicePortBuilder()
          .withName("server-8080")
          .withPort(8080)
          .withProtocol("TCP")
          .withTargetPort(new IntOrString(8080))
          .build();

  Map<String, ServerConfig> serversToExpose =
      ImmutableMap.of(
          "http-server", httpServerConfig,
          "ws-server", wsServerConfig);

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

  // then
  assertEquals(kubernetesEnvironment.getIngresses().size(), 1);
  assertThatExternalServerIsExposed(
      MACHINE_NAME,
      SERVICE_NAME,
      "http-server",
      servicePort,
      new ServerConfigImpl(httpServerConfig).withAttributes(ATTRIBUTES_MAP));
  assertThatExternalServerIsExposed(
      MACHINE_NAME,
      SERVICE_NAME,
      "ws-server",
      servicePort,
      new ServerConfigImpl(wsServerConfig).withAttributes(ATTRIBUTES_MAP));
}
 
Example #16
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 #17
Source File: KubernetesPluginsToolingApplierTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private ServicePort createServicePort(int port) {
  return new ServicePortBuilder()
      .withPort(port)
      .withProtocol("TCP")
      .withNewTargetPort(port)
      .build();
}
 
Example #18
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 #19
Source File: ExternalServiceDecoratorTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAccompanyingKubernetesResources() throws IOException {
	final List<HasMetadata> resources = this.externalServiceDecorator.buildAccompanyingKubernetesResources();
	assertEquals(1, resources.size());

	final Service restService = (Service) resources.get(0);

	assertEquals(Constants.API_VERSION, restService.getApiVersion());

	assertEquals(ExternalServiceDecorator.getExternalServiceName(CLUSTER_ID), restService.getMetadata().getName());

	final Map<String, String> expectedLabels = getCommonLabels();
	assertEquals(expectedLabels, restService.getMetadata().getLabels());

	assertEquals(KubernetesConfigOptions.ServiceExposedType.LoadBalancer.name(), restService.getSpec().getType());

	final List<ServicePort> expectedServicePorts = Collections.singletonList(
		new ServicePortBuilder()
			.withName(Constants.REST_PORT_NAME)
			.withPort(REST_PORT)
			.withNewTargetPort(Integer.valueOf(REST_BIND_PORT))
			.build());
	assertEquals(expectedServicePorts, restService.getSpec().getPorts());

	expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
	expectedLabels.putAll(userLabels);
	assertEquals(expectedLabels, restService.getSpec().getSelector());

	final Map<String, String> resultAnnotations = restService.getMetadata().getAnnotations();
	assertThat(resultAnnotations, is(equalTo(customizedAnnotations)));
}
 
Example #20
Source File: InternalServiceDecoratorTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAccompanyingKubernetesResources() throws IOException {
	final List<HasMetadata> resources = this.internalServiceDecorator.buildAccompanyingKubernetesResources();
	assertEquals(1, resources.size());

	assertEquals(
		InternalServiceDecorator.getNamespacedInternalServiceName(CLUSTER_ID, NAMESPACE),
		this.flinkConfig.getString(JobManagerOptions.ADDRESS));

	final Service internalService = (Service) resources.get(0);

	assertEquals(Constants.API_VERSION, internalService.getApiVersion());

	assertEquals(InternalServiceDecorator.getInternalServiceName(CLUSTER_ID), internalService.getMetadata().getName());

	final Map<String, String> expectedLabels = getCommonLabels();
	assertEquals(expectedLabels, internalService.getMetadata().getLabels());

	assertNull(internalService.getSpec().getType());
	assertEquals("None", internalService.getSpec().getClusterIP());

	List<ServicePort> expectedServicePorts = Arrays.asList(
		new ServicePortBuilder()
			.withName(Constants.JOB_MANAGER_RPC_PORT_NAME)
			.withPort(RPC_PORT)
			.build(),
		new ServicePortBuilder()
			.withName(Constants.BLOB_SERVER_PORT_NAME)
			.withPort(BLOB_SERVER_PORT)
			.build());
	assertEquals(expectedServicePorts, internalService.getSpec().getPorts());

	expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
	expectedLabels.putAll(userLabels);
	assertEquals(expectedLabels, internalService.getSpec().getSelector());
}
 
Example #21
Source File: KubernetesClientTestBase.java    From flink with Apache License 2.0 5 votes vote down vote up
protected Service buildExternalServiceWithLoadBalancer(@Nullable String hostname, @Nullable String ip) {
	final ServicePort servicePort = new ServicePortBuilder()
		.withName(Constants.REST_PORT_NAME)
		.withPort(REST_PORT)
		.withNewTargetPort(REST_PORT)
		.build();
	final ServiceStatus serviceStatus = new ServiceStatusBuilder()
		.withLoadBalancer(new LoadBalancerStatus(Collections.singletonList(new LoadBalancerIngress(hostname, ip))))
		.build();

	return buildExternalService(
		KubernetesConfigOptions.ServiceExposedType.LoadBalancer,
		servicePort,
		serviceStatus);
}
 
Example #22
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 #23
Source File: KubernetesDiscoveryClientFilterMetadataTest.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
private List<ServicePort> getServicePorts(Map<Integer, String> ports) {
	return ports.entrySet().stream().map(e -> {
		ServicePortBuilder servicePortBuilder = new ServicePortBuilder();
		servicePortBuilder.withPort(e.getKey());
		if (!Strings.isNullOrEmpty(e.getValue())) {
			servicePortBuilder.withName(e.getValue());
		}
		return servicePortBuilder.build();
	}).collect(toList());
}
 
Example #24
Source File: AddServiceResourceDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
private ServicePort toServicePort(Port port) {
  return new ServicePortBuilder()
    .withName(port.getName())
    .withPort(port.getContainerPort())
    .withTargetPort(new IntOrString(port.getHostPort() > 0 ? port.getHostPort() : port.getContainerPort()))
    .build();
}
 
Example #25
Source File: ServiceHandler.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
/**
 * Generate kubernetes service definition for Prometheus.
 *
 * @throws KubernetesPluginException If an error occurs while generating artifact.
 */
private void generatePrometheusService(ServiceModel serviceModel) throws KubernetesPluginException {
    ServicePortBuilder servicePortBuilder = new ServicePortBuilder()
            .withName(serviceModel.getProtocol() + "-prometheus-" + serviceModel.getName())
            .withProtocol(KubernetesConstants.KUBERNETES_SVC_PROTOCOL)
            .withPort(serviceModel.getPrometheusModel().getPort())
            .withNewTargetPort(serviceModel.getPrometheusModel().getPort());

    if (serviceModel.getPrometheusModel().getNodePort() > 0) {
        servicePortBuilder.withNodePort(serviceModel.getNodePort());
    }
    Service service = new ServiceBuilder()
            .withNewMetadata()
            .withName(serviceModel.getName() + "-prometheus")
            .withNamespace(dataHolder.getNamespace())
            .addToLabels(serviceModel.getLabels())
            .endMetadata()
            .withNewSpec()
            .withPorts(servicePortBuilder.build())
            .addToSelector(KubernetesConstants.KUBERNETES_SELECTOR_KEY, serviceModel.getSelector())
            .withSessionAffinity(serviceModel.getSessionAffinity())
            .withType(serviceModel.getPrometheusModel().getServiceType())
            .endSpec()
            .build();
    try {
        String serviceYAML = SerializationUtils.dumpWithoutRuntimeStateAsYaml(service);
        KubernetesUtils.writeToFile(serviceYAML, "_prometheus" + SVC_FILE_POSTFIX + YAML);
    } catch (IOException e) {
        String errorMessage = "error while generating yaml file for prometheus service: " + serviceModel.getName();
        throw new KubernetesPluginException(errorMessage, e);
    }
}
 
Example #26
Source File: ServiceHandler.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
/**
 * Generate kubernetes service definition from annotation.
 *
 * @throws KubernetesPluginException If an error occurs while generating artifact.
 */
private void generate(ServiceModel serviceModel) throws KubernetesPluginException {
    if (null == serviceModel.getPortName()) {
        serviceModel.setPortName(serviceModel.getProtocol() + "-" + serviceModel.getName());
    }
    ServicePortBuilder servicePortBuilder = new ServicePortBuilder()
            .withName(serviceModel.getPortName())
            .withProtocol(KubernetesConstants.KUBERNETES_SVC_PROTOCOL)
            .withPort(serviceModel.getPort())
            .withNewTargetPort(serviceModel.getTargetPort());

    if (serviceModel.getNodePort() > 0) {
        servicePortBuilder.withNodePort(serviceModel.getNodePort());
    }
    Service service = new ServiceBuilder()
            .withNewMetadata()
            .withName(serviceModel.getName())
            .withNamespace(dataHolder.getNamespace())
            .addToLabels(serviceModel.getLabels())
            .endMetadata()
            .withNewSpec()
            .withPorts(servicePortBuilder.build())
            .addToSelector(KubernetesConstants.KUBERNETES_SELECTOR_KEY, serviceModel.getSelector())
            .withSessionAffinity(serviceModel.getSessionAffinity())
            .withType(serviceModel.getServiceType())
            .endSpec()
            .build();
    try {
        String serviceYAML = SerializationUtils.dumpWithoutRuntimeStateAsYaml(service);
        KubernetesUtils.writeToFile(serviceYAML, SVC_FILE_POSTFIX + YAML);
    } catch (IOException e) {
        String errorMessage = "error while generating yaml file for service: " + serviceModel.getName();
        throw new KubernetesPluginException(errorMessage, e);
    }

}
 
Example #27
Source File: DefaultServiceEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private void normalizeServicePorts(KubernetesListBuilder builder) {
    builder.accept(new TypedVisitor<ServicePortBuilder>() {
        @Override
        public void visit(ServicePortBuilder portBuilder) {
            PORT_NORMALIZATION_MAPPING.keySet().forEach(key -> {
                if (key.intValue() == portBuilder.buildTargetPort().getIntVal()) {
                    portBuilder.withPort(PORT_NORMALIZATION_MAPPING.get(key));
                }
            });
        }
    });
}
 
Example #28
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 #29
Source File: KubernetesServerExposerTest.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private void assertThatSecureServerIsExposed(
    String machineName,
    String portProtocol,
    Integer port,
    String serverName,
    ServerConfig serverConfig)
    throws Exception {
  // then
  assertThatContainerPortIsExposed(portProtocol, port);
  // ensure that service is created

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

  // ensure that no service port is exposed
  assertTrue(
      service
          .getSpec()
          .getPorts()
          .stream()
          .noneMatch(p -> p.getTargetPort().getIntVal().equals(port)));

  ServicePort servicePort =
      new ServicePortBuilder()
          .withName("server-" + port)
          .withPort(port)
          .withProtocol(portProtocol.toUpperCase())
          .withNewTargetPort(port)
          .build();

  verify(secureServerExposer)
      .expose(
          eq(kubernetesEnvironment),
          any(),
          eq(machineName),
          isNull(), // no service exists for the backed server
          isNull(), // a non-unique server
          eq(servicePort),
          eq(ImmutableMap.of(serverName, serverConfig)));
}
 
Example #30
Source File: ResolveServicesByLabelWithConfigOKTest.java    From vxms with Apache License 2.0 4 votes vote down vote up
public void initService() {
  final ObjectMeta buildmyTestService =
      new ObjectMetaBuilder()
          .addToLabels("name", "myTestService")
          .addToLabels("version", "v1")
          .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("name", "myTestService")
          .addToLabels("version", "v2")
          .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?labelSelector=version%3Dv1")
      .andReturn(200, new ServiceListBuilder().addToItems(servicemyTestService).build())
      .times(1);
  server
      .expect()
      .withPath("/api/v1/namespaces/default/services?labelSelector=version%3Dv2")
      .andReturn(200, new ServiceListBuilder().addToItems(servicemyTestService2).build())
      .times(1);
}