io.kubernetes.client.openapi.Configuration Java Examples

The following examples show how to use io.kubernetes.client.openapi.Configuration. 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: KubeConfigFileClientExample.java    From java with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {

    // file path to your KubeConfig
    String kubeConfigPath = "~/.kube/config";

    // loading the out-of-cluster config, a kubeconfig from file-system
    ApiClient client =
        ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();

    // invokes the CoreV1Api client
    V1PodList list =
        api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
 
Example #2
Source File: KubeOpt.java    From dew with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new Kube opt.
 *
 * @param log              the log
 * @param base64KubeConfig the base64 kube config
 */
protected KubeOpt(Logger log, String base64KubeConfig) {
    this.log = log;
    YamlHelper.init(log);
    try {
        client = Config.fromConfig(
                KubeConfig.loadKubeConfig(
                        new StringReader(
                                $.security.decodeBase64ToString(base64KubeConfig, "UTF-8")
                        )
                )
        );
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    client.setReadTimeout(0);
    Configuration.setDefaultApiClient(client);
    coreApi = new CoreV1Api(client);
    appsApi = new AppsV1Api(client);
    extensionsApi = new ExtensionsV1beta1Api(client);
    rbacAuthorizationApi = new RbacAuthorizationV1Api(client);
    autoscalingApi = new AutoscalingV2beta2Api(client);
    podLogs = new PodLogs(client);
}
 
Example #3
Source File: WatchExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  // infinite timeout
  OkHttpClient httpClient =
      client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
  client.setHttpClient(httpClient);
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();

  Watch<V1Namespace> watch =
      Watch.createWatch(
          client,
          api.listNamespaceCall(null, null, null, null, null, 5, null, null, Boolean.TRUE, null),
          new TypeToken<Watch.Response<V1Namespace>>() {}.getType());

  try {
    for (Watch.Response<V1Namespace> item : watch) {
      System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName());
    }
  } finally {
    watch.close();
  }
}
 
Example #4
Source File: CopyExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
    throws IOException, ApiException, InterruptedException, CopyNotSupportedException {
  String podName = "kube-addon-manager-minikube";
  String namespace = "kube-system";

  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  Copy copy = new Copy();
  InputStream dataStream = copy.copyFileFromPod(namespace, podName, "/etc/motd");
  ByteStreams.copy(dataStream, System.out);

  copy.copyDirectoryFromPod(namespace, podName, null, "/etc", Paths.get("/tmp/etc"));

  System.out.println("Done!");
}
 
Example #5
Source File: InClusterClientExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {

    // loading the in-cluster config, including:
    //   1. service-account CA
    //   2. service-account bearer-token
    //   3. service-account namespace
    //   4. master endpoints(ip, port) from pre-set environment variables
    ApiClient client = ClientBuilder.cluster().build();

    // if you prefer not to refresh service account token, please use:
    // ApiClient client = ClientBuilder.oldCluster().build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();

    // invokes the CoreV1Api client
    V1PodList list =
        api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
 
Example #6
Source File: LeaderElectionExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  // New
  String appNamespace = "default";
  String appName = "leader-election-foobar";
  String lockHolderIdentityName = UUID.randomUUID().toString(); // Anything unique
  EndpointsLock lock = new EndpointsLock(appNamespace, appName, lockHolderIdentityName);

  LeaderElectionConfig leaderElectionConfig =
      new LeaderElectionConfig(
          lock, Duration.ofMillis(10000), Duration.ofMillis(8000), Duration.ofMillis(2000));
  LeaderElector leaderElector = new LeaderElector(leaderElectionConfig);

  leaderElector.run(
      () -> {
        System.out.println("Do something when getting leadership.");
      },
      () -> {
        System.out.println("Do something when losing leadership.");
      });
}
 
Example #7
Source File: ExampleTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void exactUrlOnly() throws IOException, ApiException {
  ApiClient client = new ApiClient();
  client.setBasePath("http://localhost:" + PORT);
  Configuration.setDefaultApiClient(client);

  V1Namespace ns1 = new V1Namespace().metadata(new V1ObjectMeta().name("name"));

  stubFor(
      get(urlEqualTo("/api/v1/namespaces/name"))
          .willReturn(
              aResponse()
                  .withHeader("Content-Type", "application/json")
                  .withBody(client.getJSON().serialize(ns1))));

  CoreV1Api api = new CoreV1Api();
  V1Namespace ns2 = api.readNamespace("name", null, null, null);
  assertEquals(ns1, ns2);
}
 
Example #8
Source File: PodWatchUtils.java    From twister2 with Apache License 2.0 5 votes vote down vote up
private static void createApiInstances() {

    try {
      apiClient = io.kubernetes.client.util.Config.defaultClient();
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "Exception when creating ApiClient: ", e);
      throw new RuntimeException(e);
    }

    OkHttpClient httpClient =
        apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);
    Configuration.setDefaultApiClient(apiClient);
    coreApi = new CoreV1Api(apiClient);
  }
 
Example #9
Source File: FluentExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();

  V1Pod pod =
      new V1PodBuilder()
          .withNewMetadata()
          .withName("apod")
          .endMetadata()
          .withNewSpec()
          .addNewContainer()
          .withName("www")
          .withImage("nginx")
          .endContainer()
          .endSpec()
          .build();

  api.createNamespacedPod("default", pod, null, null, null);

  V1Pod pod2 =
      new V1Pod()
          .metadata(new V1ObjectMeta().name("anotherpod"))
          .spec(
              new V1PodSpec()
                  .containers(Arrays.asList(new V1Container().name("www").image("nginx"))));

  api.createNamespacedPod("default", pod2, null, null, null);

  V1PodList list =
      api.listNamespacedPod("default", null, null, null, null, null, null, null, null, null);
  for (V1Pod item : list.getItems()) {
    System.out.println(item.getMetadata().getName());
  }
}
 
Example #10
Source File: YamlExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException, ClassNotFoundException {
  V1Pod pod =
      new V1PodBuilder()
          .withNewMetadata()
          .withName("apod")
          .endMetadata()
          .withNewSpec()
          .addNewContainer()
          .withName("www")
          .withImage("nginx")
          .withNewResources()
          .withLimits(new HashMap<>())
          .endResources()
          .endContainer()
          .endSpec()
          .build();
  System.out.println(Yaml.dump(pod));

  V1Service svc =
      new V1ServiceBuilder()
          .withNewMetadata()
          .withName("aservice")
          .endMetadata()
          .withNewSpec()
          .withSessionAffinity("ClientIP")
          .withType("NodePort")
          .addNewPort()
          .withProtocol("TCP")
          .withName("client")
          .withPort(8008)
          .withNodePort(8080)
          .withTargetPort(new IntOrString(8080))
          .endPort()
          .endSpec()
          .build();
  System.out.println(Yaml.dump(svc));

  // Read yaml configuration file, and deploy it
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  //  See issue #474. Not needed at most cases, but it is needed if you are using war
  //  packging or running this on JUnit.
  Yaml.addModelMap("v1", "Service", V1Service.class);

  // Example yaml file can be found in $REPO_DIR/test-svc.yaml
  File file = new File("test-svc.yaml");
  V1Service yamlSvc = (V1Service) Yaml.load(file);

  // Deployment and StatefulSet is defined in apps/v1, so you should use AppsV1Api instead of
  // CoreV1API
  CoreV1Api api = new CoreV1Api();
  V1Service createResult = api.createNamespacedService("default", yamlSvc, null, null, null);

  System.out.println(createResult);

  V1Status deleteResult =
      api.deleteNamespacedService(
          yamlSvc.getMetadata().getName(),
          "default",
          null,
          null,
          null,
          null,
          null,
          new V1DeleteOptions());
  System.out.println(deleteResult);
}
 
Example #11
Source File: ProtoExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException, InterruptedException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  ProtoClient pc = new ProtoClient(client);
  ObjectOrStatus<PodList> list = pc.list(PodList.newBuilder(), "/api/v1/namespaces/default/pods");

  if (list.object.getItemsCount() > 0) {
    Pod p = list.object.getItems(0);
    System.out.println(p);
  }

  Namespace namespace =
      Namespace.newBuilder().setMetadata(ObjectMeta.newBuilder().setName("test").build()).build();

  ObjectOrStatus<Namespace> ns = pc.create(namespace, "/api/v1/namespaces", "v1", "Namespace");
  System.out.println(ns);
  if (ns.object != null) {
    namespace =
        ns.object
            .toBuilder()
            .setSpec(NamespaceSpec.newBuilder().addFinalizers("test").build())
            .build();
    // This is how you would update an object, but you can't actually
    // update namespaces, so this returns a 405
    ns = pc.update(namespace, "/api/v1/namespaces/test", "v1", "Namespace");
    System.out.println(ns.status);
  }

  ns = pc.delete(Namespace.newBuilder(), "/api/v1/namespaces/test");
  System.out.println(ns);
}
 
Example #12
Source File: TokenFileAuthenticationTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  final ApiClient client = new ApiClient();
  client.setBasePath("http://localhost:" + PORT);
  this.auth = new TokenFileAuthentication(SERVICEACCOUNT_TOKEN1_PATH);
  this.auth.provide(client);
  Configuration.setDefaultApiClient(client);
}
 
Example #13
Source File: Example.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();
  V1PodList list =
      api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  for (V1Pod item : list.getItems()) {
    System.out.println(item.getMetadata().getName());
  }
}
 
Example #14
Source File: LogsExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException, InterruptedException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);
  CoreV1Api coreApi = new CoreV1Api(client);

  PodLogs logs = new PodLogs();
  V1Pod pod =
      coreApi
          .listNamespacedPod("default", "false", null, null, null, null, null, null, null, null)
          .getItems()
          .get(0);

  InputStream is = logs.streamNamespacedPodLog(pod);
  ByteStreams.copy(is, System.out);
}
 
Example #15
Source File: PagerExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {

    ApiClient client = Config.defaultClient();
    OkHttpClient httpClient =
        client.getHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
    client.setHttpClient(httpClient);
    Configuration.setDefaultApiClient(client);
    CoreV1Api api = new CoreV1Api();
    int i = 0;
    Pager<V1Namespace, V1NamespaceList> pager =
        new Pager<V1Namespace, V1NamespaceList>(
            (Pager.PagerParams param) -> {
              try {
                return api.listNamespaceCall(
                    null,
                    null,
                    param.getContinueToken(),
                    null,
                    null,
                    param.getLimit(),
                    null,
                    1,
                    null,
                    null);
              } catch (Exception e) {
                throw new RuntimeException(e);
              }
            },
            client,
            10,
            V1NamespaceList.class);
    for (V1Namespace namespace : pager) {
      System.out.println(namespace.getMetadata().getName());
    }
    System.out.println("------------------");
  }
 
Example #16
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Create an instance of K8 api client and initialize with the KUBERNETES config. The config used follows the below pattern.
 *      1. If $KUBECONFIG is defined, use that config file.
 *      2. If $HOME/.kube/config can be found, use that.
 *      3. If the in-cluster service account can be found, assume in cluster config.
 *      4. Default to localhost:8080 as a last resort.
 */
private ApiClient initializeApiClient() {
    ApiClient client;
    try {
        log.debug("Initialize KUBERNETES api client");
        client = Config.defaultClient();
        client.setDebugging(false); // this can be set to true enable http dump.
        client.setHttpClient(client.getHttpClient().newBuilder().readTimeout(DEFAULT_TIMEOUT_MINUTES, TimeUnit.MINUTES).build());
        Configuration.setDefaultApiClient(client);
        Runtime.getRuntime().addShutdownHook(new Thread(this::close));
    } catch (IOException e) {
        throw new TestFrameworkException(ConnectionFailed, "Connection to the k8 cluster failed, ensure .kube/config is configured correctly.", e);
    }
    return client;
}
 
Example #17
Source File: KubernetesController.java    From twister2 with Apache License 2.0 5 votes vote down vote up
/**
 * create CoreV1Api that does not time out
 */
public static CoreV1Api createCoreV1Api() {
  if (client == null) {
    getApiClient();
  }
  OkHttpClient httpClient =
      client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
  client.setHttpClient(httpClient);
  Configuration.setDefaultApiClient(client);
  return new CoreV1Api(client);
}
 
Example #18
Source File: AppsV1Controller.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
AppsV1Controller(Config configuration, Config runtimeConfiguration) {
  super(configuration, runtimeConfiguration);
  try {
    final ApiClient apiClient = io.kubernetes.client.util.Config.defaultClient();
    Configuration.setDefaultApiClient(apiClient);
    appsClient = new AppsV1Api(apiClient);
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Failed to setup Kubernetes client" + e);
    throw new RuntimeException(e);
  }
}
 
Example #19
Source File: GenericKubernetesApi.java    From java with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new Generic kubernetes api.
 *
 * @param apiTypeClass the api type class
 * @param apiListTypeClass the api list type class
 * @param apiGroup the api group
 * @param apiVersion the api version
 * @param resourcePlural the resource plural
 */
public GenericKubernetesApi(
    Class<ApiType> apiTypeClass,
    Class<ApiListType> apiListTypeClass,
    String apiGroup,
    String apiVersion,
    String resourcePlural) {
  this(
      apiTypeClass,
      apiListTypeClass,
      apiGroup,
      apiVersion,
      resourcePlural,
      new CustomObjectsApi(Configuration.getDefaultApiClient()));
}
 
Example #20
Source File: DemoApplication.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/hello")
public String hello() throws Exception {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);

    CoreV1Api api = new CoreV1Api();
    V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);

    List<String> rlt = new ArrayList<>();
    rlt.add(new Date().toString());
    rlt.addAll(list.getItems().stream().map(value -> value.getMetadata().getNamespace() + ":" + value.getMetadata().getName()).collect(Collectors.toList()));
    return new Gson().toJson(rlt);
}
 
Example #21
Source File: NetworkingApi.java    From java with Apache License 2.0 4 votes vote down vote up
public NetworkingApi() {
    this(Configuration.getDefaultApiClient());
}
 
Example #22
Source File: SchedulingV1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public SchedulingV1Api() {
    this(Configuration.getDefaultApiClient());
}
 
Example #23
Source File: SchedulingV1beta1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public SchedulingV1beta1Api() {
    this(Configuration.getDefaultApiClient());
}
 
Example #24
Source File: CertificatesApi.java    From java with Apache License 2.0 4 votes vote down vote up
public CertificatesApi() {
    this(Configuration.getDefaultApiClient());
}
 
Example #25
Source File: LogsApi.java    From java with Apache License 2.0 4 votes vote down vote up
public LogsApi() {
    this(Configuration.getDefaultApiClient());
}
 
Example #26
Source File: StorageApi.java    From java with Apache License 2.0 4 votes vote down vote up
public StorageApi() {
    this(Configuration.getDefaultApiClient());
}
 
Example #27
Source File: ConfigMapLock.java    From java with Apache License 2.0 4 votes vote down vote up
public ConfigMapLock(String namespace, String name, String identity) {
  this(namespace, name, identity, Configuration.getDefaultApiClient());
}
 
Example #28
Source File: RbacAuthorizationApi.java    From java with Apache License 2.0 4 votes vote down vote up
public RbacAuthorizationApi() {
    this(Configuration.getDefaultApiClient());
}
 
Example #29
Source File: DiscoveryApi.java    From java with Apache License 2.0 4 votes vote down vote up
public DiscoveryApi() {
    this(Configuration.getDefaultApiClient());
}
 
Example #30
Source File: NetworkingV1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public NetworkingV1Api() {
    this(Configuration.getDefaultApiClient());
}