github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/libkb/pprof.go (about)

     1  // Copyright 2018 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  package libkb
     5  
     6  import (
     7  	"fmt"
     8  	"path/filepath"
     9  	"sort"
    10  	"time"
    11  )
    12  
    13  // The number of CPU profile files to keep around and to bundle with
    14  // sent logs.
    15  const MaxCPUProfileFileCount = 5
    16  
    17  // The number of trace files to keep around and to bundle with sent
    18  // logs.
    19  const MaxTraceFileCount = 5
    20  
    21  const cpuProfilePrefix = "cpu"
    22  
    23  const tracePrefix = "trace"
    24  
    25  func makeProfileFilename(prefix, dir string, start time.Time, duration time.Duration) string {
    26  	// Copied from oldLogFileTimeRangeTimeLayout from
    27  	// logger/file.go. Chosen so that lexicographic sorting
    28  	// approximately sorts by increasing start time; time zones
    29  	// prevent it from being an exact sorting.
    30  	startStr := start.Format("20060102T150405Z0700")
    31  	filename := fmt.Sprintf("%s.%s.%s.out", prefix, startStr, duration)
    32  	return filepath.Join(dir, filename)
    33  }
    34  
    35  // MakeCPUProfileFilename returns a filename to use for a CPU profile
    36  // file in the given directory with the given start time and duration.
    37  func MakeCPUProfileFilename(dir string, start time.Time, duration time.Duration) string {
    38  	return makeProfileFilename(cpuProfilePrefix, dir, start, duration)
    39  }
    40  
    41  // MakeTraceFilename returns a filename to use for a trace file
    42  // in the given directory with the given start time and duration.
    43  func MakeTraceFilename(dir string, start time.Time, duration time.Duration) string {
    44  	return makeProfileFilename(tracePrefix, dir, start, duration)
    45  }
    46  
    47  func getSortedFiles(prefix, dir string) ([]string, error) {
    48  	pattern := filepath.Join(dir, prefix+".*.out")
    49  	matches, err := filepath.Glob(pattern)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  	sort.Strings(matches)
    54  	return matches, nil
    55  }
    56  
    57  // GetSortedCPUProfileFiles returns all CPU profile files in the given
    58  // directory approximately sorted by increasing start time.
    59  func GetSortedCPUProfileFiles(dir string) ([]string, error) {
    60  	return getSortedFiles(cpuProfilePrefix, dir)
    61  }
    62  
    63  // GetSortedTraceFiles returns all trace files in the given directory
    64  // approximately sorted by increasing start time.
    65  func GetSortedTraceFiles(dir string) ([]string, error) {
    66  	return getSortedFiles(tracePrefix, dir)
    67  }