Go语言实现超时退出

问题背景

项目中使用client-go创建了pv与pvc,必须要检测到两者都进入Bound状态才能继续业务逻辑。在检测状态时,可能由于pv/pvc创建的不正确导致永远无法进入Bound状态,因此需要设置一个超时时间,如果超过超时时间仍然未进入Bound状态,则认为创建的pv/pvc不正确。

如何实现超时退出呢?

解决方法

大体思想是:可以使用 context.WithTimeout() 与 channel 来共同完成。context.WithTimeout() 在超过设定时限后会自己出发 cancelFunc(),因此检测函数内部只要一直 select 检测 ctx 是否Done 就可以实现超时退出了。

在新协程中,如果函数是由timeout触发结束,则向 channel 中加入 false。如果是检测到想要的结果了,则向 channel 中加入 true 并提早结束。

调用者通过从 channel 中拿到的值来判断到底是超时还是成功。

func checkBound(pv *v1.PersistentVolume, pvc *v1.PersistentVolumeClaim, timeout time.Duration) error {
    // 在成功Bound后将 pvc-pv 的关系加入 clientset 的 map中
    ctx, cancelFunc := context.WithTimeout(context.TODO(), timeout)
    defer cancelFunc()

    isBoundChan := make(chan bool)  // 外界接收
    go func() {  // 起一个新协程检查
        for {
            select {
            case <-ctx.Done():
                // 超时触发
                isBoundChan <- false  // 如果是超时触发结束,则传入false
                close(isBoundChan)
                return
            default:
            }
            // 获取pv当前状态
            pvNow, err := clientset.CoreV1().PersistentVolumes().Get(context.TODO(), pv.Name, metav1.GetOptions{})
            if err != nil {
                err = fmt.Errorf("get pv error: %s", err.Error())
                log.Error(err)
                isBoundChan <- false
                close(isBoundChan)
                return
            }
            // 获取pvc当前状态
            pvcNow, err := clientset.CoreV1().PersistentVolumeClaims(metav1.NamespaceDefault).Get(context.TODO(), pvc.Name, metav1.GetOptions{})
            if err != nil {
                err = fmt.Errorf("get pvc error: %s", err.Error())
                log.Error(err)
                isBoundChan <- false
                close(isBoundChan)
                return
            }
            log.Debug("pvNow status:", pvNow.Status.Phase)
            log.Debug("pvcNow status", pvcNow.Status.Phase)
            // 判断是否pv、pvc都是Bound
            if pvNow.Status.Phase == v1.VolumeBound && pvcNow.Status.Phase == v1.ClaimBound {
                                // 在 timeout 前检测到 bound,则向管道传入true并提前返回
                isBoundChan <- true
                close(isBoundChan)
                return
            }
            // 两次查询间间隔500毫秒
            time.Sleep(500 * time.Microsecond)
        }
    }()

    // 取结果
    switch <-isBoundChan {
    case true:
        // 成功绑定
        log.Debug("bound success")
        clientset.addPvcPvRelation(pvc.Name, pv.Name)
        return nil
    default:
                // 绑定超时或其他错误
        err := fmt.Errorf("pv pvc bounding timeout")
        log.Error(err)
        return err
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容