- Mastering Kubernetes
- Gigi Sayfan
- 2623字
- 2021-06-18 18:36:58
Diving into Kubernetes architecture in depth
Kubernetes has very ambitious goals. It aims to manage and simplify the orchestration, deployment, and management of distributed systems across a wide range of environments and cloud providers. It provides many capabilities and services that should work across all that persity while evolving and remaining simple enough for mere mortals to use. This is a tall order. Kubernetes achieves this by following a crystal-clear, high-level design and well-thought-out architecture that promotes extensibility and pluggability. Many parts of Kubernetes are still hardcoded or environment-aware, but the trend is to refactor them into plugins and keep the core small, generic, and abstract. In this section, we will peel Kubernetes like an onion, starting with various distributed system design patterns and how Kubernetes supports them, then go over the surface of Kubernetes, which is its set of APIs, and then take a look at the actual components that comprise Kubernetes. Finally, we will take a quick tour of the source-code tree to gain an even better insight into the structure of Kubernetes itself.
At the end of this section, you will have a solid understanding of Kubernetes architecture and implementation, and why certain design decisions were made.
Distributed system design patterns
All happy (working) distributed systems are alike, to paraphrase Tolstoy in Anna Karenina. That means that to function properly, all well-designed distributed systems must follow some best practices and principles. Kubernetes doesn't want to be just a management system; it wants to support and enable these best practices and provide high-level services to developers and administrators. Let's look at some of those best practices, described as design patterns.
The sidecar pattern
The sidecar pattern is about co-locating another container in a pod in addition to the main application container. The application container is unaware of the sidecar container and just goes about its business. A great example is a central logging agent. Your main container can just log to stdout, but the sidecar container will send all logs to a central logging service where they will be aggregated with the logs from the entire system. The benefits of using a sidecar container versus adding central logging to the main application container are enormous. First, applications are not burdened anymore with central logging, which could be a nuisance. If you want to upgrade or change your central logging policy or switch to a totally new provider, you just need to update the sidecar container and deploy it. None of your application containers change, so you can't break them by accident. The Istio service mesh uses the sidecar pattern to inject its proxies into each pod.
The ambassador pattern
The ambassador pattern is about representing a remote service as if it were local and possibly enforcing some policy. A good example of the ambassador pattern is if you have a Redis cluster with one master for writes and many replicas for reads. A local ambassador container can serve as a proxy and expose Redis to the main application container on the localhost. The main application container simply connects to Redis on localhost:6379 (Redis default port), but it connects to the ambassador running in the same pod, which filters the requests, and sends write requests to the real Redis master and read requests randomly to one of the read replicas. Just like with the sidecar pattern, the main application has no idea what's going on. That can help a lot when testing against a real local Redis. Also, if the Redis cluster configuration changes, only the ambassador needs to be modified; the main application remains blissfully unaware.
The adapter pattern
The adapter pattern is about standardizing output from the main application container. Consider the case of a service that is being rolled out incrementally: it may generate reports in a format that doesn't conform to the previous version. Other services and applications that consume that output haven't been upgraded yet. An adapter container can be deployed in the same pod with the new application container and massage the output to match the old version until all consumers have been upgraded. The adapter container shares the filesystem with the main application container, so it can watch the local filesystem, and whenever the new application writes something, it immediately adapts it.
Multi-node patterns
Single-node patterns are all supported directly by Kubernetes via pods. Multi-node patterns such as leader election, work queues, and scatter-gather are not supported directly, but composing pods with standard interfaces to accomplish them is a viable approach with Kubernetes.
Many tools, frameworks, and add-ons that integrate deeply with Kubernetes utilize these design patterns. The beauty of these patterns is that they are all loosely coupled and don't require Kubernetes to be modified or even be aware of the presence of these integrations. The vibrant ecosystem around Kubernetes is a direct result of its architecture. Let's dig one level deeper and get familiar with the Kubernetes APIs.
The Kubernetes APIs
If you want to understand the capabilities of a system and what it provides, you must pay a lot of attention to its API. The API provides a comprehensive view of what you can do with the system as a user. Kubernetes exposes several sets of REST APIs for different purposes and audiences via API groups. Some of the APIs are used primarily by tools and some can be used directly by developers. An important aspect of the APIs is that they are under constant development. The Kubernetes developers keep it manageable by trying to extend (adding new objects and new fields to existing objects) and avoid renaming or dropping existing objects and fields. In addition, all API endpoints are versioned and often have an alpha or beta notation too; for example:
/api/v1
/api/v2alpha1
You can access the API through the kubectl CLI, via client libraries, or directly through REST API calls. There are elaborate authentication and authorization mechanisms we will explore in a later chapter. If you have the right permissions, you can list, view, create, update, and delete various Kubernetes objects. At this point, let's get a glimpse of the surface area of the APIs. The best way to explore the API is via API groups. Some API groups are enabled by default. Other groups can be enabled/disabled via flags. For example, to disable the batch V1 group and enable the batch V2 Alpha group, you can set the --runtime-config flag when running the API server as follows:
--runtime-config=batch/v1=false,batch/v2alpha=true
The following resources are enabled by default in addition to the core resources:
- DaemonSets
- Deployments
- HorizontalPodAutoscalers
- Ingress
- Jobs
- ReplicaSets
In addition to API groups, another useful classification of available APIs is by functionality. Enter resource categories...
Resource categories
The Kubernetes API is huge, and breaking it down into categories helps a lot when you're trying to find your way around. Kubernetes defines the following resource categories:
- Workloads: Objects you use to manage and run containers in the cluster
- Discovery and Load Balancing: Objects you use to expose your workloads to the world as externally accessible, load-balanced services
- Config and Storage: Objects you use to initialize and configure your applications, and to persist data that's outside the container
- Cluster: Objects that define how the cluster itself is configured; these are typically used only by cluster operators
- Metadata: Objects you use to configure the behavior of other resources within the cluster, such as HorizontalPodAutoscaler for scaling workloads
In the following sub-sections, I'll list the resources that belong to each group with the API group they belong to in the following format: <resource name>: <API group>; for example, Container: core, where the resource is Container and the API group is core. I will not specify the version here because APIs move rapidly from alpha to beta to GA (general availability) and from V1 to V2, and so on.
The workloads API
The workloads API contains many resources. Here is a list of all the resources with the API groups they belong to:
- Container: core
- CronJob: batch
- DaemonSet: apps
- Deployment: apps
- Job: batch
- Pod: core
- ReplicaSet: apps
- ReplicationController: core
- StatefulSet: apps
Containers are created by controllers through pods. Pods run containers and provide environmental dependencies such as shared or persistent storage volumes and configuration or secret data injected into the container.
Here is an example of the detailed documentation of one of the most common operations – getting a list of all the pods as a REST API:
GET /api/v1/pods
It accepts various query parameters (all optional):
- pretty: If true, the output is pretty printed
- labelSelector: A selector expression to limit the result
- watch: If true, watch for changes and return a stream of events
- resourceVersion: With watch, returns only events that occurred after that version
- timeoutSeconds: Timeout for the list or watch operation
The next category of resources deals with high-level networking.
Discovery and Load Balancing
This category is also known as service APIs. By default, workloads are only accessible within the cluster, and they must be exposed externally using either a LoadBalancer or NodePort Service.
For development, internally accessible workloads can be accessed via proxy through the API master using the kubectl proxy command:
- Endpoints: core
- Ingress: networking.k8s.io
- Service: core
The next category of resources deals with storage and internal state management.
Config and Storage
Dynamic configuration without redeployment is a cornerstone of Kubernetes and running complex distributed applications on your Kubernetes cluster. Storing data is another paramount concern for any non-trivial system. The config and storage category provides multiple resources to address these concerns:
- ConfigMap: core
- CSIDriver: storage.k8s.io
- CSINode: storage.k8s.io
- Secret: core
- PersistentVolumeClaim: core
- StorageClass: storage.k8s.io
- Volume: storage.k8s.io
- VolumeAttachment: storage.k8s.io
The next category of resources deals with helper resources that are usually part of other high-level resources.
Metadata
The metadata resources typically show up as sub-resources of the resources of the configuration. For example, a limit range will be part of a pod configuration. You will not interact with these objects directly most of the time. There are many metadata resources – there isn't much point in listing all of them. You can find the complete list here: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.16/#-strong-metadata-apis-strong-.
Clusters
The resources in the cluster category are designed for use by cluster operators as opposed to developers. There are many resources in this category as well. Here are some of the most important resources:
- Namespace: core
- Node: core
- PersistentVolume: core
- ResourceQuota: core
- Role: rbac.authorization.k8s.io
- RoleBinding: rbac.authorization.k8s.io
- ClusterRole: rbac.authorization.k8s.io
- ClusterRoleBinding: rbac.authorization.k8s.io
- NetworkPolicy: networking.k8s.io
Now that we understand how Kubernetes organizes and exposes its capabilities via API groups and resource categories, let's see how it manages the physical infrastructure and keeps it up with the state of the cluster.
Kubernetes components
A Kubernetes cluster has several master components used to control the cluster, as well as node components that run on each worker node. Let's get to know all these components and how they work together.
Master components
The master components can all run on one node, but in a highly available setup or a very large cluster, they may be spread across multiple nodes.
The API server
The Kubernetes API server exposes the Kubernetes REST API. It can easily scale horizontally as it is stateless and stores all the data in the etcd cluster. The API server is the embodiment of the Kubernetes control plane.
Etcd
Etcd is a highly reliable distributed data store. Kubernetes uses it to store the entire cluster state. In a small, transient cluster a single instance of etcd can run on the same node with all the other master components. But for more substantial clusters, it is typical to have a three-node or even five-node etcd cluster for redundancy and high availability.
The Kube controller manager
The Kube controller manager is a collection of various managers rolled up into one binary. It contains the replication controller, the pod controller, the services controller, the endpoints controller, and others. All these managers watch over the state of the cluster via the API and their job is to steer the cluster into the desired state.
Cloud controller managers
When running in the cloud, Kubernetes allows cloud providers to integrate their platform for the purpose of managing nodes, routes, services, and volumes. The cloud provider code interacts with the Kubernetes code. It replaces some of the functionality of the Kube controller manager. When running Kubernetes with a cloud controller manager, you must set the Kube controller manager flag --cloud-provider to "external". This will disable the control loops that the cloud controller manager is taking over. The cloud controller manager was introduced in Kubernetes 1.6 and it's being used by multiple cloud providers already, such as:
- GCP
- AWS
- Azure
- Baidu Cloud
- DigitalOcean
- Oracle
- Linode
A quick note about Go to help you parse the code: the method name comes first, followed by the method's parameters in parentheses. Each parameter is a pair, consisting of a name followed by its type. Finally, the return values are specified. Go allows multiple return types. It is very common to return an error object in addition to the actual result. If everything is OK, the error object will be nil.
Here is the main interface of the cloudprovider package:
package cloudprovider
import (
"errors"
"fmt"
"strings"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/informers"
"k8s.io/kubernetes/pkg/controller"
)
// Interface is an abstract, pluggable interface for cloud providers.
type Interface interface {
Initialize(clientBuilder controller.ControllerClientBuilder)
LoadBalancer() (LoadBalancer, bool)
Instances() (Instances, bool)
Zones() (Zones, bool)
Clusters() (Clusters, bool)
Routes() (Routes, bool)
ProviderName() string
HasClusterID() bool
}
Most of the methods return other interfaces with their own method. For example, here is the LoadBalancer interface:
type LoadBalancer interface {
GetLoadBalancer(clusterName string,
service \*v1.Service) (status \*v1.LoadBalancerStatus,
exists bool,
err error)
EnsureLoadBalancer(clusterName string,
service \*v1.Service,
nodes []\*v1.Node) (\*v1.LoadBalancerStatus, error)
UpdateLoadBalancer(clusterName string, service \*v1.Service, nodes []\*v1.Node) error
EnsureLoadBalancerDeleted(clusterName string, service \*v1.Service) error
}
The cloud controller manager is instrumental in bringing Kubernetes to all the major cloud providers, but the heart and soul of Kubernetes is the scheduler.
kube-scheduler
Kube-scheduler is responsible for scheduling pods into nodes. This is a very complicated task as it needs to consider multiple interacting factors, such as the following:
- Resource requirements
- Service requirements
- Hardware/software policy constraints
- Node affinity and anti-affinity specifications
- Pod affinity and anti-affinity specifications
- Taints and tolerations
- Data locality
- Deadlines
If you need some special scheduling logic not covered by the default kube-scheduler, you can replace it with your own custom scheduler. You can also run your custom scheduler side by side with the default scheduler and have your custom scheduler schedule only a subset of the pods.
DNS
Starting with Kubernetes 1.3, a DNS service is part of the standard Kubernetes cluster. It is scheduled as a regular pod. Every service (except headless services) receives a DNS name. Pods can receive a DNS name too. This is very useful for automatic discovery.
Node components
Nodes in the cluster need a couple of components to interact with the cluster master components, receive workloads to execute, and update the Kubernetes API server regarding their status.
Proxy
Kube-proxy does low-level network housekeeping on each node. It reflects the Kubernetes services locally and can perform TCP and UDP forwarding. It finds cluster IPs via environment variables or DNS.
Kubelet
The kubelet is the Kubernetes representative on the node. It oversees communicating with the master components and manages the running pods. That includes the following:
- Receiving pod specs
- Downloading pod secrets from the API server
- Mounting volumes
- Running the pod's containers (via the configured runtime)
- Reporting the status of the node and each pod
- Running the container startup, liveness, and readiness probes
In this section, we dug into the guts of Kubernetes and explored its architecture from a very high level of vision and supported design patterns, through its APIs and the components used to control and manage the cluster. In the next section, we will take a quick look at the various runtimes that Kubernetes supports.