github.com/mckael/restic@v0.8.3/cmd/restic/global_debug.go (about)

     1  // +build debug
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"net/http"
     8  	_ "net/http/pprof"
     9  	"os"
    10  
    11  	"github.com/restic/restic/internal/errors"
    12  	"github.com/restic/restic/internal/repository"
    13  
    14  	"github.com/pkg/profile"
    15  )
    16  
    17  var (
    18  	listenMemoryProfile string
    19  	memProfilePath      string
    20  	cpuProfilePath      string
    21  	insecure            bool
    22  )
    23  
    24  func init() {
    25  	f := cmdRoot.PersistentFlags()
    26  	f.StringVar(&listenMemoryProfile, "listen-profile", "", "listen on this `address:port` for memory profiling")
    27  	f.StringVar(&memProfilePath, "mem-profile", "", "write memory profile to `dir`")
    28  	f.StringVar(&cpuProfilePath, "cpu-profile", "", "write cpu profile to `dir`")
    29  	f.BoolVar(&insecure, "insecure-kdf", false, "use insecure KDF settings")
    30  }
    31  
    32  type fakeTestingTB struct{}
    33  
    34  func (fakeTestingTB) Logf(msg string, args ...interface{}) {
    35  	fmt.Fprintf(os.Stderr, msg, args...)
    36  }
    37  
    38  func runDebug() error {
    39  	if listenMemoryProfile != "" {
    40  		fmt.Fprintf(os.Stderr, "running memory profile HTTP server on %v\n", listenMemoryProfile)
    41  		go func() {
    42  			err := http.ListenAndServe(listenMemoryProfile, nil)
    43  			if err != nil {
    44  				fmt.Fprintf(os.Stderr, "memory profile listen failed: %v\n", err)
    45  			}
    46  		}()
    47  	}
    48  
    49  	if memProfilePath != "" && cpuProfilePath != "" {
    50  		return errors.Fatal("only one profile (memory or CPU) may be activated at the same time")
    51  	}
    52  
    53  	var prof interface {
    54  		Stop()
    55  	}
    56  
    57  	if memProfilePath != "" {
    58  		prof = profile.Start(profile.Quiet, profile.NoShutdownHook, profile.MemProfile, profile.ProfilePath(memProfilePath))
    59  	} else if cpuProfilePath != "" {
    60  		prof = profile.Start(profile.Quiet, profile.NoShutdownHook, profile.CPUProfile, profile.ProfilePath(cpuProfilePath))
    61  	}
    62  
    63  	if prof != nil {
    64  		AddCleanupHandler(func() error {
    65  			prof.Stop()
    66  			return nil
    67  		})
    68  	}
    69  
    70  	if insecure {
    71  		repository.TestUseLowSecurityKDFParameters(fakeTestingTB{})
    72  	}
    73  
    74  	return nil
    75  }