profiling.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package profiling contains two logical components: buffer.go and
  19. // profiling.go. The former implements a circular buffer (a.k.a. ring buffer)
  20. // in a lock-free manner using atomics. This ring buffer is used by
  21. // profiling.go to store various statistics. For example, StreamStats is a
  22. // circular buffer of Stat objects, each of which is comprised of Timers.
  23. //
  24. // This abstraction is designed to accommodate more stats in the future; for
  25. // example, if one wants to profile the load balancing layer, which is
  26. // independent of RPC queries, a separate CircularBuffer can be used.
  27. //
  28. // Note that the circular buffer simply takes any interface{}. In the future,
  29. // more types of measurements (such as the number of memory allocations) could
  30. // be measured, which might require a different type of object being pushed
  31. // into the circular buffer.
  32. package profiling
  33. import (
  34. "errors"
  35. "sync"
  36. "sync/atomic"
  37. "time"
  38. "google.golang.org/grpc/internal/profiling/buffer"
  39. )
  40. // 0 or 1 representing profiling off and on, respectively. Use IsEnabled and
  41. // Enable to get and set this in a safe manner.
  42. var profilingEnabled uint32
  43. // IsEnabled returns whether or not profiling is enabled.
  44. func IsEnabled() bool {
  45. return atomic.LoadUint32(&profilingEnabled) > 0
  46. }
  47. // Enable turns profiling on and off.
  48. //
  49. // Note that it is impossible to enable profiling for one server and leave it
  50. // turned off for another. This is intentional and by design -- if the status
  51. // of profiling was server-specific, clients wouldn't be able to profile
  52. // themselves. As a result, Enable turns profiling on and off for all servers
  53. // and clients in the binary. Each stat will be, however, tagged with whether
  54. // it's a client stat or a server stat; so you should be able to filter for the
  55. // right type of stats in post-processing.
  56. func Enable(enabled bool) {
  57. if enabled {
  58. atomic.StoreUint32(&profilingEnabled, 1)
  59. } else {
  60. atomic.StoreUint32(&profilingEnabled, 0)
  61. }
  62. }
  63. // A Timer represents the wall-clock beginning and ending of a logical
  64. // operation.
  65. type Timer struct {
  66. // Tags is a comma-separated list of strings (usually forward-slash-separated
  67. // hierarchical strings) used to categorize a Timer.
  68. Tags string
  69. // Begin marks the beginning of this timer. The timezone is unspecified, but
  70. // must use the same timezone as End; this is so shave off the small, but
  71. // non-zero time required to convert to a standard timezone such as UTC.
  72. Begin time.Time
  73. // End marks the end of a timer.
  74. End time.Time
  75. // Each Timer must be started and ended within the same goroutine; GoID
  76. // captures this goroutine ID. The Go runtime does not typically expose this
  77. // information, so this is set to zero in the typical case. However, a
  78. // trivial patch to the runtime package can make this field useful. See
  79. // goid_modified.go in this package for more details.
  80. GoID int64
  81. }
  82. // NewTimer creates and returns a new Timer object. This is useful when you
  83. // don't already have a Stat object to associate this Timer with; for example,
  84. // before the context of a new RPC query is created, a Timer may be needed to
  85. // measure transport-related operations.
  86. //
  87. // Use AppendTimer to append the returned Timer to a Stat.
  88. func NewTimer(tags string) *Timer {
  89. return &Timer{
  90. Tags: tags,
  91. Begin: time.Now(),
  92. GoID: goid(),
  93. }
  94. }
  95. // Egress sets the End field of a timer to the current time.
  96. func (timer *Timer) Egress() {
  97. if timer == nil {
  98. return
  99. }
  100. timer.End = time.Now()
  101. }
  102. // A Stat is a collection of Timers that represent timing information for
  103. // different components within this Stat. For example, a Stat may be used to
  104. // reference the entire lifetime of an RPC request, with Timers within it
  105. // representing different components such as encoding, compression, and
  106. // transport.
  107. //
  108. // The user is expected to use the included helper functions to do operations
  109. // on the Stat such as creating or appending a new timer. Direct operations on
  110. // the Stat's exported fields (which are exported for encoding reasons) may
  111. // lead to data races.
  112. type Stat struct {
  113. // Tags is a comma-separated list of strings used to categorize a Stat.
  114. Tags string
  115. // Stats may also need to store other unstructured information specific to
  116. // this stat. For example, a StreamStat will use these bytes to encode the
  117. // connection ID and stream ID for each RPC to uniquely identify it. The
  118. // encoding that must be used is unspecified.
  119. Metadata []byte
  120. // A collection of *Timers and a mutex for append operations on the slice.
  121. mu sync.Mutex
  122. Timers []*Timer
  123. }
  124. // A power of two that's large enough to hold all timers within an average RPC
  125. // request (defined to be a unary request) without any reallocation. A typical
  126. // unary RPC creates 80-100 timers for various things. While this number is
  127. // purely anecdotal and may change in the future as the resolution of profiling
  128. // increases or decreases, it serves as a good estimate for what the initial
  129. // allocation size should be.
  130. const defaultStatAllocatedTimers int32 = 128
  131. // NewStat creates and returns a new Stat object.
  132. func NewStat(tags string) *Stat {
  133. return &Stat{
  134. Tags: tags,
  135. Timers: make([]*Timer, 0, defaultStatAllocatedTimers),
  136. }
  137. }
  138. // NewTimer creates a Timer object within the given stat if stat is non-nil.
  139. // The value passed in tags will be attached to the newly created Timer.
  140. // NewTimer also automatically sets the Begin value of the Timer to the current
  141. // time. The user is expected to call stat.Egress with the returned index as
  142. // argument to mark the end.
  143. func (stat *Stat) NewTimer(tags string) *Timer {
  144. if stat == nil {
  145. return nil
  146. }
  147. timer := &Timer{
  148. Tags: tags,
  149. GoID: goid(),
  150. Begin: time.Now(),
  151. }
  152. stat.mu.Lock()
  153. stat.Timers = append(stat.Timers, timer)
  154. stat.mu.Unlock()
  155. return timer
  156. }
  157. // AppendTimer appends a given Timer object to the internal slice of timers. A
  158. // deep copy of the timer is made (i.e. no reference is retained to this
  159. // pointer) and the user is expected to lose their reference to the timer to
  160. // allow the Timer object to be garbage collected.
  161. func (stat *Stat) AppendTimer(timer *Timer) {
  162. if stat == nil || timer == nil {
  163. return
  164. }
  165. stat.mu.Lock()
  166. stat.Timers = append(stat.Timers, timer)
  167. stat.mu.Unlock()
  168. }
  169. // statsInitialized is 0 before InitStats has been called. Changed to 1 by
  170. // exactly one call to InitStats.
  171. var statsInitialized int32
  172. // Stats for the last defaultStreamStatsBufsize RPCs will be stored in memory.
  173. // This is can be configured by the registering server at profiling service
  174. // initialization with google.golang.org/grpc/profiling/service.ProfilingConfig
  175. const defaultStreamStatsSize uint32 = 16 << 10
  176. // StreamStats is a CircularBuffer containing data from the last N RPC calls
  177. // served, where N is set by the user. This will contain both server stats and
  178. // client stats (but each stat will be tagged with whether it's a server or a
  179. // client in its Tags).
  180. var StreamStats *buffer.CircularBuffer
  181. var errAlreadyInitialized = errors.New("profiling may be initialized at most once")
  182. // InitStats initializes all the relevant Stat objects. Must be called exactly
  183. // once per lifetime of a process; calls after the first one will return an
  184. // error.
  185. func InitStats(streamStatsSize uint32) error {
  186. var err error
  187. if !atomic.CompareAndSwapInt32(&statsInitialized, 0, 1) {
  188. return errAlreadyInitialized
  189. }
  190. if streamStatsSize == 0 {
  191. streamStatsSize = defaultStreamStatsSize
  192. }
  193. StreamStats, err = buffer.NewCircularBuffer(streamStatsSize)
  194. if err != nil {
  195. return err
  196. }
  197. return nil
  198. }