Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 48 additions & 11 deletions pkg/specialservices/service_syncer.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package specialservices

import (
"fmt"
"slices"

"github.com/loft-sh/vcluster/pkg/syncer/synccontext"
Expand Down Expand Up @@ -67,17 +68,7 @@ func SyncKubernetesService(
newService.Spec.IPFamilyPolicy = pObj.Spec.IPFamilyPolicy
newService.Spec.Ports = translatedPorts
if clusterIPsChanged {
// delete & create with correct ClusterIP
err = ctx.VirtualClient.Delete(ctx, vObj)
if err != nil {
return err
}

// make sure we don't set the resource version during create
newService.ResourceVersion = ""

// create the new service with the correct cluster ip
err = ctx.VirtualClient.Create(ctx, newService)
err = recreateService(ctx, vSvcToSync, vObj, newService)
if err != nil {
return err
}
Expand All @@ -92,3 +83,49 @@ func SyncKubernetesService(

return nil
}

// recreateAttempts bounds how often the delete and create is repeated when the kube-apiserver
// recreates the kubernetes service in between.
const recreateAttempts = 5

// recreateService deletes the virtual service and creates it again with the cluster ips of the host
// service. The kube-apiserver recreates default/kubernetes on its own as soon as it is gone, so the
// create can lose that race and fail with AlreadyExists. In that case the recreated service is
// deleted and the create is repeated until the service that exists carries the wanted cluster ips.
func recreateService(ctx *synccontext.SyncContext, key types.NamespacedName, vObj, newService *corev1.Service) error {
var err error
for attempt := 0; attempt < recreateAttempts; attempt++ {
err = ctx.VirtualClient.Delete(ctx, vObj)
if err != nil && !kerrors.IsNotFound(err) {
return err
}

// make sure we don't set the resource version during create
toCreate := newService.DeepCopy()
toCreate.ResourceVersion = ""
toCreate.UID = ""
err = ctx.VirtualClient.Create(ctx, toCreate)
if err == nil {
return nil
} else if !kerrors.IsAlreadyExists(err) {
return err
}

// somebody else created the service in between, check whether it already has the wanted cluster ips
current := &corev1.Service{}
getErr := ctx.VirtualClient.Get(ctx, key, current)
if getErr != nil {
if kerrors.IsNotFound(getErr) {
continue
}
return getErr
}
if current.Spec.ClusterIP == newService.Spec.ClusterIP && slices.Equal(current.Spec.ClusterIPs, newService.Spec.ClusterIPs) {
return nil
}

vObj = current
}

return fmt.Errorf("recreate service %s after %d attempts: %w", key.String(), recreateAttempts, err)
}
90 changes: 90 additions & 0 deletions pkg/specialservices/service_syncer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package specialservices

import (
"context"
"testing"

"github.com/loft-sh/vcluster/pkg/scheme"
"github.com/loft-sh/vcluster/pkg/syncer/synccontext"
testingutil "github.com/loft-sh/vcluster/pkg/util/testing"
"gotest.tools/v3/assert"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// apiserverRecreatesClient plays the kube-apiserver that recreates default/kubernetes with its own
// cluster ip as soon as the service is gone, so that the first create after a delete loses the race.
type apiserverRecreatesClient struct {
client.Client

recreateWithIP string
racesLeft int
creates int
}

func (c *apiserverRecreatesClient) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error {
c.creates++
if c.racesLeft > 0 {
c.racesLeft--
recreated := obj.(*corev1.Service).DeepCopy()
recreated.ResourceVersion = ""
recreated.Spec.ClusterIP = c.recreateWithIP
recreated.Spec.ClusterIPs = []string{c.recreateWithIP}
if err := c.Client.Create(ctx, recreated, opts...); err != nil {
return err
}
return kerrors.NewAlreadyExists(schema.GroupResource{Resource: "services"}, obj.GetName())
}

return c.Client.Create(ctx, obj, opts...)
}

func TestSyncKubernetesServiceRecreateLosesRace(t *testing.T) {
hostService := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{Name: "vcluster", Namespace: "host"},
Spec: corev1.ServiceSpec{ClusterIP: "10.0.0.5", ClusterIPs: []string{"10.0.0.5"}, Ports: []corev1.ServicePort{{Name: "https", Port: 443}}},
}
virtualService := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{Name: DefaultKubernetesSVCName, Namespace: DefaultKubernetesSVCNamespace},
Spec: corev1.ServiceSpec{ClusterIP: "10.96.0.1", ClusterIPs: []string{"10.96.0.1"}, Ports: []corev1.ServicePort{{Name: "https", Port: 443}}},
}

for _, testCase := range []struct {
name string
racesLost int
wantErr bool
}{
{name: "create wins", racesLost: 0},
{name: "create loses once", racesLost: 1},
{name: "create loses twice", racesLost: 2},
{name: "create never wins", racesLost: recreateAttempts, wantErr: true},
} {
t.Run(testCase.name, func(t *testing.T) {
virtualClient := &apiserverRecreatesClient{
Client: testingutil.NewFakeClient(scheme.Scheme, virtualService.DeepCopy()),
recreateWithIP: "10.96.0.1",
racesLeft: testCase.racesLost,
}
syncCtx := &synccontext.SyncContext{
Context: context.Background(),
VirtualClient: virtualClient,
CurrentNamespaceClient: testingutil.NewFakeClient(scheme.Scheme, hostService.DeepCopy()),
}

err := SyncKubernetesService(syncCtx, "host", "vcluster", DefaultKubernetesSvcKey, func(ports []corev1.ServicePort) []corev1.ServicePort { return ports })
if testCase.wantErr {
assert.ErrorContains(t, err, "already exists")
return
}
assert.NilError(t, err)

got := &corev1.Service{}
assert.NilError(t, virtualClient.Get(context.Background(), DefaultKubernetesSvcKey, got))
assert.Equal(t, got.Spec.ClusterIP, "10.0.0.5")
assert.Equal(t, virtualClient.creates, testCase.racesLost+1)
})
}
}