buffer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2015 Google Inc. All Rights Reserved.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package summary
  15. import (
  16. info "github.com/google/cadvisor/info/v2"
  17. )
  18. // Manages a buffer of usage samples.
  19. // This is similar to stats buffer in cache/memory.
  20. // The main difference is that we do not pre-allocate the buffer as most containers
  21. // won't live that long.
  22. type SamplesBuffer struct {
  23. // list of collected samples.
  24. samples []info.Usage
  25. // maximum size this buffer can grow to.
  26. maxSize int
  27. // index for the latest sample.
  28. index int
  29. }
  30. // Initializes an empty buffer.
  31. func NewSamplesBuffer(size int) *SamplesBuffer {
  32. return &SamplesBuffer{
  33. index: -1,
  34. maxSize: size,
  35. }
  36. }
  37. // Returns the current number of samples in the buffer.
  38. func (s *SamplesBuffer) Size() int {
  39. return len(s.samples)
  40. }
  41. // Add an element to the buffer. Oldest one is overwritten if required.
  42. func (s *SamplesBuffer) Add(stat info.Usage) {
  43. if len(s.samples) < s.maxSize {
  44. s.samples = append(s.samples, stat)
  45. s.index++
  46. return
  47. }
  48. s.index = (s.index + 1) % s.maxSize
  49. s.samples[s.index] = stat
  50. }
  51. // Returns pointers to the last 'n' stats.
  52. func (s *SamplesBuffer) RecentStats(n int) []*info.Usage {
  53. if n > len(s.samples) {
  54. n = len(s.samples)
  55. }
  56. start := s.index - (n - 1)
  57. if start < 0 {
  58. start += len(s.samples)
  59. }
  60. out := make([]*info.Usage, n)
  61. for i := 0; i < n; i++ {
  62. index := (start + i) % len(s.samples)
  63. out[i] = &s.samples[index]
  64. }
  65. return out
  66. }