我們對kubernetes有了一定的認(rèn)識,本文我們將繼續(xù)深入的對kubernetes在系統(tǒng)層面上進(jìn)行討論,一起看看kubernetes的各個基本組件,以及各個組件是如何相互配合來撐起如此復(fù)雜的集群系統(tǒng)。下面跟隨文章內(nèi)容,一起來領(lǐng)略kubernetes令人驚嘆的設(shè)計內(nèi)幕吧。
Kubernetes的基本組件
Kubernetes將整個集群分為控制節(jié)點和工作節(jié)點,如下圖所示。
Kubernetes中的Master是指集群控制節(jié)點,每個Kubernetes集群中需要一個Master節(jié)點來負(fù)責(zé)整個集群的管理和控制,Kubernetes中所有的控制指令都是交由Master來進(jìn)行處理。引起在集群中處于非常重要的地位,因此在部署中需進(jìn)行多節(jié)點單獨部署。
Maste節(jié)點關(guān)鍵進(jìn)程
Apiserver:提供kubernetes所有資源增刪改查的唯一入口,也是集群控制的入口,提供http Rest接口,完成集群管理,資源配額,訪問控制,認(rèn)證授權(quán),以及對etcd的操作。
Controller-manager:是集群內(nèi)所有資源對象的自動化控制中心,負(fù)責(zé)pod和node的管理,節(jié)點控制器,服務(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é)點外,集群中其他集群被稱為Node節(jié)點,較早的版本中也叫Minion。Node節(jié)點是集群中具體的工作負(fù)載節(jié)點,其可以使物理機也可以為虛擬機。
Node節(jié)點關(guān)鍵進(jìn)程(包括但不限于以下進(jìn)程)
kubelet:處理Master下發(fā)到本節(jié)點的任務(wù),管理pod及pod的容器,每個kubelet在Apiserver上注冊自身信息,定期向Master匯報節(jié)點的資源使用情況,并通過cAdvisor監(jiān)控容器和節(jié)點信息。
kube-proxy:將到service的訪問轉(zhuǎn)發(fā)到后端的多個pod實例上,維護(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ò)的實現(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接口來報告自身狀態(tài)。Kubelet通過watch接口,監(jiān)聽pod信息。監(jiān)聽創(chuàng)建、刪除、修改事件。
Controller-manager&Apiserver
controller-manager中包含多個controller,舉例:Node Controller模塊通過API server提供的Watch接口,實現(xiàn)監(jiān)控Node信息,并做相應(yīng)處理。
Scheduler&Apiserver
Scheduler通過API server的watch接口來監(jiān)聽,監(jiān)聽到新建pod副本后,檢索所有符合該Pod要求的Node列表,開始執(zhí)行Pod調(diào)度,調(diào)度成功后將pod綁定到具體節(jié)點。
以下是一張典型pod創(chuàng)建的流程圖,其中可以看到Apiserver處于核心的位置,集群內(nèi)的各個功能模塊的所有原數(shù)據(jù)正刪改查都是通過kube-apiserver操作etcd,當(dāng)需要獲取和操作這些數(shù)據(jù)時,通過Apiserver的REST接口來實現(xiàn)。
list-watch機制
kubernetes沒有像其他分布式系統(tǒng)中額外引入MQ,是因為其設(shè)計理念采用了level trigger而非edge trigger。其僅僅通過http+protobuffer的方式,實現(xiàn)list-watcher機制來解決各組件間的消息通知。因此,在了解各組件通信前,必須先了解list-watch機制在kubernetes的應(yīng)用。
List-watch是k8s統(tǒng)一的異步消息處理機制,list通過調(diào)用資源的list API羅列資源,基于HTTP短鏈接實現(xiàn);watch則是調(diào)用資源的watch API監(jiān)聽資源變更事件,基于HTTP長鏈接實現(xiàn)。在kubernetes中,各組件通過監(jiān)聽Apiserver的資源變化,來更新資源狀態(tài)。
這里對watch簡要說明,流程如下圖所示:
這一部分流程圖看起來并不復(fù)雜,實際上里面的實現(xiàn)相當(dāng)精妙。結(jié)合這幅圖進(jìn)行簡要的解釋:
1 首先需要強調(diào)一點,list或者watch的數(shù)據(jù),均是來自于etcd的數(shù)據(jù),因此在Apiserver中,一切的設(shè)計都是為了獲取最新的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(pathstring,storagerest.Storage,......
……
lister,isLister:=storage.(rest.Lister)
watcher,isWatcher:=storage.(rest.Watcher)...(1)...case"LIST"://Listallresourcesofakind.
……
3 創(chuàng)建了watcher,但誰來接收并緩存etcd的數(shù)據(jù)呢?Apiserver使用cacher來接收etcd的事件,cacher也是Storage類型,這里cacher可以理解為是監(jiān)聽etcd的一個實例,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)如下所示:
typeCacherstruct{
incomingHWMstorage.HighWaterMark
incomingchanwatchCacheEvent
sync.RWMutex
//Beforeaccessingthecacher'scache,waitforthereadytobeok.
//Thisisnecessarytopreventusersfromaccessingstructuresthatare
//uninitializedorarebeingrepopulatedrightnow.
//readyneedstobesettofalsewhenthecacherispausedorstopped.
//readyneedstobesettotruewhenthecacherisreadytouseafter
//initialization.
ready*ready
//Underlyingstorage.Interface.
storagestorage.Interface
//Expectedtypeofobjectsintheunderlyingcache.
objectTypereflect.Type
//"slidingwindow"ofrecentchangesofobjectsandthecurrentstate.
watchCache*watchCache
reflector*cache.Reflector
//Versionerisusedtohandleresourceversions.
versionerstorage.Versioner
//newFuncisafunctionthatcreatesnewemptyobjectstoringaobjectoftypeType.
newFuncfunc()runtime.Object
//indexedTriggerisusedforoptimizingamountofwatchersthatneedstoprocess
//anincomingevent.
indexedTrigger*indexedTriggerFunc
//watchersismappingfromthevalueoftriggerfunctionthata
//watcherisinterestedintothewatchers
watcherIdxint
watchersindexedWatchers
//Definesatimebudgetthatcanbespendonwaitingfornot-readywatchers
//whiledispatchingeventbeforeshuttingthemdown.
dispatchTimeoutBudget*timeBudget
//Handlinggracefultermination.
stopLocksync.RWMutex
stoppedbool
stopChchanstruct{}
stopWgsync.WaitGroup
clockclock.Clock
//timerisusedtoavoidunnecessaryallocationsinunderlyingwatchers.
timer*time.Timer
//dispatchingdetermineswhetherthereiscurrentlydispatchingof
//anyeventinflight.
dispatchingbool
//watchersBufferisalistofwatcherspotentiallyinterestedincurrently
//dispatchedevent.
watchersBuffer[]*cacheWatcher
//blockedWatchersisalistofwatcherswhosebufferiscurrentlyfull.
blockedWatchers[]*cacheWatcher
//watchersToStopisalistofwatchersthatweresupposedtobestopped
//duringcurrentdispatching,butstoppingwasdeferredtotheendof
//dispatchingthateventtoavoidracewithclosingchannelsinwatchers.
watchersToStop[]*cacheWatcher
//Maintainatimeoutqueuetosendthebookmarkeventbeforethewatchertimesout.
bookmarkWatchers*watcherBookmarkTimeBuckets
//watchBookmarkfeature-gate
watchBookmarkEnabledbool
}
watchCache的結(jié)構(gòu)如下所示:
typewatchCachestruct{
sync.RWMutex//同步鎖
cond*sync.Cond//條件變量
capacityint//歷史滑動窗口容量
keyFuncfunc(runtime.Object)(string,error)//從storage中獲取鍵值
getAttrsFuncfunc(runtime.Object)(labels.Set,fields.Set,bool,error)//獲取一個對象的field和label信息
cache[]watchCacheElement//循環(huán)隊列緩存
startIndexint//循環(huán)隊列的起始下標(biāo)
endIndexint//循環(huán)隊列的結(jié)束下標(biāo)
storecache.Store//
resourceVersionuint64
onReplacefunc()
onEventfunc(*watchCacheEvent)//在每次緩存中的數(shù)據(jù)發(fā)生Add/Update/Delete后都會調(diào)用該函數(shù),來獲取對象的之前版本的值
clockclock.Clock
versionerstorage.Versioner
}
cache里面存放的是所有操作事件,而store中存放的是當(dāng)前最新的事件。
4 cacheWatcher從watchCache中拿到從某個resourceVersion以來的所有數(shù)據(jù),即initEvents,然后將數(shù)據(jù)放到input這個channel里面去,通過filter然后輸出到result這個channel里面,返回數(shù)據(jù)到某個client。
typecacheWatcherstruct{
sync.Mutex//同步鎖
inputchan*watchCacheEvent//輸入管道,Apiserver都事件發(fā)生時都會通過廣播的形式向input管道進(jìn)行發(fā)送
resultchanwatch.Event//輸出管道,輸出到update管道中去
donechanstruct{}
filterfilterWithAttrsFunc//過濾器
stoppedbool
forgetfunc(bool)
versionerstorage.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)的組件。