const (
	LEASELOCKNAME      = "tes"
	LEASELOCKNAMESPACE = "kube-system"
)

func main () {
      	LeaseLockID = uuid.New().String()
		client.InitClientSet()

		run := func(ctx context.Context) {
			// 添加运行逻辑代码
			klog.Info("Controller loop...")
			select{}
		}

		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		ch := make(chan os.Signal, 1)
		signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
		go func() {
			<-ch
			klog.Info("Received termination, signaling shutdown")
			cancel()
		}()

		// 指定锁的资源对象,这里使用了Lease资源,还支持configmap,endpoint,或者multilock(即多种配合使用)
		lock := &resourcelock.LeaseLock{
			LeaseMeta: metav1.ObjectMeta{
				Name:      conf.LEASELOCKNAME,
				Namespace: conf.LEASELOCKNAMESPACE,
			},
			Client: client.K8sClientSet.CoordinationV1(),
			LockConfig: resourcelock.ResourceLockConfig{
				Identity: LeaseLockID,
			},
		}

		leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
			Lock:            lock,
			ReleaseOnCancel: true,
			LeaseDuration:   30 * time.Second, //租约时间
			RenewDeadline:   15 * time.Second, //更新租约的
			RetryPeriod:     5 * time.Second,  //非leader节点重试时间
			Callbacks: leaderelection.LeaderCallbacks{
				OnStartedLeading: func(ctx context.Context) {
					//变为leader执行的业务代码
					run(ctx)
				},
				OnStoppedLeading: func() {
					// 进程退出
					klog.Infof("leader lost: %s", LeaseLockID)
					os.Exit(0)
				},
				OnNewLeader: func(identity string) {
					//当产生新的leader后执行的方法
					if identity == LeaseLockID {
						klog.Infof("i am leader now: %s", identity)
						return
					}
					klog.Infof("new leader elected: %s, wait...", identity)
				},
			},
		})

}

参考:跳转中...

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐