|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package k8sleaderelector |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "testing" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/stretchr/testify/require" |
| 13 | + "go.opentelemetry.io/collector/component/componenttest" |
| 14 | + "go.uber.org/zap" |
| 15 | + "go.uber.org/zap/zaptest/observer" |
| 16 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 17 | + "k8s.io/client-go/kubernetes" |
| 18 | + "k8s.io/client-go/kubernetes/fake" |
| 19 | + "k8s.io/utils/ptr" |
| 20 | + |
| 21 | + "github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig" |
| 22 | +) |
| 23 | + |
| 24 | +func TestExtension(t *testing.T) { |
| 25 | + config := &Config{ |
| 26 | + LeaseName: "foo", |
| 27 | + LeaseNamespace: "default", |
| 28 | + LeaseDuration: 15 * time.Second, |
| 29 | + RenewDuration: 10 * time.Second, |
| 30 | + RetryPeriod: 2 * time.Second, |
| 31 | + } |
| 32 | + |
| 33 | + iamInvokedOnLeading := false |
| 34 | + |
| 35 | + ctx := context.TODO() |
| 36 | + fakeClient := fake.NewClientset() |
| 37 | + config.makeClient = func(_ k8sconfig.APIConfig) (kubernetes.Interface, error) { |
| 38 | + return fakeClient, nil |
| 39 | + } |
| 40 | + |
| 41 | + observedZapCore, _ := observer.New(zap.WarnLevel) |
| 42 | + |
| 43 | + leaderElection := leaderElectionExtension{ |
| 44 | + config: config, |
| 45 | + client: fakeClient, |
| 46 | + logger: zap.New(observedZapCore), |
| 47 | + leaseHolderID: "foo", |
| 48 | + } |
| 49 | + |
| 50 | + leaderElection.SetCallBackFuncs( |
| 51 | + func(_ context.Context) { |
| 52 | + iamInvokedOnLeading = true |
| 53 | + fmt.Printf("LeaderElection started leading") |
| 54 | + }, |
| 55 | + func() { |
| 56 | + fmt.Printf("LeaderElection stopped leading") |
| 57 | + }, |
| 58 | + ) |
| 59 | + |
| 60 | + require.NoError(t, leaderElection.Start(ctx, componenttest.NewNopHost())) |
| 61 | + |
| 62 | + expectedLeaseDurationSeconds := ptr.To(int32(15)) |
| 63 | + |
| 64 | + require.Eventually(t, func() bool { |
| 65 | + lease, err := fakeClient.CoordinationV1().Leases("default").Get(ctx, "foo", metav1.GetOptions{}) |
| 66 | + require.NoError(t, err) |
| 67 | + require.NotNil(t, lease) |
| 68 | + require.Equal(t, expectedLeaseDurationSeconds, lease.Spec.LeaseDurationSeconds) |
| 69 | + return true |
| 70 | + }, 10*time.Second, 100*time.Millisecond) |
| 71 | + |
| 72 | + require.True(t, iamInvokedOnLeading) |
| 73 | + require.NoError(t, leaderElection.Shutdown(ctx)) |
| 74 | +} |
0 commit comments