一篇带你kubebuilder 实战: status & event

开发 项目管理
想知道一个节点池有多少的节点,现在的资源占比是多少,这样可以清晰的知道我们现在的水位线是多少,除此之外也想知道节点池数量发生变化的相关事件信息,什么时候节点池增加或者是减少了一个节点等。

[[399605]]

在上篇文章当中我们实现了 NodePool Operator 基本的 CURD 功能,跑了一小段时间之后除了 CURD 之外我们有了更高的需求,想知道一个节点池有多少的节点,现在的资源占比是多少,这样可以清晰的知道我们现在的水位线是多少,除此之外也想知道节点池数量发生变化的相关事件信息,什么时候节点池增加或者是减少了一个节点等。

需求

我们先整理一下需求

能够通过 kubectl get Nodepool了解当前的节点池的以下信息

  • 节点池的状态,是否异常
  • 节点池现在包含多少个节点
  • 节点池的资源情况现在有多少 CPU、Memory

能够通过事件信息得知 controller 的错误情况以及节点池内节点的变化情况

实现

Status

先修改一下 status 对象,注意要确保下面的 //+kubebuilder:subresource:status注释存在,这个表示开启 status 子资源,status 对象修改好之后需要重新执行一遍 make install

  1. // NodePoolStatus defines the observed state of NodePool 
  2. type NodePoolStatus struct { 
  3.  // status=200 说明正常,其他情况为异常情况 
  4.  Status int `json:"status"
  5.  
  6.  // 节点的数量 
  7.  NodeCount int `json:"nodeCount"
  8.  
  9.  // 允许被调度的容量 
  10.  Allocatable corev1.ResourceList `json:"allocatable,omitempty" protobuf:"bytes,2,rep,name=allocatable,casttype=ResourceList,castkey=ResourceName"
  11.  
  12. //+kubebuilder:object:root=true 
  13. //+kubebuilder:resource:scope=Cluster 
  14. //+kubebuilder:subresource:status 
  15.  
  16. // NodePool is the Schema for the nodepools API 
  17. type NodePool struct { 

然后修改 Reconcile 中的逻辑

  1. func (r *NodePoolReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { 
  2.  // ...... 
  3.  
  4.  if len(nodes.Items) > 0 { 
  5.   r.Log.Info("find nodes, will merge data""nodes", len(nodes.Items)) 
  6. +  pool.Status.Allocatable = corev1.ResourceList{} 
  7. +  pool.Status.NodeCount = len(nodes.Items) 
  8.   for _, n := range nodes.Items { 
  9.    n := n 
  10.  
  11.    // 更新节点的标签和污点信息 
  12.    err := r.Update(ctx, pool.Spec.ApplyNode(n)) 
  13.    if err != nil { 
  14.     return ctrl.Result{}, err 
  15.    } 
  16.  
  17. +   for name, quantity := range n.Status.Allocatable { 
  18. +    q, ok := pool.Status.Allocatable[name
  19. +    if ok { 
  20. +     q.Add(quantity) 
  21. +     pool.Status.Allocatable[name] = q 
  22. +     continue 
  23. +    } 
  24. +    pool.Status.Allocatable[name] = quantity 
  25. +   } 
  26.   } 
  27.  } 
  28.  
  29.   // ...... 
  30.    
  31. + pool.Status.Status = 200 
  32. + err = r.Status().Update(ctx, pool) 
  33.  return ctrl.Result{}, err 

修改好了之后我们提交一个 NodePool 测试一下

  1. apiVersion: nodes.lailin.xyz/v1 
  2. kind: NodePool 
  3. metadata: 
  4.   name: worker 
  5. spec: 
  6.   taints: 
  7.     - key: node-pool.lailin.xyz 
  8.       value: worker 
  9.       effect: NoSchedule 
  10.   labels: 
  11.     "node-pool.lailin.xyz/worker""10" 
  12.   handler: runc 

可以看到我们现在是有两个 worker 节点

  1. ▶ kubectl get no  
  2. NAME                 STATUS   ROLES                  AGE   VERSION 
  3. kind-control-plane   Ready    control-plane,master   29m   v1.20.2 
  4. kind-worker          Ready    worker                 28m   v1.20.2 
  5. kind-worker2         Ready    worker                 28m   v1.20.2 

 然后我们看看 NodePool,可以发现已经存在了预期的 status

  1. status: 
  2.   allocatable: 
  3.     cpu: "8" 
  4.     ephemeral-storage: 184026512Ki 
  5.     hugepages-1Gi: "0" 
  6.     hugepages-2Mi: "0" 
  7.     memory: 6129040Ki 
  8.     pods: "220" 
  9.   nodeCount: 2 
  10.   status: 200 

现在这样只能通过查看 yaml 详情才能看到,当 NodePool 稍微多一些的时候就不太方便,我们现在给NodePool 增加一些 kubectl 展示的列

  1. +//+kubebuilder:printcolumn:JSONPath=".status.status",name=Status,type=integer 
  2. +//+kubebuilder:printcolumn:JSONPath=".status.nodeCount",name=NodeCount,type=integer 
  3. //+kubebuilder:object:root=true 
  4. //+kubebuilder:resource:scope=Cluster 
  5. //+kubebuilder:subresource:status 

如上所示只需要添加好对应的注释,然后执行 make install即可

然后再执行 kubectl get NodePool 就可以看到对应的列了

  1. ▶ kubectl get NodePool  
  2. NAME     STATUS   NODECOUNT 
  3. worker   200      2 

Event

我们在 controller 当中添加 Recorder 用来记录事件,K8s 中事件有 Normal 和 Warning 两种类型

  1. // NodePoolReconciler reconciles a NodePool object 
  2. type NodePoolReconciler struct { 
  3.  client.Client 
  4.  Log      logr.Logger 
  5.  Scheme   *runtime.Scheme 
  6. + Recorder record.EventRecorder 
  7.  
  8. func (r *NodePoolReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { 
  9.   
  10. + // 添加测试事件 
  11. + r.Recorder.Event(pool, corev1.EventTypeNormal, "test""test"
  12.  
  13.  pool.Status.Status = 200 
  14.  err = r.Status().Update(ctx, pool) 
  15.  return ctrl.Result{}, err 

添加好之后还需要在 main.go 中加上 Recorder的初始化逻辑

  1. if err = (&controllers.NodePoolReconciler{ 
  2.   Client:   mgr.GetClient(), 
  3.   Log:      ctrl.Log.WithName("controllers").WithName("NodePool"), 
  4.   Scheme:   mgr.GetScheme(), 
  5. +  Recorder: mgr.GetEventRecorderFor("NodePool"), 
  6.  }).SetupWithManager(mgr); err != nil { 
  7.   setupLog.Error(err, "unable to create controller""controller""NodePool"
  8.   os.Exit(1) 
  9.  } 

加好之后我们运行一下,然后在 describe Nodepool 对象就能看到事件信息了

  1. Events: 
  2.   Type    Reason  Age   From      Message 
  3.   ----    ------  ----  ----      ------- 
  4.   Normal  test    4s    NodePool  test 

监听更多资源

之前我们所有的代码都是围绕着 NodePool 的变化来展开的,但是我们如果修改了 Node 的相关标签,将 Node 添加到一个 NodePool,Node 上对应的属性和 NodePool 的 status 信息也不会改变。如果我们想要实现上面的效果就需要监听更多的资源变化。

在 controller 当中我们可以看到一个 SetupWithManager方法,这个方法说明了我们需要监听哪些资源的变化

  1. // SetupWithManager sets up the controller with the Manager. 
  2. func (r *NodePoolReconciler) SetupWithManager(mgr ctrl.Manager) error { 
  3.  return ctrl.NewControllerManagedBy(mgr). 
  4.   For(&nodesv1.NodePool{}). 
  5.   Complete(r) 

其中 NewControllerManagedBy是一个建造者模式,返回的是一个 builder 对象,其包含了用于构建的 For、Owns、Watches、WithEventFilter等方法

这里我们就可以利用 ``Watches方法来监听 Node 的变化,我们这里使用handler.Funcs`自定义了一个入队器

监听 Node 对象的更新事件,如果存在和 NodePool 关联的 node 对象更新就把对应的 NodePool 入队

  1. // SetupWithManager sets up the controller with the Manager. 
  2. func (r *NodePoolReconciler) SetupWithManager(mgr ctrl.Manager) error { 
  3.  return ctrl.NewControllerManagedBy(mgr). 
  4.   For(&nodesv1.NodePool{}). 
  5.   Watches(&source.Kind{Type: &corev1.Node{}}, handler.Funcs{UpdateFunc: r.nodeUpdateHandler}). 
  6.   Complete(r) 
  7.  
  8. func (r *NodePoolReconciler) nodeUpdateHandler(e event.UpdateEvent, q workqueue.RateLimitingInterface) { 
  9.  ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second
  10.  defer cancel() 
  11.  
  12.  oldPool, err := r.getNodePoolByLabels(ctx, e.ObjectOld.GetLabels()) 
  13.  if err != nil { 
  14.   r.Log.Error(err, "get node pool err"
  15.  } 
  16.  if oldPool != nil { 
  17.   q.Add(reconcile.Request{ 
  18.    NamespacedName: types.NamespacedName{Name: oldPool.Name}, 
  19.   }) 
  20.  } 
  21.  
  22.  newPool, err := r.getNodePoolByLabels(ctx, e.ObjectOld.GetLabels()) 
  23.  if err != nil { 
  24.   r.Log.Error(err, "get node pool err"
  25.  } 
  26.  if newPool != nil { 
  27.   q.Add(reconcile.Request{ 
  28.    NamespacedName: types.NamespacedName{Name: newPool.Name}, 
  29.   }) 
  30.  } 
  31.  
  32. func (r *NodePoolReconciler) getNodePoolByLabels(ctx context.Context, labels map[string]string) (*nodesv1.NodePool, error) { 
  33.  pool := &nodesv1.NodePool{} 
  34.  for k := range labels { 
  35.   ss := strings.Split(k, "node-role.kubernetes.io/"
  36.   if len(ss) != 2 { 
  37.    continue 
  38.   } 
  39.   err := r.Client.Get(ctx, types.NamespacedName{Name: ss[1]}, pool) 
  40.   if err == nil { 
  41.    return pool, nil 
  42.   } 
  43.  
  44.   if client.IgnoreNotFound(err) != nil { 
  45.    return nil, err 
  46.   } 
  47.  } 
  48.  return nil, nil 

总结

今天我们完善了 status & event 和自定义对象 watch 下一篇我们看一下如何对我们的 Operator 进行测试

 

责任编辑:姜华 来源: mohuishou
相关推荐

2021-05-12 06:18:19

KubeBuilderOperatork8s

2021-05-17 05:51:31

KubeBuilderOperator测试

2021-05-18 05:40:27

kubebuilderwebhook进阶

2021-05-08 09:02:48

KubeBuilderOperatork8s

2023-04-20 08:00:00

ES搜索引擎MySQL

2021-05-20 06:57:16

RabbitMQ开源消息

2021-06-16 08:28:25

unary 方法函数技术

2022-03-10 08:31:51

REST接口规范设计Restful架构

2022-02-24 07:56:42

开发Viteesbuild

2023-05-12 08:19:12

Netty程序框架

2022-02-21 09:44:45

Git开源分布式

2021-07-28 10:02:54

建造者模式代码

2021-07-14 08:24:23

TCPIP 通信协议

2021-06-30 00:20:12

Hangfire.NET平台

2021-08-11 07:02:21

npm包管理器工具

2022-04-08 08:32:40

mobx状态管理库redux

2023-02-28 23:04:15

2021-11-24 08:51:32

Node.js监听函数

2021-08-02 06:34:55

Redis删除策略开源

2020-11-27 08:02:41

Promise
点赞
收藏

51CTO技术栈公众号