github.com/google/cadvisor@v0.49.1/summary/buffer.go (about) 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 15 package summary 16 17 import ( 18 info "github.com/google/cadvisor/info/v2" 19 ) 20 21 // Manages a buffer of usage samples. 22 // This is similar to stats buffer in cache/memory. 23 // The main difference is that we do not pre-allocate the buffer as most containers 24 // won't live that long. 25 type SamplesBuffer struct { 26 // list of collected samples. 27 samples []info.Usage 28 // maximum size this buffer can grow to. 29 maxSize int 30 // index for the latest sample. 31 index int 32 } 33 34 // Initializes an empty buffer. 35 func NewSamplesBuffer(size int) *SamplesBuffer { 36 return &SamplesBuffer{ 37 index: -1, 38 maxSize: size, 39 } 40 } 41 42 // Returns the current number of samples in the buffer. 43 func (s *SamplesBuffer) Size() int { 44 return len(s.samples) 45 } 46 47 // Add an element to the buffer. Oldest one is overwritten if required. 48 func (s *SamplesBuffer) Add(stat info.Usage) { 49 if len(s.samples) < s.maxSize { 50 s.samples = append(s.samples, stat) 51 s.index++ 52 return 53 } 54 s.index = (s.index + 1) % s.maxSize 55 s.samples[s.index] = stat 56 } 57 58 // Returns pointers to the last 'n' stats. 59 func (s *SamplesBuffer) RecentStats(n int) []*info.Usage { 60 if n > len(s.samples) { 61 n = len(s.samples) 62 } 63 start := s.index - (n - 1) 64 if start < 0 { 65 start += len(s.samples) 66 } 67 68 out := make([]*info.Usage, n) 69 for i := 0; i < n; i++ { 70 index := (start + i) % len(s.samples) 71 out[i] = &s.samples[index] 72 } 73 return out 74 }