原文:istio源碼分析——poilt-discovery服務發現和配置中心
聲明
- 這篇文章需要瞭解istio,k8s,golang,envoy基礎知識
- 分析的環境為k8s,istio版本為0.8.0
poilt-discovery的作用
envoy提供一套通用的資料面介面,通過介面可以動態實現服務發現和配置。在istio中需要整合k8s,consul等服務發現系統,所以需要一個中介整理在k8s,consul服務註冊和配置資訊,並提供給envoy。
envoy v1 API 和 v2 API區別
v1版本API和v2版本API有一段曆史,詳情可看官網部落格。在envoy開源之初,使用HTTP+輪詢的方式實現動態服務發現和配置,但是這種方式存在以下缺點:
- 由於介面資料使用弱類型,導致實現一些泛型服務比較困難。
- 控制面更喜歡使用推送的方式,來減少資料在更新時傳輸的時間。
隨著和Google合作加強,官方使用GRPC + push開發了v2版本API,實現了v1版本的SDS/CDS/RDS/LDS介面,繼續支援JSON/YAML資料格式,還增加了ADS(把SDS/CDS/RDS/LDS4個介面合在一下),HDS等介面。
建立基礎快取資料
其實pilot-discovery已經算是一個小型的非持久性key/value資料庫了,它把istio的配置資訊和服務註冊資訊都進行了緩衝。這樣可以使配置更快的生效。
緩衝了什麼資料
istio.io/istio/pilot/pkg/model/config.govar ( ...... // RouteRule describes route rules RouteRule = ProtoSchema{ Type: "route-rule", ...... } // VirtualService describes v1alpha3 route rules VirtualService = ProtoSchema{ Type: "virtual-service", ...... } // Gateway describes a gateway (how a proxy is exposed on the network) Gateway = ProtoSchema{ Type: "gateway", ...... } // IngressRule describes ingress rules IngressRule = ProtoSchema{ Type: "ingress-rule", ...... })
做過新手任務的同學,應該都很熟悉上面的Type,就是配置資訊裡面的 kind,配置資訊儲存進k8s後,會被pilot-discovery通過api-server爬過來進行緩衝。
apiVersion: networking.istio.io/v1alpha3kind: VirtualServicemetadata: name: reviews ......
> istio.io/istio/pilot/pkg/serviceregistry/kube/controller.go #102func NewController(client kubernetes.Interface, options ControllerOptions) *Controller { ...... out.services = out.createInformer(&v1.Service{}, "Service", options.ResyncPeriod, func(opts meta_v1.ListOptions) (runtime.Object, error) { return client.CoreV1().Services(options.WatchedNamespace).List(opts) }, func(opts meta_v1.ListOptions) (watch.Interface, error) { return client.CoreV1().Services(options.WatchedNamespace).Watch(opts) }) ...... out.nodes = out.createInformer(&v1.Node{}, "Node", options.ResyncPeriod, func(opts meta_v1.ListOptions) (runtime.Object, error) { return client.CoreV1().Nodes().List(opts) }, func(opts meta_v1.ListOptions) (watch.Interface, error) { return client.CoreV1().Nodes().Watch(opts) }) ...... return out}
還有其他資料不一一列出,從上面可以看出,建立緩衝都是通過List和Watch方式進行(istio的配置資料也一樣),List:第一次初始化資料,Watch:通過輪詢的方式擷取資料並緩衝。
https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/httpapispecs?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/servicerolebindings?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/networking.istio.io/v1alpha3/virtualservices?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/quotaspecbindings?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/serviceroles?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/networking.istio.io/v1alpha3/serviceentries?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/routerules?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/egressrules?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/authentication.istio.io/v1alpha1/policies?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/httpapispecbindings?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/networking.istio.io/v1alpha3/destinationrules?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/quotaspecs?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/networking.istio.io/v1alpha3/gateways?limit=500&resourceVersion=0https://{k8s.ip}:443/apis/config.istio.io/v1alpha2/destinationpolicies?limit=500&resourceVersion=0https://{k8s.ip}:443/api/v1/nodes?limit=500&resourceVersion=0https://{k8s.ip}:443/api/v1/namespaces/istio-system/configmaps/istio-ingress-controller-leader-istiohttps://{k8s.ip}:443/api/v1/services?limit=500&resourceVersion=0https://{k8s.ip}:443/api/v1/endpoints?limit=500&resourceVersion=0https://{k8s.ip}:443/api/v1/pods?limit=500&resourceVersion=0
key的產生
在pilot-discovery中把快取資料分了二大類,一類istio配置資訊,另一類服務註冊資訊。這二類又進行了細分,分別為virtualservices,routerules,nodes,pods等,最後再以k8s空間/應用程式名稱作為下標快取資料。
k8s.io/client-go/tools/cache/store.go #76func MetaNamespaceKeyFunc(obj interface{}) (string, error) { if key, ok := obj.(ExplicitKey); ok { return string(key), nil } meta, err := meta.Accessor(obj) if err != nil { return "", fmt.Errorf("object has no meta: %v", err) } if len(meta.GetNamespace()) > 0 { return meta.GetNamespace() + "/" + meta.GetName(), nil } return meta.GetName(), nil}default/sleepkube-system/grafanaistio-system/servicegraph
儲存資料
上面提到建立緩衝都是通過List和Watch方式進行,來看看它的實現。
k8s.io/client-go/tools/cache/reflector.go #239func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { ...... list, err := r.listerWatcher.List(options) ...... resourceVersion = listMetaInterface.GetResourceVersion() items, err := meta.ExtractList(list) ...... //快取資料 if err := r.syncWith(items, resourceVersion); err != nil { return fmt.Errorf("%s: Unable to sync list result: %v", r.name, err) } ...... for { ...... w, err := r.listerWatcher.Watch(options) ...... if err := r.watchHandler(w, &resourceVersion, resyncerrc, stopCh); err != nil { ...... return nil } }}
List可以看做第一次初始化資料,Watch更像是監聽資料的變化狀態:添加,修改和刪除。針對這些狀態對緩衝的資料做增、刪、改。
k8s.io/client-go/tools/cache/reflector.go #358func (r *Reflector) watchHandler(w watch.Interface, resourceVersion *string, errc chan error, stopCh <-chan struct{}) error {......loop: for { select { case <-stopCh: return errorStopRequested case err := <-errc: return err case event, ok := <-w.ResultChan(): ...... switch event.Type { case watch.Added: err := r.store.Add(event.Object) ...... case watch.Modified: err := r.store.Update(event.Object) ...... case watch.Deleted: ...... err := r.store.Delete(event.Object) ...... default: utilruntime.HandleError(fmt.Errorf("%s: unable to understand watch event %#v", r.name, event)) } ...... } } ...... return nil}
剛剛看到監聽資料的變化是通過for{} 不斷請求k8s的api-server介面,如果不加限制,那就成了DDOS攻擊了,所以pilot-discovery使用了流量控制。
k8s.io/client-go/rest/config.goconst ( DefaultQPS float32 = 5.0 DefaultBurst int = 10)
這樣理解這個配置吧,如果1秒內訪問次數大於10,那麼在接下來的訪問中一秒最多隻能訪問5次。
k8s.io/client-go/rest/request.go #616func (r *Request) request(fn func(*http.Request, *http.Response)) error { ...... retries := 0 for { ...... if retries > 0 { ...... //使用令牌桶演算法 r.tryThrottle() } resp, err := client.Do(req) ...... done := func() bool { ...... retries++ ...... }}
在golang中使用記憶體key/value緩衝非常簡單,定義變數 map[string]interface{},再往裡面放入資料就可以了。但是map結構為非協程安全,所以像pilot-discovery這種小型資料庫,同時存在讀和寫,如果不加上鎖,很容易出現爭搶共用資源問題。所以需要加鎖:thread_safe_store.go
type ThreadSafeStore interface { Add(key string, obj interface{}) Update(key string, obj interface{}) Delete(key string) Get(key string) (item interface{}, exists bool) List() []interface{} ListKeys() []string Replace(map[string]interface{}, string) Index(indexName string, obj interface{}) ([]interface{}, error) IndexKeys(indexName, indexKey string) ([]string, error) ListIndexFuncValues(name string) []string ByIndex(indexName, indexKey string) ([]interface{}, error) GetIndexers() Indexers // AddIndexers adds more indexers to this store. If you call this after you already have data // in the store, the results are undefined. AddIndexers(newIndexers Indexers) error Resync() error}
提供介面
不管是v1 API還是v2 API,都是基於基礎緩衝的資料,按照envoy的介面文檔,把資料拼接成envoy想要的資料。
暴露v1 API RESTFUL
pilot-discovery暴露了SDS/CDS/RDS/LDS介面,envoy再使用輪詢的方式,通過這些介面擷取配置資訊
istio.io/istio/pilot/pkg/proxy/envoy/v1/discovery.go #376func (ds *DiscoveryService) Register(container *restful.Container) { ws := &restful.WebService{} ws.Produces(restful.MIME_JSON) ...... ws.Route(ws. GET(fmt.Sprintf("/v1/registration/{%s}", ServiceKey)). To(ds.ListEndpoints). Doc("SDS registration"). Param(ws.PathParameter(ServiceKey, "tuple of service name and tag name").DataType("string"))) ...... ws.Route(ws. GET(fmt.Sprintf("/v1/clusters/{%s}/{%s}", ServiceCluster, ServiceNode)). To(ds.ListClusters). Doc("CDS registration"). Param(ws.PathParameter(ServiceCluster, "client proxy service cluster").DataType("string")). Param(ws.PathParameter(ServiceNode, "client proxy service node").DataType("string"))) ...... ws.Route(ws. GET(fmt.Sprintf("/v1/routes/{%s}/{%s}/{%s}", RouteConfigName, ServiceCluster, ServiceNode)). To(ds.ListRoutes). Doc("RDS registration"). Param(ws.PathParameter(RouteConfigName, "route configuration name").DataType("string")). Param(ws.PathParameter(ServiceCluster, "client proxy service cluster").DataType("string")). Param(ws.PathParameter(ServiceNode, "client proxy service node").DataType("string"))) ...... ws.Route(ws. GET(fmt.Sprintf("/v1/listeners/{%s}/{%s}", ServiceCluster, ServiceNode)). To(ds.ListListeners). Doc("LDS registration"). Param(ws.PathParameter(ServiceCluster, "client proxy service cluster").DataType("string")). Param(ws.PathParameter(ServiceNode, "client proxy service node").DataType("string"))) ...... container.Add(ws)}
這裡的緩衝可以這樣理解:我們平常開發中,從資料庫擷取資料,經過邏輯處理,再把最終結果進行緩衝,返回給用戶端,下次進來,就從緩衝擷取資料。同理v1 API的介面從基礎緩衝擷取了資料後,把這些資料拼接成envoy需要的格式資料,再把這些資料緩衝,返回給envoy。
- ListEndpoints(EDS)
其他幾個介面方式一樣,不一一列出
istio.io/istio/pilot/pkg/proxy/envoy/v1/discovery.go #567> func (ds *DiscoveryService) ListEndpoints(request *restful.Request, response *restful.Response) { ...... key := request.Request.URL.String() out, resourceCount, cached := ds.sdsCache.cachedDiscoveryResponse(key) //沒有緩衝 if !cached { /** 邏輯處理 **/ ...... resourceCount = uint32(len(endpoints)) if resourceCount > 0 { //快取資料 ds.sdsCache.updateCachedDiscoveryResponse(key, resourceCount, out) } } observeResources(methodName, resourceCount) writeResponse(response, out)}
暴露v2 API GRPC
我也是剛剛接觸GRPC的雙向流,我對它的理解是:一個長串連,用戶端和服務端可以相互互動。在這裡的用法是,用戶端envoy開啟一個GRPC串連,初始時pilot-discovery把資料響應給envoy,接下來,如果有資料變動,pilot-discovery通過GRPC把資料推給envoy。
彙總介面就是把SDS/CDS/RDS/LDS的配置資料都放在一個介面上。實現有點長,縮減只剩一個介面,但方式是一樣的。
istio.io/istio/pilot/pkg/proxy/envoy/v2/ads.go #237func (s *DiscoveryServer) StreamAggregatedResources(stream ads.AggregatedDiscoveryService_StreamAggregatedResourcesServer) error { ...... var receiveError error reqChannel := make(chan *xdsapi.DiscoveryRequest, 1) go receiveThread(con, reqChannel, &receiveError) for { // Block until either a request is received or the ticker ticks select { case discReq, ok = <-reqChannel: ...... switch discReq.TypeUrl { case ClusterType: ...... case ListenerType: ...... case RouteType: ...... case EndpointType: ...... //推送資料 err := s.pushEds(con) if err != nil { return err } ...... } ...... //通過監聽事件觸發推送資料 case <-con.pushChannel: ...... if len(con.Clusters) > 0 { err := s.pushEds(con) if err != nil { return err } } ...... } }}
清二級緩衝和觸發推送
清除二級緩衝和觸發推送在這裡其實都是同一個觸發點:就是資料變動的時候。資料的變動應該是無序的,但是在更新配置的時候應該井然有序的進行。所以這裡使用了任務隊列,讓事件一件一件接著做。
- 初始化List和Watch,註冊Add,Update,Delete事件。
istio.io/istio/pilot/pkg/config/kube/crd/controller.go #133func (c *controller) createInformer( o runtime.Object, otype string, resyncPeriod time.Duration, lf cache.ListFunc, wf cache.WatchFunc) cacheHandler { ...... informer.AddEventHandler( cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { ...... c.queue.Push(kube.NewTask(handler.Apply, obj, model.EventAdd)) }, ...... }) return cacheHandler{informer: informer, handler: handler}}
當事件被觸發都會執行handler.Apply,再執行註冊的方法。
istio.io/istio/pilot/pkg/serviceregistry/kube/queue.go #142func (ch *ChainHandler) Apply(obj interface{}, event model.Event) error { for _, f := range ch.funcs { if err := f(obj, event); err != nil { return err } } return nil}
- 註冊方法
istio.io/istio/pilot/pkg/proxy/envoy/v1/discovery.go #328func NewDiscoveryService(ctl model.Controller, configCache model.ConfigStoreCache, environment model.Environment, o DiscoveryServiceOptions) (*DiscoveryService, error) { ...... serviceHandler := func(*model.Service, model.Event) { out.clearCache() } if err := ctl.AppendServiceHandler(serviceHandler); err != nil { return nil, err } instanceHandler := func(*model.ServiceInstance, model.Event) { out.clearCache() } if err := ctl.AppendInstanceHandler(instanceHandler); err != nil { return nil, err } if configCache != nil { ...... configHandler := func(model.Config, model.Event) { out.clearCache() } for _, descriptor := range model.IstioConfigTypes { configCache.RegisterEventHandler(descriptor.Type, configHandler) } } return out, nil}
方法 out.clearCache(),實現了清二級緩衝和推送資料
istio.io/istio/pilot/pkg/proxy/envoy/v1/discovery.go #480func (ds *DiscoveryService) clearCache() { ...... //清二級緩衝 ds.sdsCache.clear() ds.cdsCache.clear() ds.rdsCache.clear() ds.ldsCache.clear() if V2ClearCache != nil { //把資料推送到envoy V2ClearCache() }}
在pilot-discovery開放了一個清二級緩衝的介面。
istio.io/istio/pilot/pkg/proxy/envoy/v1/discovery.go #436func (ds *DiscoveryService) Register(container *restful.Container) { ws := &restful.WebService{} ws.Produces(restful.MIME_JSON) ...... ws.Route(ws. POST("/cache_stats_delete"). To(ds.ClearCacheStats). Doc("Clear discovery service cache stats")) container.Add(ws)}
小知識
萬惡的panic
在開發使用golang的過程中或多或少都接觸過panic。例如引入了一些喜歡用panic的第三包,斷言錯誤等觸發了panic,導致整個服務都掛掉。為了避免這些問題,我們一般都是使用recover來接收panic,但一直覺得自己的處理方式不是很好。所以這次源碼分析特意看了k8s的go用戶端是如何處理panic問題,畢竟是Google出品。
k8s.io/apimachinery/pkg/util/runtime/runtime.go #47func HandleCrash(additionalHandlers ...func(interface{})) { if r := recover(); r != nil { //預設會列印 出現panic問題的檔案和行數 for _, fn := range PanicHandlers { fn(r) } //留給使用方,出現了panic你還想如何處理 for _, fn := range additionalHandlers { fn(r) } //如果你確認,可以直接panic if ReallyCrash { // Actually proceed to panic. panic(r) } }}
從上面看出k8s用戶端的處理方式和我們的想法一樣,不過它的封裝更友好。在k8s的go用戶端中HandleCrash,更喜歡和for{}一起使用。
k8s.io/apimachinery/pkg/watch/streamwatcher.go #88func (sw *StreamWatcher) receive() { ...... defer utilruntime.HandleCrash() for { ...... }}k8s.io/client-go/tools/record/event.go #224func (eventBroadcaster *eventBroadcasterImpl) StartEventWatcher(eventHandler func(*v1.Event)) watch.Interface { ...... go func() { defer utilruntime.HandleCrash() for { ...... } }() return watcher}
結語
這次的源碼分析中,不單單瞭解了pilot-discovery的設計實現,還通過k8s的go用戶端學習到了延遲隊列,流量控制,協程安全資料庫等相關的實現和應用情境,收穫不少。