2024-03-21 20:10:56 +00:00
|
|
|
package kube
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
|
|
"k8s.io/apimachinery/pkg/types"
|
|
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Create(ctx context.Context, client client.Client, obj client.Object, wait bool) error {
|
|
|
|
if err := client.Create(ctx, obj); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-03 18:05:23 +00:00
|
|
|
if wait {
|
2024-03-21 20:10:56 +00:00
|
|
|
if err := WaitUntilCreated(ctx, client, obj, 10, time.Millisecond*50); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-04-30 09:19:56 +00:00
|
|
|
func Update(ctx context.Context, client client.Client, obj client.Object) error {
|
|
|
|
if err := client.Update(ctx, obj); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-03-21 20:10:56 +00:00
|
|
|
func SetOwnerRef(ctx context.Context, client client.Client, obj client.Object, owner client.Object) client.Object {
|
2024-04-03 18:05:23 +00:00
|
|
|
apiVersion := fmt.Sprintf("%s/%s", owner.GetObjectKind().GroupVersionKind().Group, owner.GetObjectKind().GroupVersionKind().Version)
|
2024-03-21 20:10:56 +00:00
|
|
|
ownerReference := []metav1.OwnerReference{
|
|
|
|
{
|
2024-04-03 18:05:23 +00:00
|
|
|
APIVersion: apiVersion,
|
|
|
|
Kind: owner.GetObjectKind().GroupVersionKind().GroupKind().Kind,
|
|
|
|
Name: owner.GetName(),
|
|
|
|
UID: owner.GetUID(),
|
2024-03-21 20:10:56 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
obj.SetOwnerReferences(ownerReference)
|
|
|
|
return obj
|
|
|
|
}
|
|
|
|
|
|
|
|
func WaitUntilCreated(ctx context.Context, client client.Client, obj client.Object, attemps int, timeout time.Duration) error {
|
|
|
|
if err := client.Get(ctx, types.NamespacedName{
|
|
|
|
Namespace: obj.GetNamespace(),
|
|
|
|
Name: obj.GetName(),
|
|
|
|
}, obj); err != nil {
|
|
|
|
if attemps > 0 {
|
|
|
|
time.Sleep(timeout)
|
|
|
|
if err := WaitUntilCreated(ctx, client, obj, attemps-1, timeout); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2024-04-05 15:40:20 +00:00
|
|
|
|
|
|
|
func Delete(ctx context.Context, client client.Client, obj client.Object, wait bool) error {
|
|
|
|
if err := client.Delete(ctx, obj); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|