kubernetes版本:1.13.2

背景

由于operator创建的redis集群,在kubernetes apiserver重启后,redis集群被异常删除(包括redis exporter statefulset、redis statefulset)。删除后operator将其重建,重新组建集群,实例IP发生变更(中间件容器化,我们开发了固定IP,当statefulset删除后,IP会被回收),导致创建集群失败,最终集群不可用。

经多次复现,apiserver重启后,通过查询redis operator日志,并没有发现主动去删除redis集群(redis statefulset)、监控实例(redis exporter)。进一步去查看kube-controller-manager的日志,将其日志级别设置--v=5,继续复现,最终在kube-controller-manager日志中发现如下日志: kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes可以看到是garbage collector触发删除操作的。这个问题在apiserver正常的时候是不存在,要想弄其究竟,就得看看kube-controller-manager内置组件garbage collector这个控制器的逻辑。

由于内容偏长,分为多节来讲: 

①、 monitors作为生产者将变化的资源放入 graphChanges队列;同时 restMapper定期检测集群内资源类型,刷新 monitors 

②、 runProcessGraphChanges从 graphChanges队列中取出变化的 item,根据情况放入 attemptToDelete队列; runAttemptToDeleteWorker取出处理垃圾资源;

③、 runProcessGraphChanges从 graphChanges队列中取出变化的 item,根据情况放入 attemptToOrphan队列; runAttemptToOrphanWorker取出处理该该孤立的资源; 

kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes_02


正文

想要启用 GC,需要在 kube-apiserver和 kube-controller-manager的启动参数中都设置 --enable-garbage-collector为 true, 1.13.2版本中默认开启 GC。

需要注意:两组件该参数必须保持同步。


kube-controller-manager启动入口, app.NewControllerManagerCommand()中加载 controller manager默认启动参数,创建 *cobra.Command对象:

  1. func main() {

  2. rand.Seed(time.Now().UnixNano())

  3. //加载controller manager默认启动参数,创建* cobra.Command对象

  4. command := app.NewControllerManagerCommand()

  5. //......省略.......

  6. //执行cobra.command,并启动controller-manager

  7. if err := command.Execute(); err != nil {

  8. fmt.Fprintf(os.Stderr, "%v\n", err)

  9. os.Exit(1)

  10. }

  11. }

以下代码处去启动 kube-controller-manager: kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes_03NewDefaultComponentConfig(ports.InsecureKubeControllerManagerPort)加载各个控制器的配置:

  1. //NewKubeControllerManagerOptions使用默认配置创建一个新的KubeControllerManagerOptions

  2. func NewKubeControllerManagerOptions() (*KubeControllerManagerOptions, error) {

  3. //加载各个控制器的默认配置

  4. componentConfig, err := NewDefaultComponentConfig(ports.InsecureKubeControllerManagerPort)

  5. if err != nil {

  6. return nil, err

  7. }

  8.  

  9. s := KubeControllerManagerOptions{

  10. Generic: cmoptions.NewGenericControllerManagerConfigurationOptions(componentConfig.Generic),

  11. //.....省略

  12. GarbageCollectorController: &GarbageCollectorControllerOptions{

  13. ConcurrentGCSyncs: componentConfig.GarbageCollectorController.ConcurrentGCSyncs,

  14. EnableGarbageCollector: componentConfig.GarbageCollectorController.EnableGarbageCollector,

  15. },

  16. //.....省略

  17. }

  18. //gc忽略的资源对象列表

  19. gcIgnoredResources := make([]kubectrlmgrconfig.GroupResource, 0, len(garbagecollector.DefaultIgnoredResources()))

  20. for r := range garbagecollector.DefaultIgnoredResources() {

  21. gcIgnoredResources = append(gcIgnoredResources, kubectrlmgrconfig.GroupResource{Group: r.Group, Resource: r.Resource})

  22. }

  23. s.GarbageCollectorController.GCIgnoredResources = gcIgnoredResources

  24. return &s, nil

  25. }

  1. // NewDefaultComponentConfig返回kube-controller管理器配置对象

  2. func NewDefaultComponentConfig(insecurePort int32) (kubectrlmgrconfig.KubeControllerManagerConfiguration, error) {

  3. scheme := runtime.NewScheme()

  4. if err := kubectrlmgrschemev1alpha1.AddToScheme(scheme); err != nil {

  5. return kubectrlmgrconfig.KubeControllerManagerConfiguration{}, err

  6. }

  7. if err := kubectrlmgrconfig.AddToScheme(scheme); err != nil {

  8. return kubectrlmgrconfig.KubeControllerManagerConfiguration{}, err

  9. }

  10.  

  11. versioned := kubectrlmgrconfigv1alpha1.KubeControllerManagerConfiguration{}

  12. //加载默认参数

  13. scheme.Default(&versioned)

  14.  

  15. internal := kubectrlmgrconfig.KubeControllerManagerConfiguration{}

  16. if err := scheme.Convert(&versioned, &internal, nil); err != nil {

  17. return internal, err

  18. }

  19. internal.Generic.Port = insecurePort

  20. return internal, nil

  21. }

  1. // 根据Object,获取提供的默认参数

  2. func (s *Scheme) Default(src Object) {

  3. if fn, ok := s.defaulterFuncs[reflect.TypeOf(src)]; ok {

  4. fn(src)

  5. }

  6. }

s.defaulterFuncs类型为map[reflect.Type]func(interface{}),用于根据指针类型获取默认值函数。该map中的数据从哪里来的呢?

代码位于src\k8s.io\kubernetes\pkg\controller\apis\config\v1alpha1\zz_generated.defaults.go kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes_04可以看到默认参数中garbage collector中默认开启gc(EnableGarbageCollector),并发数为20(ConcurrentGCSyncs)

  1. func SetDefaults_GarbageCollectorControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.GarbageCollectorControllerConfiguration) {

  2. if obj.EnableGarbageCollector == nil {

  3. obj.EnableGarbageCollector = utilpointer.BoolPtr(true)

  4. }

  5. if obj.ConcurrentGCSyncs == 0 {

  6. obj.ConcurrentGCSyncs = 20

  7. }

  8. }

回到Run函数,里面调用了NewControllerInitializers启动所有控制器: kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes_05重点来到启动garbage collector的startGarbageCollectorController函数:

  1. func startGarbageCollectorController(ctx ControllerContext) (http.Handler, bool, error) {

  2. //k8s 1.13.2中默认为true,可在kube-apiserver和kube-controller-manager的启动参数中加--enable-garbage-conllector=false设置

  3. //需保证这两个组件中参数值一致

  4. if !ctx.ComponentConfig.GarbageCollectorController.EnableGarbageCollector {

  5. return nil, false, nil

  6. }

  7.  

  8. //k8s各种原生资源对象客户端集合(默认启动参数中用SimpleControllerClientBuilder构建)

  9. gcClientset := ctx.ClientBuilder.ClientOrDie("generic-garbage-collector")

  10. discoveryClient := cacheddiscovery.NewMemCacheClient(gcClientset.Discovery())

  11.  

  12. //生成rest config

  13. config := ctx.ClientBuilder.ConfigOrDie("generic-garbage-collector")

  14. dynamicClient, err := dynamic.NewForConfig(config)

  15. if err != nil {

  16. return nil, true, err

  17. }

  18.  

  19. // Get an initial set of deletable resources to prime the garbage collector.

  20. //获取一组初始可删除资源以填充垃圾收集器。

  21. deletableResources := garbagecollector.GetDeletableResources(discoveryClient)

  22. ignoredResources := make(map[schema.GroupResource]struct{})

  23.  

  24. //忽略gc的资源类型

  25. for _, r := range ctx.ComponentConfig.GarbageCollectorController.GCIgnoredResources {

  26. ignoredResources[schema.GroupResource{Group: r.Group, Resource: r.Resource}] = struct{}{}

  27. }

  28. garbageCollector, err := garbagecollector.NewGarbageCollector(

  29. dynamicClient,

  30. ctx.RESTMapper,

  31. deletableResources,

  32. ignoredResources,

  33. ctx.InformerFactory,

  34. ctx.InformersStarted,

  35. )

  36. if err != nil {

  37. return nil, true, fmt.Errorf("Failed to start the generic garbage collector: %v", err)

  38. }

  39.  

  40. // Start the garbage collector.

  41. //启动参数中默认是20个协程

  42. workers := int(ctx.ComponentConfig.GarbageCollectorController.ConcurrentGCSyncs)

  43. //启动monitors和deleteWorkers、orphanWorkers

  44. go garbageCollector.Run(workers, ctx.Stop)

  45.  

  46. // Periodically refresh the RESTMapper with new discovery information and sync

  47. // the garbage collector.

  48. //使用新的发现信息定期刷新RESTMapper并同步垃圾收集器。

  49. go garbageCollector.Sync(gcClientset.Discovery(), 30*time.Second, ctx.Stop)

  50.  

  51. //gc提供debug dot grap依赖关系图接口

  52. return garbagecollector.NewDebugHandler(garbageCollector), true, nil

  53. }

该函数主要作用有: 

1、deletableResources := garbagecollector.GetDeletableResources(discoveryClient)获取集群内所有可删除的资源对象;排除掉忽略的资源对象。 

2、构建garbageCollector结构体对象; 

3、garbageCollector.Run(workers, ctx.Stop)启动一个monitors用来监听资源对象的变化(对应的由runProcessGraphChanges死循环处理),和默认20个deleteWorkers协程处理可删除的资源对象、20个orphanWorkers协程处理孤儿对象。

4、garbageCollector.Sync(gcClientset.Discovery(), 30*time.Second, ctx.Stop) 定时去获取一个集群内是否有新类型的资源对象的加入,并重新刷新monitors,以监听新类型的资源对象。

5、garbagecollector.NewDebugHandler(garbageCollector)注册debug接口,用来提供获取dot流程图接口:

  1. curl http://127.0.0.1:10252/debug/controllers/garbagecollector/graph?uid=11211212edsaddkqedmk12

使用graphviz提供的dot.exe可以生成svg格式的图,可用google浏览器查看如下: kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes_06

  1. // curl http://127.0.0.1:10252/debug/controllers/garbagecollector/graph?uid=11211212edsaddkqedmk12

  2. func (h *debugHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {

  3. if req.URL.Path != "/graph" {

  4. http.Error(w, "", http.StatusNotFound)

  5. return

  6. }

  7.  

  8. var graph graph.Directed

  9. if uidStrings := req.URL.Query()["uid"]; len(uidStrings) > 0 {

  10. uids := []types.UID{}

  11. for _, uidString := range uidStrings {

  12. uids = append(uids, types.UID(uidString))

  13. }

  14. graph = h.controller.dependencyGraphBuilder.uidToNode.ToGonumGraphForObj(uids...)

  15.  

  16. } else {

  17. graph = h.controller.dependencyGraphBuilder.uidToNode.ToGonumGraph()

  18. }

  19.  

  20. //生成dot流程图数据,用graphviz工具中的dot.exe工具转换为svg图(用google浏览器打开)或者png图

  21. //API参考:https://godoc.org/gonum.org/v1/gonum/graph

  22. //graphviz下载地址:https://graphviz.gitlab.io/_pages/Download/Download_windows.html

  23. //dot.exe test.dot -T svg -o test.svg

  24. data, err := dot.Marshal(graph, "full", "", " ", false)

  25. if err != nil {

  26. http.Error(w, err.Error(), http.StatusInternalServerError)

  27. return

  28. }

  29. w.Write(data)

  30. w.WriteHeader(http.StatusOK)

  31. }

kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes_07GarbageCollector通过restMapper定期重置可删除的资源类型,更新GraphBuilder中的monitors,monitors将创建所有资源类型的变更通知回调函数,将变化的资源对象加入到GraphBuilder的graphChanges队列,GraphBuilder的runProcessGraphChanges()会一直从队列中获取变化,构建一个缓存对象之间依赖关系的图形,以及触发dependencyGraphBuilder将可能被垃圾收集的对象排队到 attemptToDelete队列,并将其依赖项需要孤立的对象排队到 attemptToOrphan队列。GarbageCollector具有使用这两个队列的工作人员runAttemptToDeleteWorker和runAttemptToOrphanWorker死循环,分别从 attemptToDelete队列和 attemptToOrphan队列取出,向API服务器发送请求以相应地删除更新对象。

  1. // GarbageCollector运行反射器来监视托管API对象的更改,将结果汇总到单线程dependencyGraphBuilder,

  2. // 构建一个缓存对象之间依赖关系的图形。由图变化触发,dependencyGraphBuilder将可能被垃圾收集的对象

  3. // 排队到`attemptToDelete`队列,并将其依赖项需要孤立的对象排队到`attemptToOrphan`队列。

  4. // GarbageCollector具有使用这两个队列的工作人员,向API服务器发送请求以相应地删除更新对象。

  5. // 请注意,让dependencyGraphBuilder通知垃圾收集器确保垃圾收集器使用至少与发送通知一样最新的图形进行操作。

  6. type GarbageCollector struct {

  7. // resettableRESTMapper是一个RESTMapper,它能够在discovery资源类型时重置自己

  8. restMapper resettableRESTMapper

  9. // dynamicClient提供操作集群内所有资源对象的接口方法,包括k8s内置、CRD生成的自定义资源

  10. dynamicClient dynamic.Interface

  11. //垃圾收集器尝试在时间成熟时删除attemptToDelete队列中的item

  12. attemptToDelete workqueue.RateLimitingInterface

  13. //垃圾收集器尝试孤立attemptToOrphan队列中item的依赖项,然后删除item

  14. attemptToOrphan workqueue.RateLimitingInterface

  15. dependencyGraphBuilder *GraphBuilder

  16. // 有owner的资源对象,才会给absentOwnerCache填充不存在的Owner信息

  17. absentOwnerCache *UIDCache

  18. sharedInformers informers.SharedInformerFactory

  19.  

  20. workerLock sync.RWMutex

  21. }

  1. // GraphBuilder:基于informers提供的事件,GraphBuilder更新

  2. // uidToNode,一个缓存我们所知的依赖关系的图,并将

  3. // 项放入attemptToDelete和attemptToOrphan队列

  4. type GraphBuilder struct {

  5. restMapper meta.RESTMapper

  6.  

  7. //每个监视器列表/监视资源,结果汇集到dependencyGraphBuilder

  8. monitors monitors

  9. monitorLock sync.RWMutex

  10. // informersStarted is closed after after all of the controllers have been initialized and are running.

  11. // After that it is safe to start them here, before that it is not.

  12. // informersStarted在所有控制器初始化并运行后关闭。之后在这里启动它们是安全的,在此之前它不是。

  13. informersStarted <-chan struct{}

  14.  

  15. // stopCh drives shutdown. When a receive from it unblocks, monitors will shut down.

  16. // This channel is also protected by monitorLock.

  17. // stopCh驱动器关闭当来自它的接收解除阻塞时,监视器将关闭。此channel也受monitorLock保护。

  18. stopCh <-chan struct{}

  19.  

  20. // running tracks whether Run() has been called.

  21. // it is protected by monitorLock.

  22. //运行轨道是否已调用Run()它受monitorLock保护。

  23. running bool

  24.  

  25. dynamicClient dynamic.Interface

  26. // monitors are the producer of the graphChanges queue, graphBuilder alters

  27. // the in-memory graph according to the changes.

  28. // monitor是graphChanges队列的生成者,graphBuilder根据更改改变了内存中的图形。

  29. graphChanges workqueue.RateLimitingInterface

  30.  

  31. // uidToNode doesn't require a lock to protect, because only the

  32. // single-threaded GraphBuilder.processGraphChanges() reads/writes it.

  33. //uidToNode不需要锁保护,因为只有单线程GraphBuilder.processGraphChanges()读写它。

  34. uidToNode *concurrentUIDToNode

  35.  

  36. // GraphBuilder is the producer of attemptToDelete and attemptToOrphan, GC is the consumer.

  37. // GraphBuilder是attemptToDelete和attemptToOrphan的生产者,GC是消费者。

  38. attemptToDelete workqueue.RateLimitingInterface

  39. attemptToOrphan workqueue.RateLimitingInterface

  40.  

  41. // GraphBuilder and GC share the absentOwnerCache. Objects that are known to

  42. // be non-existent are added to the cached.

  43. // GraphBuilder和GC共享absentOwnerCache。已知不存在的对象将添加到缓存中。

  44. absentOwnerCache *UIDCache

  45.  

  46. //所有k8s资源对象集的informer

  47. sharedInformers informers.SharedInformerFactory

  48.  

  49. //监视器忽略的资源对象集

  50. ignoredResources map[schema.GroupResource]struct{}

  51. }

创建NewGarbageCollector结构体:

  1. func NewGarbageCollector(

  2. dynamicClient dynamic.Interface,

  3. mapper resettableRESTMapper,

  4. deletableResources map[schema.GroupVersionResource]struct{},

  5. ignoredResources map[schema.GroupResource]struct{},

  6. sharedInformers informers.SharedInformerFactory,

  7. informersStarted <-chan struct{},

  8. ) (*GarbageCollector, error) {

  9. attemptToDelete := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "garbage_collector_attempt_to_delete")

  10. attemptToOrphan := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "garbage_collector_attempt_to_orphan")

  11. absentOwnerCache := NewUIDCache(500)

  12. gc := &GarbageCollector{

  13. dynamicClient: dynamicClient,

  14. restMapper: mapper,

  15. attemptToDelete: attemptToDelete,

  16. attemptToOrphan: attemptToOrphan,

  17. absentOwnerCache: absentOwnerCache,

  18. }

  19. gb := &GraphBuilder{

  20. dynamicClient: dynamicClient,

  21. informersStarted: informersStarted,

  22. restMapper: mapper,

  23. graphChanges: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "garbage_collector_graph_changes"),

  24. uidToNode: &concurrentUIDToNode{

  25. uidToNode: make(map[types.UID]*node),

  26. },

  27. attemptToDelete: attemptToDelete,

  28. attemptToOrphan: attemptToOrphan,

  29. absentOwnerCache: absentOwnerCache,

  30. sharedInformers: sharedInformers,

  31. ignoredResources: ignoredResources,

  32. }

  33. //初始化各个资源对象的monitors,启动各资源对象的监听器,变化时触发回调,将其加入graphChanges 队列

  34. if err := gb.syncMonitors(deletableResources); err != nil {

  35. utilruntime.HandleError(fmt.Errorf("failed to sync all monitors: %v", err))

  36. }

  37. gc.dependencyGraphBuilder = gb

  38.  

  39. return gc, nil

  40. }

主要功能:

1、构建GarbageCollector结构体;

2、构建依赖结构图维护结构体GraphBuilder,和GarbageCollector共用attemptToDelete和attemptToOrphan队列,GraphBuilder作为生产着将适当资源放到attemptToDelete或者attemptToOrphan队列,供GarbageCollector中的worker进行消费;

3、初始化各个资源对象的monitors,启动各资源对象的监听器,变化时触发回调,将其加入graphChanges 队列。

gb.syncMonitors(deletableResources)方法中最主要的是 c,s,err:=gb.controllerFor(resource,kind)

  1. func (gb *GraphBuilder) controllerFor(resource schema.GroupVersionResource, kind schema.GroupVersionKind) (cache.Controller, cache.Store, error) {

  2. handlers := cache.ResourceEventHandlerFuncs{

  3. // add the event to the dependencyGraphBuilder's graphChanges.

  4. // 将事件添加到dependencyGraphBuilder的graphChanges中。

  5. AddFunc: func(obj interface{}) {

  6. event := &event{

  7. eventType: addEvent,

  8. obj: obj,

  9. gvk: kind,

  10. }

  11. gb.graphChanges.Add(event)

  12. },

  13. UpdateFunc: func(oldObj, newObj interface{}) {

  14. // TODO: check if there are differences in the ownerRefs,

  15. // finalizers, and DeletionTimestamp; if not, ignore the update.

  16. //TODO:检查ownerRefs, finalizers和DeletionTimestamp是否存在差异;如果没有,请忽略更新。

  17. event := &event{

  18. eventType: updateEvent,

  19. obj: newObj,

  20. oldObj: oldObj,

  21. gvk: kind,

  22. }

  23. gb.graphChanges.Add(event)

  24. },

  25. DeleteFunc: func(obj interface{}) {

  26. // delta fifo may wrap the object in a cache.DeletedFinalStateUnknown, unwrap it

  27. // delta fifo可以将对象包装在cache.DeletedFinalStateUnknown中,解包它

  28. if deletedFinalStateUnknown, ok := obj.(cache.DeletedFinalStateUnknown); ok {

  29. obj = deletedFinalStateUnknown.Obj

  30. }

  31. event := &event{

  32. eventType: deleteEvent,

  33. obj: obj,

  34. gvk: kind,

  35. }

  36. gb.graphChanges.Add(event)

  37. },

  38. }

  39. shared, err := gb.sharedInformers.ForResource(resource)

  40. if err == nil {

  41. klog.V(4).Infof("using a shared informer for resource %q, kind %q", resource.String(), kind.String())

  42. // need to clone because it's from a shared cache

  43. shared.Informer().AddEventHandlerWithResyncPeriod(handlers, ResourceResyncTime)

  44. return shared.Informer().GetController(), shared.Informer().GetStore(), nil

  45. } else {

  46. //获取资源对象时出错会到这里,比如非k8s内置RedisCluster、clusterbases、clusters、esclusters、volumeproviders、stsmasters、appapps、mysqlclusters、brokerclusters、clustertemplates;

  47. //内置的networkPolicies、apiservices、customresourcedefinitions

  48. klog.V(4).Infof("unable to use a shared informer for resource %q, kind %q: %v", resource.String(), kind.String(), err)

  49. }

  50.  

  51. // TODO: consider store in one storage.

  52. // TODO: 考虑存储在一个存储中。

  53. klog.V(5).Infof("create storage for resource %s", resource)

  54. //上面失败的资源对象的store和controller

  55. store, monitor := cache.NewInformer(

  56. listWatcher(gb.dynamicClient, resource),

  57. nil,

  58. ResourceResyncTime,

  59. // don't need to clone because it's not from shared cache

  60. //不需要克隆,因为它不是来自共享缓存

  61. handlers,

  62. )

  63. return monitor, store, nil

  64. }

该方法主要功能是:

1、将新增、更改、删除的资源对象构建为event结构体,放入GraphBuilder的graphChanges队列里,最终被runProcessGraphChanges这个worker消费;

2、构建大多数内置资源的SharedInformerFactory,构建失败的用cache.NewInformer构建(通过CRD定义的对象以及部分k8s内置对象)

代码继续回到k8s.io\kubernetes\cmd\kube-controller-manager\app\core.go中的 startGarbageCollectorController中,看 garbageCollector.Run(workers,ctx.Stop)方法:

  1. func (gc *GarbageCollector) Run(workers int, stopCh <-chan struct{}) {

  2. defer utilruntime.HandleCrash()

  3. defer gc.attemptToDelete.ShutDown()

  4. defer gc.attemptToOrphan.ShutDown()

  5. defer gc.dependencyGraphBuilder.graphChanges.ShutDown()

  6.  

  7. klog.Infof("Starting garbage collector controller")

  8. defer klog.Infof("Shutting down garbage collector controller")

  9.  

  10. //协程运行生产者monitors

  11. go gc.dependencyGraphBuilder.Run(stopCh)

  12.  

  13. //等待dependencyGraphBuilder缓存开始同步

  14. if !controller.WaitForCacheSync("garbage collector", stopCh, gc.dependencyGraphBuilder.IsSynced) {

  15. return

  16. }

  17.  

  18. //垃圾收集器:所有资源监视器都已同步。继续收集垃圾

  19. klog.Infof("Garbage collector: all resource monitors have synced. Proceeding to collect garbage")

  20.  

  21. // gc workers

  22. //协程运行消费者DeleteWorkers和OrphanWorkers

  23. for i := 0; i < workers; i++ {

  24. //默认参数为20个并发协程尝试delete worker

  25. go wait.Until(gc.runAttemptToDeleteWorker, 1*time.Second, stopCh)

  26. //默认参数为20个并发协程尝试orphan worker

  27. go wait.Until(gc.runAttemptToOrphanWorker, 1*time.Second, stopCh)

  28. }

  29.  

  30. <-stopCh

  31. }

gc.dependencyGraphBuilder.Run(stopCh)主要功能: 

1、gb.startMonitors()启动监听资源变化的informer;

2、wait.Until(gb.runProcessGraphChanges, 1*time.Second, stopCh)开启从队列GraphBuilder.graphChanges中消费的worker

启动20个runAttemptToDeleteWorker和20个runAttemptToOrphanWorker

参考:

k8s官方文档garbage-collection英文版:https://kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/

依赖图标生成库gonum Api文档:https://godoc.org/gonum.org/v1/gonum/graph

graphviz下载:https://graphviz.gitlab.io/pages/Download/Downloadwindows.html


 

kubernetes垃圾回收器GarbageCollector Controller源码分析(一)_kubernetes_08