syncthing/cmd/syncthing/heapprof.go

73 lines
1.7 KiB
Go
Raw Normal View History

2014-11-16 21:13:20 +01:00
// Copyright (C) 2014 The Syncthing Authors.
2014-09-29 21:43:32 +02:00
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.
2014-08-12 13:53:24 +02:00
package main
import (
"fmt"
"os"
"runtime"
"runtime/pprof"
2015-02-10 19:45:32 +01:00
"strconv"
2014-08-12 13:53:24 +02:00
"syscall"
"time"
)
func init() {
if innerProcess && os.Getenv("STHEAPPROFILE") != "" {
2015-02-10 19:45:32 +01:00
rate := 1
if i, err := strconv.Atoi(os.Getenv("STHEAPPROFILE")); err == nil {
rate = i
}
l.Debugln("Starting heap profiling")
2015-02-10 19:45:32 +01:00
go saveHeapProfiles(rate)
}
2014-08-12 13:53:24 +02:00
}
2015-02-10 19:45:32 +01:00
func saveHeapProfiles(rate int) {
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 {
panic(err)
}
err = pprof.WriteHeapProfile(fd)
if err != nil {
panic(err)
}
err = fd.Close()
if err != nil {
panic(err)
}
2015-02-10 19:49:49 +01:00
_ = os.Remove(name) // Error deliberately ignored
err = os.Rename(name+".tmp", name)
if err != nil {
panic(err)
}
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
}
}