gitlab.com/gitlab-org/labkit@v1.21.0/monitoring/profiler.go (about)

     1  // +build continuous_profiler_stackdriver
     2  
     3  package monitoring
     4  
     5  import (
     6  	"net/url"
     7  	"os"
     8  
     9  	"cloud.google.com/go/profiler"
    10  	"gitlab.com/gitlab-org/labkit/log"
    11  	"google.golang.org/api/option"
    12  )
    13  
    14  const profilerEnvKey = "GITLAB_CONTINUOUS_PROFILING"
    15  
    16  // Exposing to tests.
    17  var profStart = profiler.Start
    18  
    19  func initProfiler(opts profilerOpts) {
    20  	driverParams, exists := os.LookupEnv(profilerEnvKey)
    21  	if !exists {
    22  		return
    23  	}
    24  
    25  	u, err := url.Parse(driverParams)
    26  	if err != nil {
    27  		log.WithError(err).Warn("unable to parse env var content")
    28  		return
    29  	}
    30  
    31  	query := u.Query()
    32  	driverName := u.Path
    33  
    34  	if driverName != "stackdriver" {
    35  		log.WithField("driver", driverName).Warn("unknown driver")
    36  		return
    37  	}
    38  
    39  	config := profiler.Config{
    40  		Service:        query.Get("service"),
    41  		ServiceVersion: query.Get("service_version"),
    42  		ProjectID:      query.Get("project_id"),
    43  		DebugLogging:   query.Get("debug_logging") == "true",
    44  
    45  		MutexProfiling: true,
    46  	}
    47  
    48  	// If the service version is given through opts, it takes precedence.
    49  	if opts.ServiceVersion != "" {
    50  		config.ServiceVersion = opts.ServiceVersion
    51  	}
    52  
    53  	var clientOpts []option.ClientOption
    54  	if opts.CredentialsFile != "" {
    55  		clientOpts = append(clientOpts, option.WithCredentialsFile(opts.CredentialsFile))
    56  	}
    57  
    58  	if err := profStart(config, clientOpts...); err != nil {
    59  		log.WithError(err).Warnf("unable to initialize %v profiler", driverName)
    60  		return
    61  	}
    62  
    63  	log.WithFields(log.Fields{
    64  		"driver":         driverName,
    65  		"service":        config.Service,
    66  		"serviceVersion": config.ServiceVersion,
    67  		"projectId":      config.ProjectID,
    68  	}).Info("profiler enabled")
    69  }