Skip to content
Merged
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
10 changes: 8 additions & 2 deletions dubbod/discovery/pkg/model/config_snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,9 @@ func (ps *ConfigSnapshot) updateContext(env *Environment, oldSnapshot *ConfigSna

// Also check if the actual number of services has changed
// This handles cases where Kubernetes Services are added/removed without ServiceEntry updates
var currentServices []*Service
if !servicesChanged && oldSnapshot != nil {
currentServices := env.Services()
currentServices = env.Services()
// Count services in old ServiceIndex
oldServiceCount := 0
for _, namespaces := range oldSnapshot.ServiceIndex.HostnameAndNamespace {
Expand All @@ -332,7 +333,12 @@ func (ps *ConfigSnapshot) updateContext(env *Environment, oldSnapshot *ConfigSna
} else {
// make sure we copy over things that would be generated in initServiceRegistry
ps.ServiceIndex = oldSnapshot.ServiceIndex
ps.serviceAccounts = oldSnapshot.serviceAccounts
if currentServices == nil {
currentServices = env.Services()
}
// Recompute service accounts from EndpointIndex because endpoint/SA changes
// can occur without triggering servicesChanged (e.g. EDSCacheUpdate or subsequent policy pushes).
ps.initServiceAccounts(env, currentServices)
}

// Initialize or reuse Gateway API controller state.
Expand Down
24 changes: 19 additions & 5 deletions dubbod/discovery/pkg/model/endpointshards.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,14 @@ func (e *EndpointIndex) UpdateServiceEndpoints(shard ShardKey, hostname string,
// but we should not delete the keys from EndpointIndex map - that will trigger
// unnecessary full push which can become a real problem if a pod is in crashloop and thus endpoints
// flip flopping between 1 and 0.
e.DeleteServiceShard(shard, hostname, namespace, true)
if e.deleteServiceShard(shard, hostname, namespace, true) {
if logPushType {
log.Infof("Full push, service %s at shard %v has no endpoints and service accounts changed", hostname, shard)
} else {
log.Infof("Cache Update, Service %s at shard %v has no endpoints and service accounts changed", hostname, shard)
}
return FullPush
}
if logPushType {
log.Infof("Incremental push, service %s at shard %v has no endpoints", hostname, shard)
} else {
Expand Down Expand Up @@ -244,19 +251,26 @@ func (e *EndpointIndex) GetOrCreateEndpointShard(serviceName, namespace string)
}

func (e *EndpointIndex) DeleteServiceShard(shard ShardKey, serviceName, namespace string, preserveKeys bool) {
e.deleteServiceShard(shard, serviceName, namespace, preserveKeys)
}

func (e *EndpointIndex) deleteServiceShard(shard ShardKey, serviceName, namespace string, preserveKeys bool) bool {
e.mu.Lock()
defer e.mu.Unlock()
e.deleteServiceInner(shard, serviceName, namespace, preserveKeys)
return e.deleteServiceInner(shard, serviceName, namespace, preserveKeys)
}

func (e *EndpointIndex) deleteServiceInner(shard ShardKey, serviceName, namespace string, preserveKeys bool) {
func (e *EndpointIndex) deleteServiceInner(shard ShardKey, serviceName, namespace string, preserveKeys bool) bool {
if e.shardsBySvc[serviceName] == nil ||
e.shardsBySvc[serviceName][namespace] == nil {
return
return false
}
epShards := e.shardsBySvc[serviceName][namespace]
epShards.Lock()
defer epShards.Unlock()
delete(epShards.Shards, shard)
// Recompute service accounts from remaining shards so empty or deleted shards do not retain stale SAs.
saUpdated := updateShardServiceAccount(epShards, serviceName)
e.clearCacheForService(serviceName, namespace)
if !preserveKeys {
if len(epShards.Shards) == 0 {
Expand All @@ -266,7 +280,7 @@ func (e *EndpointIndex) deleteServiceInner(shard ShardKey, serviceName, namespac
delete(e.shardsBySvc, serviceName)
}
}
epShards.Unlock()
return saUpdated
}

func (e *EndpointIndex) clearCacheForService(svc, ns string) {
Expand Down
230 changes: 230 additions & 0 deletions dubbod/discovery/pkg/model/push_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,60 @@
package model

import (
"slices"
"testing"
"time"

"github.com/apache/dubbo-kubernetes/dubbod/discovery/pkg/serviceregistry/provider"
"github.com/apache/dubbo-kubernetes/pkg/config"
"github.com/apache/dubbo-kubernetes/pkg/config/host"
"github.com/apache/dubbo-kubernetes/pkg/config/mesh"
"github.com/apache/dubbo-kubernetes/pkg/config/mesh/meshwatcher"
"github.com/apache/dubbo-kubernetes/pkg/config/protocol"
"github.com/apache/dubbo-kubernetes/pkg/config/schema/collection"
"github.com/apache/dubbo-kubernetes/pkg/config/schema/kind"
"github.com/apache/dubbo-kubernetes/pkg/kube/krt"
"github.com/apache/dubbo-kubernetes/pkg/util/sets"
)

type stubConfigStore struct{}

func (stubConfigStore) Schemas() collection.Schemas { return collection.Schemas{} }
func (stubConfigStore) Get(config.GroupVersionKind, string, string) *config.Config {
return nil
}
func (stubConfigStore) List(config.GroupVersionKind, string) []config.Config {
return nil
}
func (stubConfigStore) Create(config.Config) (string, error) { return "", nil }

Check failure on line 45 in dubbod/discovery/pkg/model/push_context_test.go

View workflow job for this annotation

GitHub Actions / Lint

File is not properly formatted (gofmt)
func (stubConfigStore) Update(config.Config) (string, error) { return "", nil }
func (stubConfigStore) UpdateStatus(config.Config) (string, error) { return "", nil }
func (stubConfigStore) Patch(config.Config, config.PatchFunc) (string, error) { return "", nil }
func (stubConfigStore) Delete(config.GroupVersionKind, string, string, *string) error {
return nil
}

type stubServiceDiscovery struct {
services []*Service
}

func (s stubServiceDiscovery) Services() []*Service {
return s.services
}

func (s stubServiceDiscovery) GetService(hostname host.Name) *Service {
for _, svc := range s.services {
if svc.Hostname == hostname {
return svc
}
}
return nil
}

func (s stubServiceDiscovery) GetProxyServiceTargets(*Proxy) []ServiceTarget {
return nil
}

func TestPushRequestCopyMergePreservesQueuedUpdates(t *testing.T) {
oldPush := NewPushContext()
newPush := NewPushContext()
Expand Down Expand Up @@ -99,3 +146,186 @@
t.Fatalf("StatusJSON() = %s, want {}", string(data))
}
}

func TestConfigSnapshotRecomputesServiceAccountsOnNonServicePush(t *testing.T) {
const hostName = host.Name("payment.app.svc.cluster.local")
const wantSAN = "spiffe://cluster.local/ns/app/sa/payment"

svc := &Service{
Hostname: hostName,
Ports: PortList{{Name: "http", Port: 8080, Protocol: protocol.HTTP2}},
Attributes: ServiceAttributes{
Name: "payment",
Namespace: "app",
},
}

env := NewEnvironment()
env.ConfigStore = stubConfigStore{}
env.ServiceDiscovery = stubServiceDiscovery{services: []*Service{svc}}
env.Watcher = meshwatcher.ConfigAdapter(krt.NewStatic(&meshwatcher.MeshConfigResource{
MeshConfig: mesh.DefaultMeshConfig(),
}, true))
env.Init()

initialPush := NewPushContext()
initialPush.InitContext(env, nil, nil)
if got := initialPush.ServiceAccounts(hostName, "app"); len(got) != 0 {
t.Fatalf("initial ServiceAccounts = %v, want empty", got)
}

env.EndpointIndex.UpdateServiceEndpoints(ShardKey{}, string(hostName), "app", []*DubboEndpoint{{
Addresses: []string{"10.0.0.10"},
EndpointPort: 8080,
ServicePortName: "http",
ServiceAccount: wantSAN,
HealthStatus: Healthy,
}}, false)

nonServiceChange := &PushRequest{
Full: true,
ConfigsUpdated: sets.New(ConfigKey{
Kind: kind.PeerAuthentication,
Name: "strict",
Namespace: "app",
}),
}
updatedPush := NewPushContext()
updatedPush.InitContext(env, initialPush, nonServiceChange)

if got := updatedPush.ServiceAccounts(hostName, "app"); !slices.Equal(got, []string{wantSAN}) {
t.Fatalf("updated ServiceAccounts = %v, want [%s]", got, wantSAN)
}
if got := initialPush.ServiceAccounts(hostName, "app"); len(got) != 0 {
t.Fatalf("initial ServiceAccounts mutated to %v", got)
}

const rotatedSAN = "spiffe://cluster.local/ns/app/sa/payment-v2"
env.EndpointIndex.UpdateServiceEndpoints(ShardKey{}, string(hostName), "app", []*DubboEndpoint{{
Addresses: []string{"10.0.0.11"},
EndpointPort: 8080,
ServicePortName: "http",
ServiceAccount: rotatedSAN,
HealthStatus: Healthy,
}}, false)
rotatedPush := NewPushContext()
rotatedPush.InitContext(env, updatedPush, nonServiceChange)
if got := rotatedPush.ServiceAccounts(hostName, "app"); !slices.Equal(got, []string{rotatedSAN}) {
t.Fatalf("rotated ServiceAccounts = %v, want [%s]", got, rotatedSAN)
}
if got := updatedPush.ServiceAccounts(hostName, "app"); !slices.Equal(got, []string{wantSAN}) {
t.Fatalf("updated ServiceAccounts mutated to %v", got)
}

if pushType := env.EndpointIndex.UpdateServiceEndpoints(ShardKey{}, string(hostName), "app", nil, false); pushType != FullPush {
t.Fatalf("UpdateServiceEndpoints(..., nil, false) pushType = %v, want FullPush", pushType)
}
clearedPush := NewPushContext()
clearedPush.InitContext(env, rotatedPush, nonServiceChange)
if got := clearedPush.ServiceAccounts(hostName, "app"); len(got) != 0 {
t.Fatalf("cleared ServiceAccounts = %v, want empty", got)
}
}

func TestEndpointIndexServiceAccountPushTypeAndReset(t *testing.T) {
const (
svcName = "payment.app.svc.cluster.local"
ns = "app"
sa1 = "spiffe://cluster.local/ns/app/sa/payment"
sa2 = "spiffe://cluster.local/ns/app/sa/payment-v2"
)

index := NewEndpointIndex(DisabledCache{})
shardA := ShardKey{Provider: provider.Kubernetes}
shardB := ShardKey{Provider: provider.External}

// Empty delete on unseen service stays incremental.
if got := index.UpdateServiceEndpoints(shardA, svcName, ns, nil, false); got != IncrementalPush {
t.Fatalf("unseen empty update pushType = %v, want IncrementalPush", got)
}

// Creating shard without SA still triggers FullPush for new endpoint shard.
if got := index.UpdateServiceEndpoints(shardA, svcName, ns, []*DubboEndpoint{{
Addresses: []string{"10.0.0.10"},
EndpointPort: 8080,
ServicePortName: "http",
HealthStatus: Healthy,
}}, false); got != FullPush {
t.Fatalf("initial shard create pushType = %v, want FullPush", got)
}

// Adding an SA to an existing shard must trigger FullPush.
if got := index.UpdateServiceEndpoints(shardA, svcName, ns, []*DubboEndpoint{{
Addresses: []string{"10.0.0.10"},
EndpointPort: 8080,
ServicePortName: "http",
ServiceAccount: sa1,
HealthStatus: Healthy,
}}, false); got != FullPush {
t.Fatalf("adding SA on existing shard pushType = %v, want FullPush", got)
}

// Endpoint churn with unchanged SA set stays IncrementalPush.
if got := index.UpdateServiceEndpoints(shardA, svcName, ns, []*DubboEndpoint{{
Addresses: []string{"10.0.0.11"},
EndpointPort: 8080,
ServicePortName: "http",
ServiceAccount: sa1,
HealthStatus: Healthy,
}}, false); got != IncrementalPush {
t.Fatalf("same-SA endpoint update pushType = %v, want IncrementalPush", got)
}

// Adding a second shard with a new SA triggers FullPush.
if got := index.UpdateServiceEndpoints(shardB, svcName, ns, []*DubboEndpoint{{
Addresses: []string{"10.0.0.12"},
EndpointPort: 8080,
ServicePortName: "http",
ServiceAccount: sa2,
HealthStatus: Healthy,
}}, false); got != FullPush {
t.Fatalf("second shard new SA pushType = %v, want FullPush", got)
}

// Deleting shardB via nil endpoints recomputes ServiceAccounts from shardA and triggers FullPush.
if got := index.UpdateServiceEndpoints(shardB, svcName, ns, nil, false); got != FullPush {
t.Fatalf("deleting shardB SA pushType = %v, want FullPush", got)
}
shards, ok := index.ShardsForService(svcName, ns)
if !ok {
t.Fatal("expected EndpointShards entry to remain preserved")
}
shards.RLock()
remainingSAs := sets.SortedList(shards.ServiceAccounts)
shards.RUnlock()
if !slices.Equal(remainingSAs, []string{sa1}) {
t.Fatalf("remaining ServiceAccounts = %v, want [%s]", remainingSAs, sa1)
}

// Deleting last shard via nil endpoints clears ServiceAccounts and triggers FullPush.
if got := index.UpdateServiceEndpoints(shardA, svcName, ns, nil, false); got != FullPush {
t.Fatalf("deleting last SA shard pushType = %v, want FullPush", got)
}
shards.RLock()
clearedLen := shards.ServiceAccounts.Len()
shards.RUnlock()
if clearedLen != 0 {
t.Fatalf("cleared ServiceAccounts len = %d, want 0", clearedLen)
}

// Repeated empty update after SAs are already empty stays IncrementalPush.
if got := index.UpdateServiceEndpoints(shardA, svcName, ns, nil, false); got != IncrementalPush {
t.Fatalf("repeated empty update pushType = %v, want IncrementalPush", got)
}

// Adding SA back to preserved empty shard triggers FullPush again.
if got := index.UpdateServiceEndpoints(shardA, svcName, ns, []*DubboEndpoint{{
Addresses: []string{"10.0.0.13"},
EndpointPort: 8080,
ServicePortName: "http",
ServiceAccount: sa1,
HealthStatus: Healthy,
}}, false); got != FullPush {
t.Fatalf("re-adding SA after empty pushType = %v, want FullPush", got)
}
}
Loading
Loading