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

The following examples show how to use io.fabric8.kubernetes.api.model.IntOrString. 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: JmxTrans.java    From strimzi-kafka-operator with 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 #2
Source File: KafkaConnectClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: ZookeeperClusterTest.java    From strimzi-kafka-operator with 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, 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 #4
Source File: StrategyTest.java    From module-ballerina-kubernetes with 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 #5
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 #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: ServiceTest.java    From kubernetes-client with 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 #8
Source File: KubernetesHelper.java    From jkube with 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 #9
Source File: KafkaConnectS2IClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: SystemtestsKubernetesApps.java    From enmasse with 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 #11
Source File: RouteEnricherTest.java    From jkube with 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 #12
Source File: KafkaConnectCluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: PodDisruptionBudgetTest.java    From kubernetes-client with 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 #14
Source File: KafkaClusterTest.java    From strimzi-kafka-operator with 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 File: CruiseControl.java    From strimzi-kafka-operator with 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 #16
Source File: IngressEnricherTest.java    From jkube with 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 #17
Source File: KubernetesServerResolverTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Ingress createIngress(
    String name, String machineName, Pair<String, ServerConfig> server) {
  Serializer serializer = Annotations.newSerializer();
  serializer.machineName(machineName);
  serializer.server(server.first, server.second);

  return new IngressBuilder()
      .withNewMetadata()
      .withName(name)
      .withAnnotations(serializer.annotations())
      .endMetadata()
      .withNewSpec()
      .withRules(
          new IngressRule(
              null,
              new HTTPIngressRuleValue(
                  singletonList(
                      new HTTPIngressPath(
                          new IngressBackend(name, new IntOrString("8080")),
                          INGRESS_PATH_PREFIX)))))
      .endSpec()
      .withNewStatus()
      .withNewLoadBalancer()
      .addNewIngress()
      .withIp("127.0.0.1")
      .endIngress()
      .endLoadBalancer()
      .endStatus()
      .build();
}
 
Example #18
Source File: OpenShiftPreviewUrlCommandProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldDoNothingWhenCantFindRouteForPreviewUrl() throws InfrastructureException {
  int port = 8080;
  List<CommandImpl> commands =
      Collections.singletonList(
          new CommandImpl("a", "a", "a", new PreviewUrlImpl(port, null), Collections.emptyMap()));
  OpenShiftEnvironment env =
      OpenShiftEnvironment.builder().setCommands(new ArrayList<>(commands)).build();

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

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

  previewUrlCommandProvisioner.provision(env, mockProject);

  assertTrue(commands.containsAll(env.getCommands()));
  assertTrue(env.getCommands().containsAll(commands));
  assertEquals(
      env.getWarnings().get(0).getCode(), Warnings.NOT_ABLE_TO_PROVISION_OBJECTS_FOR_PREVIEW_URL);
}
 
Example #19
Source File: CruiseControlTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testPodDisruptionBudget() {
    int maxUnavailable = 2;
    CruiseControlSpec cruiseControlSpec = new CruiseControlSpecBuilder()
            .withImage(ccImage)
                .withNewTemplate()
                    .withNewPodDisruptionBudget()
                    .withMaxUnavailable(maxUnavailable)
                .endPodDisruptionBudget()
            .endTemplate()
            .build();

    Kafka resource =
            new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas, image, healthDelay, healthTimeout))
                    .editSpec()
                    .editKafka()
                    .withVersion(version)
                    .endKafka()
                    .withCruiseControl(cruiseControlSpec)
                    .endSpec()
                    .build();

    CruiseControl cc = CruiseControl.fromCrd(resource, VERSIONS);
    Deployment dep = cc.generateDeployment(true,  null, null, null);
    List<Container> containers = dep.getSpec().getTemplate().getSpec().getContainers();
    Container ccContainer = containers.stream().filter(container -> ccImage.equals(container.getImage())).findFirst().get();

    PodDisruptionBudget pdb = cc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(maxUnavailable)));
}
 
Example #20
Source File: IngressesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void findHostWhenPortDefinedByString() {
  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(PORT)));

  Optional<IngressRule> foundRule =
      Ingresses.findIngressRuleForServicePort(singletonList(ingress), service, PORT);
  assertTrue(foundRule.isPresent());
  assertEquals(foundRule.get().getHost(), "ingresshost");
}
 
Example #21
Source File: KafkaConnectS2IClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultPodDisruptionBudget() {
    KafkaConnectS2I resource = new KafkaConnectS2IBuilder(this.resource).build();
    KafkaConnectS2ICluster kc = KafkaConnectS2ICluster.fromCrd(resource, VERSIONS);

    PodDisruptionBudget pdb = kc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(1)));
}
 
Example #22
Source File: KafkaClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplicationPortNetworkPolicyOnOldKubernetes() {
    Kafka kafkaAssembly = ResourceUtils.createKafkaCluster(namespace, cluster, replicas,
            image, healthDelay, healthTimeout, metricsCm, configuration, emptyMap());
    KafkaCluster k = KafkaCluster.fromCrd(kafkaAssembly, VERSIONS);

    // Check Network Policies
    NetworkPolicy np = k.generateNetworkPolicy(false);

    assertThat(np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(KafkaCluster.REPLICATION_PORT))).findFirst().orElse(null), is(notNullValue()));

    List<NetworkPolicyPeer> rules = np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(KafkaCluster.REPLICATION_PORT))).map(NetworkPolicyIngressRule::getFrom).findFirst().orElse(null);
    assertThat(rules.size(), is(0));
}
 
Example #23
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 #24
Source File: KafkaClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultPodDisruptionBudget() {
    Kafka kafkaAssembly = new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas,
            image, healthDelay, healthTimeout, metricsCm, configuration, emptyMap()))
            .build();
    KafkaCluster kc = KafkaCluster.fromCrd(kafkaAssembly, VERSIONS);

    PodDisruptionBudget pdb = kc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(1)));
}
 
Example #25
Source File: JwtProxyProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(
    expectedExceptions = InfrastructureException.class,
    expectedExceptionsMessageRegExp =
        "Secure servers which expose the same port should have "
            + "the same `cookiesAuthEnabled` value\\.")
public void shouldThrowAnExceptionIfServersHaveDifferentValueForCookiesAuthEnabled()
    throws Exception {
  // given
  ServerConfigImpl server1 =
      new ServerConfigImpl(
          "4401/tcp",
          "ws",
          "/",
          ImmutableMap.of(SECURE_SERVER_COOKIES_AUTH_ENABLED_ATTRIBUTE, "true"));
  ServerConfigImpl server2 =
      new ServerConfigImpl(
          "4401/tcp",
          "http",
          "/",
          ImmutableMap.of(SECURE_SERVER_COOKIES_AUTH_ENABLED_ATTRIBUTE, "false"));
  ServerConfigImpl server3 = new ServerConfigImpl("4401/tcp", "ws", "/", emptyMap());

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

  // when
  jwtProxyProvisioner.expose(
      k8sEnv,
      podWithName(),
      "machine",
      "terminal",
      port,
      "TCP",
      ImmutableMap.of("server1", server1, "server2", server2, "server3", server3));
}
 
Example #26
Source File: JwtProxyProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldBindToLocalhostWhenNoServiceForServerExists() throws Exception {
  // given
  JwtProxyConfigBuilder configBuilder = mock(JwtProxyConfigBuilder.class);
  when(configBuilderFactory.create(any())).thenReturn(configBuilder);

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

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

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

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

  // then
  verify(configBuilder)
      .addVerifierProxy(
          eq(4400), eq("http://127.0.0.1:4401"), eq(emptySet()), eq(false), eq("/"), isNull());
}
 
Example #27
Source File: ServiceExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) {
  try (final KubernetesClient client = new DefaultKubernetesClient()) {
    Service service = new ServiceBuilder()
      .withNewMetadata()
      .withName("my-service")
      .endMetadata()
      .withNewSpec()
      .withSelector(Collections.singletonMap("app", "MyApp"))
      .addNewPort()
      .withName("test-port")
      .withProtocol("TCP")
      .withPort(80)
      .withTargetPort(new IntOrString(9376))
      .endPort()
      .withType("LoadBalancer")
      .endSpec()
      .withNewStatus()
      .withNewLoadBalancer()
      .addNewIngress()
      .withIp("146.148.47.155")
      .endIngress()
      .endLoadBalancer()
      .endStatus()
      .build();

    service = client.services().inNamespace(client.getNamespace()).create(service);
    log("Created service with name ", service.getMetadata().getName());

    String serviceURL = client.services().inNamespace(client.getNamespace()).withName(service.getMetadata().getName()).getURL("test-port");
    log("Service URL", serviceURL);

  }
}
 
Example #28
Source File: KubernetesPreviewUrlCommandProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldDoNothingWhenCantFindIngressForPreviewUrl() throws InfrastructureException {
  int port = 8080;
  List<CommandImpl> commands =
      Collections.singletonList(
          new CommandImpl("a", "a", "a", new PreviewUrlImpl(port, null), Collections.emptyMap()));
  KubernetesEnvironment env =
      KubernetesEnvironment.builder().setCommands(new ArrayList<>(commands)).build();

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

  Mockito.when(mockNamespace.ingresses()).thenReturn(mockIngresses);
  Mockito.when(mockIngresses.get()).thenReturn(Collections.emptyList());

  previewUrlCommandProvisioner.provision(env, mockNamespace);

  assertTrue(commands.containsAll(env.getCommands()));
  assertTrue(env.getCommands().containsAll(commands));
  assertEquals(
      env.getWarnings().get(0).getCode(), Warnings.NOT_ABLE_TO_PROVISION_OBJECTS_FOR_PREVIEW_URL);
}
 
Example #29
Source File: KafkaBridgeClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDifferentHttpPort()   {
    KafkaBridge resource = new KafkaBridgeBuilder(this.resource)
            .editSpec()
                .withNewHttp(1874)
            .endSpec()
            .build();

    KafkaBridgeCluster kb = KafkaBridgeCluster.fromCrd(resource, VERSIONS);

    // Check ports in container
    Deployment dep = kb.generateDeployment(emptyMap(), true, null, null);
    Container cont = dep.getSpec().getTemplate().getSpec().getContainers().get(0);

    assertThat(cont.getLivenessProbe().getHttpGet().getPort(), is(new IntOrString(KafkaBridgeCluster.REST_API_PORT_NAME)));
    assertThat(cont.getReadinessProbe().getHttpGet().getPort(), is(new IntOrString(KafkaBridgeCluster.REST_API_PORT_NAME)));
    assertThat(cont.getPorts().get(0).getContainerPort(), is(new Integer(1874)));
    assertThat(dep.getSpec().getTemplate().getSpec().getContainers().get(0).getPorts().get(0).getName(), is(KafkaBridgeCluster.REST_API_PORT_NAME));
    assertThat(dep.getSpec().getTemplate().getSpec().getContainers().get(0).getPorts().get(0).getProtocol(), is("TCP"));

    // Check ports on Service
    Service svc = kb.generateService();

    assertThat(svc.getSpec().getType(), is("ClusterIP"));
    assertThat(svc.getMetadata().getLabels(), is(expectedServiceLabels(kb.getServiceName())));
    assertThat(svc.getSpec().getSelector(), is(expectedSelectorLabels()));
    assertThat(svc.getSpec().getPorts().get(0).getPort(), is(new Integer(1874)));
    assertThat(svc.getSpec().getPorts().get(0).getName(), is(KafkaBridgeCluster.REST_API_PORT_NAME));
    assertThat(svc.getSpec().getPorts().get(0).getProtocol(), is("TCP"));
    assertThat(svc.getMetadata().getAnnotations(), is(kbc.getDiscoveryAnnotation(1874)));
    checkOwnerReference(kbc.createOwnerReference(), svc);
}
 
Example #30
Source File: KafkaBridgeClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultPodDisruptionBudget() {
    KafkaBridge resource = new KafkaBridgeBuilder(this.resource).build();
    KafkaBridgeCluster kbc = KafkaBridgeCluster.fromCrd(resource, VERSIONS);

    PodDisruptionBudget pdb = kbc.generatePodDisruptionBudget();
    assertThat(pdb.getSpec().getMaxUnavailable(), is(new IntOrString(1)));
}