github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/pprof/pprof.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package pprof
     7  
     8  import (
     9  	"fmt"
    10  	"os"
    11  	"runtime"
    12  	"runtime/pprof"
    13  
    14  	"github.com/gitbundle/modules/log"
    15  )
    16  
    17  // DumpMemProfileForUsername dumps a memory profile at pprofDataPath as memprofile_<username>_<temporary id>
    18  func DumpMemProfileForUsername(pprofDataPath, username string) error {
    19  	f, err := os.CreateTemp(pprofDataPath, fmt.Sprintf("memprofile_%s_", username))
    20  	if err != nil {
    21  		return err
    22  	}
    23  	defer f.Close()
    24  	runtime.GC() // get up-to-date statistics
    25  	return pprof.WriteHeapProfile(f)
    26  }
    27  
    28  // DumpCPUProfileForUsername dumps a CPU profile at pprofDataPath as cpuprofile_<username>_<temporary id>
    29  //
    30  //	it returns the stop function which stops, writes and closes the CPU profile file
    31  func DumpCPUProfileForUsername(pprofDataPath, username string) (func(), error) {
    32  	f, err := os.CreateTemp(pprofDataPath, fmt.Sprintf("cpuprofile_%s_", username))
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	err = pprof.StartCPUProfile(f)
    38  	if err != nil {
    39  		log.Fatal("StartCPUProfile: %v", err)
    40  	}
    41  	return func() {
    42  		pprof.StopCPUProfile()
    43  		err = f.Close()
    44  		if err != nil {
    45  			log.Fatal("StopCPUProfile Close: %v", err)
    46  		}
    47  	}, nil
    48  }