如何避免container频繁地restart?
admin
2023-02-03 17:42:56
0

如何避免container频繁地restart?相信大部分人都还没学会这个技能,为了让大家学会,给大家总结了以下内容,话不多说,一起往下看吧。

分析:

  1. 在 Pod 中 restart container 的时候(具体时机是,周期性执行 SyncPod() 的时候),Pod 会通过自身的 Status 结构找到当前这个 container(因为 Pod 中可能有多个 container)上一次退出的时间,记为 ts
  2. 如果是第一次 restart,那么直接重启 container,并且在 Kubelet 的 backOff.perItemBackoff (一个 map 结构,key 是根据 container 和所在 pod 对象计算出来的 id)中记录下次 backoff 的时间(初始值为 10s,然后按照指数增长,最大 5min)
  3. 如果不是第一次 restart,即 Kubelet 的 backOff.perItemBackoff 中已经有这个 container 的 backOff 记录,计为 backoff,那么
    • 如果 now() - ts < backoff,表明等待的时间还不够,抛出 CrashLoopBackOff Event(然后等到下一个 SyncPod 的周期到的时候,重新比较这个值)
    • 否则,说明已经等待 backoff 时间了,可以 restart 了,此时执行 backOff.Next(),将该容器对应的 backoff 翻倍,然后执行 restart 操作
  4. 在步骤 3 中计算 backoff 的过程中,还会去检查当前时间距离上一次 container 退出时的间隔,如果大于 2 * MaxContainerBackOff = 10 minutes,那么会将这个 container 对应的 backoff 重置为初始值 10s

源码细节

  1. kubernetes/pkg/kubelet/kubelet.go
    通过源码发现,kubernetes/pkg/kubelet/kubelet.go 文件中有两个常量:

    MaxContainerBackOff = 300 * time.Second
    backOffPeriod = time.Second * 10

使用这两个变量构造了一个 BackOff 对象,这个是 kubelet 的属性,对该 node 上所有 pod 都适用

    klet.backOff = flowcontrol.NewBackOff(backOffPeriod, MaxContainerBackOff)

BackOff 结构如下

type Backoff struct {
        sync.Mutex
        Clock           clock.Clock
        defaultDuration time.Duration
        maxDuration     time.Duration
        perItemBackoff  map[string]*backoffEntry
}

然后在 SyncPod 方法中使用这个对象

// Call the container runtime's SyncPod callback
result := kl.containerRuntime.SyncPod(pod, apiPodStatus, podStatus, pullSecrets, kl.backOff)
  1. kubernetes/pkg/kubelet/kuberuntime/kuberuntime_manager.go

SyncPod 具体做的事有:

// SyncPod syncs the running pod into the desired pod by executing following steps:
//
//  1. Compute sandbox and container changes.
//  2. Kill pod sandbox if necessary.
//  3. Kill any containers that should not be running.
//  4. Create sandbox if necessary.
//  5. Create init containers.
//  6. Create normal containers.
func (m *kubeGenericRuntimeManager) SyncPod(pod *v1.Pod, _ v1.PodStatus, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) {

同样在这个文件中,有一个关键的函数

// If a container is still in backoff, the function will return a brief backoff error and
// a detailed error message.
    func (m *kubeGenericRuntimeManager) doBackOff(pod *v1.Pod, container *v1.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, string, error) {
        var cStatus *kubecontainer.ContainerStatus
        for _, c := range podStatus.ContainerStatuses {
                if c.Name == container.Name && c.State == kubecontainer.ContainerStateExited {
                        cStatus = c
                        break
                }
        }

        if cStatus == nil {
                return false, "", nil
        }

        glog.Infof("checking backoff for container %q in pod %q", container.Name, format.Pod(pod))
        // Use the finished time of the latest exited container as the start point to calculate whether to do back-off.
        ts := cStatus.FinishedAt
        // backOff requires a unique key to identify the container.
        key := getStableKey(pod, container)
        if backOff.IsInBackOffSince(key, ts) {
                if ref, err := kubecontainer.GenerateContainerRef(pod, container); err == nil {
                        m.recorder.Eventf(ref, v1.EventTypeWarning, events.BackOffStartContainer, "Back-off restarting failed container")
                }
                err := fmt.Errorf("Back-off %s restarting failed container=%s pod=%s", backOff.Get(key), container.Name, format.Pod(pod))
                glog.Infof("%s", err.Error())
                return true, err.Error(), kubecontainer.ErrCrashLoopBackOff
        }

        backOff.Next(key, ts)
        return false, "", nil
}

其中 backOff.Next 函数定义如下

// move backoff to the next mark, capping at maxDuration
func (p *Backoff) Next(id string, eventTime time.Time) {
        p.Lock()
        defer p.Unlock()
        entry, ok := p.perItemBackoff[id]
        if !ok || hasExpired(eventTime, entry.lastUpdate, p.maxDuration) {
                entry = p.initEntryUnsafe(id)
        } else {
                delay := entry.backoff * 2 // exponential
                entry.backoff = time.Duration(integer.Int64Min(int64(delay), int64(p.maxDuration)))
        }
        entry.lastUpdate = p.Clock.Now()
}

看完上述内容,你们掌握避免container频繁地restart的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

相关内容

热门资讯

首次突破 屡创新高!一组数字解... 2026年上半年我国GDP同比增长4.7%经济韧性持续彰显在已经出炉的经济数据中更值得关注的还有“含...
男主播卖惨,66岁患癌老太花光... 今年3月,沈阳66岁的张阿姨在家养病期间刷视频时,被一名IP属地为湖北的男主播吸引。该主播主打演唱经...
松下智能马桶盖不喷水怎么回事 松下智能马桶盖不喷水怎么回事1、有时候新买的马桶在安装的时候工人有时候会不会告诉你需要开进水阀的,智...
松下智能马桶盖不喷水 1、有时候新买的马桶在安装的时候工人有时候会不会告诉你需要开进水阀的,智能马桶都是带有进水阀的,如果...
智能马桶盖不喷水故障维修方法 如果是出水口不喷水,先检查下是不是里面没水,或者水管出问题了,水管故障问题需找专业的维修师傅维修;若...
马桶水箱盖子碎了能换么 不能,建议更换整个水箱。方法:先检查排污管及产品内通道是否有异物;确定固定蹲便的安装位置、高度以及将...
洗衣机e1是什么故障 洗衣机e1是什么故障出现这个代码时,是表示洗衣机的进水时间超长了,洗衣机的进水系统发生了问题,比如,...
阿联酋航空发文致歉 7月23日,阿联酋航空发布致歉信:原计划于7月22日从迪拜飞往上海的阿联酋航空EK302航班,因恶劣...
给“南海仲裁案”递刀子的美国人... 执笔/李小飞刀7月12日晚,菲律宾内格罗斯东方省锡布兰镇的一处公寓内,突然响起一阵枪声,美国海洋生物...
特朗普称沙特加入《亚伯拉罕协议... △美国总统特朗普(资料图)当地时间7月23日,美国总统特朗普在社交媒体“真实社交”上发文表示,美国能...