前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >编排系统K8S Ingress-nginx源码解析

编排系统K8S Ingress-nginx源码解析

作者头像
Luga Lee
发布2021-12-09 20:24:11
8090
发布2021-12-09 20:24:11
举报
文章被收录于专栏:架构驿站

上篇文章介绍了Ingress-nginx的基本架构原理,具体可参考:

编排系统K8S Ingress-nginx介绍

本篇重点以源码为基础,深入讲解 Ingress-nginx的内部工作流以及整体工作模式。先来张工作流图:

如上述工作流图所述:Ingress-nginx 模块在运行时主要包括三个主体:NginxController、Store、SyncQueue。其中:

Store(协程)模块主要负责从 kubernetes API Server 收集运行时信息,感知各类资源(如 Ingress、Service等)的变化,并及时将更新事件消息(event)写入一个环形管道。 SyncQueue(协程)定期扫描 syncQueue 队列,发现有任务就执行更新操作,即借助 Store 完成最新运行数据的拉取,然后根据一定的规则产生新的 nginx 配置,(有些更新必须 reload,就本地写入新配置,执行 reload),然后执行动态更新操作,即构造 POST 数据,向本地 Nginx Lua 服务模块发送 post 请求,以实现配置更新。

NginxController(主程)作为中间的联系者,监听 updateChannel,一旦收到配置更新事件,就向同步队列 syncQueue 里写入一个更新请求。

下面我们看下相关源码解析:[因篇幅有限,仅列出核心的部分]

整个流程入口为main()函数,以下为~/nginx/main.go源码

代码语言:javascript
复制
func main() {
  ...
  ngx := controller.NewNGINXController(conf, mc, fs)
  ...
  ngx.Start()
}

在 main 函数中,程序首先构造了 NginxController,并执行了其 Start 方法,启动了 Controller 主程序。

关于ngx.Start(),我们可以追溯到internal/ingress/controller/nginx.go#Start(),具体:

代码语言:javascript
复制
func (n *NGINXController) Start() {
  ...
  n.store.Run(n.stopCh)
  ...
  go n.syncQueue.Run(time.Second, n.stopCh)
  ...
  for {
    select {
    ...
    case event := <-n.updateCh.Out():
      if n.isShuttingDown {
        break
      }
      if evt, ok := event.(store.Event); ok {
        if evt.Type == store.ConfigurationEvent {
          n.syncQueue.EnqueueTask(task.GetDummyObject("configmap-change"))
          continue
        }
        n.syncQueue.EnqueueSkippableTask(evt.Obj)
      } 
    ...
  }
}

NginxController 首先启动了 Store 协程,然后启动了 syncQueue 协程,最后监听 updateCh,当收到事件后,经过相关条件判断然后向 syncQueue 写入了一个 task。

关于Store 协程,跟踪到 internal/ingress/controller/store/store.go#Run(),具体:

代码语言:javascript
复制
func (s k8sStore) Run(stopCh chan struct{}) {
  s.informers.Run(stopCh)
  ...
}

通过代码我们可以看到,此方法继续调用了 informer 的 Run 方法,继续跟踪,可看到如下:

代码语言:javascript
复制
// Run initiates the synchronization of the informers against the API server.
func (i *Informer) Run(stopCh chan struct{}) {
  go i.Endpoint.Run(stopCh)
  go i.Service.Run(stopCh)
  go i.Secret.Run(stopCh)
  go i.ConfigMap.Run(stopCh)
  ...
  go i.Ingress.Run(stopCh)
  ...
}

informer 的 Run 方法,会起更多的协程,去监听不同资源的变化,包括 Endpoint、Service、Secret、ConfigMap、Ingress等等。以 Ingress 为例,在其定义处,可以找到 New() :

代码语言:javascript
复制
// New creates a new object store to be used in the ingress controller
func New(... updateCh *channels.RingChannel ...) Storer {
  ...
  store.informers.Ingress = infFactory.Extensions().V1beta1().Ingresses().Informer()
  ...
  ingEventHandler := cache.ResourceEventHandlerFuncs{
    AddFunc: func(obj interface{}) {
      ...
      updateCh.In() <- Event{
        Type: CreateEvent,
        Obj:  obj,
      }
    },
    DeleteFunc: func(obj interface{}) {
      ...
      updateCh.In() <- Event{
        Type: DeleteEvent,
        Obj:  obj,
      }
    },
    UpdateFunc: func(old, cur interface{}) {
      ...
      updateCh.In() <- Event{
        Type: UpdateEvent,
        Obj:  cur,
      }
    },
  }
...
  store.informers.Ingress.AddEventHandler(ingEventHandler)
  ...
}

可以看出,Ingress 协程定义了监听 ingress 信息的 informer 对象,并注册了相关事件的回调方法,在回调方法内向之前提到的 updateCh 写入了事件,进而也就达到了当资源变化时通知 Controller 主程向同步队列写入task的目的。

关于syncQueue,可追溯到internal/ingress/controller/nginx.go # NewNGINX-Controller():

代码语言:javascript
复制
// NewNGINXController creates a new NGINX Ingress controller.
func NewNGINXController(config *Configuration, mc metric.Collector, fs file.Filesystem) *NGINXController {
  ...
  n.syncQueue = task.NewTaskQueue(n.syncIngress)
  ...
}

队列的创建是通过 task.NewTaskQueue() 完成的,而且传入了关键的处理函数 n.syncIngress。继续跟踪到 internal/task/queue.go#NewTaskQueue():

代码语言:javascript
复制
// NewTaskQueue creates a new task queue with the given sync function.
// The sync function is called for every element inserted into the queue.
func NewTaskQueue(syncFn func(interface{}) error) *Queue {
  return NewCustomTaskQueue(syncFn, nil)
}
 
// NewCustomTaskQueue ...
func NewCustomTaskQueue(syncFn func(interface{}) error, fn func(interface{}) (interface{}, error)) *Queue {
  q := &Queue{
    queue:      workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
    sync:       syncFn,
    workerDone: make(chan bool),
    fn:         fn,
  }
  ...
  return q
}

可以看出,传入的处理函数 n.syncIngress 被赋值给 Queue 的 sync 属性了。实际上,syncQueue 的执行就是在反复执行该方法以消费队列里的元素。有关Queue 的 Run 定义可以追溯至:

代码语言:javascript
复制
// Run starts processing elements in the queue
func (t *Queue) Run(period time.Duration, stopCh <-chan struct{}) {
  wait.Until(t.worker, period, stopCh)
}
 
// worker processes work in the queue through sync.
func (t *Queue) worker() {
  for {
    key, quit := t.queue.Get()
    ...
    if err := t.sync(key); err != nil {
      t.queue.AddRateLimited(Element{
        Key:       item.Key,
        Timestamp: time.Now().UnixNano(),
      })
    } else {
      t.queue.Forget(key)
      t.lastSync = ts
    }
 
    t.queue.Done(key)
  }
}

同步队列协程的主要工作就是定期取出队列里的元素,并利用传入的 n.syncIngress (即 t.sync(key))方法处理队列里的元素。n.syncIngress 方法的定义在 internal/-ingress-/controller/controller.go#syncIngress():

代码语言:javascript
复制
// syncIngress collects all the pieces required to assemble the NGINX
// configuration file and passes the resulting data structures to the backend
// (OnUpdate) when a reload is deemed necessary.
func (n *NGINXController) syncIngress(interface{}) error {
 
  // 获取最新配置信息
  ....
  // 构造 nginx 配置
  pcfg := &ingress.Configuration{
    Backends:              upstreams,
    Servers:               servers,
    PassthroughBackends:   passUpstreams,
    BackendConfigChecksum: n.store.GetBackendConfiguration().Checksum,
  }
  ...
  // 不能避免 reload,就执行 reload 更新配置
  if !n.IsDynamicConfigurationEnough(pcfg) {
    ...
    err := n.OnUpdate(*pcfg)
    ...
  }
  ...
  // 动态更新配置
  err := wait.ExponentialBackoff(retry, func() (bool, error) {
    err := configureDynamically(pcfg, n.cfg.ListenPorts.Status, n.cfg.DynamicCertificatesEnabled)
    ...
  })
  ...
}

关于动态更新的工作机制,函数定义位于 internal/ingress/controller/nginx.go#-configureDynamically():

代码语言:javascript
复制
/ configureDynamically encodes new Backends in JSON format and POSTs the
// payload to an internal HTTP endpoint handled by Lua.
func configureDynamically(pcfg *ingress.Configuration, port int, isDynamicCertificatesEnabled bool) error {
  backends := make([]*ingress.Backend, len(pcfg.Backends))
 
  for i, backend := range pcfg.Backends {
    var service *apiv1.Service
    if backend.Service != nil {
      service = &apiv1.Service{Spec: backend.Service.Spec}
    }
    luaBackend := &ingress.Backend{
      Name:                 backend.Name,
      Port:                 backend.Port,
      SSLPassthrough:       backend.SSLPassthrough,
      SessionAffinity:      backend.SessionAffinity,
      UpstreamHashBy:       backend.UpstreamHashBy,
      LoadBalancing:        backend.LoadBalancing,
      Service:              service,
      NoServer:             backend.NoServer,
      TrafficShapingPolicy: backend.TrafficShapingPolicy,
      AlternativeBackends:  backend.AlternativeBackends,
    }
 
    var endpoints []ingress.Endpoint
    for _, endpoint := range backend.Endpoints {
          endpoints = append(endpoints, ingress.Endpoint{
        Address: endpoint.Address,
        Port:    endpoint.Port,
      })
    }
 
    luaBackend.Endpoints = endpoints
    backends[i] = luaBackend
  }
 
  url := fmt.Sprintf("http://localhost:%d/configuration/backends", port)
  err := post(url, backends)
  if err != nil {
    return err
  }
 
  if isDynamicCertificatesEnabled {
    err = configureCertificates(pcfg, port)
    if err != nil {
      return err
    }
  }
 
  return nil
}

结合源码:通过请求 Lua 后端来实现动态配置更新的,使用的是典型的 http post 方法。后续的动态更新动作转交给 Lua 模块负责。因为 Lua 以模块形式嵌入 Nginx 运行,因此其更新配置也就在一定程度上避免了 reload。

至于reload 配置的函数定义,可参考:internal/ingress/controller/nginx.go#OnUpdate-()。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-01-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 架构驿站 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档