kubectl vs json api for customdefinition or operator - kubernetes

is it possible to use json api instead of all kubectl commands.
Also how would be update a resource or custom definition in that case.

You could take a look at API client libraries.
To call the Kubernetes API from a programming language, you can use client libraries. Officially supported client libraries:
Kubernetes Go client library
Kubernetes Python client library
Kubernetes Java client library
Kubernetes JavaScript client library
To write applications using the Kubernetes REST API, you do not need to implement the API calls and request/response types yourself. You can use a client library for the programming language you are using.
Client libraries often handle common tasks such as authentication for you. Most client libraries can discover and use the Kubernetes Service Account to authenticate if the API client is running inside the Kubernetes cluster, or can understand the kubeconfig file format to read the credentials and the API Server address.
The two paths that support extending the API with custom resources are:
CustomResourceDefinition for basic CRUD needs.
aggregator for a full set of Kubernetes API semantics to
implement their own apiserver.
For example there is a way of creating crd resource with python and some code examples.
list all pods
from kubernetes import client, config
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
watch on namespace object:
from kubernetes import client, config, watch
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.CoreV1Api()
count = 10
w = watch.Watch()
for event in w.stream(v1.list_namespace, _request_timeout=60):
print("Event: %s %s" % (event['type'], event['object'].metadata.name))
count -= 1
if not count:
w.stop()
print("Ended.")
More examples can be found in examples folder.

Related

How can I remotely call the kube-apiserver command via REST operations?

There is a command kube-apiserver --feature-gates=APIPriorityAndFairness=true --runtime-config=flowcontrol.apiserver.k8s.io/v1beta1=true,flowcontrol.apiserver.k8s.io/v1beta2=true. But it seems like run on the master machine.
Now I want to remotely call the command in my laptop. I have connected the master machine via kubeconfig already.
Which statement or format of statement should I use to accomplish this function?
Please refer Kubernetes API access documentation how you can programmatically send API requests. Kubernetes supports various mechanisms and various clients in GO, Python, Java etc to send api requests. Below is the sample python code which will list all the pods from all namespaces.
from kubernetes import client, config
config.load_kube_config()
v1=client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
Also when follow command is executed "kubectl get pods -v 9" it will give verbose information of rest request which kubectl tool will send to api server, this will help you to understand how to construct the api requests.
I don't know if it is a real question.
This command kube-apiserver --feature-gates=APIPriorityAndFairness=true --runtime-config=flowcontrol.apiserver.k8s.io/v1beta1=true,flowcontrol.apiserver.k8s.io/v1beta2=true seems not like kubectl xxx. It's not a service that cluster offers to user to use.
I ssh the master machine to modify some flag or properties of the api-server.

Is there an python API function to read labels from kubernetes statefulsets?

I am trying to find an API function to read the keys and values of all the labels in a kubernetes statefulset. Can anyone point me to an example or documentation on how this can be done?
Have you taken a look at this library?
https://github.com/kubernetes-client/python
Utilizing the above library, the way that I would do to achieve what you want is:
from kubernetes import client, config
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.AppsV1Api()
print("Listing StatefulSets' labels:")
ret = v1.list_stateful_set_for_all_namespaces(watch=False)
for i in ret.items:
print(i.metadata.labels)

GKE pod replica count in cluster

How can we obtain the gke pod counts running in the cluster? I found there are ways to get node count but we needed pod count as well. it will be better if we can use something with no logging needed in gcp operations.
You can do it with Kubernetes Python Client library as shown in this question, posted by Pradeep Padmanaban C, where he was looking for more effective way of doing it, but his example is actually the best what you can do to perform such operation as there is no specific method which would allow you just to count pods without retrieving their entire json manifests:
from kubernetes import client , config
config.load_kube_config()
v1= client.CoreV1Api()
ret_pod = v1.list_pod_for_all_namespaces(watch=False)
print(len(ret_pod.items))
You can also use a different method, which allows to retrieve pods only from specific namespace e.g.:
list_namespaced_pod("default")
In kubectl way you can do it as follows (as proposed here by RammusXu):
kubectl get pods --all-namespaces --no-headers | wc -l
You can directly access the kubernetes API using a restful API call. You will need to make sure you provide the authentication token in your call by including a bearer token.
Once you are able to query the api server directly, you can use GET <master_endpoint>/api/v1/pods to list all the pods in the cluster. You can also search for specific namespaces by specifying the namespace /api/v1/namespaces/<namespace>/pods.
Keep in mind that the kubectl cli tool is just a wrapper for API calls, each kubectl command will form a RESTful API call in a similar format to the one listed above, so any interaction you have with the cluster using kubectl can also be achieved through RESTful API calls

Kube API for Listing the CustomResource instances in a namespace (or on a cluster) in Kubernetes

Using command-line utility kubectl we can list a custom resource instances as follows
kubectl get <customresource_kind>
In a similar fashion, do we have a REST API to achieve the same? i.e. the API takes the Kind of the CustomResource and lists all the instances created?
I am referring to this API Reference :
https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/
You can list crds like every other API resources using Kubernetes REST API.
The final URL path will differ, depending on object's scope: Cluster or Namespaced.
The general rule for constructing the URL path is described here in official documentation.
Just to give you an example based on calico's clusterinformations.crd.projectcalico.org (v1):
kubectl proxy --port=8080 &
curl http://localhost:8080/apis/crd.projectcalico.org/v1/clusterinformations | jq '.items[].metadata.name
"default" <- I have only one instance of this type of custom resource

Is there any API or go programming logic to get capacity of node in a kubernetes cluster?

Using kubectl describe nodes, i am able to get the capacity of resources(memory,cpu) of a node. I want to get the same via go client or kube API (if available). Can anyone help me out?
i am using minikube version: v1.7.2
kubectl version :
Client : GitVersion:"v1.16.3"
Server : GitVersion:"v1.16.2"
I am using metric-server to access the kubernetes resource.
Expected result:
Capacity of resources should be accessible through go program or kube API
There isn't any API call you could use to get kubectl describe nodes this is because this command is generating all the output.
Kubectl retrieves all relevant pods (every pod that isn't failed or succeeded) on a node and sums up all their resource definitions.
You can look into the code and find the function responsible for generating information about node here.
Same for collecting all requests and limits for pods, function is available here and it's called getPodsTotalRequestsAndLimits
Lastly the function what puts all that together can be seen here.
There is a really nice article about Kubernetes API: Allocatable Node Resources? The author is doing exactly what you are asking for but using Python.
Kubernetes Client libraries are the ones you need to look at https://kubernetes.io/docs/reference/using-api/client-libraries/#officially-supported-kubernetes-client-libraries
The following client libraries are officially maintained by Kubernetes SIG API Machinery.
Language Client Library
Go github.com/kubernetes/client-go/
Python github.com/kubernetes-client/python/
Java github.com/kubernetes-client/java
dotnet github.com/kubernetes-client/csharp
JavaScript github.com/kubernetes-client/javascript
Haskell github.com/kubernetes-client/haskell
Community-maintained client libraries
The following Kubernetes API client libraries are provided and maintained by their authors, not the Kubernetes team.
Language Client Library
Clojure github.com/yanatan16/clj-kubernetes-api
Go github.com/ericchiang/k8s
Java (OSGi) bitbucket.org/amdatulabs/amdatu-kubernetes
Java (Fabric8, OSGi) github.com/fabric8io/kubernetes-client
Lisp github.com/brendandburns/cl-k8s
Lisp github.com/xh4/cube
Node.js (TypeScript) github.com/Goyoo/node-k8s-client
Node.js github.com/tenxcloud/node-kubernetes-client
Node.js github.com/godaddy/kubernetes-client
Node.js github.com/ajpauwels/easy-k8s
Perl metacpan.org/pod/Net::Kubernetes
PHP github.com/maclof/kubernetes-client
PHP github.com/allansun/kubernetes-php-client
PHP github.com/travisghansen/kubernetes-client-php
Python github.com/eldarion-gondor/pykube
Python github.com/mnubo/kubernetes-py
Python github.com/tomplus/kubernetes_asyncio
Ruby github.com/Ch00k/kuber
Ruby github.com/abonas/kubeclient
Ruby github.com/kontena/k8s-client
Rust github.com/clux/kube-rs
Rust github.com/ynqa/kubernetes-rust
Scala github.com/doriordan/skuber
dotNet github.com/tonnyeremin/kubernetes_gen
DotNet (RestSharp) github.com/masroorhasan/Kubernetes.DotNet
Elixir github.com/obmarg/kazan
Elixir github.com/coryodaniel/k8s
Haskell github.com/kubernetes-client/haskell