Skip to content

feat: add code samples for Connect Gateway API #5299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 30 commits into from
May 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
26f3195
Add Connect Gateway Sample
hodaaaaaaaaaa Apr 23, 2025
1bb5496
Add Connect Gateway Sample
hodaaaaaaaaaa Apr 23, 2025
5a7d854
Add Connect Gateway Sample
hodaaaaaaaaaa Apr 23, 2025
c876f0c
Merge branch 'main' into connect-gateway
hodaaaaaaaaaa Apr 23, 2025
901a884
change sample to get namespace
hodaaaaaaaaaa May 1, 2025
72bb791
Update .github/CODEOWNERS
hodaaaaaaaaaa May 1, 2025
088124b
change sample to get namespace
hodaaaaaaaaaa May 1, 2025
7ed0f68
add tests
hodaaaaaaaaaa May 1, 2025
e273959
add tests
hodaaaaaaaaaa May 1, 2025
1aaaee7
Merge branch 'main' into connect-gateway
telpirion May 1, 2025
4bfebc9
Add tests for the sample
hodaaaaaaaaaa May 2, 2025
196948f
update tests to use gke lib
hodaaaaaaaaaa May 2, 2025
039c583
remove parent dir changes
hodaaaaaaaaaa May 2, 2025
7f58bc8
remove parent dir changes
hodaaaaaaaaaa May 2, 2025
28cc7a6
remove parent dir changes
hodaaaaaaaaaa May 2, 2025
fb480dd
add connectgateway to go.work
hodaaaaaaaaaa May 2, 2025
18c2b4c
add connectgateway to go.work
hodaaaaaaaaaa May 2, 2025
0928a3e
update min go version
hodaaaaaaaaaa May 2, 2025
5e3e09b
remove changes to other dirs
hodaaaaaaaaaa May 2, 2025
2555412
Merge branch 'main' into connect-gateway
telpirion May 8, 2025
36ce39a
update to address pr comments
hodaaaaaaaaaa May 12, 2025
4db817f
revert endpoint override changes
hodaaaaaaaaaa May 12, 2025
1fbdfb0
Merge branch 'main' into connect-gateway
telpirion May 15, 2025
8507c3f
use regional endpoint only
hodaaaaaaaaaa May 15, 2025
c380f82
change version to 1.23
hodaaaaaaaaaa May 19, 2025
c6283ff
change version to 1.23
hodaaaaaaaaaa May 19, 2025
e65b406
change version to 1.23
hodaaaaaaaaaa May 19, 2025
5b0cf4d
change version to 1.23
hodaaaaaaaaaa May 19, 2025
eb4b2da
Merge branch 'main' into connect-gateway
telpirion May 27, 2025
3312fac
Merge branch 'main' into connect-gateway
telpirion May 29, 2025
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
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
/secretmanager/ @GoogleCloudPlatform/go-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/cloud-secrets-team
/securitycenter/ @GoogleCloudPlatform/go-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/gcp-security-command-center
/translate/ @GoogleCloudPlatform/go-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/cloud-ml-translate-dev
/connectgateway/ @GoogleCloudPlatform/go-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/connectgateway

# Does not have owner
/cdn/ @GoogleCloudPlatform/go-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers
Expand Down
6 changes: 5 additions & 1 deletion .github/blunderbuss.yml
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,8 @@ assign_prs_by:
- labels:
- "api: securitycenter"
to:
- GoogleCloudPlatform/gcp-security-command-center
- GoogleCloudPlatform/gcp-security-command-center
- labels:
- "api: connectgateway"
to:
- GoogleCloudPlatform/connectgateway
95 changes: 95 additions & 0 deletions connectgateway/get_namespace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package connectgateway

// [START connectgateway_get_namespace]

import (
"context"
"fmt"
"io"
"net/http"

"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"

gateway "cloud.google.com/go/gkeconnect/gateway/apiv1"
gatewaypb "cloud.google.com/go/gkeconnect/gateway/apiv1/gatewaypb"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)

// getNamespace retrieves the Connect Gateway URL associated with the input
// membership. It then creates a kubernetes client using the retrieved Gateway
// URL to make requests to the underlying cluster.
func getNamespace(w io.Writer, membershipName, region string) error {
ctx := context.Background()
// If the membership location is regional, then the regional endpoint needs to be set for the client.
// Global memberships do not require this override as the default endpoint is global.
opts := option.WithEndpoint(fmt.Sprintf("%v-connectgateway.googleapis.com", region))

// Use Gateway Control to retrieve the Connect Gateway URL to be used as the
// host of the kubernetes client.
gatewayClient, err := gateway.NewGatewayControlRESTClient(ctx, opts)
if err != nil {
return fmt.Errorf("failed to create Connect Gateway client: %v", err)
}
defer gatewayClient.Close()

req := &gatewaypb.GenerateCredentialsRequest{
Name: membershipName,
}
resp, err := gatewayClient.GenerateCredentials(ctx, req)
if err != nil {
return fmt.Errorf("failed to fetch Connect Gateway URL for membership %s: %w", membershipName, err)
}
gatewayURL := resp.Endpoint
fmt.Printf("Connect Gateway Endpoint: %s\n", gatewayURL)

// Configure the kubernetes client library using the Connect Gateway URL and
// application default credentials.
scopes := "https://www.googleapis.com/auth/cloud-platform"
tokenSource, err := google.DefaultTokenSource(ctx, scopes)
if err != nil {
return fmt.Errorf("failed to get default credentials: %w", err)
}
wrapTransport := func(rt http.RoundTripper) http.RoundTripper {
return &oauth2.Transport{
Source: tokenSource,
Base: rt,
}
}
config := &rest.Config{
Host: gatewayURL,
WrapTransport: wrapTransport,
}
kubeClient, err := kubernetes.NewForConfig(config)
if err != nil {
return fmt.Errorf("failed to create Kubernetes client: %w", err)
}

// Call GetNamespace using the kubernetes client.
opt := metav1.GetOptions{}
namespace, err := kubeClient.CoreV1().Namespaces().Get(context.Background(), "default", opt)
if err != nil {
return fmt.Errorf("failed to get namespace: %w", err)
}
fmt.Fprintf(w, "\nDefault Namespace:\n%#v", namespace)
return nil
}

// [END connectgateway_get_namespace]
125 changes: 125 additions & 0 deletions connectgateway/get_namespace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package connectgateway

import (
"bytes"
"context"
"fmt"
"log"
"strings"
"testing"
"time"

"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
"github.com/google/uuid"
gke "google.golang.org/api/container/v1"
)

var (
zone = "us-central1-a"
region = "us-central1"
clusterName = fmt.Sprintf("cluster-%s", uuid.New().String()[:10])
)

func TestGetNamespace(t *testing.T) {
ctx := context.Background()
tc := testutil.EndToEndTest(t)
// Setup cluster.
if err := createCluster(ctx, tc.ProjectID, zone, clusterName); err != nil {
t.Fatalf("failed to create cluster: %v", err)
}
defer deleteCluster(ctx, tc.ProjectID, zone, clusterName)

membershipName := fmt.Sprintf("projects/%s/locations/%s/memberships/%s", tc.ProjectID, region, clusterName)
var buf bytes.Buffer
err := getNamespace(&buf, membershipName, region)
if err != nil {
t.Fatalf("getNamespace failed: %v", err)
}

got := buf.String()
fmt.Print(got)
if want := "Name:\"default\""; !strings.Contains(got, want) {
t.Errorf("got %q, want %q", got, want)
}
}

func createCluster(ctx context.Context, projectID, location, clusterName string) error {
svc, err := gke.NewService(ctx)
if err != nil {
log.Fatalf("Could not initialize gke client: %v", err)
}
clusterLocation := fmt.Sprintf("projects/%s/locations/%s", projectID, location)

req := &gke.CreateClusterRequest{
Parent: clusterLocation,
Cluster: &gke.Cluster{
Name: clusterName,
InitialNodeCount: 1,
Fleet: &gke.Fleet{
Project: projectID,
},
},
}

fmt.Printf("Creating cluster %s in %s...\n", clusterName, clusterLocation)
resp, err := svc.Projects.Zones.Clusters.Create(projectID, location, req).Do()
if err != nil {
return fmt.Errorf("failed to create cluster: %v", err.Error())
}

return pollOperation(svc, projectID, resp.Name)
}

func pollOperation(svc *gke.Service, projectId, opID string) error {
fmt.Printf("Polling operation: %s\n", opID)
for {

op, err := svc.Projects.Zones.Operations.Get(projectId, zone, opID).Do()
if err != nil {
return fmt.Errorf("failed to get operation %s: %v", opID, err)
}
fmt.Printf("Operation status: %v\n", op)

if op.Status == "RUNNING" {
fmt.Println("Waiting 30 seconds before polling again...")
time.Sleep(30 * time.Second)
continue
}

if op.Status == "DONE" {
fmt.Println("Operation completed successfully.")
return nil
}

return fmt.Errorf("operation failed with status %v", op.Status)
}
}

func deleteCluster(ctx context.Context, projectID, location, clusterName string) error {
svc, err := gke.NewService(ctx)
if err != nil {
log.Fatalf("Could not initialize gke client: %v", err)
}
clusterFullName := fmt.Sprintf("projects/%s/locations/%s/clusters/%s", projectID, location, clusterName)

fmt.Printf("Deleting cluster %s...\n", clusterFullName)
_, err = svc.Projects.Zones.Clusters.Delete(projectID, zone, clusterName).Do()
if err != nil {
return fmt.Errorf("failed to delete cluster %v: %v", clusterName, err)
}
return nil
}
91 changes: 91 additions & 0 deletions connectgateway/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
module github.com/GoogleCloudPlatform/golang-samples/connectgateway

go 1.23.0

require (
cloud.google.com/go/gkeconnect v0.12.4
github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250512171409-d5befca4cf89
github.com/google/uuid v1.6.0
golang.org/x/oauth2 v0.29.0
google.golang.org/api v0.231.0
k8s.io/apimachinery v0.32.4
k8s.io/client-go v0.32.4
)

require (
cel.dev/expr v0.20.0 // indirect
cloud.google.com/go v0.118.3 // indirect
cloud.google.com/go/auth v0.16.1 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
cloud.google.com/go/compute/metadata v0.6.0 // indirect
cloud.google.com/go/iam v1.4.0 // indirect
cloud.google.com/go/monitoring v1.24.0 // indirect
cloud.google.com/go/storage v1.50.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.26.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.49.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.49.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/emicklei/go-restful/v3 v3.12.2 // indirect
github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect
github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fxamacker/cbor/v2 v2.8.0 // indirect
github.com/go-jose/go-jose/v4 v4.0.4 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/jsonpointer v0.21.1 // indirect
github.com/go-openapi/jsonreference v0.21.0 // indirect
github.com/go-openapi/swag v0.23.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/gnostic-models v0.6.9 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/s2a-go v0.1.9 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect
github.com/googleapis/gax-go/v2 v2.14.1 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/zeebo/errs v1.4.0 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.34.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.60.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect
go.opentelemetry.io/otel v1.35.0 // indirect
go.opentelemetry.io/otel/metric v1.35.0 // indirect
go.opentelemetry.io/otel/sdk v1.35.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.35.0 // indirect
go.opentelemetry.io/otel/trace v1.35.0 // indirect
golang.org/x/crypto v0.37.0 // indirect
golang.org/x/net v0.39.0 // indirect
golang.org/x/sync v0.13.0 // indirect
golang.org/x/sys v0.32.0 // indirect
golang.org/x/term v0.31.0 // indirect
golang.org/x/text v0.24.0 // indirect
golang.org/x/time v0.11.0 // indirect
google.golang.org/genproto v0.0.0-20250303144028-a0af3efb3deb // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250428153025-10db94c68c34 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250428153025-10db94c68c34 // indirect
google.golang.org/grpc v1.72.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/api v0.32.4 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f // indirect
k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.2 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
)
Loading
Loading