You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.9 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

## Controller源码分段阅读导航
- [多实例leader选举]([https://github.com/yinwenqin/kubeSourceCodeNote/blob/master/controller/Kubernetes%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0-Controller-P1-%E5%A4%9A%E5%AE%9E%E4%BE%8Bleader%E9%80%89%E4%B8%BE.md](https://github.com/yinwenqin/kubeSourceCodeNote/blob/master/controller/Kubernetes源码学习-Controller-P1-多实例leader选举.md))
- [Kubernetes源码学习-Controller-P2-Controller与informer](https://github.com/yinwenqin/kubeSourceCodeNote/blob/master/controller/Kubernetes源码学习-Controller-P2-Controller与informer.md)
- [Kubernetes源码学习-Controller-P3-Controller分类与Deployment Controller](https://github.com/yinwenqin/kubeSourceCodeNote/blob/master/controller/Kubernetes源码学习-Controller-P3-Controller分类与Deployment Controller.md)
- [StafulSet Controller]
- 待补充
## 概述
### kube-controller的作用
**引述**
首先依照惯例,贴两篇官方对   于controller的设计逻辑和运行机制的说明文档
https://github.com/kubernetes/community/blob/master/contributors/devel/sig-api-machinery/controllers.md
https://github.com/kubernetes/community/blob/master/contributors/design-proposals/apps/controller_history.md
**Controller是做什么用的**
Controller通过watch apiServer循环地观察监控着某些特定的资源对象获取它们当前的状态对它们进行对比、修正、收敛来使这些对象的状态不断靠近、直至达成在它们的声明语义中所期望的目标状态这即是controller的作用。再通俗点来说就是使资源对象的status当前状态达到spec的期望状态。
**伪代码**
一个简单的controller工作模式的伪代码示例
```go
for {
// 期望状态
desired := getDesiredState()
// 当前状态
current := getCurrentState()
// 使当前状态达到期望状态
makeChanges(desired, current)
}
```
### kube-controller的组成
kube-controller是一个控制组件根据我们的使用经验有多种经常使用的资源都不是实际地直接进行任务计算的资源类型而在申明之后由k8s自动发现并保证以达成申明语义状态的逻辑资源例如deployment、statefulSet、pvc、endpoint等这些资源都分别由对应的controller子组件那么这样的controller子组件有多少呢如下图
![](http://mycloudn.kokoerp.com/20191206111312.jpg)
可见controller的组件数量是非常之多的因此在本部分中计划只抽选其中的deploymentController和statefulSetController这两种常见的对pod管理类型资源对应的controller来进行源码分析。
### 代码结构
**启动入口**
`kubernetes/src/k8s.io/kubernetes/cmd/kube-controller-manager/controller-manager.go`
![](http://mycloudn.kokoerp.com/20191206153026.jpg)
**功能模块**
`kubernetes/src/k8s.io/kubernetes/pkg/controller`
![](http://mycloudn.kokoerp.com/20191206154051.jpg)