github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/pprof/pprof.go (about)

     1  // Copyright 2023 LiveKit, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package pprof
    16  
    17  import (
    18  	"bytes"
    19  	"context"
    20  	"runtime/pprof"
    21  	"time"
    22  
    23  	"github.com/livekit/psrpc"
    24  )
    25  
    26  const (
    27  	cpuProfileName = "cpu"
    28  	defaultTimeout = 30
    29  )
    30  
    31  var (
    32  	ErrProfileNotFound = psrpc.NewErrorf(psrpc.NotFound, "profile not found")
    33  )
    34  
    35  func GetProfileData(ctx context.Context, profileName string, timeout int, debug int) (b []byte, err error) {
    36  	switch profileName {
    37  	case cpuProfileName:
    38  		return GetCpuProfileData(ctx, timeout)
    39  	default:
    40  		return GetGenericProfileData(profileName, debug)
    41  	}
    42  }
    43  
    44  func GetCpuProfileData(ctx context.Context, timeout int) (b []byte, err error) {
    45  	if timeout == 0 {
    46  		timeout = defaultTimeout
    47  	}
    48  
    49  	buf := &bytes.Buffer{}
    50  	err = pprof.StartCPUProfile(buf)
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	select {
    56  	case <-ctx.Done():
    57  		// finish async in order not to block, since we will not use the results
    58  		go pprof.StopCPUProfile()
    59  		return nil, context.Canceled
    60  	case <-time.After(time.Duration(timeout) * time.Second):
    61  		// break
    62  	}
    63  
    64  	pprof.StopCPUProfile()
    65  
    66  	return buf.Bytes(), nil
    67  }
    68  
    69  func GetGenericProfileData(profileName string, debug int) (b []byte, err error) {
    70  	pp := pprof.Lookup(profileName)
    71  	if pp == nil {
    72  		return nil, ErrProfileNotFound
    73  	}
    74  
    75  	buf := &bytes.Buffer{}
    76  
    77  	err = pp.WriteTo(buf, debug)
    78  	if err != nil {
    79  		return nil, err
    80  	}
    81  
    82  	return buf.Bytes(), nil
    83  }