欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-15 17:19:58
kubernetes版本:1.13.2 背景 由于operator创建的redis集群,在kubernetes apiserver重启后,redis集群被异常删除(包括redis exporter statefulset、redis statefulset)。删除后operator将其重建,重新组建 ......

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源码分析(一)
可以看到是garbage collector触发删除操作的。这个问题在apiserver正常的时候是不存在,要想弄其究竟,就得看看kube-controller-manager内置组件garbage collector这个控制器的逻辑。

由于内容偏长,分为多节来讲:
①、monitors作为生产者将变化的资源放入graphchanges队列;同时restmapper定期检测集群内资源类型,刷新monitors
②、runprocessgraphchangesgraphchanges队列中取出变化的item,根据情况放入attempttodelete队列;runattempttodeleteworker取出处理垃圾资源;
③、runprocessgraphchangesgraphchanges队列中取出变化的item,根据情况放入attempttoorphan队列;runattempttoorphanworker取出处理该该孤立的资源;
kubernetes垃圾回收器GarbageCollector源码分析(一)


正文

想要启用gc,需要在kube-apiserverkube-controller-manager的启动参数中都设置--enable-garbage-collectortrue,1.13.2版本中默认开启gc

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


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

func main() {
        rand.seed(time.now().unixnano())
        //加载controller manager默认启动参数,创建* cobra.command对象
        command := app.newcontrollermanagercommand()
        //......省略.......
        //执行cobra.command,并启动controller-manager
        if err := command.execute(); err != nil {
            fmt.fprintf(os.stderr, "%v\n", err)
            os.exit(1)
        }
}

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

//newkubecontrollermanageroptions使用默认配置创建一个新的kubecontrollermanageroptions
func newkubecontrollermanageroptions() (*kubecontrollermanageroptions, error) {
    //加载各个控制器的默认配置
    componentconfig, err := newdefaultcomponentconfig(ports.insecurekubecontrollermanagerport)
    if err != nil {
        return nil, err
    }

    s := kubecontrollermanageroptions{
        generic:         cmoptions.newgenericcontrollermanagerconfigurationoptions(componentconfig.generic),
        //.....省略
        garbagecollectorcontroller: &garbagecollectorcontrolleroptions{
            concurrentgcsyncs:      componentconfig.garbagecollectorcontroller.concurrentgcsyncs,
            enablegarbagecollector: componentconfig.garbagecollectorcontroller.enablegarbagecollector,
        },
        //.....省略
    }
    //gc忽略的资源对象列表
    gcignoredresources := make([]kubectrlmgrconfig.groupresource, 0, len(garbagecollector.defaultignoredresources()))
    for r := range garbagecollector.defaultignoredresources() {
        gcignoredresources = append(gcignoredresources, kubectrlmgrconfig.groupresource{group: r.group, resource: r.resource})
    }
    s.garbagecollectorcontroller.gcignoredresources = gcignoredresources
    return &s, nil
}
// newdefaultcomponentconfig返回kube-controller管理器配置对象
func newdefaultcomponentconfig(insecureport int32) (kubectrlmgrconfig.kubecontrollermanagerconfiguration, error) {
    scheme := runtime.newscheme()
    if err := kubectrlmgrschemev1alpha1.addtoscheme(scheme); err != nil {
        return kubectrlmgrconfig.kubecontrollermanagerconfiguration{}, err
    }
    if err := kubectrlmgrconfig.addtoscheme(scheme); err != nil {
        return kubectrlmgrconfig.kubecontrollermanagerconfiguration{}, err
    }

    versioned := kubectrlmgrconfigv1alpha1.kubecontrollermanagerconfiguration{}
    //加载默认参数
    scheme.default(&versioned)

    internal := kubectrlmgrconfig.kubecontrollermanagerconfiguration{}
    if err := scheme.convert(&versioned, &internal, nil); err != nil {
        return internal, err
    }
    internal.generic.port = insecureport
    return internal, nil
}
// 根据object,获取提供的默认参数
func (s *scheme) default(src object) {
    if fn, ok := s.defaulterfuncs[reflect.typeof(src)]; ok {
        fn(src)
    }
}

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

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

func setdefaults_garbagecollectorcontrollerconfiguration(obj *kubectrlmgrconfigv1alpha1.garbagecollectorcontrollerconfiguration) {
    if obj.enablegarbagecollector == nil {
        obj.enablegarbagecollector = utilpointer.boolptr(true)
    }
    if obj.concurrentgcsyncs == 0 {
        obj.concurrentgcsyncs = 20
    }
}

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

func startgarbagecollectorcontroller(ctx controllercontext) (http.handler, bool, error) {
    //k8s 1.13.2中默认为true,可在kube-apiserver和kube-controller-manager的启动参数中加--enable-garbage-conllector=false设置
    //需保证这两个组件中参数值一致
    if !ctx.componentconfig.garbagecollectorcontroller.enablegarbagecollector {
        return nil, false, nil
    }

    //k8s各种原生资源对象客户端集合(默认启动参数中用simplecontrollerclientbuilder构建)
    gcclientset := ctx.clientbuilder.clientordie("generic-garbage-collector")
    discoveryclient := cacheddiscovery.newmemcacheclient(gcclientset.discovery())

    //生成rest config
    config := ctx.clientbuilder.configordie("generic-garbage-collector")
    dynamicclient, err := dynamic.newforconfig(config)
    if err != nil {
        return nil, true, err
    }

    // get an initial set of deletable resources to prime the garbage collector.
    //获取一组初始可删除资源以填充垃圾收集器。
    deletableresources := garbagecollector.getdeletableresources(discoveryclient)
    ignoredresources := make(map[schema.groupresource]struct{})

    //忽略gc的资源类型
    for _, r := range ctx.componentconfig.garbagecollectorcontroller.gcignoredresources {
        ignoredresources[schema.groupresource{group: r.group, resource: r.resource}] = struct{}{}
    }
    garbagecollector, err := garbagecollector.newgarbagecollector(
        dynamicclient,
        ctx.restmapper,
        deletableresources,
        ignoredresources,
        ctx.informerfactory,
        ctx.informersstarted,
    )
    if err != nil {
        return nil, true, fmt.errorf("failed to start the generic garbage collector: %v", err)
    }

    // start the garbage collector.
    //启动参数中默认是20个协程
    workers := int(ctx.componentconfig.garbagecollectorcontroller.concurrentgcsyncs)
    //启动monitors和deleteworkers、orphanworkers
    go garbagecollector.run(workers, ctx.stop)

    // periodically refresh the restmapper with new discovery information and sync
    // the garbage collector.
    //使用新的发现信息定期刷新restmapper并同步垃圾收集器。
    go garbagecollector.sync(gcclientset.discovery(), 30*time.second, ctx.stop)

    //gc提供debug dot grap依赖关系图接口
    return garbagecollector.newdebughandler(garbagecollector), true, nil
}

该函数主要作用有:
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流程图接口:

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

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

// curl http://127.0.0.1:10252/debug/controllers/garbagecollector/graph?uid=11211212edsaddkqedmk12
func (h *debughttphandler) servehttp(w http.responsewriter, req *http.request) {
    if req.url.path != "/graph" {
        http.error(w, "", http.statusnotfound)
        return
    }

    var graph graph.directed
    if uidstrings := req.url.query()["uid"]; len(uidstrings) > 0 {
        uids := []types.uid{}
        for _, uidstring := range uidstrings {
            uids = append(uids, types.uid(uidstring))
        }
        graph = h.controller.dependencygraphbuilder.uidtonode.togonumgraphforobj(uids...)

    } else {
        graph = h.controller.dependencygraphbuilder.uidtonode.togonumgraph()
    }

    //生成dot流程图数据,用graphviz工具中的dot.exe工具转换为svg图(用google浏览器打开)或者png图
    //api参考:https://godoc.org/gonum.org/v1/gonum/graph
    //graphviz下载地址:https://graphviz.gitlab.io/_pages/download/download_windows.html
    //dot.exe test.dot -t svg -o test.svg
    data, err := dot.marshal(graph, "full", "", "  ", false)
    if err != nil {
        http.error(w, err.error(), http.statusinternalservererror)
        return
    }
    w.write(data)
    w.writeheader(http.statusok)
}

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

// garbagecollector运行反射器来监视托管api对象的更改,将结果汇总到单线程dependencygraphbuilder,
// 构建一个缓存对象之间依赖关系的图形。由图变化触发,dependencygraphbuilder将可能被垃圾收集的对象
// 排队到`attempttodelete`队列,并将其依赖项需要孤立的对象排队到`attempttoorphan`队列。
// garbagecollector具有使用这两个队列的工作人员,向api服务器发送请求以相应地删除更新对象。
// 请注意,让dependencygraphbuilder通知垃圾收集器确保垃圾收集器使用至少与发送通知一样最新的图形进行操作。
type garbagecollector struct {
    // resettablerestmapper是一个restmapper,它能够在discovery资源类型时重置自己
    restmapper    resettablerestmapper
    // dynamicclient提供操作集群内所有资源对象的接口方法,包括k8s内置、crd生成的自定义资源
    dynamicclient dynamic.interface
    //垃圾收集器尝试在时间成熟时删除attempttodelete队列中的item
    attempttodelete workqueue.ratelimitinginterface
    //垃圾收集器尝试孤立attempttoorphan队列中item的依赖项,然后删除item
    attempttoorphan        workqueue.ratelimitinginterface
    dependencygraphbuilder *graphbuilder
    // 有owner的资源对象,才会给absentownercache填充不存在的owner信息
    absentownercache *uidcache
    sharedinformers  informers.sharedinformerfactory

    workerlock sync.rwmutex
}
// graphbuilder:基于informers提供的事件,graphbuilder更新
// uidtonode,一个缓存我们所知的依赖关系的图,并将
// 项放入attempttodelete和attempttoorphan队列
type graphbuilder struct {
    restmapper meta.restmapper

    //每个监视器列表/监视资源,结果汇集到dependencygraphbuilder
    monitors    monitors
    monitorlock sync.rwmutex
    // informersstarted is closed after after all of the controllers have been initialized and are running.
    // after that it is safe to start them here, before that it is not.
    // informersstarted在所有控制器初始化并运行后关闭。之后在这里启动它们是安全的,在此之前它不是。
    informersstarted <-chan struct{}

    // stopch drives shutdown. when a receive from it unblocks, monitors will shut down.
    // this channel is also protected by monitorlock.
    // stopch驱动器关闭当来自它的接收解除阻塞时,监视器将关闭。 此channel也受monitorlock保护。
    stopch <-chan struct{}

    // running tracks whether run() has been called.
    // it is protected by monitorlock.
    //运行轨道是否已调用run()它受monitorlock保护。
    running bool

    dynamicclient dynamic.interface
    // monitors are the producer of the graphchanges queue, graphbuilder alters
    // the in-memory graph according to the changes.
    // monitor是graphchanges队列的生成者,graphbuilder根据更改改变了内存中的图形。
    graphchanges workqueue.ratelimitinginterface

    // uidtonode doesn't require a lock to protect, because only the
    // single-threaded graphbuilder.processgraphchanges() reads/writes it.
    //uidtonode不需要锁保护,因为只有单线程graphbuilder.processgraphchanges()读写它。
    uidtonode *concurrentuidtonode

    // graphbuilder is the producer of attempttodelete and attempttoorphan, gc is the consumer.
    // graphbuilder是attempttodelete和attempttoorphan的生产者,gc是消费者。
    attempttodelete workqueue.ratelimitinginterface
    attempttoorphan workqueue.ratelimitinginterface

    // graphbuilder and gc share the absentownercache. objects that are known to
    // be non-existent are added to the cached.
    // graphbuilder和gc共享absentownercache。已知不存在的对象将添加到缓存中。
    absentownercache *uidcache

    //所有k8s资源对象集的informer
    sharedinformers  informers.sharedinformerfactory

    //监视器忽略的资源对象集
    ignoredresources map[schema.groupresource]struct{}
}

创建newgarbagecollector结构体:

func newgarbagecollector(
    dynamicclient dynamic.interface,
    mapper resettablerestmapper,
    deletableresources map[schema.groupversionresource]struct{},
    ignoredresources map[schema.groupresource]struct{},
    sharedinformers informers.sharedinformerfactory,
    informersstarted <-chan struct{},
) (*garbagecollector, error) {
    attempttodelete := workqueue.newnamedratelimitingqueue(workqueue.defaultcontrollerratelimiter(), "garbage_collector_attempt_to_delete")
    attempttoorphan := workqueue.newnamedratelimitingqueue(workqueue.defaultcontrollerratelimiter(), "garbage_collector_attempt_to_orphan")
    absentownercache := newuidcache(500)
    gc := &garbagecollector{
        dynamicclient:    dynamicclient,
        restmapper:       mapper,
        attempttodelete:  attempttodelete,
        attempttoorphan:  attempttoorphan,
        absentownercache: absentownercache,
    }
    gb := &graphbuilder{
        dynamicclient:    dynamicclient,
        informersstarted: informersstarted,
        restmapper:       mapper,
        graphchanges:     workqueue.newnamedratelimitingqueue(workqueue.defaultcontrollerratelimiter(), "garbage_collector_graph_changes"),
        uidtonode: &concurrentuidtonode{
            uidtonode: make(map[types.uid]*node),
        },
        attempttodelete:  attempttodelete,
        attempttoorphan:  attempttoorphan,
        absentownercache: absentownercache,
        sharedinformers:  sharedinformers,
        ignoredresources: ignoredresources,
    }
    //初始化各个资源对象的monitors,启动各资源对象的监听器,变化时触发回调,将其加入graphchanges 队列
    if err := gb.syncmonitors(deletableresources); err != nil {
        utilruntime.handleerror(fmt.errorf("failed to sync all monitors: %v", err))
    }
    gc.dependencygraphbuilder = gb

    return gc, nil
}

主要功能:
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)

func (gb *graphbuilder) controllerfor(resource schema.groupversionresource, kind schema.groupversionkind) (cache.controller, cache.store, error) {
    handlers := cache.resourceeventhandlerfuncs{
        // add the event to the dependencygraphbuilder's graphchanges.
        // 将事件添加到dependencygraphbuilder的graphchanges中。
        addfunc: func(obj interface{}) {
            event := &event{
                eventtype: addevent,
                obj:       obj,
                gvk:       kind,
            }
            gb.graphchanges.add(event)
        },
        updatefunc: func(oldobj, newobj interface{}) {
            // todo: check if there are differences in the ownerrefs,
            // finalizers, and deletiontimestamp; if not, ignore the update.
            //todo:检查ownerrefs, finalizers和deletiontimestamp是否存在差异;如果没有,请忽略更新。
            event := &event{
                eventtype: updateevent,
                obj:       newobj,
                oldobj:    oldobj,
                gvk:       kind,
            }
            gb.graphchanges.add(event)
        },
        deletefunc: func(obj interface{}) {
            // delta fifo may wrap the object in a cache.deletedfinalstateunknown, unwrap it
            // delta fifo可以将对象包装在cache.deletedfinalstateunknown中,解包它
            if deletedfinalstateunknown, ok := obj.(cache.deletedfinalstateunknown); ok {
                obj = deletedfinalstateunknown.obj
            }
            event := &event{
                eventtype: deleteevent,
                obj:       obj,
                gvk:       kind,
            }
            gb.graphchanges.add(event)
        },
    }
    shared, err := gb.sharedinformers.forresource(resource)
    if err == nil {
        klog.v(4).infof("using a shared informer for resource %q, kind %q", resource.string(), kind.string())
        // need to clone because it's from a shared cache
        shared.informer().addeventhandlerwithresyncperiod(handlers, resourceresynctime)
        return shared.informer().getcontroller(), shared.informer().getstore(), nil
    } else {
        //获取资源对象时出错会到这里,比如非k8s内置rediscluster、clusterbases、clusters、esclusters、volumeproviders、stsmasters、appapps、mysqlclusters、brokerclusters、clustertemplates;
        //内置的networkpolicies、apiservices、customresourcedefinitions
        klog.v(4).infof("unable to use a shared informer for resource %q, kind %q: %v", resource.string(), kind.string(), err)
    }

    // todo: consider store in one storage.
    // todo: 考虑存储在一个存储中。
    klog.v(5).infof("create storage for resource %s", resource)
    //上面失败的资源对象的store和controller
    store, monitor := cache.newinformer(
        listwatcher(gb.dynamicclient, resource),
        nil,
        resourceresynctime,
        // don't need to clone because it's not from shared cache
        //不需要克隆,因为它不是来自共享缓存
        handlers,
    )
    return monitor, store, nil
}

该方法主要功能是:
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)方法:

func (gc *garbagecollector) run(workers int, stopch <-chan struct{}) {
    defer utilruntime.handlecrash()
    defer gc.attempttodelete.shutdown()
    defer gc.attempttoorphan.shutdown()
    defer gc.dependencygraphbuilder.graphchanges.shutdown()

    klog.infof("starting garbage collector controller")
    defer klog.infof("shutting down garbage collector controller")

    //协程运行生产者monitors
    go gc.dependencygraphbuilder.run(stopch)

    //等待dependencygraphbuilder缓存开始同步
    if !controller.waitforcachesync("garbage collector", stopch, gc.dependencygraphbuilder.issynced) {
        return
    }

    //垃圾收集器:所有资源监视器都已同步。继续收集垃圾
    klog.infof("garbage collector: all resource monitors have synced. proceeding to collect garbage")

    // gc workers
    //协程运行消费者deleteworkers和orphanworkers
    for i := 0; i < workers; i++ {
        //默认参数为20个并发协程尝试delete worker
        go wait.until(gc.runattempttodeleteworker, 1*time.second, stopch)
        //默认参数为20个并发协程尝试orphan worker
        go wait.until(gc.runattempttoorphanworker, 1*time.second, stopch)
    }

    <-stopch
}

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英文版:

依赖图标生成库gonum api文档:

graphviz下载:
https://graphviz.gitlab.io/_pages/download/download_windows.html



本公众号免费提供csdn下载服务,海量it学习资源,如果你准备入it坑,励志成为优秀的程序猿,那么这些资源很适合你,包括但不限于java、go、python、springcloud、elk、嵌入式 、大数据、面试资料、前端 等资源。同时我们组建了一个技术交流群,里面有很多大佬,会不定时分享技术文章,如果你想来一起学习提高,可以公众号后台回复【2】,免费邀请加技术交流群互相学习提高,会不定期分享编程it相关资源。


扫码关注,精彩内容第一时间推给你

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