2014-11-16 21:13:20 +01:00
|
|
|
// Copyright (C) 2014 The Syncthing Authors.
|
2014-09-29 21:43:32 +02:00
|
|
|
//
|
2015-03-07 21:36:35 +01:00
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2017-02-09 07:52:18 +01:00
|
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
2014-08-12 13:53:24 +02:00
|
|
|
|
2018-04-08 20:01:43 +02:00
|
|
|
package syncthing_main
|
2014-08-12 13:53:24 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"runtime"
|
|
|
|
"runtime/pprof"
|
|
|
|
"syscall"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-02-10 20:35:37 +01:00
|
|
|
func startHeapProfiler() {
|
|
|
|
l.Debugln("Starting heap profiling")
|
|
|
|
go func() {
|
|
|
|
err := saveHeapProfiles(1) // Only returns on error
|
|
|
|
l.Warnln("Heap profiler failed:", err)
|
|
|
|
panic("Heap profiler failed")
|
|
|
|
}()
|
2014-08-12 13:53:24 +02:00
|
|
|
}
|
|
|
|
|
2019-07-31 10:53:35 +02:00
|
|
|
func saveHeapProfiles(rate int) error {
|
2015-02-10 19:45:32 +01:00
|
|
|
runtime.MemProfileRate = rate
|
2014-08-12 13:53:24 +02:00
|
|
|
var memstats, prevMemstats runtime.MemStats
|
|
|
|
|
2015-02-10 19:49:49 +01:00
|
|
|
name := fmt.Sprintf("heap-%05d.pprof", syscall.Getpid())
|
|
|
|
for {
|
2014-08-12 13:53:24 +02:00
|
|
|
runtime.ReadMemStats(&memstats)
|
2015-02-10 19:49:49 +01:00
|
|
|
|
2014-08-12 13:53:24 +02:00
|
|
|
if memstats.HeapInuse > prevMemstats.HeapInuse {
|
2015-02-10 19:49:49 +01:00
|
|
|
fd, err := os.Create(name + ".tmp")
|
2014-08-12 13:53:24 +02:00
|
|
|
if err != nil {
|
2019-07-31 10:53:35 +02:00
|
|
|
return err
|
2014-08-12 13:53:24 +02:00
|
|
|
}
|
|
|
|
err = pprof.WriteHeapProfile(fd)
|
|
|
|
if err != nil {
|
2019-07-31 10:53:35 +02:00
|
|
|
return err
|
2014-08-12 13:53:24 +02:00
|
|
|
}
|
|
|
|
err = fd.Close()
|
|
|
|
if err != nil {
|
2019-07-31 10:53:35 +02:00
|
|
|
return err
|
2014-08-12 13:53:24 +02:00
|
|
|
}
|
2015-02-10 19:49:49 +01:00
|
|
|
|
2019-02-02 12:16:27 +01:00
|
|
|
os.Remove(name) // Error deliberately ignored
|
2015-02-10 19:49:49 +01:00
|
|
|
err = os.Rename(name+".tmp", name)
|
|
|
|
if err != nil {
|
2019-07-31 10:53:35 +02:00
|
|
|
return err
|
2015-02-10 19:49:49 +01:00
|
|
|
}
|
|
|
|
|
2014-08-12 13:53:24 +02:00
|
|
|
prevMemstats = memstats
|
|
|
|
}
|
2015-02-10 19:49:49 +01:00
|
|
|
|
|
|
|
time.Sleep(250 * time.Millisecond)
|
2014-08-12 13:53:24 +02:00
|
|
|
}
|
|
|
|
}
|