From 4abd9cfb64b03e64af8cedc141b12784542627a4 Mon Sep 17 00:00:00 2001 From: qingliu Date: Wed, 24 Aug 2022 22:43:21 +0800 Subject: [PATCH] feat: add timeout function for check approval --- apis/meta/v1alpha1/check_funcs.go | 10 +++++++ apis/meta/v1alpha1/check_funcs_test.go | 38 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/apis/meta/v1alpha1/check_funcs.go b/apis/meta/v1alpha1/check_funcs.go index 4f659802..b5881f62 100644 --- a/apis/meta/v1alpha1/check_funcs.go +++ b/apis/meta/v1alpha1/check_funcs.go @@ -81,3 +81,13 @@ func (as ApprovalStatuses) GetBySubject(subject rbacv1.Subject) *ApprovalStatus } return nil } + +// IsTimeout determine if the current is timeout. +// Take the current time as a reference, and compare it to the start time and the timeout duration. +func IsTimeout(startTime *metav1.Time, timeout metav1.Duration) bool { + if startTime.IsZero() || timeout.Duration == 0 { + return false + } + runtime := time.Since(startTime.Time) + return runtime >= timeout.Duration +} diff --git a/apis/meta/v1alpha1/check_funcs_test.go b/apis/meta/v1alpha1/check_funcs_test.go index b775f1ef..ed4adeb9 100644 --- a/apis/meta/v1alpha1/check_funcs_test.go +++ b/apis/meta/v1alpha1/check_funcs_test.go @@ -17,9 +17,12 @@ limitations under the License. package v1alpha1 import ( + "time" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" rbacv1 "k8s.io/api/rbac/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var _ = Describe("Test.Check", func() { @@ -83,3 +86,38 @@ var _ = Describe("Test.Check", func() { ), ) }) + +var _ = Describe("Test.IsTimeout", func() { + DescribeTable("IsTimeout", + func(startTime *metav1.Time, timeout time.Duration, expected bool) { + v1time := metav1.Duration{Duration: timeout} + actual := IsTimeout(startTime, v1time) + Expect(actual).To(Equal(expected)) + }, + Entry("nil startTime", + nil, + 1*time.Second, + false, + ), + Entry("timeout is zero", + &metav1.Time{Time: time.Now()}, + 0*time.Second, + false, + ), + Entry("not timeout", + &metav1.Time{Time: time.Now().Add(1 * time.Minute)}, + 30*time.Second, + false, + ), + Entry("timeout", + &metav1.Time{Time: time.Now().Add(-1 * time.Minute)}, + 30*time.Second, + true, + ), + Entry("just a timeout", + &metav1.Time{Time: time.Now().Add(-1 * time.Minute)}, + 60*time.Second, + true, + ), + ) +})