├── .gitignore ├── LICENSE ├── README.md ├── SUMMARY.md ├── book.json ├── cri ├── README.md └── containerd.md ├── csi ├── README.md ├── csi-driver-host-path.md └── how-to-write-csi-driver.md └── keda ├── README.md └── source.md /.gitignore: -------------------------------------------------------------------------------- 1 | _book/ 2 | node_modules/ 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kubernetes book 2 | 关于kubernetes以及周边生态组件的笔记。 3 | 4 | > 并不会短时间内完成,更倾向于在实践的过程中的总结。 5 | 6 | **内容包含** 7 | 8 | - Kubernetes基本概念 9 | - Kubernetes安装 10 | - Kubernetes核心组件介绍/源码分析 11 | - CNI/CSI/CRI 标准介绍以及如何自己动手实现一个 12 | - CNCF下的一些周边组件涉及源码分析 13 | - 遇到的问题分析 14 | - TODO 15 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | * [序言](README.md) 4 | * KEDA 5 | * [介绍](./keda/README.md) 6 | * [源码分析](./keda/source.md) 7 | 8 | - [CSI](./csi/README.md) 9 | - [如何编写一个CSI插件](./csi/how-to-write-csi-driver.md) 10 | - [csi-driver-host-path插件安装](./csi/csi-driver-host-path.md) 11 | - [CRI](.cri/README.md) 12 | - [Containerd介绍](./cri/containerd.md) 13 | 14 | -------------------------------------------------------------------------------- /book.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "kubernetes笔记", 3 | "author": "silenceper", 4 | "description": "kubernets笔记", 5 | "links": { 6 | "sidebar": {} 7 | }, 8 | "plugins": [ 9 | "github-buttons", 10 | "edit-link", 11 | "code", 12 | "back-to-top-button", 13 | "tbfed-pagefooter", 14 | "baidu-v3", 15 | "ga" 16 | ], 17 | "pluginsConfig": { 18 | "github": { 19 | "url": "https://github.com/silenceper/kubernetes-book" 20 | }, 21 | "github-buttons": { 22 | "buttons": [ 23 | { 24 | "user": "silenceper", 25 | "repo": "kubernetes-book", 26 | "type": "star", 27 | "size": "small" 28 | } 29 | ] 30 | }, 31 | "edit-link": { 32 | "base": "https://github.com/silenceper/kubernetes-book/blob/main", 33 | "label": "更新该页" 34 | }, 35 | "tbfed-pagefooter": { 36 | "copyright": "Copyright © silenceper 2020", 37 | "modify_label": "该文件修订时间:", 38 | "modify_format": "YYYY-MM-DD HH:mm:ss" 39 | }, 40 | "ga": { 41 | "token": "UA-139557989-1" 42 | }, 43 | "baidu": { 44 | "token": "fe23775b1a9ea11a6797646a56df1cc7" 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /cri/README.md: -------------------------------------------------------------------------------- 1 | # CRI 容器运行时接口 2 | 3 | 容器运行时插件(Container Runtime Interface,简称 CRI)是 Kubernetes v1.5 引入的容器运行时接口,它将 Kubelet 与容器运行时解耦,将原来完全面向 Pod 级别的内部接口拆分成面向 Sandbox 和 Container 的 gRPC 接口,并将镜像管理和容器管理分离到不同的服务。 4 | 5 | ![cri](https://silenceper.oss-cn-beijing.aliyuncs.com/images/cri.png) 6 | 7 | 8 | 9 | > 在kubernetes 1.20的changelog中,表示未来会移除对docker的依赖,觉得dockershim放在k8s中内部维护是不合适的,而更加专注CRI的实现,提供CRI接口,又第三方组件来维护 10 | 11 | ## 容器运行时 12 | 13 | | **CRI** **容器运行时** | **维护者** | **主要特性** | **容器引擎** | 14 | | ---------------------- | ---------- | ---------------------------- | -------------------------- | 15 | | **Dockershim** | Kubernetes | 内置实现、特性最新 | docker | 16 | | **cri-o** | Kubernetes | OCI标准不需要Docker | OCI(runc、kata、gVisor…) | 17 | | **cri-containerd** | Containerd | 基于 containerd 不需要Docker | OCI(runc、kata、gVisor…) | 18 | | **Frakti** | Kubernetes | 虚拟化容器 | hyperd、docker | 19 | | **rktlet** | Kubernetes | 支持rkt | rkt | 20 | | **PouchContainer** | Alibaba | 富容器 | OCI(runc、kata…) | 21 | | **Virtlet** | Mirantis | 虚拟机和QCOW2镜像 | Libvirt(KVM) | 22 | 23 | 目前基于 CRI 容器引擎已经比较丰富了,包括 24 | 25 | - Docker: 核心代码依然保留在 kubelet 内部([pkg/kubelet/dockershim](https://github.com/kubernetes/kubernetes/tree/master/pkg/kubelet/dockershim)),是最稳定和特性支持最好的运行时 26 | 27 | - OCI 容器运行时: 28 | - 社区有两个实现 29 | - [Containerd](https://github.com/containerd/cri),支持 kubernetes v1.7+ 30 | - [CRI-O](https://github.com/kubernetes-incubator/cri-o),支持 Kubernetes v1.6+ 31 | - 支持的 OCI 容器引擎包括 32 | - [runc](https://github.com/opencontainers/runc):OCI 标准容器引擎 33 | - [gVisor](https://github.com/google/gvisor):谷歌开源的基于用户空间内核的沙箱容器引擎 34 | - [Clear Containers](https://github.com/clearcontainers/runtime):Intel 开源的基于虚拟化的容器引擎 35 | - [Kata Containers](https://github.com/kata-containers/runtime):基于虚拟化的容器引擎,由 Clear Containers 和 runV 合并而来 36 | 37 | - [PouchContainer](https://github.com/alibaba/pouch):阿里巴巴开源的胖容器引擎 38 | 39 | - [Frakti](https://github.com/kubernetes/frakti):支持 Kubernetes v1.6+,提供基于 hypervisor 和 docker 的混合运行时,适用于运行非可信应用,如多租户和 NFV 等场景 40 | 41 | - [Rktlet](https://github.com/kubernetes-incubator/rktlet):支持 [rkt](https://github.com/rkt/rkt) 容器引擎(rknetes 代码已在 v1.10 中弃用) 42 | 43 | - [Virtlet](https://github.com/Mirantis/virtlet):Mirantis 开源的虚拟机容器引擎,直接管理 libvirt 虚拟机,镜像须是 qcow2 格式 44 | 45 | - [Infranetes](https://github.com/apporbit/infranetes):直接管理 IaaS 平台虚拟机,如 GCE、AWS 等 46 | 47 | 48 | 49 | ## 接口描述 50 | 51 | https://github.com/kubernetes/cri-api -------------------------------------------------------------------------------- /cri/containerd.md: -------------------------------------------------------------------------------- 1 | # Containerd 2 | 3 | Containerd是一个容器运行时,可以在宿主机中管理完整的容器生命周期:容器镜像的传输和存储、容器的执行和管理、存储和网络等。 4 | 5 | containerd是从docker中抽离出来的,并提供了实现了cri接口(cri-containerd组件)使得containerd可以作为kubelet的运行时。这样相比docker的调用少了一层dockershim(在kubelet内置的实现的cri接口): 6 | 7 | ![cri-containerd architecture](https://silenceper.oss-cn-beijing.aliyuncs.com/images/cri-containerd.png) 8 | 9 | 10 | 11 | 这是在containerd1.0上的调用关系,在这里cri-containerd还是作为独立的进程,相比dockershim的调度少了一层。在1.1之后这个将cri-containerd嵌入到containerd,调用层级又少了一层。 12 | 13 | ![containerd architecture](https://silenceper.oss-cn-beijing.aliyuncs.com/images/containerd.png) 14 | 15 | 这样相当于调用关系少了两层,所以在性能上肯定会优于默认的dockershim调用docker的方式。 16 | 17 | 18 | 19 | Containerd 内置的 CRI 插件实现了 Kubelet CRI 接口中的 Image Service 和 Runtime Service,通过内部接口管理容器和镜像,并通过 CNI 插件给 Pod 配置网络。 20 | 21 | ![img](https://gblobscdn.gitbook.com/assets%2F-LDAOok5ngY4pc1lEDes%2F-LpOIkR-zouVcB8QsFj_%2F-LpOIs1LZxBhsxPgKp4w%2Fcontainerd.png?alt=media) 22 | 23 | ## 安装 24 | 25 | 安装参考官方文档:https://github.com/containerd/containerd/blob/master/docs/ops.md 26 | 27 | 注意:可以通过`containerd default> /etc/containerd/config.toml`的方式生成默认的配置文件。 28 | 29 | 30 | 31 | **kubelet配置containerd** 32 | 33 | ``` 34 | kubelet --container-runtime=remote --container-runtime-endpoint=unix:///run/containerd/containerd.sock --image-service-endpoint=unix:///run/containerd/containerd.sock 35 | ``` 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /csi/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # CSI - 容器存储接口 4 | 5 | [容器存储接口](https://github.com/container-storage-interface/spec/blob/master/spec.md)(CSI)是用于将任意块和文件存储系统暴露给诸如Kubernetes之类的容器编排系统(CO)上的容器化工作负载的标准。 使用CSI的第三方存储提供商可以编写和部署在Kubernetes中公开新存储系统的插件,而无需接触核心的Kubernetes代码。 6 | 7 | 8 | 9 | 具体来说,Kubernetes针对CSI规定了以下内容: 10 | 11 | - Kubelet到CSI驱动程序的通信 12 | - Kubelet通过Unix域套接字直接向CSI驱动程序发起CSI调用(例如`NodeStageVolume`,`NodePublishVolume`等),以挂载和卸载卷。 13 | - Kubelet通过kubelet插件注册机制发现CSI驱动程序(以及用于与CSI驱动程序进行交互的Unix域套接字)。 14 | - 因此,部署在Kubernetes上的所有CSI驱动程序**必须**在每个受支持的节点上使用kubelet插件注册机制进行注册。 15 | - Master到CSI驱动程序的通信 16 | - Kubernetes master组件不会直接(通过Unix域套接字或其他方式)与CSI驱动程序通信。 17 | - Kubernetes master组件仅与Kubernetes API交互。 18 | - 因此,需要依赖于Kubernetes API的操作的CSI驱动程序(例如卷创建,卷attach,卷快照等)必须监听Kubernetes API并针对它触发适当的CSI操作(例如下面的一系列的external组件)。 19 | 20 | ## 组件 21 | 22 | ![CSI调用说明](https://silenceper.oss-cn-beijing.aliyuncs.com/images/1*bkMOGMuyCYXH8ZyR5Tngig.png) 23 | 24 | 25 | 26 | CSI实现中的组件分为两部分: 27 | 28 | - 由k8s官方维护的一系列external组件负责注册CSI driver 或监听k8s对象资源,从而发起csi driver调用,比如(node-driver-registrar,external-attacher,external-provisioner,external-resizer,external-snapshotter,livenessprobe) 29 | - 各云厂商or开发者自行开发的组件(需要实现CSI Identity,CSI Controller,CSI Node 接口) 30 | 31 | 32 | 33 | ### RPC接口(开发商实现) 34 | 35 | **Identity Service** 36 | 37 | ```go 38 | service Identity { 39 | //返回driver的信息,比如名字,版本 40 | rpc GetPluginInfo(GetPluginInfoRequest) 41 | returns (GetPluginInfoResponse) {} 42 | //返回driver提供的能力,比如是否提供Controller Service,volume 访问能能力 43 | rpc GetPluginCapabilities(GetPluginCapabilitiesRequest) 44 | returns (GetPluginCapabilitiesResponse) {} 45 | //探针 46 | rpc Probe (ProbeRequest) 47 | returns (ProbeResponse) {} 48 | } 49 | ``` 50 | 51 | **Controller service** 52 | 53 | ```go 54 | service Controller { 55 | //创建卷 56 | rpc CreateVolume (CreateVolumeRequest) 57 | returns (CreateVolumeResponse) {} 58 | //删除卷 59 | rpc DeleteVolume (DeleteVolumeRequest) 60 | returns (DeleteVolumeResponse) {} 61 | //attach 卷 62 | rpc ControllerPublishVolume (ControllerPublishVolumeRequest) 63 | returns (ControllerPublishVolumeResponse) {} 64 | //unattach卷 65 | rpc ControllerUnpublishVolume (ControllerUnpublishVolumeRequest) 66 | returns (ControllerUnpublishVolumeResponse) {} 67 | //返回存储卷的功能点,如是否支持挂载到多个节点上,是否支持多个节点同时读写 68 | rpc ValidateVolumeCapabilities (ValidateVolumeCapabilitiesRequest) 69 | returns (ValidateVolumeCapabilitiesResponse) {} 70 | //列出所有卷 71 | rpc ListVolumes (ListVolumesRequest) 72 | returns (ListVolumesResponse) {} 73 | //返回存储资源池的可用空间大小 74 | rpc GetCapacity (GetCapacityRequest) 75 | returns (GetCapacityResponse) {} 76 | //返回controller插件的功能点,如是否支持GetCapacity接口,是否支持snapshot功能等 77 | rpc ControllerGetCapabilities (ControllerGetCapabilitiesRequest) 78 | returns (ControllerGetCapabilitiesResponse) {} 79 | //创建快照 80 | rpc CreateSnapshot (CreateSnapshotRequest) 81 | returns (CreateSnapshotResponse) {} 82 | //删除快照 83 | rpc DeleteSnapshot (DeleteSnapshotRequest) 84 | returns (DeleteSnapshotResponse) {} 85 | //列出快照 86 | rpc ListSnapshots (ListSnapshotsRequest) 87 | returns (ListSnapshotsResponse) {} 88 | //扩容 89 | rpc ControllerExpandVolume (ControllerExpandVolumeRequest) 90 | returns (ControllerExpandVolumeResponse) {} 91 | //获得卷 92 | rpc ControllerGetVolume (ControllerGetVolumeRequest) 93 | returns (ControllerGetVolumeResponse) { 94 | option (alpha_method) = true; 95 | } 96 | } 97 | ``` 98 | 99 | **Node Service** 100 | 101 | ```go 102 | service Node { 103 | //如果存储卷没有格式化,首先要格式化。然后把存储卷mount到一个临时的目录(这个目录通常是节点上的一个全局目录)。再通过NodePublishVolume将存储卷mount到pod的目录中。mount过程分为2步,原因是为了支持多个pod共享同一个volume(如NFS)。 104 | rpc NodeStageVolume (NodeStageVolumeRequest) 105 | returns (NodeStageVolumeResponse) {} 106 | //NodeStageVolume的逆操作,将一个存储卷从临时目录umount掉 107 | rpc NodeUnstageVolume (NodeUnstageVolumeRequest) 108 | returns (NodeUnstageVolumeResponse) {} 109 | //将存储卷从临时目录mount到目标目录(pod目录) 110 | rpc NodePublishVolume (NodePublishVolumeRequest) 111 | returns (NodePublishVolumeResponse) {} 112 | //将存储卷从pod目录umount掉 113 | rpc NodeUnpublishVolume (NodeUnpublishVolumeRequest) 114 | returns (NodeUnpublishVolumeResponse) {} 115 | //返回可用于该卷的卷容量统计信息。 116 | rpc NodeGetVolumeStats (NodeGetVolumeStatsRequest) 117 | returns (NodeGetVolumeStatsResponse) {} 118 | 119 | //noe上执行卷扩容 120 | rpc NodeExpandVolume(NodeExpandVolumeRequest) 121 | returns (NodeExpandVolumeResponse) {} 122 | 123 | //返回Node插件的功能点,如是否支持stage/unstage功能 124 | rpc NodeGetCapabilities (NodeGetCapabilitiesRequest) 125 | returns (NodeGetCapabilitiesResponse) {} 126 | //返回节点信息 127 | rpc NodeGetInfo (NodeGetInfoRequest) 128 | returns (NodeGetInfoResponse) {} 129 | } 130 | ``` 131 | 132 | 133 | 134 | ###External 组件(k8s Team) 135 | 136 | 这部分组件是由k8s官方提供的,作为k8s api跟csi driver的桥梁: 137 | 138 | - **node-driver-registrar** 139 | 140 | CSI node-driver-registrar是一个sidecar容器,可从CSI driver获取驱动程序信息(使用NodeGetInfo),并使用kubelet插件注册机制在该节点上的kubelet中对其进行注册。 141 | 142 | - **external-attacher** 143 | 144 | 它是一个sidecar容器,用于监视Kubernetes VolumeAttachment对象并针对驱动程序端点触发CSI ControllerPublish和ControllerUnpublish操作 145 | 146 | - **external-provisioner** 147 | 148 | 它是一个sidecar容器,用于监视Kubernetes PersistentVolumeClaim对象并针对驱动程序端点触发CSI CreateVolume和DeleteVolume操作。 149 | external-attacher还支持快照数据源。 如果将快照CRD资源指定为PVC对象上的数据源,则此sidecar容器通过获取SnapshotContent对象获取有关快照的信息,并填充数据源字段,该字段向存储系统指示应使用指定的快照填充新卷 。 150 | 151 | - **external-resizer** 152 | 153 | 它是一个sidecar容器,用于监视Kubernetes API服务器上的PersistentVolumeClaim对象的改动,如果用户请求在PersistentVolumeClaim对象上请求更多存储,则会针对CSI端点触发ControllerExpandVolume操作。 154 | 155 | - **external-snapshotter** 156 | 157 | 它是一个sidecar容器,用于监视Kubernetes API服务器上的VolumeSnapshot和VolumeSnapshotContent CRD对象。创建新的VolumeSnapshot对象(引用与此驱动程序对应的SnapshotClass CRD对象)将导致sidecar容器提供新的快照。 158 | 该Sidecar侦听指示成功创建VolumeSnapshot的服务,并立即创建VolumeSnapshotContent资源。 159 | 160 | - **livenessprobe** 161 | 162 | 它是一个sidecar容器,用于监视CSI驱动程序的运行状况,并通过[Liveness Probe机制](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/)将其报告给Kubernetes。 这使Kubernetes能够自动检测驱动程序问题并重新启动Pod以尝试解决问题。 163 | 164 | 165 | 166 | ## 参考 167 | 168 | - [kubernetes-csi-introduction](https://kubernetes-csi.github.io/docs/introduction.html) 169 | - [详解 Kubernetes Volume 的实现原理](https://draveness.me/kubernetes-volume/) 170 | 171 | - [CSI存储接口解释](https://www.dazhuanlan.com/2020/01/31/5e33a33ba05d1/) -------------------------------------------------------------------------------- /csi/csi-driver-host-path.md: -------------------------------------------------------------------------------- 1 | # csi-driver-host-path安装 2 | 3 | > 集群 v1.19.0 4 | 5 | ## 安装 6 | 7 | https://github.com/kubernetes-csi/csi-driver-host-path/blob/master/docs/deploy-1.17-and-later.md 8 | 9 | ### VolumeSnapshot CRDs and snapshot controller installation 10 | 11 | ```shell 12 | 13 | # Apply VolumeSnapshot CRDs version:v2.0.1 14 | kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v2.0.1/config/crd/snapshot.storage.k8s.io_volumesnapshotclasses.yaml 15 | kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v2.0.1/config/crd/snapshot.storage.k8s.io_volumesnapshotcontents.yaml 16 | kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v2.0.1/config/crd/snapshot.storage.k8s.io_volumesnapshots.yaml 17 | # Create snapshot controller 18 | kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v2.0.1/deploy/kubernetes/snapshot-controller/rbac-snapshot-controller.yaml 19 | kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v2.0.1/deploy/kubernetes/snapshot-controller/setup-snapshot-controller.yaml 20 | ``` 21 | 22 | ### Deployment 23 | 24 | 代码地址:https://github.com/kubernetes-csi/csi-driver-host-path 25 | 26 | ```shell 27 | sh deploy/kubernetes-latest/deploy.sh 28 | ``` 29 | 30 | 安装成功: 31 | 32 | ```shell 33 | ➜ ~ kubectl get pod|grep csi 34 | csi-hostpath-attacher-0 1/1 Running 0 76m 35 | csi-hostpath-provisioner-0 1/1 Running 0 76m 36 | csi-hostpath-resizer-0 1/1 Running 1 76m 37 | csi-hostpath-snapshotter-0 1/1 Running 0 76m 38 | csi-hostpath-socat-0 1/1 Running 0 76m 39 | csi-hostpathplugin-0 3/3 Running 1 76m 40 | my-csi-app 1/1 Running 0 46m 41 | ``` 42 | 43 | 因为验证而已,这里`csi-hostpathplugin`组件只部署了一个,provisioner和attacher组件都会调用这个组件上来 44 | 45 | ### 验证 46 | 47 | 部署测试应用,storageClass,pvc,app: 48 | 49 | ```shell 50 | $ for i in ./examples/csi-storageclass.yaml ./examples/csi-pvc.yaml ./examples/csi-app.yaml; do kubectl apply -f $i; done 51 | storageclass.storage.k8s.io/csi-hostpath-sc created 52 | persistentvolumeclaim/csi-pvc created 53 | pod/my-csi-app created 54 | 55 | ``` 56 | 57 | 查看pv已自动创建出来了 58 | 59 | ```shell 60 | $ kubectl get pv 61 | NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE 62 | pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e 1Gi RWO Delete Bound default/csi-pvc csi-hostpath-sc 50m 63 | 64 | $ kubectl get pvc 65 | NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE 66 | csi-pvc Bound pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e 1Gi RWO csi-hostpath-sc 50m 67 | ``` 68 | 69 | > 在节点上的/var/lib/csi-hostpath-data/目录下已经有目录创建出来了 70 | 71 | 72 | 73 | 可以通过查看容器`csi-hostpathplugin-0 `的log来看整个pv的创建以及attach过程: 74 | 75 | ```shell 76 | I1116 06:54:50.518286 1 server.go:117] GRPC call: /csi.v1.Controller/CreateVolume 77 | I1116 06:54:50.518384 1 server.go:118] GRPC request: {"accessibility_requirements":{"preferred":[{"segments":{"topology.hostpath.csi/node":"minikube"}}],"requisite":[{"segments":{"topology.hostpath.csi/node":"minikube"}}]},"capacity_range":{"required_bytes":1073741824},"name":"pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e","volume_capabilities":[{"AccessType":{"Mount":{}},"access_mode":{"mode":1}}]} 78 | I1116 06:54:50.581056 1 controllerserver.go:165] created volume 9f684dbc-27d8-11eb-884a-0242ac120016 at path /csi-data-dir/9f684dbc-27d8-11eb-884a-0242ac120016 79 | I1116 06:54:50.581129 1 server.go:123] GRPC response: {"volume":{"accessible_topology":[{"segments":{"topology.hostpath.csi/node":"minikube"}}],"capacity_bytes":1073741824,"volume_id":"9f684dbc-27d8-11eb-884a-0242ac120016"}} 80 | I1116 06:54:52.020457 1 server.go:117] GRPC call: /csi.v1.Identity/Probe 81 | I1116 06:54:56.879104 1 server.go:117] GRPC call: /csi.v1.Node/NodeGetCapabilities 82 | I1116 06:54:56.879169 1 server.go:118] GRPC request: {} 83 | I1116 06:54:56.879866 1 server.go:123] GRPC response: {"capabilities":[{"Type":{"Rpc":{"type":1}}},{"Type":{"Rpc":{"type":3}}}]} 84 | I1116 06:54:57.020014 1 server.go:117] GRPC call: /csi.v1.Node/NodeStageVolume 85 | I1116 06:54:57.020087 1 server.go:118] GRPC request: {"staging_target_path":"/var/lib/kubelet/plugins/kubernetes.io/csi/pv/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/globalmount","volume_capability":{"AccessType":{"Mount":{}},"access_mode":{"mode":1}},"volume_context":{"storage.kubernetes.io/csiProvisionerIdentity":"1605508257344-8081-hostpath.csi.k8s.io"},"volume_id":"9f684dbc-27d8-11eb-884a-0242ac120016"} 86 | I1116 06:54:57.022399 1 server.go:123] GRPC response: {} 87 | I1116 06:54:57.041971 1 server.go:117] GRPC call: /csi.v1.Node/NodeGetCapabilities 88 | I1116 06:54:57.042036 1 server.go:118] GRPC request: {} 89 | I1116 06:54:57.043319 1 server.go:123] GRPC response: {"capabilities":[{"Type":{"Rpc":{"type":1}}},{"Type":{"Rpc":{"type":3}}}]} 90 | I1116 06:54:57.068101 1 server.go:117] GRPC call: /csi.v1.Node/NodePublishVolume 91 | I1116 06:54:57.068159 1 server.go:118] GRPC request: {"staging_target_path":"/var/lib/kubelet/plugins/kubernetes.io/csi/pv/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/globalmount","target_path":"/var/lib/kubelet/pods/9c5aa371-e5a7-4b67-8795-ec7013811363/volumes/kubernetes.io~csi/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/mount","volume_capability":{"AccessType":{"Mount":{}},"access_mode":{"mode":1}},"volume_context":{"csi.storage.k8s.io/ephemeral":"false","csi.storage.k8s.io/pod.name":"my-csi-app","csi.storage.k8s.io/pod.namespace":"default","csi.storage.k8s.io/pod.uid":"9c5aa371-e5a7-4b67-8795-ec7013811363","csi.storage.k8s.io/serviceAccount.name":"default","storage.kubernetes.io/csiProvisionerIdentity":"1605508257344-8081-hostpath.csi.k8s.io"},"volume_id":"9f684dbc-27d8-11eb-884a-0242ac120016"} 92 | I1116 06:54:57.104975 1 mount_linux.go:164] Detected OS without systemd 93 | I1116 06:54:57.146159 1 nodeserver.go:166] target /var/lib/kubelet/pods/9c5aa371-e5a7-4b67-8795-ec7013811363/volumes/kubernetes.io~csi/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/mount 94 | fstype 95 | device 96 | readonly false 97 | volumeId 9f684dbc-27d8-11eb-884a-0242ac120016 98 | attributes map[csi.storage.k8s.io/ephemeral:false csi.storage.k8s.io/pod.name:my-csi-app csi.storage.k8s.io/pod.namespace:default csi.storage.k8s.io/pod.uid:9c5aa371-e5a7-4b67-8795-ec7013811363 csi.storage.k8s.io/serviceAccount.name:default storage.kubernetes.io/csiProvisionerIdentity:1605508257344-8081-hostpath.csi.k8s.io] 99 | mountflags [] 100 | I1116 06:54:57.146375 1 mount_linux.go:164] Detected OS without systemd 101 | I1116 06:54:57.146449 1 mount_linux.go:146] Mounting cmd (mount) with arguments ([-o bind /csi-data-dir/9f684dbc-27d8-11eb-884a-0242ac120016 /var/lib/kubelet/pods/9c5aa371-e5a7-4b67-8795-ec7013811363/volumes/kubernetes.io~csi/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/mount]) 102 | I1116 06:54:57.448129 1 mount_linux.go:146] Mounting cmd (mount) with arguments ([-o bind,remount /csi-data-dir/9f684dbc-27d8-11eb-884a-0242ac120016 /var/lib/kubelet/pods/9c5aa371-e5a7-4b67-8795-ec7013811363/volumes/kubernetes.io~csi/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/mount]) 103 | ``` 104 | 105 | 先进行create volume,在进行NodePublishVolume 106 | 107 | #### NodeStageVolume的作用 108 | 109 | 对于块存储来说,设备只能mount到一个目录上,所以NodeStageVolume就是先mount到一个globalmount目录(类似:/var/lib/kubelet/plugins/kubernetes.io/csi/pv/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/globalmount),然后再bind到pod的目录(/var/lib/kubelet/pods/9c5aa371-e5a7-4b67-8795-ec7013811363/volumes/kubernetes.io~csi/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/mount/hello-world),这样就可以pv挂载在多个pod中(NodePublishVolume)。在这一步可以进行格式化 110 | 111 | 112 | 113 | ## 参考 114 | 115 | - https://github.com/kubernetes-csi/csi-driver-host-path/blob/master/docs/deploy-1.17-and-later.md 116 | - https://arslan.io/2018/06/21/how-to-write-a-container-storage-interface-csi-plugin/ -------------------------------------------------------------------------------- /csi/how-to-write-csi-driver.md: -------------------------------------------------------------------------------- 1 | # 如何编写一个CSI插件 2 | 3 | > 这里以[csi-driver-host-path](https://github.com/kubernetes-csi/csi-driver-host-path)作为例子,来看看是如何实现一个csi插件的? 4 | 5 | **目标:** 6 | 7 | - 支持PV动态创建,并且能够挂载在POD中 8 | - volume来自本地目录,主要是模拟volume产生的过程,这样就不依赖于某个特定的存储服务 9 | 10 | ## 预备知识 11 | 12 | 在[上一篇文章](./README.)中,已经对CSI概念有个了解,并且提出了CSI组件需要实现的RPC接口,那我们为什么需要这些接口,这需要从volume要被使用经过了以下流程: 13 | 14 | - volume创建 15 | - volume `attach`到节点(比如像EBS硬盘,NFS可能就直接下一步mount了) 16 | - volume 被`mount`到指定目录(这个目录其实就被映射到容器中,由kubelet 中的`VolumeManager` 调用) 17 | 18 | 而当卸载时正好是相反的:`unmount`,`detach`,`delete volume` 19 | 20 | 正好对应如下图: 21 | 22 | ``` 23 | CreateVolume +------------+ DeleteVolume 24 | +------------->| CREATED +--------------+ 25 | | +---+----^---+ | 26 | | Controller | | Controller v 27 | +++ Publish | | Unpublish +++ 28 | |X| Volume | | Volume | | 29 | +-+ +---v----+---+ +-+ 30 | | NODE_READY | 31 | +---+----^---+ 32 | Node | | Node 33 | Stage | | Unstage 34 | Volume | | Volume 35 | +---v----+---+ 36 | | VOL_READY | 37 | +---+----^---+ 38 | Node | | Node 39 | Publish | | Unpublish 40 | Volume | | Volume 41 | +---v----+---+ 42 | | PUBLISHED | 43 | +------------+ 44 | ``` 45 | 46 | 而为什么多个`NodeStageVolume`的过程是因为: 47 | 48 | > 对于块存储来说,设备只能mount到一个目录上,所以`NodeStageVolume`就是先mount到一个globalmount目录(类似:`/var/lib/kubelet/plugins/kubernetes.io/csi/pv/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/globalmount`),然后再`NodePublishVolume`这一步中通过`mount bind`到pod的目录(`/var/lib/kubelet/pods/9c5aa371-e5a7-4b67-8795-ec7013811363/volumes/kubernetes.io~csi/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/mount/hello-world`),这样就可以实现一个pv挂载在多个pod中使用。 49 | 50 | 51 | 52 | ## 代码实现 53 | 54 | 我们并不一定要实现所有的接口,这个可以通过CSI中`Capabilities`能力标识出来,我们组件提供的能力,比如 55 | 56 | - `IdentityServer`中的`GetPluginCapabilities`方法 57 | 58 | - `ControllerServer`中的`ControllerGetCapabilities`方法 59 | - `NodeServer`中的`NodeGetCapabilities` 60 | 61 | 这些方法都是在告诉调用方,我们的组件实现了哪些能力,未实现的方法就不会调用了。 62 | 63 | ### IdentityServer 64 | 65 | `IdentityServer`包含了三个接口,这里我们主要实现 66 | 67 | ```go 68 | // IdentityServer is the server API for Identity service. 69 | type IdentityServer interface { 70 | GetPluginInfo(context.Context, *GetPluginInfoRequest) (*GetPluginInfoResponse, error) 71 | GetPluginCapabilities(context.Context, *GetPluginCapabilitiesRequest) (*GetPluginCapabilitiesResponse, error) 72 | Probe(context.Context, *ProbeRequest) (*ProbeResponse, error) 73 | } 74 | ``` 75 | 76 | 主要看下`GetPluginCapabilities`这个方法: 77 | 78 | [identityserver.go#L60](https://github.com/kubernetes-csi/csi-driver-host-path/blob/master/pkg/hostpath/identityserver.go#L60): 79 | 80 | ```go 81 | func (ids *identityServer) GetPluginCapabilities(ctx context.Context, req *csi.GetPluginCapabilitiesRequest) (*csi.GetPluginCapabilitiesResponse, error) { 82 | return &csi.GetPluginCapabilitiesResponse{ 83 | Capabilities: []*csi.PluginCapability{ 84 | { 85 | Type: &csi.PluginCapability_Service_{ 86 | Service: &csi.PluginCapability_Service{ 87 | Type: csi.PluginCapability_Service_CONTROLLER_SERVICE, 88 | }, 89 | }, 90 | }, 91 | { 92 | Type: &csi.PluginCapability_Service_{ 93 | Service: &csi.PluginCapability_Service{ 94 | Type: csi.PluginCapability_Service_VOLUME_ACCESSIBILITY_CONSTRAINTS, 95 | }, 96 | }, 97 | }, 98 | }, 99 | }, nil 100 | } 101 | ``` 102 | 103 | 以上就告诉调用者我们提供了ControllerService的能力,以及volume访问限制的能力(CSI 处理时需要根据集群拓扑作调整) 104 | 105 | > PS:其实在k8s还提供了一个包:github.com/kubernetes-csi/drivers/pkg/csi-common,里面提供了比如`DefaultIdentityServer`,`DefaultControllerServer`,`DefaultNodeServer`的struct,只要在我们自己的`XXXServer struct`中继承这些`struct`,我们的代码中就只要包含自己实现的方法就行了,可以参考[alibaba-cloud-csi-driver](https://github.com/kubernetes-sigs/alibaba-cloud-csi-driver/blob/master/pkg/disk/identityserver.go#L26)中的。 106 | 107 | ###ControllerServer 108 | 109 | `ControllerServer`我们主要关注`CreateVolume`,`DeleteVolume`,因为是hostpath volume,所以就没有attach的这个过程了,我们放在NodeServer中实现: 110 | 111 | #### CreateVolume 112 | 113 | [controllerserver.go#L73](https://github.com/kubernetes-csi/csi-driver-host-path/blob/b1cfe85dd7bfffce2bbe5b1228c994a9bc3649fb/pkg/hostpath/controllerserver.go#L73) 114 | 115 | ```go 116 | func (cs *controllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) { 117 | //校验参数是否有CreateVolume的能力 118 | if err := cs.validateControllerServiceRequest(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME); err != nil { 119 | glog.V(3).Infof("invalid create volume req: %v", req) 120 | return nil, err 121 | } 122 | 123 | //.....这里省略的校验参数的过程 124 | 125 | 126 | //这里根据volume name判断是否已经存在了,存在了就返回就行了 127 | if exVol, err := getVolumeByName(req.GetName()); err == nil { 128 | // volume已经存在,但是大小不符合 129 | if exVol.VolSize < capacity { 130 | return nil, status.Errorf(codes.AlreadyExists, "Volume with the same name: %s but with different size already exist", req.GetName()) 131 | } 132 | //这里判断是否设置了pvc.dataSource,就表示是一个restore过程 133 | if req.GetVolumeContentSource() != nil { 134 | volumeSource := req.VolumeContentSource 135 | switch volumeSource.Type.(type) { 136 | //校验:从快照中恢复 137 | case *csi.VolumeContentSource_Snapshot: 138 | if volumeSource.GetSnapshot() != nil && exVol.ParentSnapID != "" && exVol.ParentSnapID != volumeSource.GetSnapshot().GetSnapshotId() { 139 | return nil, status.Error(codes.AlreadyExists, "existing volume source snapshot id not matching") 140 | } 141 | //校验:clone过程 142 | case *csi.VolumeContentSource_Volume: 143 | if volumeSource.GetVolume() != nil && exVol.ParentVolID != volumeSource.GetVolume().GetVolumeId() { 144 | return nil, status.Error(codes.AlreadyExists, "existing volume source volume id not matching") 145 | } 146 | default: 147 | return nil, status.Errorf(codes.InvalidArgument, "%v not a proper volume source", volumeSource) 148 | } 149 | } 150 | // TODO (sbezverk) Do I need to make sure that volume still exists? 151 | return &csi.CreateVolumeResponse{ 152 | Volume: &csi.Volume{ 153 | VolumeId: exVol.VolID, 154 | CapacityBytes: int64(exVol.VolSize), 155 | VolumeContext: req.GetParameters(), 156 | ContentSource: req.GetVolumeContentSource(), 157 | }, 158 | }, nil 159 | } 160 | 161 | //创建volume 162 | volumeID := uuid.NewUUID().String() 163 | //创建hostpath的volume 164 | vol, err := createHostpathVolume(volumeID, req.GetName(), capacity, requestedAccessType, false /* ephemeral */) 165 | if err != nil { 166 | return nil, status.Errorf(codes.Internal, "failed to create volume %v: %v", volumeID, err) 167 | } 168 | glog.V(4).Infof("created volume %s at path %s", vol.VolID, vol.VolPath) 169 | 170 | //判断是从快照恢复,还是clone 171 | if req.GetVolumeContentSource() != nil { 172 | path := getVolumePath(volumeID) 173 | volumeSource := req.VolumeContentSource 174 | switch volumeSource.Type.(type) { 175 | //从快照恢复 176 | case *csi.VolumeContentSource_Snapshot: 177 | if snapshot := volumeSource.GetSnapshot(); snapshot != nil { 178 | err = loadFromSnapshot(capacity, snapshot.GetSnapshotId(), path, requestedAccessType) 179 | vol.ParentSnapID = snapshot.GetSnapshotId() 180 | } 181 | //clone 182 | case *csi.VolumeContentSource_Volume: 183 | if srcVolume := volumeSource.GetVolume(); srcVolume != nil { 184 | err = loadFromVolume(capacity, srcVolume.GetVolumeId(), path, requestedAccessType) 185 | vol.ParentVolID = srcVolume.GetVolumeId() 186 | } 187 | default: 188 | err = status.Errorf(codes.InvalidArgument, "%v not a proper volume source", volumeSource) 189 | } 190 | if err != nil { 191 | if delErr := deleteHostpathVolume(volumeID); delErr != nil { 192 | glog.V(2).Infof("deleting hostpath volume %v failed: %v", volumeID, delErr) 193 | } 194 | return nil, err 195 | } 196 | glog.V(4).Infof("successfully populated volume %s", vol.VolID) 197 | } 198 | 199 | //Topology表示volume能够部署在哪些节点(生产情况可能就对应可用区) 200 | topologies := []*csi.Topology{&csi.Topology{ 201 | Segments: map[string]string{TopologyKeyNode: cs.nodeID}, 202 | }} 203 | 204 | return &csi.CreateVolumeResponse{ 205 | Volume: &csi.Volume{ 206 | VolumeId: volumeID, 207 | CapacityBytes: req.GetCapacityRange().GetRequiredBytes(), 208 | VolumeContext: req.GetParameters(), 209 | ContentSource: req.GetVolumeContentSource(), 210 | AccessibleTopology: topologies, 211 | }, 212 | }, nil 213 | } 214 | ``` 215 | 216 | **`createHostpathVolume`** 217 | 218 | 再来看下`createHostpathVolume`方法,这里`accessType`有两个选项,是创建文件系统,还是创建块,其实就是对应pvc中`volumeMode`字段: 219 | 220 | [pkg/hostpath/hostpath.go#L208](https://github.com/kubernetes-csi/csi-driver-host-path/blob/b1cfe85dd7bfffce2bbe5b1228c994a9bc3649fb/pkg/hostpath/hostpath.go#L208) 221 | 222 | ```go 223 | 224 | // createVolume create the directory for the hostpath volume. 225 | // It returns the volume path or err if one occurs. 226 | func createHostpathVolume(volID, name string, cap int64, volAccessType accessType, ephemeral bool) (*hostPathVolume, error) { 227 | path := getVolumePath(volID) 228 | 229 | switch volAccessType { 230 | case mountAccess: 231 | //创建文件 232 | err := os.MkdirAll(path, 0777) 233 | if err != nil { 234 | return nil, err 235 | } 236 | case blockAccess: 237 | //创建块 238 | executor := utilexec.New() 239 | size := fmt.Sprintf("%dM", cap/mib) 240 | // Create a block file. 241 | _, err := os.Stat(path) 242 | if err != nil { 243 | if os.IsNotExist(err) { 244 | out, err := executor.Command("fallocate", "-l", size, path).CombinedOutput() 245 | if err != nil { 246 | return nil, fmt.Errorf("failed to create block device: %v, %v", err, string(out)) 247 | } 248 | } else { 249 | return nil, fmt.Errorf("failed to stat block device: %v, %v", path, err) 250 | } 251 | } 252 | 253 | // 通过losetup将文件虚拟成块设备 254 | // Associate block file with the loop device. 255 | volPathHandler := volumepathhandler.VolumePathHandler{} 256 | _, err = volPathHandler.AttachFileDevice(path) 257 | if err != nil { 258 | // Remove the block file because it'll no longer be used again. 259 | if err2 := os.Remove(path); err2 != nil { 260 | glog.Errorf("failed to cleanup block file %s: %v", path, err2) 261 | } 262 | return nil, fmt.Errorf("failed to attach device %v: %v", path, err) 263 | } 264 | default: 265 | return nil, fmt.Errorf("unsupported access type %v", volAccessType) 266 | } 267 | 268 | hostpathVol := hostPathVolume{ 269 | VolID: volID, 270 | VolName: name, 271 | VolSize: cap, 272 | VolPath: path, 273 | VolAccessType: volAccessType, 274 | Ephemeral: ephemeral, 275 | } 276 | hostPathVolumes[volID] = hostpathVol 277 | return &hostpathVol, nil 278 | } 279 | ``` 280 | 281 | #### DeleteVolume 282 | 283 | 在DeleteVolume这里主要是删除volume: 284 | 285 | [pkg/hostpath/controllerserver.go#L2](https://github.com/kubernetes-csi/csi-driver-host-path/blob/b1cfe85dd7bfffce2bbe5b1228c994a9bc3649fb/pkg/hostpath/controllerserver.go#L208) 286 | 287 | ```go 288 | func (cs *controllerServer) DeleteVolume(ctx context.Context, req *csi.DeleteVolumeRequest) (*csi.DeleteVolumeResponse, error) { 289 | // Check arguments 290 | if len(req.GetVolumeId()) == 0 { 291 | return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") 292 | } 293 | 294 | if err := cs.validateControllerServiceRequest(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME); err != nil { 295 | glog.V(3).Infof("invalid delete volume req: %v", req) 296 | return nil, err 297 | } 298 | 299 | volId := req.GetVolumeId() 300 | if err := deleteHostpathVolume(volId); err != nil { 301 | return nil, status.Errorf(codes.Internal, "failed to delete volume %v: %v", volId, err) 302 | } 303 | 304 | glog.V(4).Infof("volume %v successfully deleted", volId) 305 | 306 | return &csi.DeleteVolumeResponse{}, nil 307 | } 308 | ``` 309 | 310 | 311 | 312 | 313 | 314 | 在`ControllerService`中还有一些其他接口,比如`CreateSnapshot`创建快照,`DeleteSnapshot`删除快照,`扩容`等,其实都会依赖于我们存储服务端的提供的能力,调用相应的接口就行了。 315 | 316 | ### NodeServer 317 | 318 | 在`nodeServer`中就是实现我们的`mount`,`unmount`过程了,分别对应`NodePublishVolume`和`NodeUnpublishVolume` 319 | 320 | 321 | 322 | #### NodePublishVolume 323 | 324 | [pkg/hostpath/nodeserver.go#L5](https://github.com/kubernetes-csi/csi-driver-host-path/blob/b1cfe85dd7bfffce2bbe5b1228c994a9bc3649fb/pkg/hostpath/nodeserver.go#L50) 325 | 326 | ```go 327 | func (ns *nodeServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) { 328 | //......这里省略校验参数代码 329 | 330 | 331 | 332 | vol, err := getVolumeByID(req.GetVolumeId()) 333 | if err != nil { 334 | return nil, status.Error(codes.NotFound, err.Error()) 335 | } 336 | //对应pvc.volumeBind字段是block的情况 337 | if req.GetVolumeCapability().GetBlock() != nil { 338 | if vol.VolAccessType != blockAccess { 339 | return nil, status.Error(codes.InvalidArgument, "cannot publish a non-block volume as block volume") 340 | } 341 | 342 | volPathHandler := volumepathhandler.VolumePathHandler{} 343 | 344 | //获取device地址(通过loopset -l命令,因为是通过文件虚拟出来的块设备) 345 | // Get loop device from the volume path. 346 | loopDevice, err := volPathHandler.GetLoopDevice(vol.VolPath) 347 | if err != nil { 348 | return nil, status.Error(codes.Internal, fmt.Sprintf("failed to get the loop device: %v", err)) 349 | } 350 | 351 | mounter := mount.New("") 352 | 353 | // Check if the target path exists. Create if not present. 354 | _, err = os.Lstat(targetPath) 355 | if os.IsNotExist(err) { 356 | if err = mounter.MakeFile(targetPath); err != nil { 357 | return nil, status.Error(codes.Internal, fmt.Sprintf("failed to create target path: %s: %v", targetPath, err)) 358 | } 359 | } 360 | if err != nil { 361 | return nil, status.Errorf(codes.Internal, "failed to check if the target block file exists: %v", err) 362 | } 363 | 364 | // Check if the target path is already mounted. Prevent remounting. 365 | notMount, err := mounter.IsNotMountPoint(targetPath) 366 | if err != nil { 367 | if !os.IsNotExist(err) { 368 | return nil, status.Errorf(codes.Internal, "error checking path %s for mount: %s", targetPath, err) 369 | } 370 | notMount = true 371 | } 372 | if !notMount { 373 | // It's already mounted. 374 | glog.V(5).Infof("Skipping bind-mounting subpath %s: already mounted", targetPath) 375 | return &csi.NodePublishVolumeResponse{}, nil 376 | } 377 | 378 | //进行绑定挂载(mount bind),将块设备绑定到容器目录(targetpath类似这种:/var/lib/kubelet/pods/9c5aa371-e5a7-4b67-8795-ec7013811363/volumes/kubernetes.io~csi/pvc-bcfe33ed-e822-4b0e-954a-0f5c0468525e/mount) 379 | options := []string{"bind"} 380 | if err := mount.New("").Mount(loopDevice, targetPath, "", options); err != nil { 381 | return nil, status.Error(codes.Internal, fmt.Sprintf("failed to mount block device: %s at %s: %v", loopDevice, targetPath, err)) 382 | } 383 | //对应pvc.volumeBind字段是filesystem的情况 384 | } else if req.GetVolumeCapability().GetMount() != nil { 385 | //....这里省略,因为跟上面类似也是mount bind过程 386 | } 387 | 388 | return &csi.NodePublishVolumeResponse{}, nil 389 | } 390 | ``` 391 | 392 | 393 | 394 | ####NodeUnpublishVolume 395 | 396 | `NodeUnpublishVolume`过程就是unmount过程,如下: 397 | 398 | [pkg/hostpath/nodeserver.go#L191](https://github.com/kubernetes-csi/csi-driver-host-path/blob/b1cfe85dd7bfffce2bbe5b1228c994a9bc3649fb/pkg/hostpath/nodeserver.go#L191) 399 | 400 | ```go 401 | func (ns *nodeServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) { 402 | 403 | // Check arguments 404 | if len(req.GetVolumeId()) == 0 { 405 | return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") 406 | } 407 | if len(req.GetTargetPath()) == 0 { 408 | return nil, status.Error(codes.InvalidArgument, "Target path missing in request") 409 | } 410 | targetPath := req.GetTargetPath() 411 | volumeID := req.GetVolumeId() 412 | 413 | vol, err := getVolumeByID(volumeID) 414 | if err != nil { 415 | return nil, status.Error(codes.NotFound, err.Error()) 416 | } 417 | 418 | // Unmount only if the target path is really a mount point. 419 | if notMnt, err := mount.IsNotMountPoint(mount.New(""), targetPath); err != nil { 420 | if !os.IsNotExist(err) { 421 | return nil, status.Error(codes.Internal, err.Error()) 422 | } 423 | } else if !notMnt { 424 | // Unmounting the image or filesystem. 425 | err = mount.New("").Unmount(targetPath) 426 | if err != nil { 427 | return nil, status.Error(codes.Internal, err.Error()) 428 | } 429 | } 430 | // Delete the mount point. 431 | // Does not return error for non-existent path, repeated calls OK for idempotency. 432 | if err = os.RemoveAll(targetPath); err != nil { 433 | return nil, status.Error(codes.Internal, err.Error()) 434 | } 435 | glog.V(4).Infof("hostpath: volume %s has been unpublished.", targetPath) 436 | 437 | if vol.Ephemeral { 438 | glog.V(4).Infof("deleting volume %s", volumeID) 439 | if err := deleteHostpathVolume(volumeID); err != nil && !os.IsNotExist(err) { 440 | return nil, status.Error(codes.Internal, fmt.Sprintf("failed to delete volume: %s", err)) 441 | } 442 | } 443 | 444 | return &csi.NodeUnpublishVolumeResponse{}, nil 445 | } 446 | ``` 447 | 448 | ### 启动grpc server 449 | 450 | [pkg/hostpath/hostpath.go#L164](https://github.com/kubernetes-csi/csi-driver-host-path/blob/b1cfe85dd7bfffce2bbe5b1228c994a9bc3649fb/pkg/hostpath/hostpath.go#L164) 451 | 452 | ```go 453 | func (hp *hostPath) Run() { 454 | // Create GRPC servers 455 | hp.ids = NewIdentityServer(hp.name, hp.version) 456 | hp.ns = NewNodeServer(hp.nodeID, hp.ephemeral, hp.maxVolumesPerNode) 457 | hp.cs = NewControllerServer(hp.ephemeral, hp.nodeID) 458 | 459 | 460 | s := NewNonBlockingGRPCServer() 461 | s.Start(hp.endpoint, hp.ids, hp.cs, hp.ns) 462 | s.Wait() 463 | } 464 | ``` 465 | 466 | 467 | 468 | ##测试 469 | 470 | 我们可以通过[csc](https://github.com/rexray/gocsi/tree/master/csc)工具来进行grpc接口的测试: 471 | 472 | ```sh 473 | $ GO111MODULE=off go get -u github.com/rexray/gocsi/csc 474 | ``` 475 | 476 | **Get plugin info** 477 | 478 | ``` 479 | $ csc identity plugin-info --endpoint tcp://127.0.0.1:10000 480 | "csi-hostpath" "0.1.0" 481 | ``` 482 | 483 | **Create a volume** 484 | 485 | ``` 486 | $ csc controller new --endpoint tcp://127.0.0.1:10000 --cap 1,block CSIVolumeName 487 | CSIVolumeID 488 | ``` 489 | 490 | **Delete a volume** 491 | 492 | ``` 493 | $ csc controller del --endpoint tcp://127.0.0.1:10000 CSIVolumeID 494 | CSIVolumeID 495 | ``` 496 | 497 | **Validate volume capabilities** 498 | 499 | ``` 500 | $ csc controller validate-volume-capabilities --endpoint tcp://127.0.0.1:10000 --cap 1,block CSIVolumeID 501 | CSIVolumeID true 502 | ``` 503 | 504 | **NodePublish a volume** 505 | 506 | ``` 507 | $ csc node publish --endpoint tcp://127.0.0.1:10000 --cap 1,block --target-path /mnt/hostpath CSIVolumeID 508 | CSIVolumeID 509 | ``` 510 | 511 | **NodeUnpublish a volume** 512 | 513 | ``` 514 | $ csc node unpublish --endpoint tcp://127.0.0.1:10000 --target-path /mnt/hostpath CSIVolumeID 515 | CSIVolumeID 516 | ``` 517 | 518 | **Get Nodeinfo** 519 | 520 | ``` 521 | $ csc node get-info --endpoint tcp://127.0.0.1:10000 522 | CSINode 523 | ``` 524 | 525 | 526 | 527 | ## 部署 528 | 529 | 从上一篇文章中我们可以看到,CSI真正运行起来,其实还需要一些官方提供的组件进行配合,比如`node-driver-registrar`,`csi-provision`,`csi-attacher`,我们将这些container作为我们的sidecar容器,通过volume共享socket连接,方便调用,部署在一起。 530 | 531 | 我们把服务分为两个部分: 532 | 533 | - controller :以Deployment或者Statefulset方式部署,通过leader selector,控制只有一个在工作。 534 | - node:以DaemonSet方式部署,在每个节点上都调度 535 | 536 | > hostpath因为只有在单个节点上测试用,所以它的都使用了Statefulset,因为只是测试。 537 | 538 | 在生产部署的话可以参考[csi-driver-nfs]( https://github.com/kubernetes-csi/csi-driver-nfs/tree/master/deploy) 服务的部署,这个服务比较完整。 539 | 540 | - https://github.com/kubernetes-csi/csi-driver-nfs/blob/master/deploy/csi-nfs-node.yaml 541 | - https://github.com/kubernetes-csi/csi-driver-nfs/blob/master/deploy/csi-nfs-controller.yaml 542 | 543 | 当然还有一些rbac,CSIDriver的创建,这里就不贴出来了。 544 | 545 | 546 | 547 | ## 总结 548 | 549 | 回顾下整个组件是怎么协调工作的: 550 | 551 | - `csi-provisioner`组件监听pvc的创建,从而通过 CSI socket 创建 [CreateVolumeRequest](https://github.com/container-storage-interface/spec/blob/master/spec.md#createvolume) 请求至`CreateVolume`方法 552 | - `csi-provisioner`创建 PV 以及更新 PVC状态至 bound ,从而由 controller-manager创建`VolumeAttachment`对象 553 | - `csi-attacher` 监听`VolumeAttachments` 对象创建,从而调用[ ControllerPublishVolume](https://github.com/container-storage-interface/spec/blob/master/spec.md#controllerpublishvolume) 方法。 554 | - `kubelet`一直都在等待volume attach, 从而调用 [NodeStageVolume](https://github.com/container-storage-interface/spec/blob/master/spec.md#nodestagevolume) (主要做格式化以及mount到节点上一个全局目录) 方法 - *这一步可选* 555 | - CSI Driver在 在 [NodeStageVolume](https://github.com/container-storage-interface/spec/blob/master/spec.md#nodestagevolume) 方法中将volumemount到 `/var/lib/kubelet/plugins/kubernetes.io/csi/pv//globalmount`这个目录并返回给kubelet - *这一步可选* 556 | - `kubelet`调用[NodePublishVolume](https://github.com/container-storage-interface/spec/blob/master/spec.md#nodepublishvolume) (挂载到pod目录通过`mount bind`) 557 | - CSI Driver相应[ NodePublishVolume](https://github.com/container-storage-interface/spec/blob/master/spec.md#nodepublishvolume) 请求,将volume挂载到pod目录 `/var/lib/kubelet/pods//volumes/[kubernetes.io](http://kubernetes.io/)~csi//mount` 558 | - 最后,kubelet启动容器 559 | 560 | 561 | 562 | ## 参考 563 | 564 | - https://medium.com/velotio-perspectives/kubernetes-csi-in-action-explained-with-features-and-use-cases-4f966b910774 565 | 566 | - https://kubernetes-csi.github.io/docs/developing.html 567 | 568 | -------------------------------------------------------------------------------- /keda/README.md: -------------------------------------------------------------------------------- 1 | # KEDA - 一个基于事件驱动的伸缩控制器 2 | 3 | keda是一个基于事件驱动的伸缩控制器,可以实现应用缩容至0,以及从0开始扩容。目前已支持像CPU/Memroy、Mysql、Prometheus、Redis等20多种事件来源(Scaler)。 4 | 5 | 目前也是CNCF下的sandbox项目,最初主要由微软、redhat以及社区的人员参与贡献。 6 | 7 | **网站**:https://keda.sh/ 8 | 9 | **项目地址**:https://github.com/kedacore/keda 10 | 11 | **KEDA架构图**: 12 | 13 | keda架构图 14 | 15 | 16 | 17 | ## 安装 18 | 19 | > keda 2.0版本要求k8s集群>=1.16 20 | 21 | 支持多种安装方式,可以查看keda文档:https://keda.sh/docs/2.0/deploy/#install 22 | 23 | 比如直接使用YAML文件安装: 24 | 25 | ```shell 26 | kubectl apply -f https://github.com/kedacore/keda/releases/download/v2.0.0/keda-2.0.0.yaml 27 | ``` 28 | 29 | 检查集群中是否安装成功: 30 | 31 | ```shell 32 | >kubectl get pod -n keda 33 | NAME READY STATUS RESTARTS AGE 34 | keda-metrics-apiserver-5bffbfbd68-s7pbn 1/1 Running 10 2d23h 35 | keda-operator-7b98595dc7-tvgr9 1/1 Running 19 2d23h 36 | ``` 37 | 38 | ## 基本使用 39 | 40 | KEDA 2.0有两种控制对象: 41 | 42 | - [ScaledObject](https://keda.sh/docs/2.0/concepts/scaling-deployments/):基于HPA,根据事件触发器(scaler)控制应用(Deployments, StatefulSets & Custom Resources)的水平伸缩 43 | - [ScaledJob](https://keda.sh/docs/2.0/concepts/scaling-jobs/):根据事件触发器(scaler),生成job 44 | 45 | ###ScaledObject配置 46 | 47 | ```yaml 48 | apiVersion: keda.sh/v1alpha1 49 | kind: ScaledObject 50 | metadata: 51 | name: {scaled-object-name} 52 | spec: 53 | scaleTargetRef: 54 | apiVersion: {api-version-of-target-resource} # Optional. Default: apps/v1 55 | kind: {kind-of-target-resource} # Optional. Default: Deployment 56 | name: {name-of-target-resource} # Mandatory. Must be in the same namespace as the ScaledObject 57 | envSourceContainerName: {container-name} # Optional. Default: .spec.template.spec.containers[0] 58 | pollingInterval: 30 # Optional. Default: 30 seconds 59 | cooldownPeriod: 300 # Optional. Default: 300 seconds 60 | minReplicaCount: 0 # Optional. Default: 0 61 | maxReplicaCount: 100 # Optional. Default: 100 62 | advanced: # Optional. Section to specify advanced options 63 | restoreToOriginalReplicaCount: true/false # Optional. Default: false 64 | horizontalPodAutoscalerConfig: # Optional. Section to specify HPA related options 65 | behavior: # Optional. Use to modify HPA's scaling behavior 66 | scaleDown: 67 | stabilizationWindowSeconds: 300 68 | policies: 69 | - type: Percent 70 | value: 100 71 | periodSeconds: 15 72 | triggers: 73 | # {list of triggers to activate scaling of the target resource} 74 | ``` 75 | 76 | **参数说明:** 77 | 78 | | 参数 | 说明 | 79 | | ------------------------------------------- | :------------------------------------------- | 80 | | spec.scaleTargetRef | 需要扩缩容的对象资源 | 81 | | spec.pollingInterval | 定时获取触发器(scaler)的时间间隔,默认30s | 82 | | spec.cooldownPeriod | 上次active至缩容为0需要等待的时间,默认300s | 83 | | spec.minReplicaCount | 应用最小值 | 84 | | spec.maxReplicaCount | 应用最大值 | 85 | | spec.advanced.restoreToOriginalReplicaCount | 在删除ScaledObject之后,是否将应用恢复为原值 | 86 | | spec.advanced.horizontalPodAutoscalerConfig | HPA对应的配置 | 87 | | spec.triggers | scaler列表 | 88 | 89 | 比如创建一个基于prometheus的数据作为触发器的`scaledobject`: 90 | 91 | ```yaml 92 | apiVersion: keda.k8s.io/v1alpha1 93 | kind: ScaledObject 94 | metadata: 95 | name: prometheus-scaledobject 96 | namespace: default 97 | spec: 98 | scaleTargetRef: 99 | deploymentName: http-demo 100 | minReplicaCount: 1 101 | triggers: 102 | - type: prometheus 103 | metadata: 104 | serverAddress: http://192.168.99.100:31046/ 105 | metricName: gin_requests_total 106 | threshold: '2' 107 | query: sum(rate(gin_requests_total{app="http-demo",code="200"}[2m])) 108 | ``` 109 | 110 | ###Scaling Jobs配置 111 | 112 | ```yaml 113 | apiVersion: keda.sh/v1alpha1 114 | kind: ScaledJob 115 | metadata: 116 | name: {scaled-job-name} 117 | spec: 118 | jobTargetRef: 119 | parallelism: 1 # [max number of desired pods](https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#controlling-parallelism) 120 | completions: 1 # [desired number of successfully finished pods](https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#controlling-parallelism) 121 | activeDeadlineSeconds: 600 # Specifies the duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer 122 | backoffLimit: 6 # Specifies the number of retries before marking this job failed. Defaults to 6 123 | template: 124 | # describes the [job template](https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/) 125 | pollingInterval: 30 # Optional. Default: 30 seconds 126 | successfulJobsHistoryLimit: 5 # Optional. Default: 100. How many completed jobs should be kept. 127 | failedJobsHistoryLimit: 5 # Optional. Default: 100. How many failed jobs should be kept. 128 | envSourceContainerName: {container-name} # Optional. Default: .spec.JobTargetRef.template.spec.containers[0] 129 | maxReplicaCount: 100 # Optional. Default: 100 130 | scalingStrategy: 131 | strategy: "custom" # Optional. Default: default. Which Scaling Strategy to use. 132 | customScalingQueueLengthDeduction: 1 # Optional. A parameter to optimize custom ScalingStrategy. 133 | customScalingRunningJobPercentage: "0.5" # Optional. A parameter to optimize custom ScalingStrategy. 134 | triggers: 135 | # {list of triggers to create jobs} 136 | ``` 137 | 138 | **参数说明:** 139 | 140 | | 参数 | 说明 | 141 | | ------------------------------- | ------------------------------------------------------------ | 142 | | spec.jobTargetRef | 生成的job描述, | 143 | | spec.pollingInterval | 定时获取触发器(scaler)的时间间隔,默认30s | 144 | | spec.successfulJobsHistoryLimit | 保留的success job数量 | 145 | | spec.failedJobsHistoryLimit | 保留的failed job数量 | 146 | | spec.envSourceContainerName | 通过环境变量设置参数的容器,比如“iam.amazonaws.com/role”参数等 | 147 | | spec.maxReplicaCount | job最大数量 | 148 | | spec.scalingStrategy | job生成策略 | 149 | | spec.triggers | scaler列表 | 150 | 151 | ### Scaler 152 | 153 | 支持的Scaler如下: 154 | 155 | - ActiveMQ Artemis 156 | - Apache Kafka 157 | - AWS CloudWatch 158 | - AWS Kinesis Stream 159 | - AWS SQS Queue 160 | - Azure Blob Storage 161 | - Azure Event Hubs 162 | - Azure Log Analytics 163 | - Azure Monitor 164 | - Azure Service Bus 165 | - Azure Storage Queue 166 | - CPU 167 | - Cron 168 | - External 169 | - External Push 170 | - Google Cloud Platform‎ Pub/Sub 171 | - Huawei Cloudeye 172 | - IBM MQ 173 | - Liiklus Topic 174 | - Memory 175 | - Metrics API 176 | - MySQL 177 | - NATS Streaming 178 | - PostgreSQL 179 | - Prometheus 180 | - RabbitMQ Queue 181 | - Redis Lists 182 | - Redis Streams 183 | 184 | #### -------------------------------------------------------------------------------- /keda/source.md: -------------------------------------------------------------------------------- 1 | # 源码分析:KEDA是如何工作的? 2 | 3 | > 文章中源码是基于KEDA 2.0( [50bec80](https://github.com/kedacore/keda/commit/50bec808f8b4656922797e4bcb7c2b61fabd6d0e))来进行分析 4 | > 5 | > keda 2.0 要求k8s集群版本 >=1.16 6 | 7 | 8 | KEDA 在[2020年11月4号release了2.0版本](https://keda.sh/blog/keda-2.0-release/),包含了一些新的比较有用的特性,比如`ScaledObject/ScaledJob`中支持多触发器、支持HPA原始的CPU、Memory scaler等。 9 | 10 | 具体的安装使用请参考上一篇文章[使用keda完成基于事件的弹性伸缩](./introduction.md),这篇文章主要深入的看下KEDA内部机制以及是如何工作的。 11 | 12 | **我们先提出几个问题,带着问题去看代码,方便我们理解整个机制:** 13 | 14 | - KEDA是如何获取到多种事件的指标,以及如何判断扩缩容的? 15 | - KEDA是如何做到将应用的副本数缩容0,依据是什么? 16 | 17 | ## 代码结构 18 | 19 | 对一些主要目录说明,其他一些MD文件主要是文字说明: 20 | 21 | ``` 22 | ├── BRANDING.md 23 | ├── BUILD.md //如何在本地编译和运行 24 | ├── CHANGELOG.md 25 | ├── CONTRIBUTING.md //如何参与贡献次项目 26 | ├── CREATE-NEW-SCALER.md 27 | ├── Dockerfile 28 | ├── Dockerfile.adapter 29 | ├── GOVERNANCE.md 30 | ├── LICENSE 31 | ├── MAINTAINERS.md 32 | ├── Makefile // 构建编译相关命令 33 | ├── PROJECT 34 | ├── README.md 35 | ├── RELEASE-PROCESS.MD 36 | ├── adapter // keda-metrics-apiserver 组件入口 37 | ├── api // 自定义资源定义,例如ScaledObject的定义 38 | ├── bin 39 | ├── config //组件yaml资源,通过kustomization工具生成 40 | ├── controllers //kubebuilder 中controller 代码控制crd资源 41 | ├── go.mod 42 | ├── go.sum 43 | ├── hack 44 | ├── images 45 | ├── main.go //keda-operator controller入口 46 | ├── pkg //包含组件核心代码实现 47 | ├── tests //e2e测试 48 | ├── tools 49 | ├── vendor 50 | └── version 51 | ``` 52 | 53 | keda中主要是两个组件`keda-operator`以及`keda-metrics-apiserver`。 54 | 55 | - keda-operator : 负责创建/更新HPA以及通过Loop控制应用副本数 56 | - keda-metrics-apiserver:实现external-metrics接口,以对接给HPA的external类型的指标查询(比如各种prometheus指标,mysql等) 57 | 58 | 59 | ## keda-operator 60 | 项目中用到了[kubebuilder](https://github.com/kubernetes-sigs/kubebuilder) SDK,用来完成这个Operator的编写。 61 | 62 | 对于k8s中的自定义controller不了解的可以看看这边文章:[如何在Kubernetes中创建一个自定义Controller?](/blog/202005/custom-resources-and-controllers/)。 63 | 64 | keda controller的主要流程,画了幅图: 65 | ![keda-controller 分析流程](https://silenceper.oss-cn-beijing.aliyuncs.com/images/keda-controller-analyze.png) 66 | 67 | 组件启动入口在于`main.go`文件中: 68 | 69 | 通过`controller-runtime`组件启动两个自定义controller:`ScaledObjectReconciler`,`ScaledJobReconciler`: 70 | 71 | ```go 72 | mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ 73 | Scheme: scheme, 74 | MetricsBindAddress: metricsAddr, 75 | HealthProbeBindAddress: ":8081", 76 | Port: 9443, 77 | LeaderElection: enableLeaderElection, 78 | LeaderElectionID: "operator.keda.sh", 79 | }) 80 | ... 81 | 82 | // Add readiness probe 83 | err = mgr.AddReadyzCheck("ready-ping", healthz.Ping) 84 | ... 85 | // Add liveness probe 86 | err = mgr.AddHealthzCheck("health-ping", healthz.Ping) 87 | .... 88 | //注册 ScaledObject 处理的controller 89 | if err = (&controllers.ScaledObjectReconciler{ 90 | Client: mgr.GetClient(), 91 | Log: ctrl.Log.WithName("controllers").WithName("ScaledObject"), 92 | Scheme: mgr.GetScheme(), 93 | }).SetupWithManager(mgr); err != nil { 94 | setupLog.Error(err, "unable to create controller", "controller", "ScaledObject") 95 | os.Exit(1) 96 | } 97 | ////注册 ScaledJob 处理的controller 98 | if err = (&controllers.ScaledJobReconciler{ 99 | Client: mgr.GetClient(), 100 | Log: ctrl.Log.WithName("controllers").WithName("ScaledJob"), 101 | Scheme: mgr.GetScheme(), 102 | }).SetupWithManager(mgr); err != nil { 103 | setupLog.Error(err, "unable to create controller", "controller", "ScaledJob") 104 | os.Exit(1) 105 | } 106 | 107 | if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { 108 | setupLog.Error(err, "problem running manager") 109 | os.Exit(1) 110 | } 111 | ``` 112 | ### ScaledObjectReconciler 处理 113 | 我们主要关注[`Reconcile`](https://github.com/kedacore/keda/blob/main/controllers/scaledobject_controller.go#L100)方法,当`ScaledObject`发生变化时将会触发该方法: 114 | 方法内部主要功能实现: 115 | 116 | ```go 117 | ... 118 | // 处理删除ScaledObject的情况 119 | if scaledObject.GetDeletionTimestamp() != nil { 120 | //进入垃圾回收(比如停止goroutine中Loop,恢复原有副本数) 121 | return ctrl.Result{}, r.finalizeScaledObject(reqLogger, scaledObject) 122 | } 123 | 124 | // 给ScaledObject资源加上Finalizer:finalizer.keda.sh 125 | if err := r.ensureFinalizer(reqLogger, scaledObject); err != nil { 126 | return ctrl.Result{}, err 127 | } 128 | ... 129 | 130 | 131 | // 真正处理ScaledObject资源 132 | msg, err := r.reconcileScaledObject(reqLogger, scaledObject) 133 | // 设置Status字段说明 134 | conditions := scaledObject.Status.Conditions.DeepCopy() 135 | if err != nil { 136 | reqLogger.Error(err, msg) 137 | conditions.SetReadyCondition(metav1.ConditionFalse, "ScaledObjectCheckFailed", msg) 138 | conditions.SetActiveCondition(metav1.ConditionUnknown, "UnkownState", "ScaledObject check failed") 139 | } else { 140 | reqLogger.V(1).Info(msg) 141 | conditions.SetReadyCondition(metav1.ConditionTrue, "ScaledObjectReady", msg) 142 | } 143 | kedacontrollerutil.SetStatusConditions(r.Client, reqLogger, scaledObject, &conditions) 144 | return ctrl.Result{}, err 145 | ``` 146 | 147 | **r.reconcileScaledObject方法:** 148 | 149 | 这个方法中主要两个动作: 150 | - `ensureHPAForScaledObjectExists`创建HPA资源 151 | - 进入`requestScaleLoop`(不断的检测scaler 是否active,进行副本数的修改) 152 | 153 | #### ensureHPAForScaledObjectExists 154 | 通过跟踪进入到[newHPAForScaledObject](https://github.com/kedacore/keda/blob/50bec808f8b4656922797e4bcb7c2b61fabd6d0e/controllers/hpa.go#L43)方法: 155 | 156 | ```go 157 | scaledObjectMetricSpecs, err := r.getScaledObjectMetricSpecs(logger, scaledObject) 158 | ...省略代码 159 | 160 | hpa := &autoscalingv2beta2.HorizontalPodAutoscaler{ 161 | Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{ 162 | MinReplicas: getHPAMinReplicas(scaledObject), 163 | MaxReplicas: getHPAMaxReplicas(scaledObject), 164 | Metrics: scaledObjectMetricSpecs, 165 | Behavior: behavior, 166 | ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{ 167 | Name: scaledObject.Spec.ScaleTargetRef.Name, 168 | Kind: gvkr.Kind, 169 | APIVersion: gvkr.GroupVersion().String(), 170 | }}, 171 | ObjectMeta: metav1.ObjectMeta{ 172 | Name: getHPAName(scaledObject), 173 | Namespace: scaledObject.Namespace, 174 | Labels: labels, 175 | }, 176 | TypeMeta: metav1.TypeMeta{ 177 | APIVersion: "v2beta2", 178 | }, 179 | } 180 | ``` 181 | 可以看到创建ScalerObject其实最终也是创建了HPA,其实还是通过HPA本身的特性来控制应用的弹性伸缩。 182 | 183 | 其中[getScaledObjectMetricSpecs](https://github.com/kedacore/keda/blob/50bec808f8b4656922797e4bcb7c2b61fabd6d0e/controllers/hpa.go#L135)方法中就是获取到`triggers`中的metrics指标。 184 | 185 | 这里有区分一下External的metrics和resource metrics,因为CPU/Memory scaler是通过resource metrics 来获取的。 186 | 187 | #### requestScaleLoop 188 | [requestScaleLoop](https://github.com/kedacore/keda/blob/50bec808f8b4656922797e4bcb7c2b61fabd6d0e/controllers/scaledobject_controller.go#L299)方法中用来循环check Scaler中的IsActive状态并作出对应的处理,比如修改副本数,直接来看最终的处理吧: 189 | 这里有两种模型来触发`RequestScale`: 190 | 191 | - Pull模型:即主动的调用scaler 中的`IsActive`方法 192 | - Push模型:由Scaler来触发,`PushScaler`多了一个Run方法,通过channel传入active状态。 193 | 194 | > `IsActive`是由Scaler实现的,比如对于prometheus来说,可能指标为0则为false 195 | 196 | 这个具体的scaler实现后续再讲,我们来看看RequestScale做了什么事: 197 | 198 | ```go 199 | //当前副本数为0,并是所有scaler属于active状态,则修改副本数为MinReplicaCount 或 1 200 | if currentScale.Spec.Replicas == 0 && isActive { 201 | e.scaleFromZero(ctx, logger, scaledObject, currentScale) 202 | } else if !isActive && 203 | currentScale.Spec.Replicas > 0 && 204 | (scaledObject.Spec.MinReplicaCount == nil || *scaledObject.Spec.MinReplicaCount == 0) { 205 | // 所有scaler都处理not active状态,并且当前副本数大于0,且MinReplicaCount设定为0 206 | // 则缩容副本数为0 207 | e.scaleToZero(ctx, logger, scaledObject, currentScale) 208 | } else if !isActive && 209 | scaledObject.Spec.MinReplicaCount != nil && 210 | currentScale.Spec.Replicas < *scaledObject.Spec.MinReplicaCount { 211 | // 所有scaler都处理not active状态,并且当前副本数小于MinReplicaCount,则修改为MinReplicaCount 212 | currentScale.Spec.Replicas = *scaledObject.Spec.MinReplicaCount 213 | 214 | err := e.updateScaleOnScaleTarget(ctx, scaledObject, currentScale) 215 | .... 216 | } else if isActive { 217 | // 处理active状态,并且副本数大于0,则更新LastActiveTime 218 | e.updateLastActiveTime(ctx, logger, scaledObject) 219 | } else { 220 | // 不处理 221 | logger.V(1).Info("ScaleTarget no change") 222 | } 223 | ``` 224 | 225 | 226 | ### ScaledJobReconciler 处理 227 | `ScaledJobReconciler`相比`ScalerObject`少了创建HPA的步骤,其余的步骤主要是通过[checkScaledJobScalers](https://github.com/kedacore/keda/blob/50bec808f8b4656922797e4bcb7c2b61fabd6d0e/pkg/scaling/scale_handler.go#L223),[RequestJobScale](https://github.com/kedacore/keda/blob/50bec808f8b4656922797e4bcb7c2b61fabd6d0e/pkg/scaling/executor/scale_jobs.go#L24)两个方法来判断Job创建: 228 | 229 | - `checkScaledJobScalers` 方法,用于计算isActive,maxValue的值 230 | - `RequestJobScale` 方法,用于负责创建Job,里面还涉及到三种扩容策略 231 | 232 | 这里直接看代码吧,不贴代码了。 233 | 234 | 235 | **如何停止Loop** 236 | 237 | 这里有个问题就是`startPushScalers`和`startScaleLoop`都是在Goroutine中处理的,所以当ScaleObject/ScalerJob被删除的时候,这里需要能够被删除,这里就用到了`context.Cancel`方法,在Goroutine启动的时候就将,context保存在[scaleLoopContexts *sync.Map](https://github.com/kedacore/keda/blob/50bec808f8b4656922797e4bcb7c2b61fabd6d0e/pkg/scaling/scale_handler.go#L43)中(如果已经有了,就先Cancel一次),在删除资源的时候,进行删除: 238 | 239 | ```go 240 | func (h *scaleHandler) DeleteScalableObject(scalableObject interface{}) error { 241 | withTriggers, err := asDuckWithTriggers(scalableObject) 242 | if err != nil { 243 | h.logger.Error(err, "error duck typing object into withTrigger") 244 | return err 245 | } 246 | 247 | key := generateKey(withTriggers) 248 | 249 | result, ok := h.scaleLoopContexts.Load(key) 250 | if ok { 251 | cancel, ok := result.(context.CancelFunc) 252 | if ok { 253 | cancel() 254 | } 255 | h.scaleLoopContexts.Delete(key) 256 | } else { 257 | h.logger.V(1).Info("ScaleObject was not found in controller cache", "key", key) 258 | } 259 | 260 | return nil 261 | } 262 | 263 | ``` 264 | 265 | ps: 这里的妙啊,学到了 266 | 267 | ## keda-metrics-apiserver 268 | keda-metrics-apiserver实现了`ExternalMetricsProvider`接口: 269 | 270 | ```go 271 | type ExternalMetricsProvider interface { 272 | GetExternalMetric(namespace string, metricSelector labels.Selector, info ExternalMetricInfo) (*external_metrics.ExternalMetricValueList, error) 273 | 274 | ListAllExternalMetrics() []ExternalMetricInfo 275 | } 276 | ``` 277 | - GetExternalMetric 用于返回Scaler的指标,调用`scaler.GetMetrics`方法 278 | - ListAllExternalMetrics 返回所有支持的external metrics,例如prometheus,mysql等 279 | 280 | 281 | 282 | 当代码写好之后,再通过apiservice注册到apiservier上(当然还涉及到鉴权,这里不啰嗦了): 283 | 284 | ``` 285 | apiVersion: apiregistration.k8s.io/v1 286 | kind: APIService 287 | metadata: 288 | labels: 289 | app.kubernetes.io/name: v1beta1.external.metrics.k8s.io 290 | app.kubernetes.io/version: latest 291 | app.kubernetes.io/part-of: keda-operator 292 | name: v1beta1.external.metrics.k8s.io 293 | spec: 294 | service: 295 | name: keda-metrics-apiserver 296 | namespace: keda 297 | group: external.metrics.k8s.io 298 | version: v1beta1 299 | insecureSkipTLSVerify: true 300 | groupPriorityMinimum: 100 301 | versionPriority: 100 302 | ``` 303 | 304 | ## 实现一个Scaler 305 | 其实有两种Scaler,即上面将的一个pull,一个push的模型,PushScaler多了一个Run方法: 306 | 307 | 实现一个Scaler,主要实现以下接口: 308 | 309 | ```go 310 | // Scaler interface 311 | type Scaler interface { 312 | 313 | // 返回external_metrics.ExternalMetricValue对象,其实就是用于 keda-metrics-apiserver中获取到scaler的指标 314 | GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) 315 | 316 | // 返回v2beta2.MetricSpec 结构,主要用于ScalerObject描述创建HPA的类型和Target指标等 317 | GetMetricSpecForScaling() []v2beta2.MetricSpec 318 | // 返回该Scaler是否Active,可能会影响Loop中直接修改副本数 319 | IsActive(ctx context.Context) (bool, error) 320 | 321 | //调用完一次上面的方法就会调用一次Close 322 | Close() error 323 | } 324 | 325 | // PushScaler interface 326 | type PushScaler interface { 327 | Scaler 328 | 329 | // 通过scaler实现Run方法,往active channel中,写入值,而非上面的直接调用IsActive放回 330 | Run(ctx context.Context, active chan<- bool) 331 | } 332 | ``` 333 | 334 | ## 总结 335 | 回过头来我们解答下在开头留下的问题: 336 | 337 | - KEDA是如何获取到多种事件的指标,以及如何判断扩缩容的? 338 | 339 | 答:keda controler中生成了external 类型的hpa,并且实现了external metrics 的api 340 | - KEDA是如何做到将应用的副本数缩容0,依据是什么? 341 | 342 | 答: keda 内部有个loop,不断的check isActive状态,会主动的修改应用副本 343 | 344 | --------------------------------------------------------------------------------