io.fabric8.kubernetes.client.NamespacedKubernetesClient Java Examples

The following examples show how to use io.fabric8.kubernetes.client.NamespacedKubernetesClient. 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: KubernetesMockServerTestResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> start() {
    final Map<String, String> systemProps = new HashMap<>();
    systemProps.put(Config.KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY, "true");
    systemProps.put(Config.KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, "false");
    systemProps.put(Config.KUBERNETES_AUTH_TRYSERVICEACCOUNT_SYSTEM_PROPERTY, "false");
    systemProps.put(Config.KUBERNETES_NAMESPACE_SYSTEM_PROPERTY, "test");

    mockServer = new KubernetesMockServer(useHttps());
    mockServer.init();
    try (NamespacedKubernetesClient client = mockServer.createClient()) {
        systemProps.put(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, client.getConfiguration().getMasterUrl());
    }

    configureMockServer(mockServer);

    return systemProps;
}
 
Example #2
Source File: ConfigMapTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testLiteralConfigMap() throws InterruptedException {
  HashMap<String, String> data = new HashMap<>();
  data.put("foo", "bar");
  data.put("cheese", "gouda");

  server.expect().withPath("/api/v1/namespaces/test/configmaps").andReturn(200,
    new ConfigMapBuilder()
      .withNewMetadata()
        .withName("cfg1")
      .endMetadata()
      .addToData(data)
      .build())
    .once();

  NamespacedKubernetesClient client = server.getClient();
  ConfigMapList cfgList = client.configMaps().list();
  assertNotNull(cfgList);
  assertEquals(1, cfgList.getAdditionalProperties().size());
  Map<String, String> keys = (Map<String, String>) cfgList.getAdditionalProperties().get("data");
  assertEquals("gouda",keys.get("cheese"));
  assertEquals("bar",keys.get("foo"));
}
 
Example #3
Source File: OpenShift.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public static boolean isOpenShift(NamespacedKubernetesClient client) throws InterruptedException {
    if (System.getenv().containsKey(ENMASSE_OPENSHIFT)) {
        return Boolean.parseBoolean(System.getenv().get(ENMASSE_OPENSHIFT));
    }
    int retries = 10;
    while (true) {
        // Need to query the full API path because Kubernetes does not allow GET on /
        OkHttpClient httpClient = client.adapt(OkHttpClient.class);
        HttpUrl url = HttpUrl.get(client.getMasterUrl()).resolve("/apis/route.openshift.io");
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .get();

        try (Response response = httpClient.newCall(requestBuilder.build()).execute()) {
            return response.code() >= 200 && response.code() < 300;
        } catch (IOException e) {
            retries--;
            if (retries <= 0) {
                throw new UncheckedIOException(e);
            } else {
                log.warn("Exception when checking API availability, retrying {} times", retries, e);
            }
        }
        Thread.sleep(5000);
    }
}
 
Example #4
Source File: StyxScheduler.java    From styx with Apache License 2.0 6 votes vote down vote up
private static DockerRunner createDockerRunner(
    String id,
    Environment environment,
    StateManager stateManager,
    Stats stats,
    Debug debug,
    Set<String> secretWhitelist,
    Time time) {
  final Config config = environment.config();
  final Closer closer = environment.closer();

  final String styxEnvironment = config.getString(STYX_ENVIRONMENT);
  final NamespacedKubernetesClient kubernetes = closer.register(getKubernetesClient(config, id));
  final ServiceAccountKeyManager serviceAccountKeyManager = createServiceAccountKeyManager();
  var fabric8Client = TracingProxy.instrument(Fabric8KubernetesClient.class,
      MeteredFabric8KubernetesClientProxy.instrument(
          Fabric8KubernetesClient.of(kubernetes), stats, time));
  return closer.register(DockerRunner.kubernetes(id, fabric8Client, stateManager, stats,
      serviceAccountKeyManager, debug, styxEnvironment, secretWhitelist));
}
 
Example #5
Source File: StyxScheduler.java    From styx with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static NamespacedKubernetesClient getKubernetesClient(Config rootConfig, String id,
                                                      Container gke, KubernetesClientFactory clientFactory) {
  try {
    final Config config = rootConfig
        .getConfig(GKE_CLUSTER_PATH)
        .getConfig(id);

    final Cluster cluster = gke.projects().locations().clusters()
        .get(String.format("projects/%s/locations/%s/clusters/%s",
                           config.getString(GKE_CLUSTER_PROJECT_ID),
                           config.getString(GKE_CLUSTER_ZONE),
                           config.getString(GKE_CLUSTER_ID))).execute();

    final io.fabric8.kubernetes.client.Config kubeConfig = new ConfigBuilder()
        .withMasterUrl("https://" + cluster.getEndpoint())
        // missing container.clusters.getCredentials permission in GCP will result null cert and key
        // and we want it to fail loudly
        .withCaCertData(Objects.requireNonNull(cluster.getMasterAuth().getClusterCaCertificate(),
            "clusterCaCertificate"))
        .withClientCertData(Objects.requireNonNull(cluster.getMasterAuth().getClientCertificate(),
            "clientCertificate"))
        .withClientKeyData(Objects.requireNonNull(cluster.getMasterAuth().getClientKey(),
            "clientKey"))
        .withNamespace(config.getString(GKE_CLUSTER_NAMESPACE))
        .withRequestTimeout(get(rootConfig, rootConfig::getInt, KUBERNETES_REQUEST_TIMEOUT)
            .orElse(DEFAULT_KUBERNETES_REQUEST_TIMEOUT_MILLIS))
        .build();

    final OkHttpClient httpClient = HttpClientUtils.createHttpClient(kubeConfig).newBuilder()
        .protocols(Collections.singletonList(Protocol.HTTP_1_1))
        .build();

    return clientFactory.apply(httpClient, kubeConfig);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #6
Source File: StyxSchedulerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
private NamespacedKubernetesClient getKubernetesClient(String k8sRequestTimeoutConfig,
                                                       String clusterCaCertificate,
                                                       String clientCertificate,
                                                       String clientKey) throws Exception {
  var project = "test-project";
  var zone = "test-zone";
  var cluster = "test-cluster";

  var configMap = ImmutableMap.<String, String>builder()
      .put("styx.gke.foo.project-id", project)
      .put("styx.gke.foo.cluster-zone", zone)
      .put("styx.gke.foo.cluster-id", cluster)
      .put("styx.gke.foo.namespace", TEST_NAMESPACE);

  if (!k8sRequestTimeoutConfig.isEmpty()) {
    configMap.put("styx.k8s.request-timeout", k8sRequestTimeoutConfig);
  }

  var config = ConfigFactory.parseMap(configMap.build());

  var gkeCluster = new Cluster();
  gkeCluster.setEndpoint(ENDPOINT);

  var masterAuth = new MasterAuth();
  masterAuth.setClusterCaCertificate(clusterCaCertificate);
  masterAuth.setClientCertificate(clientCertificate);
  masterAuth.setClientKey(clientKey);
  gkeCluster.setMasterAuth(masterAuth);

  when(gkeClusterGet.execute()).thenReturn(gkeCluster);

  return StyxScheduler.getKubernetesClient(config, "foo", gkeClient, kubernetesClientFactory);
}
 
Example #7
Source File: KubernetesMockServer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NamespacedKubernetesClient createClient() {
    Config config = new ConfigBuilder()
            .withMasterUrl(url("/"))
            .withTrustCerts(true)
            .withTlsVersions(TLS_1_0)
            .withNamespace("test")
            .build();
    return new DefaultKubernetesClient(createHttpClientForMockServer(config), config);
}
 
Example #8
Source File: KubernetesMockServer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NamespacedKubernetesClient createClient() {
    Config config = new ConfigBuilder()
            .withMasterUrl(url("/"))
            .withTrustCerts(true)
            .withTlsVersions(TLS_1_0)
            .withNamespace("test")
            .build();
    return new DefaultKubernetesClient(createHttpClientForMockServer(config), config);
}
 
Example #9
Source File: LeaderElectorBuilderTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void withConfigAndValidConfigurationShouldReturnConfig() {
  // Given
  final LeaderElectionConfig validConfig = defaultConfigBuilder.build();
  // When
  final LeaderElector<NamespacedKubernetesClient> leadElector = new LeaderElectorBuilder<>(mockKubernetesClient)
    .withConfig(validConfig).build();
  // Expect
  assertNotNull(leadElector);
}
 
Example #10
Source File: RequestConfigTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testList() throws InterruptedException {
 server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, new PodBuilder()
   .withNewMetadata()
   .withName("testPod")
   .endMetadata()
   .build()).always();

  server.expect().withPath("/api/v1/namespaces/test/pods/pod2").andReturn(200, new PodBuilder()
    .withNewMetadata()
    .withName("testPod")
    .endMetadata()
    .build()).always();

  NamespacedKubernetesClient client = server.getClient();

  Pod pod1 = client.withRequestConfig(new RequestConfigBuilder().withOauthToken("TOKEN").build()).call(c -> c.pods().inNamespace("test").withName("pod1").get());

  //Let's check that request config actually works
  RecordedRequest request1 = server.getMockServer().takeRequest();
  String authHeader1 = request1.getHeader("Authorization");
  assertEquals("Bearer TOKEN", authHeader1);

  //Let's also check that we didn't pollute client config.
  Pod pod2 = client.pods().inNamespace("test").withName("pod2").get();
  RecordedRequest request2 = server.getMockServer().takeRequest();
  String authHeader2 = request2.getHeader("Authorization");
  assertNotEquals("Bearer TOKEN", authHeader2);
}
 
Example #11
Source File: ServiceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamspacedClients() throws Exception {
    Assert.assertNotNull(kubernetesClient);
    Assert.assertNotNull(openShiftClient);

    NamespacedKubernetesClient knc = kubernetesClient.inNamespace("mytest1");
    Assert.assertEquals("mytest1", knc.getNamespace());

    NamespacedOpenShiftClient onc = openShiftClient.inNamespace("mytest2");
    Assert.assertEquals("mytest2", onc.getNamespace());
}
 
Example #12
Source File: MixedKubernetesServer.java    From flink with Apache License 2.0 4 votes vote down vote up
public NamespacedKubernetesClient getClient() {
	return client;
}
 
Example #13
Source File: StyxScheduler.java    From styx with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public static NamespacedKubernetesClient getKubernetesClient(Config config, String id) {
  return getKubernetesClient(config, id, createGkeClient(), DefaultKubernetesClient::new);
}
 
Example #14
Source File: KubernetesServer.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public NamespacedKubernetesClient getClient() {
  return client;
}
 
Example #15
Source File: ManagedKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public FunctionCallable<NamespacedKubernetesClient> withRequestConfig(RequestConfig requestConfig) {
  return delegate.withRequestConfig(requestConfig);
}
 
Example #16
Source File: ManagedKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public NamespacedKubernetesClient inNamespace(String name) {
  return delegate.inNamespace(name);
}
 
Example #17
Source File: ManagedKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public NamespacedKubernetesClient inAnyNamespace() {
  return delegate.inAnyNamespace();
}
 
Example #18
Source File: ManagedKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public LeaderElectorBuilder<NamespacedKubernetesClient> leaderElector() {
  return delegate.leaderElector();
}
 
Example #19
Source File: RequestConfigTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private void sendRequest(RequestConfig requestConfig) {
  NamespacedKubernetesClient client = server.getClient();
  client.withRequestConfig(requestConfig)
        .call(c -> c.pods().inNamespace("test").withName("podName").get());
}
 
Example #20
Source File: K8SConsecutiveAllocationPolicy.java    From dynein with Apache License 2.0 4 votes vote down vote up
public List<Integer> getPartitions() {
  String podName = System.getenv("K8S_POD_NAME");
  String namespace = System.getenv("K8S_NAMESPACE");
  NamespacedKubernetesClient namespacedClient = kubernetesClient.inNamespace(namespace);
  ReplicaSet replicaSet;

  Pod pod = namespacedClient.pods().withName(podName).get();
  String replicaSetName = pod.getMetadata().getOwnerReferences().get(0).getName();
  replicaSet = appsClient.replicaSets().inNamespace(namespace).withName(replicaSetName).get();
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> deploymentPods =
      namespacedClient.pods().withLabelSelector(replicaSet.getSpec().getSelector());

  List<String> activePods =
      deploymentPods
          .list()
          .getItems()
          .stream()
          .filter(
              isActive ->
                  isActive
                      .getStatus()
                      .getConditions()
                      .stream()
                      .anyMatch(
                          condition ->
                              condition.getType().equals(K8S_CONDITION_READY)
                                  && condition.getStatus().equals(K8S_CONDITION_TRUE)))
          .map(it -> it.getMetadata().getName())
          .sorted(Collator.getInstance())
          .collect(Collectors.toList());

  int podIndex = activePods.indexOf(podName);
  int numPods = activePods.size();

  if (numPods == 0 || podIndex == -1) {
    return new ArrayList<>();
  }
  List<Integer> partitions = new ArrayList<>();
  int split = numPartitions / numPods;
  int start = podIndex * split;
  int end = (podIndex == numPods - 1) ? numPartitions - 1 : ((podIndex + 1) * split) - 1;
  for (int i = start; i <= end; i++) {
    partitions.add(i);
  }
  return partitions;
}
 
Example #21
Source File: KubernetesServer.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public NamespacedKubernetesClient getClient() {
  return client;
}
 
Example #22
Source File: AbstractKubernetesBasedService.java    From enmasse with Apache License 2.0 4 votes vote down vote up
protected NamespacedKubernetesClient getClient() {
    return this.client;
}
 
Example #23
Source File: KubeAuthApi.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public KubeAuthApi(NamespacedKubernetesClient client, String apiToken) {
    this.client = client;
    this.namespace = client.getNamespace();
    this.apiToken = apiToken;
}