当前位置: 首页 > news >正文

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源码

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 《黑神话·悟空》是用什么编程语言开发的?
  • 豆包大模型升级:日均Tokens使用量破5000亿,字节跳动打造即刻体验的《Her》式AI
  • yield生成器生成表单字段,并进行验证,利用fetch方法和formData对象传递数据给后端,后端返回成功,返回数据
  • LambdaQueryWrapper 是 MyBatis-Plus超级利器
  • Telegram mini app 本地开发配置
  • 跟着GPT学习 Kubernetes ,简称 K8s -- Kind(三)
  • redis 过期监听:高效管理数据生命周期
  • 回归预测|基于北方苍鹰优化极端梯度提升树的数据回归预测Matlab程序NGO-XGBoost多特征输入单输出
  • 光伏电站设备设施巡视卡之转变二维码登记卡
  • 计算机毕业设计 毕业季旅游一站式定制服务平台 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试
  • 使用kubeadm快速部署一套K8S集群
  • 设置虚拟机使用主机以太网而不是WiF连接
  • 普元EOS-低开页面下拉选择控件加载列表数据
  • 修改wls2上的默认用户为root
  • mariadb centos 7 安装
  • [译]CSS 居中(Center)方法大合集
  • CentOS从零开始部署Nodejs项目
  • ES6之路之模块详解
  • iOS仿今日头条、壁纸应用、筛选分类、三方微博、颜色填充等源码
  • Lsb图片隐写
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • nfs客户端进程变D,延伸linux的lock
  • php中curl和soap方式请求服务超时问题
  • REST架构的思考
  • 初识 webpack
  • 第13期 DApp 榜单 :来,吃我这波安利
  • 精益 React 学习指南 (Lean React)- 1.5 React 与 DOM
  • 开源SQL-on-Hadoop系统一览
  • 三分钟教你同步 Visual Studio Code 设置
  • 一个6年java程序员的工作感悟,写给还在迷茫的你
  •  一套莫尔斯电报听写、翻译系统
  • 用 vue 组件自定义 v-model, 实现一个 Tab 组件。
  • 用Canvas画一棵二叉树
  • 【云吞铺子】性能抖动剖析(二)
  • ​Linux·i2c驱动架构​
  • ## 1.3.Git命令
  • #、%和$符号在OGNL表达式中经常出现
  • #AngularJS#$sce.trustAsResourceUrl
  • #includecmath
  • $(this) 和 this 关键字在 jQuery 中有何不同?
  • (160)时序收敛--->(10)时序收敛十
  • (4)事件处理——(6)给.ready()回调函数传递一个参数(Passing an argument to the .ready() callback)...
  • (day 12)JavaScript学习笔记(数组3)
  • (done) ROC曲线 和 AUC值 分别是什么?
  • (Redis使用系列) SpringBoot中Redis的RedisConfig 二
  • (Repost) Getting Genode with TrustZone on the i.MX
  • (博弈 sg入门)kiki's game -- hdu -- 2147
  • (附源码)ssm跨平台教学系统 毕业设计 280843
  • (附源码)计算机毕业设计SSM基于java的云顶博客系统
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation
  • (十三)Flask之特殊装饰器详解
  • (四)进入MySQL 【事务】
  • (四)库存超卖案例实战——优化redis分布式锁
  • (原創) 如何解决make kernel时『clock skew detected』的warning? (OS) (Linux)
  • .DFS.