fixed resource version conflict when updating serivce

Signed-off-by: calvin <wen.chen@daocloud.io>
This commit is contained in:
calvin 2023-11-24 17:47:42 +08:00
parent 05afc3f3c5
commit 4e09f5e6b5
1 changed files with 16 additions and 9 deletions

View File

@ -19,6 +19,7 @@ package apiclient
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"strings" "strings"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1" admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
@ -90,19 +91,25 @@ func CreateOrUpdateSecret(client clientset.Interface, secret *corev1.Secret) err
func CreateOrUpdateService(client clientset.Interface, service *corev1.Service) error { func CreateOrUpdateService(client clientset.Interface, service *corev1.Service) error {
_, err := client.CoreV1().Services(service.GetNamespace()).Create(context.TODO(), service, metav1.CreateOptions{}) _, err := client.CoreV1().Services(service.GetNamespace()).Create(context.TODO(), service, metav1.CreateOptions{})
if err != nil { if err != nil {
if apierrors.IsAlreadyExists(err) { if !apierrors.IsAlreadyExists(err) {
_, err := client.CoreV1().Services(service.GetNamespace()).Update(context.TODO(), service, metav1.UpdateOptions{}) // Ignore if the Service is invalid with this error message:
// Service "apiserver" is invalid: provided Port is already allocated.
if apierrors.IsInvalid(err) && strings.Contains(err.Error(), errAllocated.Error()) {
klog.V(2).ErrorS(err, "failed to create or update serivce", "service", klog.KObj(service))
return nil
}
return fmt.Errorf("unable to create Service: %v", err)
}
older, err := client.CoreV1().Services(service.GetNamespace()).Get(context.TODO(), service.GetName(), metav1.GetOptions{})
if err != nil {
return err return err
} }
// Ignore if the Service is invalid with this error message: service.ResourceVersion = older.ResourceVersion
// Service "apiserver" is invalid: provided Port is already allocated. if _, err := client.CoreV1().Services(service.GetNamespace()).Update(context.TODO(), service, metav1.UpdateOptions{}); err != nil {
if apierrors.IsInvalid(err) && strings.Contains(err.Error(), errAllocated.Error()) { return fmt.Errorf("unable to update Service: %v", err)
klog.V(2).ErrorS(err, "failed to create or update serivce", "service", klog.KObj(service))
return nil
} }
return err
} }
klog.V(5).InfoS("Successfully created or updated service", "service", service.GetName()) klog.V(5).InfoS("Successfully created or updated service", "service", service.GetName())