blockprof.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "fmt"
  9. "os"
  10. "runtime"
  11. "runtime/pprof"
  12. "syscall"
  13. "time"
  14. )
  15. func init() {
  16. if innerProcess && os.Getenv("STBLOCKPROFILE") != "" {
  17. profiler := pprof.Lookup("block")
  18. if profiler == nil {
  19. panic("Couldn't find block profiler")
  20. }
  21. l.Debugln("Starting block profiling")
  22. go saveBlockingProfiles(profiler)
  23. }
  24. }
  25. func saveBlockingProfiles(profiler *pprof.Profile) {
  26. runtime.SetBlockProfileRate(1)
  27. t0 := time.Now()
  28. for t := range time.NewTicker(20 * time.Second).C {
  29. startms := int(t.Sub(t0).Seconds() * 1000)
  30. fd, err := os.Create(fmt.Sprintf("block-%05d-%07d.pprof", syscall.Getpid(), startms))
  31. if err != nil {
  32. panic(err)
  33. }
  34. err = profiler.WriteTo(fd, 0)
  35. if err != nil {
  36. panic(err)
  37. }
  38. err = fd.Close()
  39. if err != nil {
  40. panic(err)
  41. }
  42. }
  43. }