kubernetest中wait.Until()方法的源码解读

2024-08-24 02:12

本文主要是介绍kubernetest中wait.Until()方法的源码解读,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

概述

摘要:本文从源码层面解读了kubernetes源码中常用的wait.Until()方法的源码实现,并且本文也举例说明了wait.Until()方法的在kubernete源码中的典型使用场景。

wait.Until()源码解读

在Kubernetes源码中, 我们经常会读到wait.Until()函数,它的作用是在一个goroutine中执行一个函数,直到接收到停止信号。这个函数通常用于执行一些需要定期执行的任务。wait.Until源码位于k8s.io/apimachinery项目下,该项目是一个关于Kubernetes API资源的工具集。

Until()

Until()方法作用是每间隔 period 时间而周期性的执行f()函数,直到收到stopCh信号

f 是一个无参数的函数,表示要执行的任务。
period 是一个 time.Duration 类型的值,表示执行任务的周期。
stopCh 是一个 <-chan struct{} 类型的通道,用于接收停止信号

// Until loops until stop channel is closed, running f every period.
//
// Until is syntactic sugar on top of JitterUntil with zero jitter factor and
// with sliding = true (which means the timer for period starts after the f
// completes).
func Until(f func(), period time.Duration, stopCh <-chan struct{}) {// 内部调用了JitterUntil函数,并且将参数jitterfactor设置为0,sliding为trueJitterUntil(f, period, 0.0, true, stopCh)
}

JitterUntil()

Utill调用JitterUntil()并传入参数jitterFactor=0,sliding=true

jitterFactor=0的作用是,每隔 period 时间段,就执行一个f(). 假如jitterFactor不等于0,间隔时间就是“period加一个随机时间”。

sliding=true的作用是在f()执行后,再等待一个 period 定时周期。假如sliding=false,先等一个 period 定时周期,再执行f()

源码解读如下,请留意注释


// JitterUntil loops until stop channel is closed, running f every period.
//
// If jitterFactor is positive, the period is jittered before every run of f.
// If jitterFactor is not positive, the period is unchanged and not jittered.
//
// If sliding is true, the period is computed after f runs. If it is false then
// period includes the runtime for f.
//
// Close stopCh to stop. f may not be invoked if stop channel is already
// closed. Pass NeverStop to if you don't want it stop.
func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) {// 定义一个定时器var t *time.Timer// 用于控制resetOrReuseTimer()函数,让resetOrReuseTimer()每次都返回以 jitteredPeriod 为周期的定时器t.Reset(jitteredPeriod)var sawTimeout boolfor {// 如果收到stop信号,就退出JitterUntil函数select {case <-stopCh:returndefault:}// period和jitteredPeriod,一起控制“抖动”时间,jitteredPeriod := period// 抖动的时间jitteredPeriod的范围是从period 到 period*(1+maxFactor)之间的随机时间;// 如果jitterFactor<=0时,就jitteredPeriod就不变。也就是时间不抖动(或者说波动)if jitterFactor > 0.0 {jitteredPeriod = Jitter(period, jitterFactor)}// 如果sliding为true,则跳过这步。if !sliding {// 用jitteredPeriod为时间周期,重置定时器t = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)}func() {defer runtime.HandleCrash()f()}()// 如果sliding为true,则这里会执行if sliding {// 用jitteredPeriod为时间周期,重置定时器t = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)}// NOTE: b/c there is no priority selection in golang// it is possible for this to race, meaning we could// trigger t.C and stopCh, and t.C select falls through.// In order to mitigate we re-check stopCh at the beginning// of every loop to prevent extra executions of f().select {case <-stopCh:returncase <-t.C:sawTimeout = true}}
}

Jitter()作用是返回一个波动时间,波动时间的范围是x附近的一个值。值的范围是:min=x, max=x*(1+maxFactor)

如果maxFactor小于0,wait的取值范围是: x<wait<2x 备注:(x的单位是duration)

如果maxFactor大于0,wait的取值范围是: x<x*(1+ (0~1)*maxFactor)<x(1+maxFactor)

源码解读如下,请留意注释

// Jitter returns a time.Duration between duration and duration + maxFactor *
// duration.
//
// This allows clients to avoid converging on periodic behavior. If maxFactor
// is 0.0, a suggested default value will be chosen.
func Jitter(duration time.Duration, maxFactor float64) time.Duration {if maxFactor <= 0.0 {maxFactor = 1.0}// wait = duration加一个随机时间// rand.Float64()是返回(0,1)之间的小数,// maxFactor = 1.0时,wait = x + (0~1) * maxFactor * x = x*(1+ (0~1)*1),故wait取值范围 (x<wait<2x)// wait = x + (0~1) * maxFactor * x = x*(1+ (0~1)*maxFactor)wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))return wait
}

resetOrReuseTimer用jitteredPeriod为时间周期,重置定时器.注意改函数不是线程安全的

源码解读如下,请留意注释

// resetOrReuseTimer avoids allocating a new timer if one is already in use.
// Not safe for multiple threads.
// 改函数不是线程安全的
func resetOrReuseTimer(t *time.Timer, d time.Duration, sawTimeout bool) *time.Timer {// 如果t==nil,就用d为时间周期,初始化一个定时器if t == nil {return time.NewTimer(d)}// sawTimeout为true会跳过 t.Cif !t.Stop() && !sawTimeout {<-t.C}// d为时间周期,重置一个定时器t.Reset(d)return t
}

测试

编写一个简单程序,测试wait.Until()方法的使用

package mainimport ("fmt""k8s.io/apimachinery/pkg/util/wait""time"
)func main() {// 创建一个停止通道stopCh := make(chan struct{})var num = 0// 每秒执行一次任务,直到stopCh被关闭go wait.Until(func() {fmt.Printf("do one times job,num = %v\n", num)num++}, 1*time.Second, stopCh)// 等待10秒,确保定时任务执行完毕time.Sleep(10 * time.Second)// 关闭停止通道,停止定时任务close(stopCh)
}
---------------执行与输出如下-----------------
dev ✗ $ go run main.go                                                                                                                                                
do one times job,num = 0
do one times job,num = 1
do one times job,num = 2
do one times job,num = 3
do one times job,num = 4
do one times job,num = 5
do one times job,num = 6
do one times job,num = 7
do one times job,num = 8
do one times job,num = 9

在这个例子中,Until 函数会在一个新的goroutine中执行一个函数,这个函数会打印当前时间。这个函数会每秒执行一次,直到接收到 stopCh 通道的信号。
注意,Until 函数不会返回任何值,它只是在一个新的goroutine中执行一个函数,直到接收到停止信号。

使用场景

在kubernetes源码中,wait.Until()经常用于启动需要后台循环执行的任务。比如informer中的reflector的启动,kube-scheduler中的schedulerCache的启动。

示例1 reflector的启动

reflector是informer中的重要组件,用于实现对kube-apiserver的资源变化事件的监听与获取。关于reflector的详解,请见我的另一篇博文 informer中reflector机制的实现分析与源码解读

wait.Until在Informer中的使用场景如下,用于reflector的启动

// Run starts a watch and handles watch events. Will restart the watch if it is closed.
// Run will exit when stopCh is closed.
func (r *Reflector) Run(stopCh <-chan struct{}) {// 使用wait.Until方法,周期性的执行r.ListAndWatch()函数wait.Until(func() { 				// 启动List/Watch机制if err := r.ListAndWatch(stopCh); err != nil {	utilruntime.HandleError(err)}}, r.period, stopCh)
}

示例2 schedulerCache的启动

wait.Until在 kube-sheduler 中的使用场景如下,用于newSchedulerCache的启动

// New returns a Cache implementation.
// It automatically starts a go routine that manages expiration of assumed pods.
// "ttl" is how long the assumed pod will get expired.
// "stop" is the channel that would close the background goroutine.
func New(ttl time.Duration, stop <-chan struct{}) Cache {cache := newSchedulerCache(ttl, cleanAssumedPeriod, stop)// 启动cache的运行cache.run()return cache
}func (cache *schedulerCache) run() {// 利用go wait.Until()周期的运行cache.cleanupExpiredAssumedPods函数go wait.Until(cache.cleanupExpiredAssumedPods, cache.period, cache.stop)
}

结论

wait.Until广泛的适用于kubernetes源码,通过对其源码的解读,我们了解到了其如何实现与使用场景。我们可以在平时日常开发中,如果有需要周期性的执行某项任务,除了可以go + for + select来自己实现外,不妨多多尝试wait.Until方法。

参考资料

Kubernete-v1.12源码

这篇关于kubernetest中wait.Until()方法的源码解读的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1101153

相关文章

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法

《JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法》:本文主要介绍JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法,每种方法结合实例代码给大家介绍的非常... 目录引言:为什么"相等"判断如此重要?方法1:使用some()+includes()(适合小数组)方法2

504 Gateway Timeout网关超时的根源及完美解决方法

《504GatewayTimeout网关超时的根源及完美解决方法》在日常开发和运维过程中,504GatewayTimeout错误是常见的网络问题之一,尤其是在使用反向代理(如Nginx)或... 目录引言为什么会出现 504 错误?1. 探索 504 Gateway Timeout 错误的根源 1.1 后端

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据

python 线程池顺序执行的方法实现

《python线程池顺序执行的方法实现》在Python中,线程池默认是并发执行任务的,但若需要实现任务的顺序执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋... 目录方案一:强制单线程(伪顺序执行)方案二:按提交顺序获取结果方案三:任务间依赖控制方案四:队列顺序消

SpringBoot通过main方法启动web项目实践

《SpringBoot通过main方法启动web项目实践》SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置Spring... 目录1. 启动入口:SpringApplication.run()2. SpringApplicat

使用Java读取本地文件并转换为MultipartFile对象的方法

《使用Java读取本地文件并转换为MultipartFile对象的方法》在许多JavaWeb应用中,我们经常会遇到将本地文件上传至服务器或其他系统的需求,在这种场景下,MultipartFile对象非... 目录1. 基本需求2. 自定义 MultipartFile 类3. 实现代码4. 代码解析5. 自定

Python文本相似度计算的方法大全

《Python文本相似度计算的方法大全》文本相似度是指两个文本在内容、结构或语义上的相近程度,通常用0到1之间的数值表示,0表示完全不同,1表示完全相同,本文将深入解析多种文本相似度计算方法,帮助您选... 目录前言什么是文本相似度?1. Levenshtein 距离(编辑距离)核心公式实现示例2. Jac