Java Code Examples for io.fabric8.kubernetes.client.KubernetesClient#adapt()

The following examples show how to use io.fabric8.kubernetes.client.KubernetesClient#adapt() . 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: AdaptTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedClient() {
  server.expect().withPath("/apis").andReturn(200, new APIGroupListBuilder()
    .addNewGroup()
    .withApiVersion("v1")
    .withName("autoscaling.k8s.io")
    .endGroup()
    .addNewGroup()
    .withApiVersion("v1")
    .withName("security.openshift.io")
    .endGroup()
    .build()).once();

  KubernetesClient client = server.getClient();
  OpenShiftClient oclient = client.adapt(OpenShiftClient.class);
  assertNotNull(client.adapt(OkHttpClient.class));
  assertNotNull(oclient.adapt(OkHttpClient.class));
}
 
Example 2
Source File: URLFromOpenshiftRouteImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public String getURL(Service service, String portName, String namespace, KubernetesClient client) {
  String serviceName = service.getMetadata().getName();
  ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName);
  if(port != null && port.getName() != null && isOpenShift(client)) {
    try {
      String serviceProtocol = port.getProtocol();
      OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
      Route route = openShiftClient.routes().inNamespace(namespace).withName(service.getMetadata().getName()).get();
      if (route != null) {
        return (serviceProtocol + "://" + route.getSpec().getHost()).toLowerCase(Locale.ROOT);
      }
    } catch (KubernetesClientException e) {
      if(e.getCode() == HttpURLConnection.HTTP_FORBIDDEN) {
        logger.warn("Could not lookup route:" + serviceName + " in namespace:"+ namespace +", due to: " + e.getMessage());
      }
    }
  }
  return null;
}
 
Example 3
Source File: OpenshiftHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static OpenShiftClient asOpenShiftClient(KubernetesClient client) {
    if (client instanceof OpenShiftClient) {
        return (OpenShiftClient) client;
    }
    try {
        return client.adapt(OpenShiftClient.class);
    } catch (KubernetesClientException | OpenShiftNotAvailableException e) {
        return null;
    }
}
 
Example 4
Source File: ResourceOperatorSupplier.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public ResourceOperatorSupplier(Vertx vertx, KubernetesClient client, ZookeeperLeaderFinder zlf,
                                AdminClientProvider adminClientProvider, ZookeeperScalerProvider zkScalerProvider,
                                MetricsProvider metricsProvider, PlatformFeaturesAvailability pfa, long operationTimeoutMs) {
    this(new ServiceOperator(vertx, client),
            pfa.hasRoutes() ? new RouteOperator(vertx, client.adapt(OpenShiftClient.class)) : null,
            new ZookeeperSetOperator(vertx, client, zlf, operationTimeoutMs),
            new KafkaSetOperator(vertx, client, operationTimeoutMs, adminClientProvider),
            new ConfigMapOperator(vertx, client),
            new SecretOperator(vertx, client),
            new PvcOperator(vertx, client),
            new DeploymentOperator(vertx, client),
            new ServiceAccountOperator(vertx, client),
            new RoleBindingOperator(vertx, client),
            new ClusterRoleBindingOperator(vertx, client, operationTimeoutMs),
            new NetworkPolicyOperator(vertx, client),
            new PodDisruptionBudgetOperator(vertx, client),
            new PodOperator(vertx, client),
            new IngressOperator(vertx, client),
            pfa.hasImages() ? new ImageStreamOperator(vertx, client.adapt(OpenShiftClient.class)) : null,
            pfa.hasBuilds() ? new BuildConfigOperator(vertx, client.adapt(OpenShiftClient.class)) : null,
            pfa.hasApps() ? new DeploymentConfigOperator(vertx, client.adapt(OpenShiftClient.class)) : null,
            new CrdOperator<>(vertx, client, Kafka.class, KafkaList.class, DoneableKafka.class, Crds.kafka()),
            new CrdOperator<>(vertx, client, KafkaConnect.class, KafkaConnectList.class, DoneableKafkaConnect.class, Crds.kafkaConnect()),
            pfa.hasBuilds() && pfa.hasApps() && pfa.hasImages() ? new CrdOperator<>(vertx, client.adapt(OpenShiftClient.class), KafkaConnectS2I.class, KafkaConnectS2IList.class, DoneableKafkaConnectS2I.class, Crds.kafkaConnectS2I()) : null,
            new CrdOperator<>(vertx, client, KafkaMirrorMaker.class, KafkaMirrorMakerList.class, DoneableKafkaMirrorMaker.class, Crds.kafkaMirrorMaker()),
            new CrdOperator<>(vertx, client, KafkaBridge.class, KafkaBridgeList.class, DoneableKafkaBridge.class, Crds.kafkaBridge()),
            new CrdOperator<>(vertx, client, KafkaConnector.class, KafkaConnectorList.class, DoneableKafkaConnector.class, Crds.kafkaConnector()),
            new CrdOperator<>(vertx, client, KafkaMirrorMaker2.class, KafkaMirrorMaker2List.class, DoneableKafkaMirrorMaker2.class, Crds.kafkaMirrorMaker2()),
            new CrdOperator<>(vertx, client, KafkaRebalance.class, KafkaRebalanceList.class, DoneableKafkaRebalance.class, Crds.kafkaRebalance()),
            new StorageClassOperator(vertx, client, operationTimeoutMs),
            new NodeOperator(vertx, client, operationTimeoutMs),
            zkScalerProvider,
            metricsProvider);
}
 
Example 5
Source File: PlatformFeaturesAvailability.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private static OkHttpClient getOkHttpClient(KubernetesClient client)   {
    if (client.isAdaptable(OkHttpClient.class)) {
        return client.adapt(OkHttpClient.class);
    } else {
        log.error("Cannot adapt KubernetesClient to OkHttpClient");
        throw new RuntimeException("Cannot adapt KubernetesClient to OkHttpClient");
    }
}
 
Example 6
Source File: CustomResourceCondition.java    From dekorate with Apache License 2.0 4 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
 Optional<OnCustomResourcePresentCondition> annotation = context.getElement().map(e -> e.getAnnotation(OnCustomResourcePresentCondition.class));
 if (!annotation.isPresent()) {
  return ConditionEvaluationResult.enabled("Condition not found!");
 }
 OnCustomResourcePresentCondition condition = annotation.get();
  try {
    String apiVersion = condition.apiVersion();
    String kind = condition.kind();
    String plural = Strings.isNotNullOrEmpty(condition.plural()) ? condition.plural() : Pluralize.FUNCTION.apply(kind).toLowerCase();
    String name = condition.name();
    String namespace = condition.namespace();

    KubernetesClient client = getKubernetesClient(context);
    Config config = client.getConfiguration();
    OkHttpClient http = client.adapt(OkHttpClient.class);

    List<String> parts = new ArrayList<>();
    parts.add(config.getMasterUrl());
    parts.add("apis");
    parts.add(apiVersion);

    if (Strings.isNotNullOrEmpty(namespace)) {
      parts.add("namespaces");
      parts.add(namespace);
    }

    parts.add(plural);
    if (Strings.isNotNullOrEmpty(name)) {
      parts.add(name);
    }
    parts.add(plural);
    String requestUrl = URLUtils.join(parts.stream().toArray(s->new String[s]));
    Request request = new Request.Builder().get().url(requestUrl).build();
    Response response = http.newCall(request).execute();

    if (!response.isSuccessful()) {
      return ConditionEvaluationResult.disabled("Could not lookup custom resource.");
    }


    //TODO: Add support for cases where name() is empty. In this case the result will be a list.
    //We need to check if empty.
    return ConditionEvaluationResult.enabled("Found resource with apiVersion:" + apiVersion + " kind:" + kind + " namespace: " + (Strings.isNullOrEmpty(namespace) ? "any" : namespace) + " name: " + (Strings.isNullOrEmpty(name) ? "any" : name));

  } catch (Throwable t) {
    return ConditionEvaluationResult.disabled("Could not lookup for service.");
  }
}
 
Example 7
Source File: AdaptClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  KubernetesClient client = new DefaultKubernetesClient();
  OpenShiftClient oclient = client.adapt(OpenShiftClient.class);
  System.out.println("Adapted to an openshift client: " + oclient);
}
 
Example 8
Source File: DeploymentConfigExamples.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  Config config = new ConfigBuilder().build();
  KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);
  OpenShiftClient client = kubernetesClient.adapt(OpenShiftClient.class);

  try {
    ProjectRequest  projectRequest = new ProjectRequestBuilder()
        .withNewMetadata()
          .withName("thisisatest")
          .addToLabels("project", "thisisatest")
        .endMetadata()
        .build();


    log("Created project", client.projectrequests().create(projectRequest));

    ServiceAccount fabric8 = new ServiceAccountBuilder().withNewMetadata().withName("fabric8").endMetadata().build();

    client.serviceAccounts().inNamespace("thisisatest").createOrReplace(fabric8);

    log("Created deployment", client.deploymentConfigs().inNamespace("thisisatest").createOrReplaceWithNew()
      .withNewMetadata()
        .withName("nginx")
      .endMetadata()
      .withNewSpec()
        .withReplicas(1)
        .addNewTrigger()
          .withType("ConfigChange")
        .endTrigger()
        .addToSelector("app", "nginx")
        .withNewTemplate()
          .withNewMetadata()
            .addToLabels("app", "nginx")
          .endMetadata()
          .withNewSpec()
            .addNewContainer()
              .withName("nginx")
              .withImage("nginx")
              .addNewPort()
                .withContainerPort(80)
              .endPort()
            .endContainer()
          .endSpec()
        .endTemplate()
      .endSpec()
      .done());


    client.deploymentConfigs().inNamespace("thisisatest").withName("nginx").scale(2, true);
    log("Created pods:", client.pods().inNamespace("thisisatest").list().getItems());
    client.deploymentConfigs().inNamespace("thisisatest").withName("nginx").delete();
    log("Pods:", client.pods().inNamespace("thisisatest").list().getItems());
    log("Replication Controllers:", client.replicationControllers().inNamespace("thisisatest").list().getItems());

    log("Done.");
  }finally {
   // client.projects().withName("thisisatest").delete();
    client.close();
  }
}
 
Example 9
Source File: OpenShiftClientRegistryImpl.java    From brooklyn-server with Apache License 2.0 3 votes vote down vote up
/**
 * The default OpenShift URL is set using the Kubernetes
 * {@code KubernetesLocationConfig#MASTER_URL master URL} as follows:
 * <pre>
 * openShiftUrl = URLUtils.join(getMasterUrl(), "oapi", oapiVersion);
 * </pre>
 */
@Override
public KubernetesClient getKubernetesClient(ConfigBag conf) {
    KubernetesClient client = super.getKubernetesClient(conf);
    OpenShiftClient oClient = client.adapt(OpenShiftClient.class);
    return oClient;
}