metrics_cached.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 volume
  14. import (
  15. "sync"
  16. "sync/atomic"
  17. )
  18. var _ MetricsProvider = &cachedMetrics{}
  19. // cachedMetrics represents a MetricsProvider that wraps another provider and
  20. // caches the result.
  21. type cachedMetrics struct {
  22. wrapped MetricsProvider
  23. resultError error
  24. resultMetrics *Metrics
  25. once cacheOnce
  26. }
  27. // NewCachedMetrics creates a new cachedMetrics wrapping another
  28. // MetricsProvider and caching the results.
  29. func NewCachedMetrics(provider MetricsProvider) MetricsProvider {
  30. return &cachedMetrics{wrapped: provider}
  31. }
  32. // GetMetrics runs the wrapped metrics provider's GetMetrics methd once and
  33. // caches the result. Will not cache result if there is an error.
  34. // See MetricsProvider.GetMetrics
  35. func (md *cachedMetrics) GetMetrics() (*Metrics, error) {
  36. md.once.cache(func() error {
  37. md.resultMetrics, md.resultError = md.wrapped.GetMetrics()
  38. return md.resultError
  39. })
  40. return md.resultMetrics, md.resultError
  41. }
  42. // Copied from sync.Once but we don't want to cache the results if there is an
  43. // error
  44. type cacheOnce struct {
  45. m sync.Mutex
  46. done uint32
  47. }
  48. // Copied from sync.Once but we don't want to cache the results if there is an
  49. // error
  50. func (o *cacheOnce) cache(f func() error) {
  51. if atomic.LoadUint32(&o.done) == 1 {
  52. return
  53. }
  54. // Slow-path.
  55. o.m.Lock()
  56. defer o.m.Unlock()
  57. if o.done == 0 {
  58. err := f()
  59. if err == nil {
  60. atomic.StoreUint32(&o.done, 1)
  61. }
  62. }
  63. }