softplayer-backend/internal/helpers/kube/kube.go
2024-04-05 17:40:20 +02:00

62 lines
1.6 KiB
Go

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
}
if wait {
if err := WaitUntilCreated(ctx, client, obj, 10, time.Millisecond*50); err != nil {
return err
}
}
return nil
}
func SetOwnerRef(ctx context.Context, client client.Client, obj client.Object, owner client.Object) client.Object {
apiVersion := fmt.Sprintf("%s/%s", owner.GetObjectKind().GroupVersionKind().Group, owner.GetObjectKind().GroupVersionKind().Version)
ownerReference := []metav1.OwnerReference{
{
APIVersion: apiVersion,
Kind: owner.GetObjectKind().GroupVersionKind().GroupKind().Kind,
Name: owner.GetName(),
UID: owner.GetUID(),
},
}
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
}
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
}