-
Notifications
You must be signed in to change notification settings - Fork 363
/
infra_client.go
69 lines (59 loc) · 1.77 KB
/
infra_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright Envoy Gateway Authors
// SPDX-License-Identifier: Apache-2.0
// The full text of the Apache license is available in the LICENSE file at
// the root of the repo.
package kubernetes
import (
"context"
"fmt"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type InfraClient struct {
client.Client
}
func New(cli client.Client) *InfraClient {
return &InfraClient{
Client: cli,
}
}
func (cli *InfraClient) CreateOrUpdate(ctx context.Context, key client.ObjectKey, current client.Object, specific client.Object, updateChecker func() bool) error {
return retry.RetryOnConflict(retry.DefaultBackoff, func() error {
if err := cli.Client.Get(ctx, key, current); err != nil {
if kerrors.IsNotFound(err) {
// Create if it does not exist.
if err := cli.Client.Create(ctx, specific); err != nil {
return fmt.Errorf("for Create: %w", err)
}
}
} else {
// Since the client.Object does not have a specific Spec field to compare
// just perform an update for now.
if updateChecker() {
specific.SetUID(current.GetUID())
if err := cli.Client.Update(ctx, specific); err != nil {
return fmt.Errorf("for Update: %w", err)
}
}
}
return nil
})
}
func (cli *InfraClient) Delete(ctx context.Context, object client.Object) error {
if err := cli.Client.Delete(ctx, object); err != nil {
if kerrors.IsNotFound(err) {
return nil
}
return err
}
return nil
}
// GetUID retrieves the uid of one resource.
func (cli *InfraClient) GetUID(ctx context.Context, key client.ObjectKey, current client.Object) (types.UID, error) {
if err := cli.Client.Get(ctx, key, current); err != nil {
return "", err
}
return current.GetUID(), nil
}