github.com/cilium/cilium@v1.16.2/pkg/endpointmanager/gc_test.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package endpointmanager 5 6 import ( 7 "context" 8 "fmt" 9 "testing" 10 "time" 11 12 "github.com/stretchr/testify/require" 13 14 "github.com/cilium/cilium/pkg/endpoint" 15 testidentity "github.com/cilium/cilium/pkg/testutils/identity" 16 testipcache "github.com/cilium/cilium/pkg/testutils/ipcache" 17 ) 18 19 // fakeCheck detects endpoints as unhealthy if they have an even EndpointID. 20 func fakeCheck(ep *endpoint.Endpoint) error { 21 if ep.GetID()%2 == 0 { 22 return fmt.Errorf("Endpoint has an even EndpointID") 23 } 24 return nil 25 } 26 27 func TestMarkAndSweep(t *testing.T) { 28 s := setupEndpointManagerSuite(t) 29 // Open-code WithPeriodicGC() to avoid running the controller 30 mgr := New(&dummyEpSyncher{}, nil, nil) 31 mgr.checkHealth = fakeCheck 32 mgr.deleteEndpoint = endpointDeleteFunc(mgr.waitEndpointRemoved) 33 34 timeout := 30 * time.Second 35 ctx, cancel := context.WithTimeout(context.Background(), timeout) 36 defer cancel() 37 38 endpointIDToDelete := uint16(2) 39 healthyEndpointIDs := []uint16{1, 3, 5, 7} 40 allEndpointIDs := append(healthyEndpointIDs, endpointIDToDelete) 41 for _, id := range allEndpointIDs { 42 ep := endpoint.NewTestEndpointWithState(t, s, s, testipcache.NewMockIPCache(), &endpoint.FakeEndpointProxy{}, testidentity.NewMockIdentityAllocator(nil), id, endpoint.StateReady) 43 err := mgr.expose(ep) 44 require.Nil(t, err) 45 } 46 require.Equal(t, len(allEndpointIDs), len(mgr.GetEndpoints())) 47 48 // Two-phase mark and sweep: Mark should not yet delete any endpoints. 49 err := mgr.markAndSweep(ctx) 50 require.Equal(t, true, mgr.EndpointExists(endpointIDToDelete)) 51 require.Nil(t, err) 52 require.Equal(t, len(allEndpointIDs), len(mgr.GetEndpoints())) 53 54 // Second phase: endpoint should be marked now and we should only sweep 55 // that particular endpoint. 56 err = mgr.markAndSweep(ctx) 57 require.Equal(t, false, mgr.EndpointExists(endpointIDToDelete)) 58 require.Nil(t, err) 59 require.Equal(t, len(healthyEndpointIDs), len(mgr.GetEndpoints())) 60 }