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

The following examples show how to use io.fabric8.kubernetes.api.model.IntOrString. 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: jkube   Source File: RouteEnricherTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private ServiceBuilder getTestService() {
    return new ServiceBuilder()
            .withNewMetadata()
            .withName("test-svc")
            .addToLabels("expose", "true")
            .endMetadata()
            .withNewSpec()
            .addNewPort()
            .withName("http")
            .withPort(8080)
            .withProtocol("TCP")
            .withTargetPort(new IntOrString(8080))
            .endPort()
            .addToSelector("group", "test")
            .withType("LoadBalancer")
            .endSpec();
}
 
Example 2
Source Project: jkube   Source File: IngressEnricherTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private ServiceBuilder getTestService() {
    return new ServiceBuilder()
            .withNewMetadata()
            .withName("test-svc")
            .addToLabels("expose", "true")
            .endMetadata()
            .withNewSpec()
            .addNewPort()
            .withName("http")
            .withPort(8080)
            .withProtocol("TCP")
            .withTargetPort(new IntOrString(8080))
            .endPort()
            .addToSelector("group", "test")
            .withType("LoadBalancer")
            .endSpec();
}
 
Example 3
Source Project: jkube   Source File: KubernetesHelper.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an IntOrString from the given string which could be a number or a name
 *
 * @param nameOrNumber String containing name or number
 * @return IntOrString object
 */
public static IntOrString createIntOrString(String nameOrNumber) {
    if (StringUtils.isBlank(nameOrNumber)) {
        return null;
    } else {
        IntOrString answer = new IntOrString();
        Integer intVal = null;
        try {
            intVal = Integer.parseInt(nameOrNumber);
        } catch (Exception e) {
            // ignore invalid number
        }
        if (intVal != null) {
            answer.setIntVal(intVal);
            answer.setKind(0);
        } else {
            answer.setStrVal(nameOrNumber);
            answer.setKind(1);
        }
        return answer;
    }
}
 
Example 4
Source Project: kubernetes-client   Source File: ServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void prepareService() {
  service = new ServiceBuilder()
    .withNewMetadata()
    .withName("httpbin")
    .withLabels(Collections.singletonMap("app", "httpbin"))
    .endMetadata()
    .withNewSpec()
    .addNewPort()
    .withName("http")
    .withPort(5511)
    .withTargetPort(new IntOrString(8080))
    .endPort()
    .addToSelector("deploymentconfig", "httpbin")
    .endSpec()
    .build();
}
 
Example 5
@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 6
Source Project: module-ballerina-kubernetes   Source File: StrategyTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Build bal file with deployment annotations having strategy annotations.
 *
 * @throws IOException               Error when loading the generated yaml.
 * @throws InterruptedException      Error when compiling the ballerina file.
 * @throws KubernetesPluginException Error when deleting the generated artifacts folder.
 */
@Test
public void rollingUpdateConfigTest() throws IOException, InterruptedException, KubernetesPluginException,
        DockerTestException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(BAL_DIRECTORY, "rolling_config.bal"), 0);

    // Check if docker image exists and correct
    validateDockerfile();
    validateDockerImage();

    // Validate deployment yaml
    File deploymentYAML = KUBERNETES_TARGET_PATH.resolve("rolling_config_deployment.yaml").toFile();
    Assert.assertTrue(deploymentYAML.exists());
    Deployment deployment = KubernetesTestUtils.loadYaml(deploymentYAML);
    final DeploymentStrategy strategy = deployment.getSpec().getStrategy();
    Assert.assertEquals(strategy.getType(), "RollingUpdate", "Invalid strategy found.");
    Assert.assertNotNull(strategy.getRollingUpdate());
    Assert.assertEquals(strategy.getRollingUpdate().getMaxSurge(), new IntOrString("45%"),
            "Invalid max surge found.");
    Assert.assertEquals(strategy.getRollingUpdate().getMaxUnavailable(), new IntOrString(3),
            "Invalid max unavailable found.");
    KubernetesUtils.deleteDirectory(KUBERNETES_TARGET_PATH);
    KubernetesUtils.deleteDirectory(DOCKER_TARGET_PATH);
    KubernetesTestUtils.deleteDockerImage(DOCKER_IMAGE);
}
 
Example 7
public Deployment generateDeployment(Map<String, String> annotations, boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets) {
    DeploymentStrategy updateStrategy = new DeploymentStrategyBuilder()
            .withType("RollingUpdate")
            .withRollingUpdate(new RollingUpdateDeploymentBuilder()
                    .withMaxSurge(new IntOrString(1))
                    .withMaxUnavailable(new IntOrString(0))
                    .build())
            .build();

    return createDeployment(
            updateStrategy,
            Collections.emptyMap(),
            annotations,
            getMergedAffinity(),
            getInitContainers(imagePullPolicy),
            getContainers(imagePullPolicy),
            getVolumes(isOpenShift),
            imagePullSecrets);
}
 
Example 8
Source Project: strimzi-kafka-operator   Source File: CruiseControl.java    License: Apache License 2.0 6 votes vote down vote up
public Deployment generateDeployment(boolean isOpenShift, Map<String, String> annotations, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets) {
    if (!isDeployed()) {
        return null;
    }

    DeploymentStrategy updateStrategy = new DeploymentStrategyBuilder()
            .withType("RollingUpdate")
            .withRollingUpdate(new RollingUpdateDeploymentBuilder()
                    .withMaxSurge(new IntOrString(1))
                    .withMaxUnavailable(new IntOrString(0))
                    .build())
            .build();

    return createDeployment(
            updateStrategy,
            Collections.emptyMap(),
            Collections.emptyMap(),
            getMergedAffinity(),
            getInitContainers(imagePullPolicy),
            getContainers(imagePullPolicy),
            getVolumes(isOpenShift),
            imagePullSecrets);
}
 
Example 9
Source Project: strimzi-kafka-operator   Source File: JmxTrans.java    License: Apache License 2.0 6 votes vote down vote up
public Deployment generateDeployment(ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets) {
    if (!isDeployed()) {
        return null;
    }

    DeploymentStrategy updateStrategy = new DeploymentStrategyBuilder()
            .withType("RollingUpdate")
            .withRollingUpdate(new RollingUpdateDeploymentBuilder()
                    .withMaxSurge(new IntOrString(1))
                    .withMaxUnavailable(new IntOrString(0))
                    .build())
            .build();

    return createDeployment(
            updateStrategy,
            Collections.emptyMap(),
            Collections.emptyMap(),
            getMergedAffinity(),
            getInitContainers(imagePullPolicy),
            getContainers(imagePullPolicy),
            getVolumes(),
            imagePullSecrets
    );
}
 
Example 10
Source Project: kubernetes-client   Source File: PodDisruptionBudgetTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
  server.expect().withPath("/apis/policy/v1beta1/namespaces/test/poddisruptionbudgets/poddisruptionbudget1").andReturn(200, new PodDisruptionBudgetBuilder()
    .withNewMetadata().withName("poddisruptionbudget1").withNamespace("test").endMetadata()
    .withNewSpec()
    .withMaxUnavailable(new IntOrString("1%"))
    .withNewSelector()
    .withMatchLabels(Collections.singletonMap("app", "zookeeper"))
    .endSelector()
    .endSpec()
    .build()).once();

  KubernetesClient client = server.getClient();

  Boolean deleted = client.policy().podDisruptionBudget().withName("poddisruptionbudget1").delete();
  assertNotNull(deleted);
  assertTrue(deleted);
}
 
Example 11
@Test
public void testPodDisruptionBudget() {
    KafkaConnect resource = new KafkaConnectBuilder(this.resource)
            .editSpec()
                .withNewTemplate()
                    .withNewPodDisruptionBudget()
                        .withMaxUnavailable(2)
                    .endPodDisruptionBudget()
                .endTemplate()
            .endSpec()
            .build();
    KafkaConnectCluster kc = KafkaConnectCluster.fromCrd(resource, VERSIONS);

    PodDisruptionBudget pdb = kc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(2)));
}
 
Example 12
@Test
public void testPodDisruptionBudget() {
    Kafka kafkaAssembly = new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas,
            image, healthDelay, healthTimeout, metricsCmJson, configurationJson, emptyMap()))
            .editSpec()
                .editZookeeper()
                    .withNewTemplate()
                        .withNewPodDisruptionBudget()
                            .withMaxUnavailable(2)
                        .endPodDisruptionBudget()
                    .endTemplate()
                .endZookeeper()
            .endSpec()
            .build();
    ZookeeperCluster zc = ZookeeperCluster.fromCrd(kafkaAssembly, VERSIONS);

    PodDisruptionBudget pdb = zc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(2)));
}
 
Example 13
@Test
public void testPodDisruptionBudget() {
    KafkaConnectS2I resource = new KafkaConnectS2IBuilder(this.resource)
            .editSpec()
                .withNewTemplate()
                    .withNewPodDisruptionBudget()
                        .withMaxUnavailable(2)
                    .endPodDisruptionBudget()
                .endTemplate()
            .endSpec()
            .build();
    KafkaConnectS2ICluster kc = KafkaConnectS2ICluster.fromCrd(resource, VERSIONS);

    PodDisruptionBudget pdb = kc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(2)));
}
 
Example 14
Source Project: strimzi-kafka-operator   Source File: KafkaClusterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPodDisruptionBudget() {
    Kafka kafkaAssembly = new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas,
            image, healthDelay, healthTimeout, metricsCm, configuration, emptyMap()))
            .editSpec()
                .editKafka()
                .withNewTemplate()
                    .withNewPodDisruptionBudget()
                        .withMaxUnavailable(2)
                    .endPodDisruptionBudget()
                .endTemplate()
                .endKafka()
            .endSpec()
            .build();
    KafkaCluster kc = KafkaCluster.fromCrd(kafkaAssembly, VERSIONS);

    PodDisruptionBudget pdb = kc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(2)));
}
 
Example 15
Source Project: enmasse   Source File: SystemtestsKubernetesApps.java    License: Apache License 2.0 6 votes vote down vote up
private static Ingress getSystemtestsIngressResource(String appName, int port) throws Exception {
    IngressBackend backend = new IngressBackend();
    backend.setServiceName(appName);
    backend.setServicePort(new IntOrString(port));
    HTTPIngressPath path = new HTTPIngressPath();
    path.setPath("/");
    path.setBackend(backend);

    return new IngressBuilder()
            .withNewMetadata()
            .withName(appName)
            .addToLabels("route", appName)
            .endMetadata()
            .withNewSpec()
            .withRules(new IngressRuleBuilder()
                    .withHost(appName + "."
                            + (env.kubernetesDomain().equals("nip.io") ? new URL(env.getApiUrl()).getHost() + ".nip.io" : env.kubernetesDomain()))
                    .withNewHttp()
                    .withPaths(path)
                    .endHttp()
                    .build())
            .endSpec()
            .build();
}
 
Example 16
@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 17
Source Project: data-highway   Source File: LanderPodFactory.java    License: Apache License 2.0 5 votes vote down vote up
private Container container(String roadName, List<String> args, Map<String, String> config, String truckParkName) {
  List<EnvVar> env = ImmutableList
      .<EnvVar> builder()
      .add(envFromFieldPath("KUBERNETES_NAMESPACE", "metadata.namespace"))
      .add(env("POD_NAME", truckParkName))
      .add(env("ENVIRONMENT", environment))
      .add(env("JVM_ARGS", config.get(JVM_ARGS)))
      .add(env("CLOUDWATCH_REGION", config.get(CLOUDWATCH_REGION)))
      .add(env("CLOUDWATCH_GROUP", config.get(CLOUDWATCH_GROUP)))
      .add(env("CLOUDWATCH_STREAM", "${KUBERNETES_NAMESPACE}-truck-park-" + roadName))
      .build();
  Map<String, Quantity> limits = ImmutableMap
      .<String, Quantity> builder()
      .put(CPU, new Quantity(config.get(CPU)))
      .put(MEMORY, new Quantity(config.get(MEMORY)))
      .build();
  return new ContainerBuilder()
      .withName(truckParkName)
      .withImage(config.get(DOCKER_IMAGE))
      .withArgs(args)
      .withEnv(env)
      .withResources(new ResourceRequirementsBuilder().withLimits(limits).withRequests(limits).build())
      .withLivenessProbe(new ProbeBuilder()
          .withHttpGet(new HTTPGetActionBuilder().withPath("/").withPort(new IntOrString("http")).build())
          .withInitialDelaySeconds(getConfigOrDefault(config, "livenessInitialDelay", 30))
          .withPeriodSeconds(getConfigOrDefault(config, "livenessPeriod", 5))
          .withSuccessThreshold(getConfigOrDefault(config, "livenessSuccessThreshold", 1))
          .withTimeoutSeconds(getConfigOrDefault(config, "livenessTimeout", 5))
          .withFailureThreshold(getConfigOrDefault(config, "livenessFailureThreshold", 3))
          .build())
      .build();
}
 
Example 18
Source Project: jkube   Source File: ProbeHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private HTTPGetAction getHTTPGetAction(String getUrl) {
    if (getUrl == null || !getUrl.subSequence(0,4).toString().equalsIgnoreCase("http")) {
        return null;
    }
    try {
        URL url = new URL(getUrl);
        return new HTTPGetAction(url.getHost(),
                null /* headers */,
                url.getPath(),
                new IntOrString(url.getPort()),
                url.getProtocol().toUpperCase());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Invalid URL " + getUrl + " given for HTTP GET readiness check");
    }
}
 
Example 19
Source Project: jkube   Source File: DefaultServiceEnricher.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private String getPortValue(IntOrString port) {
    String val = port.getStrVal();
    if (val == null) {
        val = Integer.toString(port.getIntVal());
    }
    return val;
}
 
Example 20
@Test
public void testConvertionFromExtensionsV1beta1Deployment() {
    // Given
    DeploymentConfigEnricher deploymentConfigEnricher = new DeploymentConfigEnricher(context);
    io.fabric8.kubernetes.api.model.extensions.Deployment appsV1Deployment = new io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder()
            .withNewMetadata().withName("test-app").addToLabels("app", "test-app").endMetadata()
            .withNewSpec()
            .withReplicas(3)
            .withRevisionHistoryLimit(2)
            .withNewSelector().addToMatchLabels("app", "test-app").endSelector()
            .withNewTemplate()
            .withNewMetadata().addToLabels("app", "test-app").endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName("test-container")
            .withImage("test-image:1.0.0")
            .addNewPort()
            .withContainerPort(80)
            .endPort()
            .endContainer()
            .endSpec()
            .endTemplate()
            .withNewStrategy()
            .withType("Rolling")
            .withNewRollingUpdate().withMaxSurge(new IntOrString(5)).endRollingUpdate()
            .endStrategy()
            .endSpec()
            .build();
    KubernetesListBuilder kubernetesListBuilder = new KubernetesListBuilder().addToItems(appsV1Deployment);

    // When
    deploymentConfigEnricher.create(PlatformMode.openshift, kubernetesListBuilder);

    // Then
    assertEquals(1, kubernetesListBuilder.buildItems().size());
    HasMetadata result = kubernetesListBuilder.buildFirstItem();
    assertTrue(result instanceof DeploymentConfig);
    assertDeploymentConfig((DeploymentConfig) result, "Rolling");
}
 
Example 21
Source Project: jkube   Source File: PatchServiceTest.java    License: 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()));
}
 
Example 22
Source Project: jkube   Source File: KubernetesHelper.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates an IntOrString from the given string which could be a number or a name
 *
 * @param intVal integer as value
 * @return wrapped object as IntOrString
 */
public static IntOrString createIntOrString(int intVal) {
    IntOrString answer = new IntOrString();
    answer.setIntVal(intVal);
    answer.setKind(0);
    return answer;
}
 
Example 23
private void createServiceInMockServer(String name, String serviceIp, Map<String,String> labels) {
    final ServicePort port = new ServicePort(SERVICE_PROTOCOL, 0, SERVICE_PORT, SERVICE_PROTOCOL, new IntOrString(SERVICE_PORT));
    final Service service = new ServiceBuilder().withNewMetadata()
                                                    .withName(name)
                                                    .withLabels(labels)
                                                .endMetadata()
                                                .withNewSpec()
                                                    .withClusterIP(serviceIp)
                                                    .withType("ClusterIP")
                                                    .withSessionAffinity("ClientIP")
                                                    .withPorts(port)
                                                .endSpec()
                                                .build();
    server.getClient().services().inNamespace(NAMESPACE).create(service);
}
 
Example 24
/**
 * Get Deployment strategy.
 *
 * @param keyValue Value of strategy field of deployment annotation.
 * @return DeploymentStrategy..
 */
private DeploymentStrategy getStrategy(BLangRecordLiteral.BLangRecordKeyValueField keyValue)
        throws KubernetesPluginException {
    DeploymentStrategy strategy = new DeploymentStrategy();

    if (keyValue.getValue().type.getKind() == TypeKind.STRING) {
        // Rolling Update for Recreate with default values
        strategy.setType((getStringValue(keyValue.getValue())));
        return strategy;
    }
    RollingUpdateDeployment rollingParams = new RollingUpdateDeployment();
    strategy.setType("RollingUpdate");
    for (BLangRecordLiteral.RecordField strategyField : ((BLangRecordLiteral) keyValue.valueExpr).fields) {
        BLangRecordLiteral.BLangRecordKeyValueField strategyKeyValueField =
                ((BLangRecordLiteral.BLangRecordKeyValueField) strategyField);
        switch (strategyKeyValueField.getKey().toString()) {
            case "maxUnavailable":
                if (strategyKeyValueField.getValue().type.getKind() == TypeKind.INT) {
                    rollingParams.setMaxUnavailable(new IntOrString(getIntValue(strategyKeyValueField.getValue())));
                } else {
                    rollingParams.setMaxUnavailable(new IntOrString(
                            getStringValue(strategyKeyValueField.getValue())));
                }
                break;
            case "maxSurge":
                if (strategyKeyValueField.getValue().type.getKind() == TypeKind.INT) {
                    rollingParams.setMaxSurge(new IntOrString(getIntValue(strategyKeyValueField.getValue())));
                } else {
                    rollingParams.setMaxSurge(new IntOrString(getStringValue(strategyKeyValueField.getValue())));
                }
                break;
            default:
                break;
        }
    }
    strategy.setRollingUpdate(rollingParams);
    return strategy;
}
 
Example 25
Source Project: dekorate   Source File: AddServiceResourceDecorator.java    License: 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 26
Source Project: dekorate   Source File: AbstractAddProbeDecorator.java    License: Apache License 2.0 5 votes vote down vote up
private HTTPGetAction httpGetAction(Probe probe, ContainerFluent<?> container) {
  if (!container.hasPorts()) {
    return new HTTPGetAction(null, Collections.emptyList(), probe.getHttpActionPath(), new IntOrString(8080), "HTTP");
  }

  return new HTTPGetAction(null, Collections.emptyList(), probe.getHttpActionPath(), new IntOrString(Ports.getHttpPort(container).get().getContainerPort()), "HTTP");
}
 
Example 27
Source Project: che   Source File: IngressesTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void emptyWhenPortByIntAndNotFound() {
  final String SERVER_PORT_NAME = "server-8080";
  final int PORT = 8080;

  Service service = createService(SERVER_PORT_NAME, PORT);
  Ingress ingress = createIngress(new IngressBackend("servicename", new IntOrString(666)));

  Optional<IngressRule> foundRule =
      Ingresses.findIngressRuleForServicePort(singletonList(ingress), service, PORT);
  assertFalse(foundRule.isPresent());
}
 
Example 28
Source Project: microbean-helm   Source File: TillerInstaller.java    License: Apache License 2.0 5 votes vote down vote up
protected ServiceSpec createServiceSpec(final Map<String, String> labels) {
  final ServiceSpec serviceSpec = new ServiceSpec();
  serviceSpec.setType("ClusterIP");

  final ServicePort servicePort = new ServicePort();
  servicePort.setName(DEFAULT_NAME);
  servicePort.setPort(Integer.valueOf(44134));
  servicePort.setTargetPort(new IntOrString(DEFAULT_NAME));
  serviceSpec.setPorts(Arrays.asList(servicePort));

  serviceSpec.setSelector(normalizeLabels(labels));
  return serviceSpec;
}
 
Example 29
Source Project: che   Source File: Ingresses.java    License: 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 30
Source Project: che   Source File: PreviewUrlExposerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldProvisionIngressWhenNotFound() throws InternalInfrastructureException {
  Mockito.when(
          externalServiceExposureStrategy.getExternalPath(Mockito.anyString(), Mockito.any()))
      .thenReturn("some-server-path");

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

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

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

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

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

  previewUrlExposer.expose(env);
  assertEquals(env.getIngresses().size(), 1);
  Ingress provisionedIngress = env.getIngresses().values().iterator().next();
  IngressBackend provisionedIngressBackend =
      provisionedIngress.getSpec().getRules().get(0).getHttp().getPaths().get(0).getBackend();
  assertEquals(provisionedIngressBackend.getServicePort().getStrVal(), SERVER_PORT_NAME);
  assertEquals(provisionedIngressBackend.getServiceName(), SERVICE_NAME);
}