io.kubernetes.client.util.Config Java Examples
The following examples show how to use
io.kubernetes.client.util.Config.
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: KubernetesEnvImpl.java From kruize with Apache License 2.0 | 6 votes |
private boolean checkMonitoringAgentRunning() throws IOException, ApiException { ApiClient client = Config.defaultClient(); Configuration.setDefaultApiClient(client); CoreV1Api api = new CoreV1Api(); V1ServiceList serviceList = api.listServiceForAllNamespaces( null, null, null, null, null, null, null, null, null ); for (V1Service service : serviceList.getItems()) { String serviceName = service.getMetadata().getName(); if (serviceName.toUpperCase().contains(DeploymentInfo.getMonitoringAgent())) return true; } return false; }
Example #2
Source File: KubeClusterMembershipConnectorComponent.java From titus-control-plane with Apache License 2.0 | 6 votes |
@Bean public ApiClient getApiClient(KubeConnectorConfiguration configuration) { String kubeApiServerUri = StringExt.safeTrim(configuration.getKubeApiServerUri()); String kubeConfigPath = StringExt.safeTrim(configuration.getKubeConfigPath()); Preconditions.checkState(!kubeApiServerUri.isEmpty() || !kubeConfigPath.isEmpty(), "Kubernetes address not set" ); ApiClient client; if (kubeApiServerUri.isEmpty()) { try { logger.info("Initializing Kube ApiClient from config file: {}", kubeConfigPath); client = Config.fromConfig(kubeConfigPath); } catch (IOException e) { throw new RuntimeException(e); } } else { logger.info("Initializing Kube ApiClient with URI: {}", kubeApiServerUri); client = Config.fromUrl(kubeApiServerUri); } client.setReadTimeout(0); // infinite timeout return client; }
Example #3
Source File: KubeOpt.java From dew with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: WatchExample.java From java with Apache License 2.0 | 6 votes |
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 #5
Source File: LeaderElectionExample.java From java with Apache License 2.0 | 6 votes |
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 #6
Source File: CopyExample.java From java with Apache License 2.0 | 6 votes |
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 #7
Source File: K8sClient.java From pravega with Apache License 2.0 | 5 votes |
/** * 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 #8
Source File: KubernetesJobResource.java From HolandaCatalinaFw with Apache License 2.0 | 5 votes |
public KubernetesJobResource() { try { client = Config.fromCluster(); } catch (IOException e) { throw new RuntimeException(); } Configuration.setDefaultApiClient(client); this.coreApi = new CoreV1Api(); this.batchApi = new BatchV1Api(); }
Example #9
Source File: KubernetesSpyResource.java From HolandaCatalinaFw with Apache License 2.0 | 5 votes |
public KubernetesSpyResource() { super(NAME); try { client = Config.fromCluster(); } catch (IOException e) { throw new RuntimeException(); } Configuration.setDefaultApiClient(client); this.api = new CoreV1Api(); this.batchApi = new BatchV1Api(); }
Example #10
Source File: DemoApplication.java From blog_demos with Apache License 2.0 | 5 votes |
@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 #11
Source File: KubeApiClients.java From titus-control-plane with Apache License 2.0 | 5 votes |
public static ApiClient createApiClient(String kubeApiServerUrl, String kubeConfigPath, String metricsNamePrefix, TitusRuntime titusRuntime, Function<Request, String> uriMapper, long readTimeoutMs) { OkHttpMetricsInterceptor metricsInterceptor = new OkHttpMetricsInterceptor(metricsNamePrefix, titusRuntime.getRegistry(), titusRuntime.getClock(), uriMapper); ApiClient client; if (Strings.isNullOrEmpty(kubeApiServerUrl)) { try { client = Config.fromConfig(kubeConfigPath); } catch (IOException e) { throw new RuntimeException(e); } } else { client = Config.fromUrl(kubeApiServerUrl); } client.setHttpClient( client.getHttpClient().newBuilder() .addInterceptor(metricsInterceptor) .readTimeout(readTimeoutMs, TimeUnit.SECONDS) .build() ); return client; }
Example #12
Source File: ParseExample.java From java with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException, ApiException, ClassNotFoundException { if (args.length < 2) { System.err.println("Usage: ParseExample <file-name> <class-name e.g. V1Pod>"); System.exit(1); } ApiClient client = Config.defaultClient(); FileReader json = new FileReader(args[0]); Object obj = client .getJSON() .getGson() .fromJson(json, Class.forName("io.kubernetes.client.models." + args[1])); String output = client.getJSON().getGson().toJson(obj); // Test round tripping... Object obj2 = client .getJSON() .getGson() .fromJson( new StringReader(output), Class.forName("io.kubernetes.client.models." + args[1])); String output2 = client.getJSON().getGson().toJson(obj2); // Validate round trip if (!output.equals(output2)) { System.err.println("Error, expected:\n" + output + "\nto equal\n" + output2); System.exit(2); } System.out.println(output); }
Example #13
Source File: LogsExample.java From java with Apache License 2.0 | 5 votes |
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 #14
Source File: ProtoExample.java From java with Apache License 2.0 | 5 votes |
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 #15
Source File: FluentExample.java From java with Apache License 2.0 | 5 votes |
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 #16
Source File: YamlExample.java From java with Apache License 2.0 | 5 votes |
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 #17
Source File: PagerExample.java From java with Apache License 2.0 | 5 votes |
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 #18
Source File: Example.java From java with Apache License 2.0 | 5 votes |
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 #19
Source File: KubernetesClient.java From cubeai with Apache License 2.0 | 5 votes |
public KubernetesClient(String k8sApiUrl, String k8sApiToken, String nameSpace) { Configuration.setDefaultApiClient(Config.fromToken(k8sApiUrl, k8sApiToken, false)); this.coreApi = new CoreV1Api(); this.appsApi = new AppsV1Api(); this.networkingApi = new NetworkingV1Api(); this.nameSpace = nameSpace; }
Example #20
Source File: KubernetesEnvImpl.java From kruize with Apache License 2.0 | 5 votes |
private void getMonitoringEndpointFromService() throws IOException, ApiException { ApiClient client = Config.defaultClient(); Configuration.setDefaultApiClient(client); CoreV1Api api = new CoreV1Api(); V1ServiceList serviceList = api.listServiceForAllNamespaces( null, null, null, null, null, null, null, null, null ); for (V1Service service : serviceList.getItems()) { String serviceName = service.getMetadata().getName(); if (serviceName.toUpperCase().equals(DeploymentInfo.getMonitoringAgentService())) { String clusterIP = service.getSpec().getClusterIP(); int port = service.getSpec().getPorts().get(0).getPort(); DeploymentInfo.setMonitoringAgentEndpoint("http://" + clusterIP + ":" + port); } } }
Example #21
Source File: KubernetesOperation.java From k8s-Azure-Container-Service-AKS--on-Azure with MIT License | 4 votes |
/** * Constructor */ public KubernetesOperation() { ApiClient client = Config.fromToken(API_SERVER_NAME, ACCESS_TOKEN, false); Configuration.setDefaultApiClient(client); corev1Api = new CoreV1Api(client); }