From 26e27a71e80b1fd9d50bcfd4baad8a9eba91ddc0 Mon Sep 17 00:00:00 2001 From: Nik Klassen Date: Sun, 26 Dec 2021 12:14:02 -0500 Subject: [PATCH] Extract region name from Cloud Run metadata server response Previously this was returning a full string like /projects/123/regions/r, which does not match up with what the semvconv.CloudRegionKey value is supposed to be. --- detectors/gcp/cloud-run.go | 13 ++++++++++++- detectors/gcp/cloud-run_test.go | 2 +- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/detectors/gcp/cloud-run.go b/detectors/gcp/cloud-run.go index 44805834bd9..527ec9ce561 100644 --- a/detectors/gcp/cloud-run.go +++ b/detectors/gcp/cloud-run.go @@ -18,6 +18,7 @@ import ( "context" "fmt" "os" + "strings" "cloud.google.com/go/compute/metadata" @@ -56,6 +57,16 @@ func NewCloudRun() *CloudRun { } } +func (c *CloudRun) cloudRegion(ctx context.Context) (string, error) { + region, err := c.mc.Get("instance/region") + if err != nil { + return "", err + } + // Region from the metadata server is in the format /projects/123/regions/r. + // https://cloud.google.com/run/docs/reference/container-contract#metadata-server + return region[strings.LastIndex(region, "/")+1:], nil +} + // Detect detects associated resources when running on Cloud Run hosts. // NOTE: the service.namespace attribute is currently hardcoded to be // "cloud-run-managed". This may change in the future, please do not rely on @@ -80,7 +91,7 @@ func (c *CloudRun) Detect(ctx context.Context) (*resource.Resource, error) { attributes = append(attributes, semconv.CloudAccountIDKey.String(projectID)) } - if region, err := c.mc.Get("instance/region"); hasProblem(err) { + if region, err := c.cloudRegion(ctx); hasProblem(err) { errInfo = append(errInfo, err.Error()) } else if region != "" { attributes = append(attributes, semconv.CloudRegionKey.String(region)) diff --git a/detectors/gcp/cloud-run_test.go b/detectors/gcp/cloud-run_test.go index d8abcc3b9c3..1d9e2960a85 100644 --- a/detectors/gcp/cloud-run_test.go +++ b/detectors/gcp/cloud-run_test.go @@ -85,7 +85,7 @@ func TestCloudRunDetectorExpectSuccess(t *testing.T) { metadata := map[string]string{ "project/project-id": "foo", "instance/id": "bar", - "instance/region": "utopia", + "instance/region": "/projects/123/regions/utopia", } envvars := map[string]string{ "K_SERVICE": "x-service",