Skip to content

Commit

Permalink
Merge pull request #234 from briantkennedy/cleantool
Browse files Browse the repository at this point in the history
Cleantool
  • Loading branch information
google-oss-prow[bot] authored Oct 1, 2024
2 parents 5e23f91 + 8aadc2d commit da81e2a
Show file tree
Hide file tree
Showing 8 changed files with 246 additions and 187 deletions.
26 changes: 26 additions & 0 deletions cmd/e2e-cleaner/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"context"
"flag"
"fmt"
"os"

"github.com/GoogleCloudPlatform/k8s-cloud-provider/e2e"
_ "k8s.io/klog/v2"
)

func init() {
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprint(flag.CommandLine.Output(), "\n\n Example Usage: go run ./cmd/e2e-cleaner/main.go -project my-project -run-id \"\"\n")
}
}

func main() {
e2e.ParseFlagsOrDie()
ctx := context.Background()
e2e.SetupCloudOrDie(ctx)
e2e.FallbackCleanup(ctx)
}
4 changes: 2 additions & 2 deletions e2e/backend_service_update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ func buildBackendServiceWithLBScheme(graphBuilder *rgraph.Builder, name string,
}

func buildBackendServiceWith(graphBuilder *rgraph.Builder, name string, f func(x *compute.BackendService)) (*cloud.ResourceID, error) {
bsID := backendservice.ID(testFlags.project, meta.GlobalKey(resourceName(name)))
bsMutResource := backendservice.NewMutableBackendService(testFlags.project, bsID.Key)
bsID := backendservice.ID(TestFlags.Project, meta.GlobalKey(resourceName(name)))
bsMutResource := backendservice.NewMutableBackendService(TestFlags.Project, bsID.Key)
bsMutResource.Access(f)
bsResource, err := bsMutResource.Freeze()
if err != nil {
Expand Down
94 changes: 94 additions & 0 deletions e2e/cleanup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package e2e

import (
"context"
"fmt"
"log"
"path"
"strings"

"github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud/filter"
"github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud/meta"
)

func matchTestResource(name string) bool {
if RunID == "" {
return strings.HasPrefix(name, TestFlags.ResourcePrefix)
} else {
return strings.HasPrefix(name, fmt.Sprintf("%s%s-", TestFlags.ResourcePrefix, RunID))
}
}

func cleanupMeshes(ctx context.Context) {
tcprs, err := theCloud.Meshes().List(ctx, filter.None)
if err != nil {
log.Printf("FallbackCleanup: theCloud.Meshes().List(ctx, _): %v\n", err)
return
}
for _, tcpr := range tcprs {
name := path.Base(tcpr.Name)
if !matchTestResource(name) {
continue
}
key := meta.GlobalKey(name)
err = theCloud.Meshes().Delete(ctx, key)
log.Printf("FallbackCleanup: theCloud.Meshes().Delete(ctx, %s): %v\n", key, err)
}
}

func cleanupTcpRoutes(ctx context.Context) {
tcprs, err := theCloud.TcpRoutes().List(ctx, filter.None)
if err != nil {
log.Printf("FallbackCleanup: theCloud.TcpRoutes().List(ctx, _): %v\n", err)
return
}
for _, tcpr := range tcprs {
name := path.Base(tcpr.Name)
if !matchTestResource(name) {
continue
}
key := meta.GlobalKey(name)
err = theCloud.TcpRoutes().Delete(ctx, key)
log.Printf("FallbackCleanup: theCloud.TcpRoutes().Delete(ctx, %s): %v\n", key, err)
}
}

func cleanupBackendServices(ctx context.Context) {
bss, err := theCloud.BackendServices().List(ctx, filter.None)
if err != nil {
log.Printf("FallbackCleanup: theCloud.BackendServices().List(ctx, _): %v\n", err)
return
}
for _, bs := range bss {
if !matchTestResource(bs.Name) {
continue
}
key := meta.GlobalKey(bs.Name)
err = theCloud.BackendServices().Delete(ctx, key)
log.Printf("FallbackCleanup: theCloud.BackendServices().Delete(ctx, %s): %v\n", key, err)
}
}

func cleanupHealthChecks(ctx context.Context) {
hcs, err := theCloud.HealthChecks().List(ctx, filter.None)
if err != nil {
log.Printf("FallbackCleanup: theCloud.HealthChecks().List(ctx, _): %v\n", err)
return
}
for _, hc := range hcs {
if !matchTestResource(hc.Name) {
continue
}
key := meta.GlobalKey(hc.Name)
err = theCloud.HealthChecks().Delete(ctx, key)
log.Printf("FallbackCleanup: theCloud.HealthChecks().Delete(ctx, %s): %v\n", key, err)
}
}

// FallbackCleanup cleans all the resources created during the test run.
func FallbackCleanup(ctx context.Context) {
cleanupTcpRoutes(ctx)
cleanupBackendServices(ctx)
cleanupHealthChecks(ctx)
cleanupMeshes(ctx)
}
63 changes: 63 additions & 0 deletions e2e/cloud.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package e2e

import (
"context"
"log"
"time"

"github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
"google.golang.org/api/impersonate"
"google.golang.org/api/option"
)

var (
// theCloud is a global to be used in the e2e tests.
theCloud cloud.Cloud
)

func SetupCloudOrDie(ctx context.Context) {
credentials, err := google.FindDefaultCredentials(ctx, compute.ComputeScope)
if err != nil {
log.Fatal(err)
}
ts := credentials.TokenSource

// Optionally, impersonate service account by replacing token source for http client.
if TestFlags.ServiceAccountName != "" {
ts, err = impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{
TargetPrincipal: TestFlags.ServiceAccountName,
Scopes: []string{compute.ComputeScope, compute.CloudPlatformScope},
}, option.WithCredentials(credentials))
if err != nil {
log.Fatalf("Failed to use %q credentials: %v", TestFlags.ServiceAccountName, err)
}
}
client := oauth2.NewClient(ctx, ts)

mrl := &cloud.MinimumRateLimiter{RateLimiter: &cloud.NopRateLimiter{}, Minimum: 50 * time.Millisecond}
crl := cloud.NewCompositeRateLimiter(mrl)

// The default limit is 1500 per minute. Leave 200 buffer.
computeRL := cloud.NewTickerRateLimiter(1300, time.Minute)
crl.Register("HealthChecks", "", computeRL)
crl.Register("BackendServices", "", computeRL)
crl.Register("NetworkEndpointGroups", "", computeRL)

// The default limit is 1200 per minute. Leave 200 buffer.
networkServicesRL := cloud.NewTickerRateLimiter(1000, time.Minute)
crl.Register("TcpRoutes", "", networkServicesRL)
crl.Register("Meshes", "", networkServicesRL)

// To ensure minimum time between operations, wrap the network services rate limiter.
orl := &cloud.MinimumRateLimiter{RateLimiter: networkServicesRL, Minimum: 100 * time.Millisecond}
crl.Register("Operations", "", orl)

svc, err := cloud.NewService(ctx, client, &cloud.SingleProjectRouter{ID: TestFlags.Project}, crl)
if err != nil {
log.Fatal(err)
}
theCloud = cloud.NewGCE(svc)
}
42 changes: 42 additions & 0 deletions e2e/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package e2e

import (
"flag"
"fmt"
"math/rand"
"os"

"k8s.io/klog/v2"
)

var (
// TestFlags passed in from the command line.
TestFlags = struct {
Project string
ResourcePrefix string
ServiceAccountName string
RunID string
}{
Project: "",
ResourcePrefix: "k8scp-",
ServiceAccountName: "",
}
RunID string
)

func init() {
klog.InitFlags(flag.CommandLine)

flag.StringVar(&TestFlags.Project, "project", TestFlags.Project, "GCP Project ID")
flag.StringVar(&TestFlags.ResourcePrefix, "resourcePrefix", TestFlags.ResourcePrefix, "Prefix used to name all resources created in the tests. Any resources with this prefix will be removed during cleanup.")
flag.StringVar(&TestFlags.ServiceAccountName, "sa-name", TestFlags.ServiceAccountName, "Name of the Service Account to impersonate")
flag.StringVar(&RunID, "run-id", fmt.Sprintf("%0x", rand.Int63()&0xffff), "The RunID to use when managing resources.")
}
func ParseFlagsOrDie() {
flag.Parse()

if TestFlags.Project == "" {
fmt.Println("-project must be set")
os.Exit(1)
}
}
12 changes: 6 additions & 6 deletions e2e/rgraph_update_action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ import (
)

func buildBackendService(graphBuilder *rgraph.Builder, name string, hcID *cloud.ResourceID, port int64) (*cloud.ResourceID, error) {
bsID := backendservice.ID(testFlags.project, meta.GlobalKey(resourceName(name)))
bsID := backendservice.ID(TestFlags.Project, meta.GlobalKey(resourceName(name)))

bsMutResource := backendservice.NewMutableBackendService(testFlags.project, bsID.Key)
bsMutResource := backendservice.NewMutableBackendService(TestFlags.Project, bsID.Key)
bsMutResource.Access(func(x *compute.BackendService) {
x.LoadBalancingScheme = "INTERNAL_SELF_MANAGED"
x.Protocol = "TCP"
Expand All @@ -60,8 +60,8 @@ func buildBackendService(graphBuilder *rgraph.Builder, name string, hcID *cloud.
}

func buildHealthCheck(graphBuilder *rgraph.Builder, name string, checkIntervalSec int64) (*cloud.ResourceID, error) {
hcID := healthcheck.ID(testFlags.project, meta.GlobalKey(resourceName(name)))
hcMutRes := healthcheck.NewMutableHealthCheck(testFlags.project, hcID.Key)
hcID := healthcheck.ID(TestFlags.Project, meta.GlobalKey(resourceName(name)))
hcMutRes := healthcheck.NewMutableHealthCheck(TestFlags.Project, hcID.Key)
hcMutRes.Access(func(x *compute.HealthCheck) {
x.CheckIntervalSec = checkIntervalSec
x.HealthyThreshold = 5
Expand All @@ -86,8 +86,8 @@ func buildHealthCheck(graphBuilder *rgraph.Builder, name string, checkIntervalSe
return hcID, nil
}
func buildTCPHealthCheck(graphBuilder *rgraph.Builder, name string, checkIntervalSec int64) (*cloud.ResourceID, error) {
hcID := healthcheck.ID(testFlags.project, meta.GlobalKey(resourceName(name)))
hcMutRes := healthcheck.NewMutableHealthCheck(testFlags.project, hcID.Key)
hcID := healthcheck.ID(TestFlags.Project, meta.GlobalKey(resourceName(name)))
hcMutRes := healthcheck.NewMutableHealthCheck(TestFlags.Project, hcID.Key)
hcMutRes.Access(func(x *compute.HealthCheck) {
x.CheckIntervalSec = checkIntervalSec
x.HealthyThreshold = 5
Expand Down
18 changes: 9 additions & 9 deletions e2e/tcproute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func TestTcpRoute(t *testing.T) {
}

// Current API does not support the new URL scheme.
serviceName := fmt.Sprintf("https://compute.googleapis.com/v1/projects/%s/global/backendServices/%s", testFlags.project, bs.Name)
serviceName := fmt.Sprintf("https://compute.googleapis.com/v1/projects/%s/global/backendServices/%s", TestFlags.Project, bs.Name)
tcpr := &networkservices.TcpRoute{
Name: resourceName("route1"),
Rules: []*networkservices.TcpRouteRouteRule{
Expand Down Expand Up @@ -113,8 +113,8 @@ func TestTcpRoute(t *testing.T) {
}

func buildNEG(graphBuilder *rgraph.Builder, name, zone string) (*cloud.ResourceID, error) {
negID := networkendpointgroup.ID(testFlags.project, meta.ZonalKey(resourceName(name), zone))
negMut := networkendpointgroup.NewMutableNetworkEndpointGroup(testFlags.project, negID.Key)
negID := networkendpointgroup.ID(TestFlags.Project, meta.ZonalKey(resourceName(name), zone))
negMut := networkendpointgroup.NewMutableNetworkEndpointGroup(TestFlags.Project, negID.Key)
negMut.Access(func(x *compute.NetworkEndpointGroup) {
x.Zone = zone
x.NetworkEndpointType = "GCE_VM_IP_PORT"
Expand Down Expand Up @@ -160,8 +160,8 @@ func buildBackendServiceWithNEG(graphBuilder *rgraph.Builder, name string, hcID,
}

func buildTCPRoute(graphBuilder *rgraph.Builder, name, meshURL string, rules []*networkservices.TcpRouteRouteRule) (*cloud.ResourceID, error) {
tcpID := tcproute.ID(testFlags.project, meta.GlobalKey(resourceName(name)))
tcpMutRes := tcproute.NewMutableTcpRoute(testFlags.project, tcpID.Key)
tcpID := tcproute.ID(TestFlags.Project, meta.GlobalKey(resourceName(name)))
tcpMutRes := tcproute.NewMutableTcpRoute(TestFlags.Project, tcpID.Key)

tcpMutRes.Access(func(x *networkservices.TcpRoute) {
x.Description = "tcp route for rGraph test"
Expand Down Expand Up @@ -190,8 +190,8 @@ type routesServices struct {
}

func buildTCPRouteWithBackends(graphBuilder *rgraph.Builder, name, meshURL string, services []routesServices) (*cloud.ResourceID, error) {
tcpID := tcproute.ID(testFlags.project, meta.GlobalKey(resourceName(name)))
tcpMutRes := tcproute.NewMutableTcpRoute(testFlags.project, tcpID.Key)
tcpID := tcproute.ID(TestFlags.Project, meta.GlobalKey(resourceName(name)))
tcpMutRes := tcproute.NewMutableTcpRoute(TestFlags.Project, tcpID.Key)

tcpMutRes.Access(func(x *networkservices.TcpRoute) {
x.Description = "tcp route for rGraph test"
Expand Down Expand Up @@ -421,11 +421,11 @@ func processGraphAndExpectActions(t *testing.T, graphBuilder *rgraph.Builder, ex
}

func defaultNetworkURL() string {
return cloud.NewNetworksResourceID(testFlags.project, "default").SelfLink(meta.VersionGA)
return cloud.NewNetworksResourceID(TestFlags.Project, "default").SelfLink(meta.VersionGA)
}

func defaultSubnetworkURL() string {
return cloud.NewSubnetworksResourceID(testFlags.project, region, "default").SelfLink(meta.VersionGA)
return cloud.NewSubnetworksResourceID(TestFlags.Project, region, "default").SelfLink(meta.VersionGA)
}

func createHealthchecks(graphBuilder *rgraph.Builder, hcNum int, name string) ([]*cloud.ResourceID, error) {
Expand Down
Loading

0 comments on commit da81e2a

Please sign in to comment.