# Kubernetes中的CRI
## 前言
**Kubernetes** 節點的底層由一個叫做**容器運行時**的軟件進行支撐,它主要負責啟停容器。
**Docker** 是目前最廣為人知的容器運行時軟件,但是它并非唯一。在這幾年中,容器運行時這個領域發展的迅速。為了使得 **Kubernetes** 的擴展變得更加容易,一直在打磨支持容器運行時的 **K8S**插件 **API**,也就是 容器運行時接口 ( Container Runtime Interface, CRI) 。
## k8s架構
這里通過分析 **k8s** 目前默認的一種容器運行時架構,來幫助我們更好的理解 **k8s** 運行時的背后邏輯,同時引出 **CRI** 和 **OCI** 提出的背景。
我們在創建 **k8s** 集群的時候,首先需要搭建 **master** 節點,其次需要創建 **node** 節點,并將 **node** 節點加入到 **k8s** 集群中。當我們構建好 **k8s** 集群后,可以通過 下面命令來創建應用對應的pod
```bash
kubectl create -f nginx.yml
```
執行完成后,該命令首先會提交給 **API Server** ,然后解析 **yml** 文件,并對其以 **API** 對象的形式存到 **etcd** 里。
這時候,**master** 組件中的 **Controller Manager** 會通過控制循環的方式來做編排工作,創建應用所需的Pod。同時 **Scheduler** 會 **watch etcd** 中新 **pod** 的變化,如果他發現有一個新的 **pod** 的變化。
如果 **Scheduler** 發現有一個新的 **pod** 出現,它會運行調度算法,然后選擇出最佳的 **Node** 節點,并將這個節點的名字寫到 **pod** 對象的 **NodeName** 字段上,這一步就是所謂的 **Bind Pod to Node**,然后把 **bind** 的結果寫到 **etcd**。
其次,當我們在構建 **k8s** 集群的時候,默認每個節點都會初始化創建一個 **kubectl** 進程,**kubectl** 進程會 **watch etcd** 中 **pod** 的變化,當 **kubectl** 進程監聽到 **pod** 的 **bind** 的更新操作,并且 **bind** 的節點是本節點時,它會接管接下來的所有事情,如鏡像下載,創建容器等。

## k8s默認容器運行時架構
接下來將通過 **k8s** 默認集成的容器運行時架構,來看 **kubernetes** 如何創建一個容器 (如下圖)
- **kubernetes** 通過 **CRI** (Container Runtime Interface) 接口調用 **dockershim**,請求創建一個容器。這一步中,**Kubectl** 可以視作一個簡單的 **CRI Client**,而 **dockershim** 就是接收的 **Server**。
- **dockershim** 收到請求后,通過適配的方式,適配成 **Docker Daemon** 的請求格式,發到 **Docker Daemon** 上請求創建一個容器。在 docker 1.12 后的版本,docker daemon 被拆分成了 **dockerd** 和 **containerd**,其中,**containerd** 負責操作容器。
- **dockerd** 收到請求后,會調用 **containerd** 進程去創建一個容器
- **containerd** 收到請求后,并不會自己直接去操作容器,而是創建一個叫做 **containerd-shim** 的進程,讓 **containerd-shim** 去操作容器,創建 **containerd-shim** 的目的主要有以下幾個
- 讓 **containerd-shim** 做諸如收集狀態,維持 stdin 等 fd 打開等工作。
- 允許容器運行時( **runC** ) 啟動容器后退出,不必為每個容器一直運行一個容器運行時的 **runC**
- 即使在 **containerd** 和 **dockerd** 都掛掉的情況下,容器的標準 IO 和其它的文件描述符也是可以用的
- 向 **containerd** 報告容器的退出狀態
- 在不中斷容器運行時的情況下,升級或重啟 **dockerd**
- 而 **containerd-shim** 在這一步需要調用 **runC** 這個命令行工具,來啟動容器,**runC** 是 **OCI** (Open Container Initiative, 開放標準協議) 的一個參考實現。主要用來設置 **namespaces** 和 **cgroups**,掛載 root filesystem等操作。
- **runC** 啟動完容器后,本身會直接退出。**containerd-shim** 則會成為容器進程的父進程,負責收集容器進程的狀態,上報給 **containerd**,并在容器中的 **pid** 為 **1** 的進程退出后接管容器中的子進程進行清理,確保不會出現僵尸進程 (關閉進程描述符)。

## 容器與容器編排背景
從 **k8s** 的容器運行時可以看出,**kubectl** 啟動容器的過程經過了很長的一段調用鏈路。這個是由于在容器及編排領域各大廠商與 **docker** 之間的競爭以及 **docker** 公司為了搶占 **Pass** ( Platform-as-a-service,平臺服務) 領域市場,對架構做出的一系列調整。
其實 **k8s** 最開始的運行時架構鏈路調用沒有這么復雜:kubelet想要創建容器直接通過 **docker api** 調用 **Docker Daemon** , 然后Docker Daemon 調用 libcontainer 這個庫來啟動容器。
后面為了防止 **docker** 壟斷以及受控 docker 運行時,各大廠商于是就聯合起來,制訂出 開放容器標準**OCI** ( Open Containers Initiative ) 。大家可以基于這個標準開發自己的容器運行時。Docker公司則把 **libcontainer** 做了一層封裝,變成 **runC** 捐獻給 **CNCF** 作為 **OCI** 的參考實現。
接下來就是 **Docker** 要搞 **Swarm** 進軍 **PaaS** 市場,于是做了個架構切分,把容器操作都移動到一個單獨的 **Daemon** 進程的 **containerd** 中去,讓 Docker Daemon專門負責上層封裝編排,但是最終 **Swarm** 敗給了 **K8S** ,于是Docker公司就把 **Containerd** 捐給了 CNCF,專注于搞 **Docker** 企業版了。
與此同時,容器領域 **core os** 公司推出了 **rkt** 容器運行時,希望 **k8s** 原生支持 **rkt** 作為運行時,由于 **core os** 與 **Google** 的關系,最終 **rkt** 運行時的支持在 **2016** 年也被合并進 **kubelet** 主干代碼里,這樣做反而給 **k8s** 中負責維護 **kubelet** 的小組 **SIG-Node** 帶來了更大的負擔,每一次 **kubectl** 的更新都要維護 **docker** 和 **rkt** 作為兩部分代碼。與此同時,隨著虛擬化技術強隔離容器技術 **runV** (Kata Containers 前身, 后與 intel clear container 合并)的逐漸成熟。**K8S** 上游對虛擬化容器的支持很快被提上日程。為了從集成每一種運行時都要維護的一份代碼中解救出來,**K8S SIG-Node** 工作組決定對容器的操作統一地抽象成一個接口,這樣 **kubelet** 只需要跟這個接口打交道,而具體地容器運行時,他們只需要實現該接口,并對kubelet暴露 **gRPC** 服務即可。這個統一地抽象的接口就是 **k8s** 中俗稱的 **CRI**。
## CRI接口
**CRI** (容器運行時接口)基于 **gRPC** 定義了 **RuntimeService** 和 **ImageService** 等兩個 **gRPC** 服務,分別用于容器運行時和鏡像的管理。如下所示
```go
// Runtime service defines the public APIs for remote container runtimes
service RuntimeService {
// Version returns the runtime name, runtime version, and runtime API version.
rpc Version(VersionRequest) returns (VersionResponse) {}
// RunPodSandbox creates and starts a pod-level sandbox. Runtimes must ensure
// the sandbox is in the ready state on success.
rpc RunPodSandbox(RunPodSandboxRequest) returns (RunPodSandboxResponse) {}
// StopPodSandbox stops any running process that is part of the sandbox and
// reclaims network resources (e.g., IP addresses) allocated to the sandbox.
// If there are any running containers in the sandbox, they must be forcibly
// terminated.
// This call is idempotent, and must not return an error if all relevant
// resources have already been reclaimed. kubelet will call StopPodSandbox
// at least once before calling RemovePodSandbox. It will also attempt to
// reclaim resources eagerly, as soon as a sandbox is not needed. Hence,
// multiple StopPodSandbox calls are expected.
rpc StopPodSandbox(StopPodSandboxRequest) returns (StopPodSandboxResponse) {}
// RemovePodSandbox removes the sandbox. If there are any running containers
// in the sandbox, they must be forcibly terminated and removed.
// This call is idempotent, and must not return an error if the sandbox has
// already been removed.
rpc RemovePodSandbox(RemovePodSandboxRequest) returns (RemovePodSandboxResponse) {}
// PodSandboxStatus returns the status of the PodSandbox. If the PodSandbox is not
// present, returns an error.
rpc PodSandboxStatus(PodSandboxStatusRequest) returns (PodSandboxStatusResponse) {}
// ListPodSandbox returns a list of PodSandboxes.
rpc ListPodSandbox(ListPodSandboxRequest) returns (ListPodSandboxResponse) {}
// CreateContainer creates a new container in specified PodSandbox
rpc CreateContainer(CreateContainerRequest) returns (CreateContainerResponse) {}
// StartContainer starts the container.
rpc StartContainer(StartContainerRequest) returns (StartContainerResponse) {}
// StopContainer stops a running container with a grace period (i.e., timeout).
// This call is idempotent, and must not return an error if the container has
// already been stopped.
// TODO: what must the runtime do after the grace period is reached?
rpc StopContainer(StopContainerRequest) returns (StopContainerResponse) {}
// RemoveContainer removes the container. If the container is running, the
// container must be forcibly removed.
// This call is idempotent, and must not return an error if the container has
// already been removed.
rpc RemoveContainer(RemoveContainerRequest) returns (RemoveContainerResponse) {}
// ListContainers lists all containers by filters.
rpc ListContainers(ListContainersRequest) returns (ListContainersResponse) {}
// ContainerStatus returns status of the container. If the container is not
// present, returns an error.
rpc ContainerStatus(ContainerStatusRequest) returns (ContainerStatusResponse) {}
// UpdateContainerResources updates ContainerConfig of the container.
rpc UpdateContainerResources(UpdateContainerResourcesRequest) returns (UpdateContainerResourcesResponse) {}
// ReopenContainerLog asks runtime to reopen the stdout/stderr log file
// for the container. This is often called after the log file has been
// rotated. If the container is not running, container runtime can choose
// to either create a new log file and return nil, or return an error.
// Once it returns error, new container log file MUST NOT be created.
rpc ReopenContainerLog(ReopenContainerLogRequest) returns (ReopenContainerLogResponse) {}
// ExecSync runs a command in a container synchronously.
rpc ExecSync(ExecSyncRequest) returns (ExecSyncResponse) {}
// Exec prepares a streaming endpoint to execute a command in the container.
rpc Exec(ExecRequest) returns (ExecResponse) {}
// Attach prepares a streaming endpoint to attach to a running container.
rpc Attach(AttachRequest) returns (AttachResponse) {}
// PortForward prepares a streaming endpoint to forward ports from a PodSandbox.
rpc PortForward(PortForwardRequest) returns (PortForwardResponse) {}
// ContainerStats returns stats of the container. If the container does not
// exist, the call returns an error.
rpc ContainerStats(ContainerStatsRequest) returns (ContainerStatsResponse) {}
// ListContainerStats returns stats of all running containers.
rpc ListContainerStats(ListContainerStatsRequest) returns (ListContainerStatsResponse) {}
// UpdateRuntimeConfig updates the runtime configuration based on the given request.
rpc UpdateRuntimeConfig(UpdateRuntimeConfigRequest) returns (UpdateRuntimeConfigResponse) {}
// Status returns the status of the runtime.
rpc Status(StatusRequest) returns (StatusResponse) {}
}
// ImageService defines the public APIs for managing images.
service ImageService {
// ListImages lists existing images.
rpc ListImages(ListImagesRequest) returns (ListImagesResponse) {}
// ImageStatus returns the status of the image. If the image is not
// present, returns a response with ImageStatusResponse.Image set to
// nil.
rpc ImageStatus(ImageStatusRequest) returns (ImageStatusResponse) {}
// PullImage pulls an image with authentication config.
rpc PullImage(PullImageRequest) returns (PullImageResponse) {}
// RemoveImage removes the image.
// This call is idempotent, and must not return an error if the image has
// already been removed.
rpc RemoveImage(RemoveImageRequest) returns (RemoveImageResponse) {}
// ImageFSInfo returns information of the filesystem that is used to store images.
rpc ImageFsInfo(ImageFsInfoRequest) returns (ImageFsInfoResponse) {}
}
```
具體容器運行時則需要實現 **CRI** 定義的接口(即 **gRPC Server**,通常稱為 **CRI shim**)。容器運行時在啟動 **gRPC server** 時需要監聽在本地的 **Unix Socket** (Windows 使用 tcp 格式)。
## 參考
https://www.kubernetes.org.cn/1079.html
https://www.cnblogs.com/justinli/p/11578951.html
- Kubernetes簡介
- 搭建K8S集群前置知識
- 使用kubeadm方式搭建K8S集群
- 使用二進制方式搭建K8S集群
- Kubeadm和二進制方式對比
- Kubernetes集群管理工具kubectl
- Kubernetes集群YAML文件詳解
- Kubernetes核心技術Pod
- Kubernetes核心技術Controller
- Kubernetes核心技術Service
- Kubernetes控制器Controller詳解
- Kubernetes配置管理
- Kubernetes集群安全機制
- Kubernetes核心技術Ingress
- Kubernetes核心技術Helm
- Kubernetes持久化存儲
- Kubernetes集群資源監控
- Kubernetes搭建高可用集群
- Kubernetes容器交付介紹
- 使用kubeadm-ha腳本一鍵安裝K8S
- Kubernetes可視化界面kubesphere
- Kubernetes配置默認存儲類
- 使用Rancher搭建Kubernetes集群
- Kubernetes中的CRI