|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "os" |
| 6 | + "runtime" |
| 7 | + "runtime/pprof" |
| 8 | + |
| 9 | + "github.com/moby/buildkit/util/bklog" |
| 10 | + "github.com/sirupsen/logrus" |
| 11 | +) |
| 12 | + |
| 13 | +func setupDebugProfiles(ctx context.Context) (stop func()) { |
| 14 | + var stopFuncs []func() |
| 15 | + if fn := setupCPUProfile(ctx); fn != nil { |
| 16 | + stopFuncs = append(stopFuncs, fn) |
| 17 | + } |
| 18 | + if fn := setupHeapProfile(ctx); fn != nil { |
| 19 | + stopFuncs = append(stopFuncs, fn) |
| 20 | + } |
| 21 | + return func() { |
| 22 | + for _, fn := range stopFuncs { |
| 23 | + fn() |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func setupCPUProfile(ctx context.Context) (stop func()) { |
| 29 | + if cpuProfile := os.Getenv("BUILDX_CPU_PROFILE"); cpuProfile != "" { |
| 30 | + f, err := os.Create(cpuProfile) |
| 31 | + if err != nil { |
| 32 | + bklog.G(ctx).Warn("could not create cpu profile", logrus.WithError(err)) |
| 33 | + return nil |
| 34 | + } |
| 35 | + |
| 36 | + if err := pprof.StartCPUProfile(f); err != nil { |
| 37 | + bklog.G(ctx).Warn("could not start cpu profile", logrus.WithError(err)) |
| 38 | + _ = f.Close() |
| 39 | + return nil |
| 40 | + } |
| 41 | + |
| 42 | + return func() { |
| 43 | + pprof.StopCPUProfile() |
| 44 | + if err := f.Close(); err != nil { |
| 45 | + bklog.G(ctx).Warn("could not close file for cpu profile", logrus.WithError(err)) |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + return nil |
| 50 | +} |
| 51 | + |
| 52 | +func setupHeapProfile(ctx context.Context) (stop func()) { |
| 53 | + if heapProfile := os.Getenv("BUILDX_MEM_PROFILE"); heapProfile != "" { |
| 54 | + // Memory profile is only created on stop. |
| 55 | + return func() { |
| 56 | + f, err := os.Create(heapProfile) |
| 57 | + if err != nil { |
| 58 | + bklog.G(ctx).Warn("could not create memory profile", logrus.WithError(err)) |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + // get up-to-date statistics |
| 63 | + runtime.GC() |
| 64 | + |
| 65 | + if err := pprof.WriteHeapProfile(f); err != nil { |
| 66 | + bklog.G(ctx).Warn("could not write memory profile", logrus.WithError(err)) |
| 67 | + } |
| 68 | + |
| 69 | + if err := f.Close(); err != nil { |
| 70 | + bklog.G(ctx).Warn("could not close file for memory profile", logrus.WithError(err)) |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + return nil |
| 75 | +} |
0 commit comments