转载请声明出处哦~,本篇文章发布于luozhiyun的博客:https://www.luozhiyun.com

本文使用的Istio源码是 release 1.5。

Config Controller用于管理各种配置数据,包括用户创建的流量管理规则和策略。Istio目前支持三种类型的Config Controller:

  • MCP:是一种网络配置协议,用于隔离Pilot和底层平台(文件系统、K8s),使得Pilot无须感知底层平台的差异,从而达到解耦的目的。
  • File:通过监视器周期性地读取本地配置文件,将配置规则缓存在内存中,并维护配置的增加、更新、删除事件,当缓存由变化的时候,异步通知执行事件回调。
  • Kubernetes:基于k8s的Config发现利用了k8s Informer的监听能力。在k8s集群中,Config以CustomResource的形式存在。通过监听apiserver配置规则资源,维护所有资源的缓存Store,并触发事件处理回调函数。

ConfigController初始化

ConfigController是在initConfigController中被初始化的,在initConfigController方法中会调用makeKubeConfigController进行controller的初始化。

func (s *Server) makeKubeConfigController(args *PilotArgs) (model.ConfigStoreCache, error) {
//创建configClient
configClient, err := controller.NewClient(args.Config.KubeConfig, "", collections.Pilot,
args.Config.ControllerOptions.DomainSuffix, buildLedger(args.Config), args.Revision)
if err != nil {
return nil, multierror.Prefix(err, "failed to open a config client.")
}
//创建controller,并为config资源设置监听
return controller.NewController(configClient, args.Config.ControllerOptions), nil
} func NewController(client *Client, options controller2.Options) model.ConfigStoreCache {
log.Infof("CRD controller watching namespaces %q", options.WatchedNamespace) // The queue requires a time duration for a retry delay after a handler error
out := &controller{
client: client,
queue: queue.NewQueue(1 * time.Second),
kinds: make(map[resource.GroupVersionKind]*cacheHandler),
} // add stores for CRD kinds
//获取所有的CRD类型
for _, s := range client.Schemas().All() {
//为每一种Config资源都创建一个informer,监听所有的Config资源
out.addInformer(s, options.WatchedNamespace, options.ResyncPeriod)
}
return out
}

初始化完controller之后会获取所有的CRD类型,为每一种Config资源都创建一个informer,监听所有的Config资源。

	Pilot = collection.NewSchemasBuilder().
//MeshPolicy
MustAdd(IstioAuthenticationV1Alpha1Meshpolicies).
MustAdd(IstioAuthenticationV1Alpha1Policies).
MustAdd(IstioConfigV1Alpha2Httpapispecbindings).
MustAdd(IstioConfigV1Alpha2Httpapispecs).
MustAdd(IstioMixerV1ConfigClientQuotaspecbindings).
MustAdd(IstioMixerV1ConfigClientQuotaspecs).
//DestinationRule
MustAdd(IstioNetworkingV1Alpha3Destinationrules).
//EnvoyFilter
MustAdd(IstioNetworkingV1Alpha3Envoyfilters).
//Gateway
MustAdd(IstioNetworkingV1Alpha3Gateways).
//ServiceEntry
MustAdd(IstioNetworkingV1Alpha3Serviceentries).
//Sidecar
MustAdd(IstioNetworkingV1Alpha3Sidecars).
//VirtualService
MustAdd(IstioNetworkingV1Alpha3Virtualservices).
MustAdd(IstioRbacV1Alpha1Clusterrbacconfigs).
MustAdd(IstioRbacV1Alpha1Rbacconfigs).
MustAdd(IstioRbacV1Alpha1Servicerolebindings).
MustAdd(IstioRbacV1Alpha1Serviceroles).
MustAdd(IstioSecurityV1Beta1Authorizationpolicies).
MustAdd(IstioSecurityV1Beta1Peerauthentications).
MustAdd(IstioSecurityV1Beta1Requestauthentications).
Build()

这里定义好了所有要用到的Config资源类型,主要涉及网络配置、认证、鉴权、策略管理等。

ConfigController事件处理

下面我们看一下controller定义:

type controller struct {
client *Client
queue queue.Instance
kinds map[resource.GroupVersionKind]*cacheHandler
}

client是调用controller.NewClient初始化的client;queue会在Informer监听到资源的变动的时候将数据push到队列中,controller在调用run方法的时候单独运行一个线程运行queue中的函数;kinds在调用addInformer方法的时候初始化进去。

queue.Instance的定义如下:

type Task func() error

type Instance interface {
Push(task Task)
Run(<-chan struct{})
} type queueImpl struct {
delay time.Duration
tasks []Task
cond *sync.Cond
closing bool
}

queueImpl继承了Instance接口,在调用push方法的时候,会将Task放入到tasks数组中,并在调用Run方法的时候消费数组中的数据。

controller继承了ConfigStoreCache接口:

type ConfigStoreCache interface {
ConfigStore
// 注册规则事件处理函数
RegisterEventHandler(kind resource.GroupVersionKind, handler func(Config, Config, Event))
// 运行
Run(stop <-chan struct{}) // 配置缓存是否已同步
HasSynced() bool
}

ConfigStoreCache通过RegisterEventHandler接口为上面提到的配置资源都注册事件处理函数,通过Run方法启动控制器。

func (c *controller) Run(stop <-chan struct{}) {
log.Infoa("Starting Pilot K8S CRD controller")
go func() {
cache.WaitForCacheSync(stop, c.HasSynced)
//单独启动一个线程运行queue里面的函数
c.queue.Run(stop)
}() for _, ctl := range c.kinds {
go ctl.informer.Run(stop)
} <-stop
log.Info("controller terminated")
}

在调用Run方法的时候会单独的启动一个线程调用queue的Run方法消费队列中的数据,并遍历所有的配置信息,调用informer的Run方法开启监听。

监听器的EventHandler通过如下代码注册:

func (c *controller) newCacheHandler(
schema collection.Schema,
o runtime.Object,
otype string,
resyncPeriod time.Duration,
lf cache.ListFunc,
wf cache.WatchFunc) *cacheHandler {
informer := cache.NewSharedIndexInformer(
&cache.ListWatch{ListFunc: lf, WatchFunc: wf}, o,
resyncPeriod, cache.Indexers{}) h := &cacheHandler{
c: c,
schema: schema,
informer: informer,
} informer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
incrementEvent(otype, "add")
//将ADD事件发送至队列
c.queue.Push(func() error {
return h.onEvent(nil, obj, model.EventAdd)
})
},
UpdateFunc: func(old, cur interface{}) {
if !reflect.DeepEqual(old, cur) {
incrementEvent(otype, "update")
//将Update事件发送至队列
c.queue.Push(func() error {
return h.onEvent(old, cur, model.EventUpdate)
})
} else {
incrementEvent(otype, "updatesame")
}
},
DeleteFunc: func(obj interface{}) {
incrementEvent(otype, "delete")
//将Delete事件发送至队列
c.queue.Push(func() error {
return h.onEvent(nil, obj, model.EventDelete)
})
},
}) return h
}

当Config资源创建、更新、删除时,EventHandler创建任务对象并将其发送到任务队列中,然后由任务处理线程处理。当对应的事件被调用的时候会触发onEvent方法,会调用到cacheHandler的onEvent方法,最后设置完毕后将cacheHandler返回,controller会将此cacheHandler设置到kinds数组中存下来。

下面我们看一下cacheHandler的定义:

type cacheHandler struct {
c *controller
schema collection.Schema
informer cache.SharedIndexInformer
handlers []func(model.Config, model.Config, model.Event)
}

cacheHandler在上面初始化的时候,会传入对应的controller、Schema、informer,然后在调用configController的RegisterEventHandler方法的时候会初始化对应的configHandler。

configController的RegisterEventHandler方法会在初始化DiscoveryService的时候调用initEventHandlers方法进行初始化:

func (s *Server) initEventHandlers() error {
...
if s.configController != nil {
configHandler := func(old, curr model.Config, _ model.Event) {
pushReq := &model.PushRequest{
Full: true,
ConfigTypesUpdated: map[resource.GroupVersionKind]struct{}{curr.GroupVersionKind(): {}},
Reason: []model.TriggerReason{model.ConfigUpdate},
}
s.EnvoyXdsServer.ConfigUpdate(pushReq)
}
//遍历所有的资源
for _, schema := range collections.Pilot.All() {
// This resource type was handled in external/servicediscovery.go, no need to rehandle here.
//ServiceEntry 这个资源不在这里注册,感兴趣的朋友可以自己找一下
if schema.Resource().GroupVersionKind() == collections.IstioNetworkingV1Alpha3Serviceentries.
Resource().GroupVersionKind() {
continue
}
//注册configHandler到configController中
s.configController.RegisterEventHandler(schema.Resource().GroupVersionKind(), configHandler)
}
} return nil
}

initEventHandlers会调用collections.Pilot.All方法获取所有的资源配置,然后遍历调用RegisterEventHandler方法将configHandler函数注册到cacheHandler的handlers中,至于configHandler函数做了什么,我们到下一篇讲XdsServer的时候再讲。

这一部分的代码是比较绕的,这里画个图理解一下吧。

整个执行流程为:

总结

至此,ConfigController的核心原理及工作流程就介绍完毕了。本篇主要讲解了我们常用的Istio的Gateway、DestinationRule及VirtualService等配置是如何被Istio监听到并作出相应改变的。希望大家能有所收获。

Reference

https://ruofeng.me/2018/11/08/how-does-istio-pilot-push-eds-config/

https://zhaohuabing.com/post/2019-10-21-pilot-discovery-code-analysi

https://www.servicemesher.com/blog/envoy-proxy-config-deep-dive/

https://www.cnblogs.com/163yun/p/8962278.html

3.深入Istio:Pilot配置规则ConfigController的更多相关文章

  1. istio路由配置

    istio路由配置   istio的代理配置参考文档: 中文文档: https://istio.io/zh/docs/reference/config/istio.networking.v1alpha ...

  2. Istio 的配置分析

    Istio 的配置分析 目录 Istio 的配置分析 Analyzer 的消息格式 ConflictingMeshGatewayVirtualServiceHosts 问题解决 举例 Conflict ...

  3. quartz 时间配置规则

    quartz 时间配置规则 格式: [秒] [分] [小时] [日] [月] [周] [年]  序号 说明  是否必填  允许填写的值 允许的通配符  1  秒  是  0-59    , - * / ...

  4. Linux iptables 配置规则

    Linux iptables 防火墙配置规则 前言:把网上我感觉不错iptables的访问规则都统一在这里,以后做参考. modprobe ipt_MASQUERADE modprobe ip_con ...

  5. 【Web】Nginx配置规则

    Nginx配置基本说明 以下是nginx的基本配置文件如下(编辑命令:vi /usr/local/nginx/conf/nginx.conf): #user nobody; #nginx进程数,建议设 ...

  6. linux 下crontab相关定时触发的配置规则

    linux 下crontab相关定时触发的配置规则: 1.基本格式 :* * * * * command(分 时 日 月 周 命令)2.取值范围:分钟1-59 每分钟用*或者 */1表示小时1-23( ...

  7. dubbo之配置规则

    配置规则 向注册中心写入动态配置覆盖规则 1.该功能通常由监控中心或治理中心的页面完成. RegistryFactory registryFactory = ExtensionLoader.getEx ...

  8. Springboot中以配置类方式自定义Mybatis的配置规则(如开启驼峰映射等)

    什么是自定义Mybatis的配置规则? 答:即原来在mybatis配置文件中中我们配置到<settings>标签中的内容,如下第6-10行内容: 1 <?xml version=&q ...

  9. Istio DestinationRule 目标规则

    概念及示例 与VirtualService一样,DestinationRule也是 Istio 流量路由功能的关键部分.您可以将虚拟服务视为将流量如何路由到给定目标地址,然后使用目标规则来配置该目标的 ...

随机推荐

  1. Luogu P2536 [AHOI2005]病毒检测

    题意 给一个有通配符的模式串和 \(n\) 个文本串,其中 ? 可以匹配任意字符,* 可以匹配 \(0\) 或任意多个字符,求 \(n\) 个文本串中无法与模式串匹配的数量. \(\texttt{Da ...

  2. 手写Express.js源码

    上一篇文章我们讲了怎么用Node.js原生API来写一个web服务器,虽然代码比较丑,但是基本功能还是有的.但是一般我们不会直接用原生API来写,而是借助框架来做,比如本文要讲的Express.通过上 ...

  3. Ubuntu Kylin 部署 .Net Core 应用程序

    前几日在头条上看到了 优麒麟(https://www.ubuntukylin.com/) ,出于好奇,就下载安装玩玩,整体感觉不错.当然这不是重点,重点是要在它上面部署的.Net Core 应用程序. ...

  4. PHP date_formate使用相关

    $date=date_create("2016-09-25"); echo date_format($date,"Y/m/d H:i:s");要使用date_f ...

  5. linux查找大文件及详细问题

    查询大文件du -h --max-depth=1 查询指定目录下面的文件大小du -h --max-depth=1 /path 使用find命令查找大于200M文件 find / -type f -s ...

  6. MapStruct 解了对象映射的毒

    前言 MVC模式是目前主流项目的标准开发模式,这种模式下框架的分层结构清晰,主要分为Controller,Service,Dao.分层的结构下,各层之间的数据传输要求就会存在差异,我们不能用一个对象来 ...

  7. DTU的工作原理和流程

    DTU是无线数据传输模块,采用2G,3G,4G网络,将本地串口数据经DTU打包成TCP或者UDP数据进行远程传输的设备.使用方便.已经在各行业远程数据传输,设备监控等领域大量应用.如智能仪器仪表.智能 ...

  8. WPF应用中一种比较完美的权限控制设计方式

    如题近段时间 需要在wpf应用中设计一个权限控制 , 简而言之的说 你懂的 对于IT人员来说都知道的 常见的软件功能 首先要有用户 用户,然后用户属于哪个角色 ,然后各个角色都有自己的可供操作的一堆功 ...

  9. Pytest学习(七) - skip、skipif的使用

    前言 作为一个java党,我还是觉得pytest和testng很像,有时候真的会感觉到代码语言在某种程度上是相通的,那么今天来说说这两个知识点. skip和skipif,见名知意,就是跳过测试呗,直白 ...

  10. Moment.js的常见用法

    Moment.js是一个轻量级的JavaScript时间库,它方便了日常开发中对时间的操作,提高了开发效率.通常是用来获取时间,设置时间,格式化时间,比较时间等操作.  1.获取时间       St ...