profiling.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cmd
  14. import (
  15. "fmt"
  16. "os"
  17. "runtime"
  18. "runtime/pprof"
  19. "github.com/spf13/pflag"
  20. )
  21. var (
  22. profileName string
  23. profileOutput string
  24. )
  25. func addProfilingFlags(flags *pflag.FlagSet) {
  26. flags.StringVar(&profileName, "profile", "none", "Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex)")
  27. flags.StringVar(&profileOutput, "profile-output", "profile.pprof", "Name of the file to write the profile to")
  28. }
  29. func initProfiling() error {
  30. switch profileName {
  31. case "none":
  32. return nil
  33. case "cpu":
  34. f, err := os.Create(profileOutput)
  35. if err != nil {
  36. return err
  37. }
  38. return pprof.StartCPUProfile(f)
  39. // Block and mutex profiles need a call to Set{Block,Mutex}ProfileRate to
  40. // output anything. We choose to sample all events.
  41. case "block":
  42. runtime.SetBlockProfileRate(1)
  43. return nil
  44. case "mutex":
  45. runtime.SetMutexProfileFraction(1)
  46. return nil
  47. default:
  48. // Check the profile name is valid.
  49. if profile := pprof.Lookup(profileName); profile == nil {
  50. return fmt.Errorf("unknown profile '%s'", profileName)
  51. }
  52. }
  53. return nil
  54. }
  55. func flushProfiling() error {
  56. switch profileName {
  57. case "none":
  58. return nil
  59. case "cpu":
  60. pprof.StopCPUProfile()
  61. case "heap":
  62. runtime.GC()
  63. fallthrough
  64. default:
  65. profile := pprof.Lookup(profileName)
  66. if profile == nil {
  67. return nil
  68. }
  69. f, err := os.Create(profileOutput)
  70. if err != nil {
  71. return err
  72. }
  73. profile.WriteTo(f, 0)
  74. }
  75. return nil
  76. }