This article presuppositions several, will pay attention to kubectl in what the students, basically already have a certain understanding of K8S, at least has used Kubectl to explore some of the basic functions of K8S.

Above is an architecture diagram of k8S core components, which shows that Kubectl only deals with Apiserver. Exploring what Kubectl is doing is about exploring what Apiserver offers.

So let’s take a look at what Apiserver provides in general.

Kubectl proxy Starting to serve on 127.0.0.1:8001Copy the code

The preceding command is used to enable apiserver proxy on a Kubectl executable node. You can use curl to access apiserver without authentication.

The curl http://127.0.0.1:8001/ {" paths ": [ "/api", "/api/v1", "/apis", "...", "/apis/apiextensions.k8s.io/v1", "/healthz", "/...", "/healthz/poststarthook/apiservice-openapi-controller", "...", "/healthz/poststarthook/start-kube-apiserver-admission-initializer", "/livez", "/...", "/livez/poststarthook/start-kube-apiserver-admission-initializer", "/logs", "/metrics", "/openapi/v2", "/readyz", "....", "/readyz/shutdown", "/version" ] }Copy the code

Using curl to access the root path of apiserver, you can see that a list of accessible paths is displayed. General classification can be divided into:

  1. api/v1
  2. apis/*
  3. healthz/*
  4. livez/*
  5. logs
  6. metrics
  7. Openapi/v2
  8. readyz
  9. Version

Again classified and sorted as:

  1. API Resource Related interfaces
    1. api/*
    2. apis/*
  2. openapi
  3. Checking class Interfaces
    1. Health Check/HealthZ /*
    2. Survival check /livez/*
    3. Ready check /readyz/*
  4. other
    1. The log
    2. indicators
    3. version

According to the interface classification above, the interfaces that mainly provide business logic phase processing are API Resource-related interfaces.

According to kubernetes/staging/SRC/k8s. IO/client – go/discovery discovery – cient. Go: 482

// NewDiscoveryClientForConfig creates a new DiscoveryClient for the given config. This client
// can be used to discover supported resources in the API server.
func NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error) {
	config := *c
	iferr := setDiscoveryDefaults(&config); err ! =nil {
		return nil, err
	}
	client, err := restclient.UnversionedRESTClientFor(&config)
	return &DiscoveryClient{restClient: client, LegacyPrefix: "/api"}, err
}
Copy the code

And kubernetes/staging/SRC/k8s. IO/client – go/discovery discovery – cient. Go: 192

// ServerResourcesForGroupVersion returns the supported resources for a group and version.
func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *metav1.APIResourceList, err error) {
	url := url.URL{}
	if len(groupVersion) == 0 {
		return nil, fmt.Errorf("groupVersion shouldn't be empty")}if len(d.LegacyPrefix) > 0 && groupVersion == "v1" {
		url.Path = d.LegacyPrefix + "/" + groupVersion
	} else {
		url.Path = "/apis/" + groupVersion
	}
	resources = &metav1.APIResourceList{
		GroupVersion: groupVersion,
	}
	err = d.restClient.Get().AbsPath(url.String()).Do(context.TODO()).Into(resources)
	iferr ! =nil {
		// ignore 403 or 404 error to be compatible with an v1.0 server.
		if groupVersion == "v1" && (errors.IsNotFound(err) || errors.IsForbidden(err)) {
			return resources, nil
		}
		return nil, err
	}
	return resources, nil
}
Copy the code

According to the code logic, API /v1 API resource list is a legacy problem.

/ API/v1 and/apis/apiextensions k8s. IO/v1 such interfaces are APIResourceList type of object returned.

Namespaced Resources are basically made up of this path specification. API /v1 is the case where the group field is missing.

The/API /v1/ POD interface is used as an example to analyze the composition of interfaces for a single resource

    {
      "name": "pods"."singularName": ""."namespaced": true."kind": "Pod"."verbs": [
        "create"."delete"."deletecollection"."get"."list"."patch"."update"."watch"]."shortNames": [
        "po"]."categories": [
        "all"]."storageVersionHash": "xPOwRZ+Yhw8="},..."name": "pods/status"."singularName": ""."namespaced": true."kind": "Pod"."verbs": [
        "get"."patch"."update"]},Copy the code

An important field is namespaced. When this field is true, the resource object is a namespace-isolated resource, and most operations require a namespace to be specified.

A list of actions for a certain type of resource can be obtained in the Verbs field

  1. The create / / create
  2. Delete / / deleted
  3. Deletecollection // deletecollection
  4. Get // Obtains a single resource
  5. List // Get the resource list
  6. Patch // Modifies data in the form of patch data
  7. Update // Modify data in overwrite form
  8. Watch // Subscription resource list data changes

The corresponding verbs for the Pods resource are described in OpenAPI

And actions for individual resources other than add, delete, modify, and search are available through interfaces like ‘Pods/Status’. The corresponding OpenAPI description is

In addition, there is usually a list interface across NS queries

kubectl

When kubectl options is executed, you can see that there is a parameter -v to set the log printing level

-v, --v=0: number for the log level verbosity

-v 7 You can view HTTP logs of all requests to apiserver, for example

2. To bounce over or cache discovery info due to the server is currently unavailable To handle the request I0221 12:40:50.993222 34765 round_trippers. Go :420] GET http://localhost:8666/cluster/preee/api/v1/namespaces/default/services? Limit =500 I0221 12:40:50.993232 34765 round_trippers. I0221 12:40:50.993236 round_trippers. Go :431] Accept: application/json; as=Table; v=v1; g=meta.k8s.io,application/json; as=Table; v=v1beta1; G = meta. K8s. IO, application/json I0221 12:40:50. 993240 34765 round_trippers. Go: 431] the user-agent: Kubectl /v1.18.2 (Darwin /amd64) kubernetes/ 52C56CE I0221 12:40:51.048394 34765 round_trippers. Go :446] Response Status: 200 OK in 55 milliseconds NAME TYPE cluster-ip external-ip PORT(S) AGE kube-user NodePort 192.168.255.192 <none> 443:31524/TCP 324d Kubernetes ClusterIP 192.168.255.1 < None > 443/TCP 338DCopy the code

Kubectl get ns after the first request or the ~/. Kube /cache directory is deleted

INFO[0014] GET/api                                      
INFO[0015] GET/apis                                     
INFO[0015] GET/apis/events.k8s.io/v1beta1               
INFO[0015] GET/apis/scheduling.k8s.io/v1                
INFO[0015] GET/apis/coordination.k8s.io/v1              
...
INFO[0015] GET/api/v1                                   
INFO[0015] GET/apis/extensions/v1beta1                  
...           
INFO[0018] GET/api/v1/namespaces 
Copy the code

Kubectl get ns is executed the second time

INFO[0085] GET/api/v1/namespaces 
Copy the code

The first conclusion is that kubectl caches all apI-Resource fields when executing the first request for subsequent request assembly, etc

kubectl get po

/api/v1/namespaces/default/pods
Copy the code

kubectl get po -A

/api/v1/pods
Copy the code

/apis/apps/v1/namespaces/kube-system/deployments? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500

INFO[0007] GET/apis/apps/v1/namespaces/kube-system/deployments? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500Copy the code

The get all command obtains these values separately

  1. pods
  2. replicationcontrollers
  3. services
  4. daemonsets
  5. deployments
  6. replicasets
  7. statefulsets
  8. horizontalpodautoscalers
  9. jobs
  10. cronjobs

kubectl get all -A -l kubernetes.io/cluster-service=true

INFO[0064] GET/api/v1/pods? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0064] GET/api/v1/replicationcontrollers? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0064] GET/api/v1/services? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0064] GET/apis/apps/v1/daemonsets? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0064] GET/apis/apps/v1/deployments? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0064] GET/apis/apps/v1/replicasets? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0065] GET/apis/apps/v1/statefulsets? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0065] GET/apis/autoscaling/v1/horizontalpodautoscalers? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0065] GET/apis/batch/v1/jobs? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500 INFO[0065] GET/apis/batch/v1beta1/cronjobs? labelSelector=kubernetes.io%2Fcluster-service%3Dtrue&limit=500Copy the code

describe deploy

  1. deployments
  2. events
  3. replicasets

kubectl -nkube-system describe deploy coredns

INFO[0651] GET/apis/apps/v1/namespaces/kube-system/deployments/coredns? INFO[0651] GET/api/v1/namespaces/kube-system/events? fieldSelector=involvedObject.name%3Dcoredns%2CinvolvedObject.namespace%3Dkube-system%2CinvolvedObject.kind%3DDeployment% 2CinvolvedObject.uid%3D1aa51196-7468-4aba-b26f-5908a50c31a7 INFO[0651] GET/apis/apps/v1/namespaces/kube-system/replicasets?labelSelector=k8s-app%3Dkube-dnsCopy the code

describe po

  1. pods
  2. Events

kubectl -nkube-system describe po coredns coredns-5488fc95f4-5jr6l

INFO[0840] GET/api/v1/namespaces/kube-system/pods/coredns-5488fc95f4-5jr6l? INFO[0840] GET/api/v1/namespaces/kube-system/pods/coredns-5488fc95f4-5jr6l? INFO[0840] GET/api/v1/namespaces/kube-system/events? fieldSelector=involvedObject.name%3Dcoredns-5488fc95f4-5jr6l%2CinvolvedObject.namespace%3Dkube-system%2CinvolvedObject.u id%3D3f0b3909-35ae-4c22-bfdc-5f5ddd84a9b8Copy the code

describe svc

  1. services
  2. endpoints
  3. events

kubectl -nkube-system describe svc prometheus

INFO[0886] GET/api/v1/namespaces/kube-system/services/prometheus? INFO[0886] GET/api/v1/namespaces/kube-system/services/prometheus? INFO[0886] GET/api/v1/namespaces/kube-system/endpoints/prometheus? INFO[0886] GET/api/v1/namespaces/kube-system/events? fieldSelector=involvedObject.name%3Dprometheus%2CinvolvedObject.namespace%3Dkube-system%2CinvolvedObject.kind%3DService% 2CinvolvedObject.uid%3D1c27a873-4c53-42d6-ab86-f7050a35fd6cCopy the code

describe node

  1. nodes
  2. leases
  3. pods
  4. events

kubectl -nkube-system describe no vm-2-177-centos

INFO[1055] GET/api/v1/nodes/vm-2-177-centos? INFO[1056] GET/api/v1/nodes/vm-2-177-centos? INFO[1056] GET/apis/coordination.k8s.io/v1/namespaces/kube-node-lease/leases/vm-2-177-centos? INFO[1056] GET/api/v1/pods? fieldSelector=spec.nodeName%3Dvm-2-177-centos%2Cstatus.phase%21%3DFailed%2Cstatus.phase%21%3DSucceeded INFO[1056] GET/api/v1/events? fieldSelector=involvedObject.kind%3DNode%2CinvolvedObject.uid%3Dvm-2-177-centos%2CinvolvedObject.name%3Dvm-2-177-centos% 2CinvolvedObject.namespace%3DCopy the code

kubectl auth can-i get po

INFO[1516] GET/api/v1? timeout=32s INFO[1516] POST/apis/authorization.k8s.io/v1/selfsubjectaccessreviews?Copy the code