runtime.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. /*
  2. Copyright 2014 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 runtime
  14. import (
  15. "fmt"
  16. "runtime"
  17. "sync"
  18. "time"
  19. "github.com/golang/glog"
  20. )
  21. var (
  22. // ReallyCrash controls the behavior of HandleCrash and now defaults
  23. // true. It's still exposed so components can optionally set to false
  24. // to restore prior behavior.
  25. ReallyCrash = true
  26. )
  27. // PanicHandlers is a list of functions which will be invoked when a panic happens.
  28. var PanicHandlers = []func(interface{}){logPanic}
  29. // HandleCrash simply catches a crash and logs an error. Meant to be called via
  30. // defer. Additional context-specific handlers can be provided, and will be
  31. // called in case of panic. HandleCrash actually crashes, after calling the
  32. // handlers and logging the panic message.
  33. //
  34. // TODO: remove this function. We are switching to a world where it's safe for
  35. // apiserver to panic, since it will be restarted by kubelet. At the beginning
  36. // of the Kubernetes project, nothing was going to restart apiserver and so
  37. // catching panics was important. But it's actually much simpler for monitoring
  38. // software if we just exit when an unexpected panic happens.
  39. func HandleCrash(additionalHandlers ...func(interface{})) {
  40. if r := recover(); r != nil {
  41. for _, fn := range PanicHandlers {
  42. fn(r)
  43. }
  44. for _, fn := range additionalHandlers {
  45. fn(r)
  46. }
  47. if ReallyCrash {
  48. // Actually proceed to panic.
  49. panic(r)
  50. }
  51. }
  52. }
  53. // logPanic logs the caller tree when a panic occurs.
  54. func logPanic(r interface{}) {
  55. callers := getCallers(r)
  56. glog.Errorf("Observed a panic: %#v (%v)\n%v", r, r, callers)
  57. }
  58. func getCallers(r interface{}) string {
  59. callers := ""
  60. for i := 0; true; i++ {
  61. _, file, line, ok := runtime.Caller(i)
  62. if !ok {
  63. break
  64. }
  65. callers = callers + fmt.Sprintf("%v:%v\n", file, line)
  66. }
  67. return callers
  68. }
  69. // ErrorHandlers is a list of functions which will be invoked when an unreturnable
  70. // error occurs.
  71. // TODO(lavalamp): for testability, this and the below HandleError function
  72. // should be packaged up into a testable and reusable object.
  73. var ErrorHandlers = []func(error){
  74. logError,
  75. (&rudimentaryErrorBackoff{
  76. lastErrorTime: time.Now(),
  77. // 1ms was the number folks were able to stomach as a global rate limit.
  78. // If you need to log errors more than 1000 times a second you
  79. // should probably consider fixing your code instead. :)
  80. minPeriod: time.Millisecond,
  81. }).OnError,
  82. }
  83. // HandlerError is a method to invoke when a non-user facing piece of code cannot
  84. // return an error and needs to indicate it has been ignored. Invoking this method
  85. // is preferable to logging the error - the default behavior is to log but the
  86. // errors may be sent to a remote server for analysis.
  87. func HandleError(err error) {
  88. // this is sometimes called with a nil error. We probably shouldn't fail and should do nothing instead
  89. if err == nil {
  90. return
  91. }
  92. for _, fn := range ErrorHandlers {
  93. fn(err)
  94. }
  95. }
  96. // logError prints an error with the call stack of the location it was reported
  97. func logError(err error) {
  98. glog.ErrorDepth(2, err)
  99. }
  100. type rudimentaryErrorBackoff struct {
  101. minPeriod time.Duration // immutable
  102. // TODO(lavalamp): use the clock for testability. Need to move that
  103. // package for that to be accessible here.
  104. lastErrorTimeLock sync.Mutex
  105. lastErrorTime time.Time
  106. }
  107. // OnError will block if it is called more often than the embedded period time.
  108. // This will prevent overly tight hot error loops.
  109. func (r *rudimentaryErrorBackoff) OnError(error) {
  110. r.lastErrorTimeLock.Lock()
  111. defer r.lastErrorTimeLock.Unlock()
  112. d := time.Since(r.lastErrorTime)
  113. if d < r.minPeriod {
  114. // If the time moves backwards for any reason, do nothing
  115. time.Sleep(r.minPeriod - d)
  116. }
  117. r.lastErrorTime = time.Now()
  118. }
  119. // GetCaller returns the caller of the function that calls it.
  120. func GetCaller() string {
  121. var pc [1]uintptr
  122. runtime.Callers(3, pc[:])
  123. f := runtime.FuncForPC(pc[0])
  124. if f == nil {
  125. return fmt.Sprintf("Unable to find caller")
  126. }
  127. return f.Name()
  128. }
  129. // RecoverFromPanic replaces the specified error with an error containing the
  130. // original error, and the call tree when a panic occurs. This enables error
  131. // handlers to handle errors and panics the same way.
  132. func RecoverFromPanic(err *error) {
  133. if r := recover(); r != nil {
  134. callers := getCallers(r)
  135. *err = fmt.Errorf(
  136. "recovered from panic %q. (err=%v) Call stack:\n%v",
  137. r,
  138. *err,
  139. callers)
  140. }
  141. }
  142. // Must panics on non-nil errors. Useful to handling programmer level errors.
  143. func Must(err error) {
  144. if err != nil {
  145. panic(err)
  146. }
  147. }