Skip to content

Commit

Permalink
feat: add support for Cloud Run Jobs profiling
Browse files Browse the repository at this point in the history
The profiler is enabled by default when calling cloudrunner.Run() but
fails if deploy in a Cloud Run Jobs environment as it only looks for
Cloud Run service environment variables
  • Loading branch information
alethenorio committed Aug 22, 2023
1 parent 14e66f3 commit 92429d5
Showing 1 changed file with 43 additions and 17 deletions.
60 changes: 43 additions & 17 deletions cloudprofiler/profiler.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cloudprofiler

import (
"errors"
"fmt"

"cloud.google.com/go/profiler"
Expand Down Expand Up @@ -29,26 +30,51 @@ func Start(config Config) error {
if !config.Enabled {
return nil
}
service, ok := cloudruntime.Service()
if !ok {
return fmt.Errorf("start profiler: missing service")
}
projectID, ok := cloudruntime.ProjectID()
if !ok {
return fmt.Errorf("start profiler: missing project ID")

var cloudConfig cloudruntime.Config
if err := cloudConfig.Autodetect(); err != nil {
return fmt.Errorf("start profiler: %w", err)
}
serviceVersion, ok := cloudruntime.ServiceVersion()
if !ok {
return fmt.Errorf("start profiler: missing service version")

var svcConfig profiler.Config
switch {
case cloudConfig.Service != "":
var err error
svcConfig, err = cloudRunServiceConfig(cloudConfig)
if err != nil {
return fmt.Errorf("start profiler: %w", err)
}
case cloudConfig.Job != "":
var err error
svcConfig, err = cloudRunJobConfig(cloudConfig)
if err != nil {
return fmt.Errorf("start profiler: %w", err)
}
default:
return errors.New("unable to autodetect runtime environment")
}
if err := profilerStart(profiler.Config{
ProjectID: projectID,
Service: service,
ServiceVersion: serviceVersion,
MutexProfiling: config.MutexProfiling,
AllocForceGC: config.AllocForceGC,
}); err != nil {

svcConfig.MutexProfiling = config.MutexProfiling
svcConfig.AllocForceGC = config.AllocForceGC

if err := profilerStart(svcConfig); err != nil {
return fmt.Errorf("start profiler: %w", err)
}
return nil
}

func cloudRunServiceConfig(cloudCfg cloudruntime.Config) (profiler.Config, error) {
return profiler.Config{
ProjectID: cloudCfg.ProjectID,
Service: cloudCfg.Service,
ServiceVersion: cloudCfg.ServiceVersion,
}, nil
}

func cloudRunJobConfig(cloudCfg cloudruntime.Config) (profiler.Config, error) {
return profiler.Config{
ProjectID: cloudCfg.ProjectID,
Service: cloudCfg.Job,
ServiceVersion: cloudCfg.Execution,
}, nil
}

0 comments on commit 92429d5

Please sign in to comment.