Skip to content

Commit

Permalink
Get Cloud Run env vars before calling metadata service for project ID
Browse files Browse the repository at this point in the history
Checking the env vars is faster than calling the metadata service, so
hopefully this will bail out faster if we're not on Cloud Run.

Even if the call to the metadata service takes a long time it will only
happen on the first request to trigger it.
  • Loading branch information
mtraver committed Nov 15, 2022
1 parent 06713aa commit f570144
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
16 changes: 8 additions & 8 deletions gaelog.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,18 +80,18 @@ func newServiceInfo() (serviceInfo, error) {
}, nil
}

// Try the metadata service for the project ID.
crProjectID, err := projectIDFromMetadataService()
if err != nil {
return serviceInfo{}, err
}

// We got the project ID, so get and check the env vars expected to be set on Cloud Run.
// Get and check the env vars expected to be set on Cloud Run.
crService := os.Getenv("K_SERVICE")
crRevision := os.Getenv("K_REVISION")
crConfiguration := os.Getenv("K_CONFIGURATION")
if crService == "" || crRevision == "" || crConfiguration == "" {
return serviceInfo{}, fmt.Errorf("gaelog: the project ID was fetched from the metadata service so $K_SERVICE, $K_REVISION, and $K_CONFIGURATION are expected to be set, but one or more are not. Falling back to standard library log.")
return serviceInfo{}, fmt.Errorf("gaelog: GAE env vars were not set so Cloud Run vars $K_SERVICE, $K_REVISION, and $K_CONFIGURATION are expected to be set, but one or more are not. Falling back to standard library log.")
}

// Finally, try the metadata service for the project ID.
crProjectID, err := projectIDFromMetadataService()
if err != nil {
return serviceInfo{}, err
}

return serviceInfo{
Expand Down
4 changes: 2 additions & 2 deletions gaelog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ func TestNew(t *testing.T) {
expectResource *monitoredres.MonitoredResource
expectErr string
}{
{"no_env_vars_without_header", nil, false, nil, "the project ID was fetched from the metadata service"},
{"no_env_vars_with_header", nil, true, nil, "the project ID was fetched from the metadata service"},
{"no_env_vars_without_header", nil, false, nil, "GAE env vars were not set so Cloud Run vars"},
{"no_env_vars_with_header", nil, true, nil, "GAE env vars were not set so Cloud Run vars"},
{
"gae_env_vars_with_header",
map[string]string{
Expand Down

0 comments on commit f570144

Please sign in to comment.