HAOJX

CRD开发中监控deployment的变化,并且显示在控制台

字数统计: 370阅读时长: 1 min
2021/11/25 Share

前提:

  1. 要在crd中的定义yaml文件上写上这个
1
2
3
4
5
6
7
status:
type: object
properties:
replicas:
type: integer
ready:
type: string

这个ready就是状态中要显示的

之后在设置自定义资源的时候 在type中也写上这个状态的字段 就是在status中(我加的字段是ready字段)

之后就代码的编写了

第一步 先要在控制器中去watch他的变化, 比如update的变化, 并写个函数

1
2
3
4
5
6
7
8
9
10
11
12
13
....
if err = builder.ControllerManagedBy(mgr).
For(&v1.DbConfig{}).
Watches(&source.Kind{Type: &appsv1.Deployment{}},
handler.Funcs{
DeleteFunc: dbConfigController.OnDelete,
UpdateFunc: dbConfigController.OnUpdate},).
Complete(controllers.NewDbConfigController());err!=nil{
mgr.GetLogger().Error(err,"unable to create manager")
os.Exit(1)
}

...

也就是这个updatefunc函数

他长这样

1
2
3
4
5
6
7
8
9
10
11
func (d *DbConfigController) OnUpdate(event event.UpdateEvent,limitingInterface workqueue.RateLimitingInterface)  {
for _, ref:= range event.ObjectNew.GetOwnerReferences(){
if ref.Kind=="DbConfig" && ref.APIVersion=="api.test.com/v1" {
limitingInterface.Add(
reconcile.Request{types.NamespacedName{
Name: ref.Name,
Namespace: event.ObjectNew.GetNamespace(),
}})
}
}
}

就是当有新的request的时候 就如队列

之后在reconcile函数中更新他

1
2
3
4
5
6
7
8
9
10
11
...
replicas:=d.deploy.Status.Replicas //这个是取现在状态的副本数量
d.config.Status.Ready=fmt.Sprintf("%d/%d",replicas,d.deploy.Spec.Replicas) //把这个期望状态和现在状态显示出来
d.config.Status.Replicas=replicas //

err=d.Client.Status().Update(ctx,d.config) //之后更新这个状态
if err != nil {
fmt.Println("status update error:",err)
return err
}
....

这个d.config.Status.Ready 是在前提中早就设置好的 是在显示控制台的时候 显示出来的字段

CATALOG