一篇文章帶你了解kubernetes各組件間的通信機(jī)制
我們對kubernetes有了一定的認(rèn)識,本文我們將繼續(xù)深入的對kubernetes在系統(tǒng)層面上進(jìn)行討論,一起看看kubernetes的各個基本組件,以及各個組件是如何相互配合來撐起如此復(fù)雜的集群系統(tǒng)。下面跟隨文章內(nèi)容,一起來領(lǐng)略kubernetes令人驚嘆的設(shè)計(jì)內(nèi)幕吧。
Kubernetes的基本組件
Kubernetes將整個集群分為控制節(jié)點(diǎn)和工作節(jié)點(diǎn),如下圖所示。

Kubernetes中的Master是指集群控制節(jié)點(diǎn),每個Kubernetes集群中需要一個Master節(jié)點(diǎn)來負(fù)責(zé)整個集群的管理和控制,Kubernetes中所有的控制指令都是交由Master來進(jìn)行處理。引起在集群中處于非常重要的地位,因此在部署中需進(jìn)行多節(jié)點(diǎn)單獨(dú)部署。
Maste節(jié)點(diǎn)關(guān)鍵進(jìn)程

Apiserver:提供kubernetes所有資源增刪改查的唯一入口,也是集群控制的入口,提供http Rest接口,完成集群管理,資源配額,訪問控制,認(rèn)證授權(quán),以及對etcd的操作。
Controller-manager:是集群內(nèi)所有資源對象的自動化控制中心,負(fù)責(zé)pod和node的管理,節(jié)點(diǎn)控制器,服務(wù)控制器,副本控制器,服務(wù)賬戶和令牌控制器等
Scheduler:負(fù)責(zé)資源調(diào)度,監(jiān)聽Apiserver,查詢是否有未調(diào)度的pod。
Etcd:在kubernetes系統(tǒng)中,主要有兩個服務(wù)需要用到etcd來存儲:
網(wǎng)絡(luò)插件:如flannel等需要存儲網(wǎng)絡(luò)配置信息
Kubernetes本身,包括各種對象的狀態(tài)和原信息配置。
除Master節(jié)點(diǎn)外,集群中其他集群被稱為Node節(jié)點(diǎn),較早的版本中也叫Minion。Node節(jié)點(diǎn)是集群中具體的工作負(fù)載節(jié)點(diǎn),其可以使物理機(jī)也可以為虛擬機(jī)。
Node節(jié)點(diǎn)關(guān)鍵進(jìn)程(包括但不限于以下進(jìn)程)

kubelet:處理Master下發(fā)到本節(jié)點(diǎn)的任務(wù),管理pod及pod的容器,每個kubelet在Apiserver上注冊自身信息,定期向Master匯報(bào)節(jié)點(diǎn)的資源使用情況,并通過cAdvisor監(jiān)控容器和節(jié)點(diǎn)信息。
kube-proxy:將到service的訪問轉(zhuǎn)發(fā)到后端的多個pod實(shí)例上,維護(hù)路由信息,對于每一個TCP類型的k8s service,kube-proxy會在本地建立一個sockerserver來負(fù)責(zé)均衡算法,使用rr負(fù)載均衡算法。
CNI網(wǎng)絡(luò)組件:作為容器平臺的網(wǎng)絡(luò)標(biāo)準(zhǔn)化組件,為容器提供跨網(wǎng)段的通信支持,是kubernetes集群overlay網(wǎng)絡(luò)的實(shí)現(xiàn)關(guān)鍵。
Docker:kubernetes支持多種容器工具,目前Docker作為主流的容器,為kubernetes集群提供容器創(chuàng)建及管理。
集群各組件間的交互
Kubernetes為所有資源增刪改查的唯一入口,各組件均以list-watch的方式向Apiserve發(fā)送請求。為減少Apiserver的壓力,各組件都采用緩存來緩存數(shù)據(jù)。功能模塊在某些情況下不直接訪問Apiserver,而是通過訪問緩存來間接訪問Apiserver。
Kubelet&Apiserver
每個node上的kubelet每個一個時間周期,就會調(diào)用Apiserver的REST接口來報(bào)告自身狀態(tài)。Kubelet通過watch接口,監(jiān)聽pod信息。監(jiān)聽創(chuàng)建、刪除、修改事件。
Controller-manager&Apiserver
controller-manager中包含多個controller,舉例:Node Controller模塊通過API server提供的Watch接口,實(shí)現(xiàn)監(jiān)控Node信息,并做相應(yīng)處理。
Scheduler&Apiserver
Scheduler通過API server的watch接口來監(jiān)聽,監(jiān)聽到新建pod副本后,檢索所有符合該P(yáng)od要求的Node列表,開始執(zhí)行Pod調(diào)度,調(diào)度成功后將pod綁定到具體節(jié)點(diǎn)。
以下是一張典型pod創(chuàng)建的流程圖,其中可以看到Apiserver處于核心的位置,集群內(nèi)的各個功能模塊的所有原數(shù)據(jù)正刪改查都是通過kube-apiserver操作etcd,當(dāng)需要獲取和操作這些數(shù)據(jù)時,通過Apiserver的REST接口來實(shí)現(xiàn)。

list-watch機(jī)制
kubernetes沒有像其他分布式系統(tǒng)中額外引入MQ,是因?yàn)槠湓O(shè)計(jì)理念采用了level trigger而非edge trigger。其僅僅通過http+protobuffer的方式,實(shí)現(xiàn)list-watcher機(jī)制來解決各組件間的消息通知。因此,在了解各組件通信前,必須先了解list-watch機(jī)制在kubernetes的應(yīng)用。
List-watch是k8s統(tǒng)一的異步消息處理機(jī)制,list通過調(diào)用資源的list API羅列資源,基于HTTP短鏈接實(shí)現(xiàn);watch則是調(diào)用資源的watch API監(jiān)聽資源變更事件,基于HTTP長鏈接實(shí)現(xiàn)。在kubernetes中,各組件通過監(jiān)聽Apiserver的資源變化,來更新資源狀態(tài)。
這里對watch簡要說明,流程如下圖所示:

這一部分流程圖看起來并不復(fù)雜,實(shí)際上里面的實(shí)現(xiàn)相當(dāng)精妙。結(jié)合這幅圖進(jìn)行簡要的解釋:
1 首先需要強(qiáng)調(diào)一點(diǎn),list或者watch的數(shù)據(jù),均是來自于etcd的數(shù)據(jù),因此在Apiserver中,一切的設(shè)計(jì)都是為了獲取最新的etcd數(shù)據(jù)并返回給client。
2 當(dāng)Apiserver監(jiān)聽到各組件發(fā)來的watch請求時,由于list和watch請求的格式相似,先進(jìn)入ListResource函數(shù)進(jìn)行分析,若解析為watch請求,便會創(chuàng)建一個watcher結(jié)構(gòu)來響應(yīng)請求。watcher的生命周期是每個http請求的。
- //每一個Watch請求對應(yīng)一個watcher結(jié)構(gòu)
- func (a *APIInstaller) registerResourceHandlers(path string, storage rest.Storage,... ...
- ……
- lister, isLister := storage.(rest.Lister)
- watcher, isWatcher := storage.(rest.Watcher) ...(1) ... case "LIST": // List all resources of a kind.
- ……
3 創(chuàng)建了watcher,但誰來接收并緩存etcd的數(shù)據(jù)呢?Apiserver使用cacher來接收etcd的事件,cacher也是Storage類型,這里cacher可以理解為是監(jiān)聽etcd的一個實(shí)例,cacher針對于某個類型的數(shù)據(jù),其cacher通過ListAndWatch()這個方法,向etcd發(fā)送watch請求。etcd會將某一類型的數(shù)據(jù)同步到watchCache這個結(jié)構(gòu),也就是說,ListAndWatch()將遠(yuǎn)端數(shù)據(jù)源源不斷同步到cacher結(jié)構(gòu)中來。Cacher的結(jié)構(gòu)如下所示:
- type Cacher struct {
- incomingHWM storage.HighWaterMark
- incoming chan watchCacheEvent
- sync.RWMutex
- // Before accessing the cacher's cache, wait for the ready to be ok.
- // This is necessary to prevent users from accessing structures that are
- // uninitialized or are being repopulated right now.
- // ready needs to be set to false when the cacher is paused or stopped.
- // ready needs to be set to true when the cacher is ready to use after
- // initialization.
- ready *ready
- // Underlying storage.Interface.
- storage storage.Interface
- // Expected type of objects in the underlying cache.
- objectType reflect.Type
- // "sliding window" of recent changes of objects and the current state.
- watchCache *watchCache
- reflector *cache.Reflector
- // Versioner is used to handle resource versions.
- versioner storage.Versioner
- // newFunc is a function that creates new empty object storing a object of type Type.
- newFunc func() runtime.Object
- // indexedTrigger is used for optimizing amount of watchers that needs to process
- // an incoming event.
- indexedTrigger *indexedTriggerFunc
- // watchers is mapping from the value of trigger function that a
- // watcher is interested into the watchers
- watcherIdx int
- watchers indexedWatchers
- // Defines a time budget that can be spend on waiting for not-ready watchers
- // while dispatching event before shutting them down.
- dispatchTimeoutBudget *timeBudget
- // Handling graceful termination.
- stopLock sync.RWMutex
- stopped bool
- stopCh chan struct{}
- stopWg sync.WaitGroup
- clock clock.Clock
- // timer is used to avoid unnecessary allocations in underlying watchers.
- timer *time.Timer
- // dispatching determines whether there is currently dispatching of
- // any event in flight.
- dispatching bool
- // watchersBuffer is a list of watchers potentially interested in currently
- // dispatched event.
- watchersBuffer []*cacheWatcher
- // blockedWatchers is a list of watchers whose buffer is currently full.
- blockedWatchers []*cacheWatcher
- // watchersToStop is a list of watchers that were supposed to be stopped
- // during current dispatching, but stopping was deferred to the end of
- // dispatching that event to avoid race with closing channels in watchers.
- watchersToStop []*cacheWatcher
- // Maintain a timeout queue to send the bookmark event before the watcher times out.
- bookmarkWatchers *watcherBookmarkTimeBuckets
- // watchBookmark feature-gate
- watchBookmarkEnabled bool
- }
watchCache的結(jié)構(gòu)如下所示:
- type watchCache struct {
- sync.RWMutex //同步鎖
- cond *sync.Cond //條件變量
- capacity int//歷史滑動窗口容量
- keyFunc func(runtime.Object) (string, error)//從storage中獲取鍵值
- getAttrsFunc func(runtime.Object) (labels.Set, fields.Set, bool, error)//獲取一個對象的field和label信息
- cache []watchCacheElement//循環(huán)隊(duì)列緩存
- startIndex int//循環(huán)隊(duì)列的起始下標(biāo)
- endIndex int//循環(huán)隊(duì)列的結(jié)束下標(biāo)
- store cache.Store//
- resourceVersion uint64
- onReplace func()
- onEvent func(*watchCacheEvent)//在每次緩存中的數(shù)據(jù)發(fā)生Add/Update/Delete后都會調(diào)用該函數(shù),來獲取對象的之前版本的值
- clock clock.Clock
- versioner storage.Versioner
- }
cache里面存放的是所有操作事件,而store中存放的是當(dāng)前最新的事件。
4 cacheWatcher從watchCache中拿到從某個resourceVersion以來的所有數(shù)據(jù),即initEvents,然后將數(shù)據(jù)放到input這個channel里面去,通過filter然后輸出到result這個channel里面,返回?cái)?shù)據(jù)到某個client。
- type cacheWatcher struct {
- sync.Mutex//同步鎖
- input chan *watchCacheEvent//輸入管道,Apiserver都事件發(fā)生時都會通過廣播的形式向input管道進(jìn)行發(fā)送
- result chan watch.Event//輸出管道,輸出到update管道中去
- done chan struct{}
- filter filterWithAttrsFunc//過濾器
- stopped bool
- forget func(bool)
- versioner storage.Versioner
- }
從一個pod創(chuàng)建過程看k8s組件通信
我們再回到上面的Pod創(chuàng)建流程圖。從圖中我們可以看出以下信息:
1 首先各組件也會在初始化時向Apiserver發(fā)送watch請求,即在圖中標(biāo)0的指令。Apiserver在創(chuàng)建kubeApiserver并注冊各API路由信息時,獲取Watch請求的路由信息
2 從Kubectl向Apiserver發(fā)送創(chuàng)建pod請求起,每一步創(chuàng)建、更新操作,都會存儲到etcd中。
3 各組件向Apiserver發(fā)送watch請求,Apiserver從etcd獲取最新數(shù)據(jù)并返回。
注意:當(dāng)事件發(fā)生時,Apiserver會給這些watcher中的通道推送,每個watcher都有自己的Filter過濾,找到自己想要監(jiān)聽的事件則通過管道的方式將該數(shù)據(jù)發(fā)送到相應(yīng)的組件。