cubefs
525 строк · 14.6 Кб
1// Copyright 2015 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package timeseries implements a time series structure for stats collection.
6package timeseries // import "golang.org/x/net/internal/timeseries"
7
8import (
9"fmt"
10"log"
11"time"
12)
13
14const (
15timeSeriesNumBuckets = 64
16minuteHourSeriesNumBuckets = 60
17)
18
19var timeSeriesResolutions = []time.Duration{
201 * time.Second,
2110 * time.Second,
221 * time.Minute,
2310 * time.Minute,
241 * time.Hour,
256 * time.Hour,
2624 * time.Hour, // 1 day
277 * 24 * time.Hour, // 1 week
284 * 7 * 24 * time.Hour, // 4 weeks
2916 * 7 * 24 * time.Hour, // 16 weeks
30}
31
32var minuteHourSeriesResolutions = []time.Duration{
331 * time.Second,
341 * time.Minute,
35}
36
37// An Observable is a kind of data that can be aggregated in a time series.
38type Observable interface {
39Multiply(ratio float64) // Multiplies the data in self by a given ratio
40Add(other Observable) // Adds the data from a different observation to self
41Clear() // Clears the observation so it can be reused.
42CopyFrom(other Observable) // Copies the contents of a given observation to self
43}
44
45// Float attaches the methods of Observable to a float64.
46type Float float64
47
48// NewFloat returns a Float.
49func NewFloat() Observable {
50f := Float(0)
51return &f
52}
53
54// String returns the float as a string.
55func (f *Float) String() string { return fmt.Sprintf("%g", f.Value()) }
56
57// Value returns the float's value.
58func (f *Float) Value() float64 { return float64(*f) }
59
60func (f *Float) Multiply(ratio float64) { *f *= Float(ratio) }
61
62func (f *Float) Add(other Observable) {
63o := other.(*Float)
64*f += *o
65}
66
67func (f *Float) Clear() { *f = 0 }
68
69func (f *Float) CopyFrom(other Observable) {
70o := other.(*Float)
71*f = *o
72}
73
74// A Clock tells the current time.
75type Clock interface {
76Time() time.Time
77}
78
79type defaultClock int
80
81var defaultClockInstance defaultClock
82
83func (defaultClock) Time() time.Time { return time.Now() }
84
85// Information kept per level. Each level consists of a circular list of
86// observations. The start of the level may be derived from end and the
87// len(buckets) * sizeInMillis.
88type tsLevel struct {
89oldest int // index to oldest bucketed Observable
90newest int // index to newest bucketed Observable
91end time.Time // end timestamp for this level
92size time.Duration // duration of the bucketed Observable
93buckets []Observable // collections of observations
94provider func() Observable // used for creating new Observable
95}
96
97func (l *tsLevel) Clear() {
98l.oldest = 0
99l.newest = len(l.buckets) - 1
100l.end = time.Time{}
101for i := range l.buckets {
102if l.buckets[i] != nil {
103l.buckets[i].Clear()
104l.buckets[i] = nil
105}
106}
107}
108
109func (l *tsLevel) InitLevel(size time.Duration, numBuckets int, f func() Observable) {
110l.size = size
111l.provider = f
112l.buckets = make([]Observable, numBuckets)
113}
114
115// Keeps a sequence of levels. Each level is responsible for storing data at
116// a given resolution. For example, the first level stores data at a one
117// minute resolution while the second level stores data at a one hour
118// resolution.
119
120// Each level is represented by a sequence of buckets. Each bucket spans an
121// interval equal to the resolution of the level. New observations are added
122// to the last bucket.
123type timeSeries struct {
124provider func() Observable // make more Observable
125numBuckets int // number of buckets in each level
126levels []*tsLevel // levels of bucketed Observable
127lastAdd time.Time // time of last Observable tracked
128total Observable // convenient aggregation of all Observable
129clock Clock // Clock for getting current time
130pending Observable // observations not yet bucketed
131pendingTime time.Time // what time are we keeping in pending
132dirty bool // if there are pending observations
133}
134
135// init initializes a level according to the supplied criteria.
136func (ts *timeSeries) init(resolutions []time.Duration, f func() Observable, numBuckets int, clock Clock) {
137ts.provider = f
138ts.numBuckets = numBuckets
139ts.clock = clock
140ts.levels = make([]*tsLevel, len(resolutions))
141
142for i := range resolutions {
143if i > 0 && resolutions[i-1] >= resolutions[i] {
144log.Print("timeseries: resolutions must be monotonically increasing")
145break
146}
147newLevel := new(tsLevel)
148newLevel.InitLevel(resolutions[i], ts.numBuckets, ts.provider)
149ts.levels[i] = newLevel
150}
151
152ts.Clear()
153}
154
155// Clear removes all observations from the time series.
156func (ts *timeSeries) Clear() {
157ts.lastAdd = time.Time{}
158ts.total = ts.resetObservation(ts.total)
159ts.pending = ts.resetObservation(ts.pending)
160ts.pendingTime = time.Time{}
161ts.dirty = false
162
163for i := range ts.levels {
164ts.levels[i].Clear()
165}
166}
167
168// Add records an observation at the current time.
169func (ts *timeSeries) Add(observation Observable) {
170ts.AddWithTime(observation, ts.clock.Time())
171}
172
173// AddWithTime records an observation at the specified time.
174func (ts *timeSeries) AddWithTime(observation Observable, t time.Time) {
175
176smallBucketDuration := ts.levels[0].size
177
178if t.After(ts.lastAdd) {
179ts.lastAdd = t
180}
181
182if t.After(ts.pendingTime) {
183ts.advance(t)
184ts.mergePendingUpdates()
185ts.pendingTime = ts.levels[0].end
186ts.pending.CopyFrom(observation)
187ts.dirty = true
188} else if t.After(ts.pendingTime.Add(-1 * smallBucketDuration)) {
189// The observation is close enough to go into the pending bucket.
190// This compensates for clock skewing and small scheduling delays
191// by letting the update stay in the fast path.
192ts.pending.Add(observation)
193ts.dirty = true
194} else {
195ts.mergeValue(observation, t)
196}
197}
198
199// mergeValue inserts the observation at the specified time in the past into all levels.
200func (ts *timeSeries) mergeValue(observation Observable, t time.Time) {
201for _, level := range ts.levels {
202index := (ts.numBuckets - 1) - int(level.end.Sub(t)/level.size)
203if 0 <= index && index < ts.numBuckets {
204bucketNumber := (level.oldest + index) % ts.numBuckets
205if level.buckets[bucketNumber] == nil {
206level.buckets[bucketNumber] = level.provider()
207}
208level.buckets[bucketNumber].Add(observation)
209}
210}
211ts.total.Add(observation)
212}
213
214// mergePendingUpdates applies the pending updates into all levels.
215func (ts *timeSeries) mergePendingUpdates() {
216if ts.dirty {
217ts.mergeValue(ts.pending, ts.pendingTime)
218ts.pending = ts.resetObservation(ts.pending)
219ts.dirty = false
220}
221}
222
223// advance cycles the buckets at each level until the latest bucket in
224// each level can hold the time specified.
225func (ts *timeSeries) advance(t time.Time) {
226if !t.After(ts.levels[0].end) {
227return
228}
229for i := 0; i < len(ts.levels); i++ {
230level := ts.levels[i]
231if !level.end.Before(t) {
232break
233}
234
235// If the time is sufficiently far, just clear the level and advance
236// directly.
237if !t.Before(level.end.Add(level.size * time.Duration(ts.numBuckets))) {
238for _, b := range level.buckets {
239ts.resetObservation(b)
240}
241level.end = time.Unix(0, (t.UnixNano()/level.size.Nanoseconds())*level.size.Nanoseconds())
242}
243
244for t.After(level.end) {
245level.end = level.end.Add(level.size)
246level.newest = level.oldest
247level.oldest = (level.oldest + 1) % ts.numBuckets
248ts.resetObservation(level.buckets[level.newest])
249}
250
251t = level.end
252}
253}
254
255// Latest returns the sum of the num latest buckets from the level.
256func (ts *timeSeries) Latest(level, num int) Observable {
257now := ts.clock.Time()
258if ts.levels[0].end.Before(now) {
259ts.advance(now)
260}
261
262ts.mergePendingUpdates()
263
264result := ts.provider()
265l := ts.levels[level]
266index := l.newest
267
268for i := 0; i < num; i++ {
269if l.buckets[index] != nil {
270result.Add(l.buckets[index])
271}
272if index == 0 {
273index = ts.numBuckets
274}
275index--
276}
277
278return result
279}
280
281// LatestBuckets returns a copy of the num latest buckets from level.
282func (ts *timeSeries) LatestBuckets(level, num int) []Observable {
283if level < 0 || level > len(ts.levels) {
284log.Print("timeseries: bad level argument: ", level)
285return nil
286}
287if num < 0 || num >= ts.numBuckets {
288log.Print("timeseries: bad num argument: ", num)
289return nil
290}
291
292results := make([]Observable, num)
293now := ts.clock.Time()
294if ts.levels[0].end.Before(now) {
295ts.advance(now)
296}
297
298ts.mergePendingUpdates()
299
300l := ts.levels[level]
301index := l.newest
302
303for i := 0; i < num; i++ {
304result := ts.provider()
305results[i] = result
306if l.buckets[index] != nil {
307result.CopyFrom(l.buckets[index])
308}
309
310if index == 0 {
311index = ts.numBuckets
312}
313index -= 1
314}
315return results
316}
317
318// ScaleBy updates observations by scaling by factor.
319func (ts *timeSeries) ScaleBy(factor float64) {
320for _, l := range ts.levels {
321for i := 0; i < ts.numBuckets; i++ {
322l.buckets[i].Multiply(factor)
323}
324}
325
326ts.total.Multiply(factor)
327ts.pending.Multiply(factor)
328}
329
330// Range returns the sum of observations added over the specified time range.
331// If start or finish times don't fall on bucket boundaries of the same
332// level, then return values are approximate answers.
333func (ts *timeSeries) Range(start, finish time.Time) Observable {
334return ts.ComputeRange(start, finish, 1)[0]
335}
336
337// Recent returns the sum of observations from the last delta.
338func (ts *timeSeries) Recent(delta time.Duration) Observable {
339now := ts.clock.Time()
340return ts.Range(now.Add(-delta), now)
341}
342
343// Total returns the total of all observations.
344func (ts *timeSeries) Total() Observable {
345ts.mergePendingUpdates()
346return ts.total
347}
348
349// ComputeRange computes a specified number of values into a slice using
350// the observations recorded over the specified time period. The return
351// values are approximate if the start or finish times don't fall on the
352// bucket boundaries at the same level or if the number of buckets spanning
353// the range is not an integral multiple of num.
354func (ts *timeSeries) ComputeRange(start, finish time.Time, num int) []Observable {
355if start.After(finish) {
356log.Printf("timeseries: start > finish, %v>%v", start, finish)
357return nil
358}
359
360if num < 0 {
361log.Printf("timeseries: num < 0, %v", num)
362return nil
363}
364
365results := make([]Observable, num)
366
367for _, l := range ts.levels {
368if !start.Before(l.end.Add(-l.size * time.Duration(ts.numBuckets))) {
369ts.extract(l, start, finish, num, results)
370return results
371}
372}
373
374// Failed to find a level that covers the desired range. So just
375// extract from the last level, even if it doesn't cover the entire
376// desired range.
377ts.extract(ts.levels[len(ts.levels)-1], start, finish, num, results)
378
379return results
380}
381
382// RecentList returns the specified number of values in slice over the most
383// recent time period of the specified range.
384func (ts *timeSeries) RecentList(delta time.Duration, num int) []Observable {
385if delta < 0 {
386return nil
387}
388now := ts.clock.Time()
389return ts.ComputeRange(now.Add(-delta), now, num)
390}
391
392// extract returns a slice of specified number of observations from a given
393// level over a given range.
394func (ts *timeSeries) extract(l *tsLevel, start, finish time.Time, num int, results []Observable) {
395ts.mergePendingUpdates()
396
397srcInterval := l.size
398dstInterval := finish.Sub(start) / time.Duration(num)
399dstStart := start
400srcStart := l.end.Add(-srcInterval * time.Duration(ts.numBuckets))
401
402srcIndex := 0
403
404// Where should scanning start?
405if dstStart.After(srcStart) {
406advance := int(dstStart.Sub(srcStart) / srcInterval)
407srcIndex += advance
408srcStart = srcStart.Add(time.Duration(advance) * srcInterval)
409}
410
411// The i'th value is computed as show below.
412// interval = (finish/start)/num
413// i'th value = sum of observation in range
414// [ start + i * interval,
415// start + (i + 1) * interval )
416for i := 0; i < num; i++ {
417results[i] = ts.resetObservation(results[i])
418dstEnd := dstStart.Add(dstInterval)
419for srcIndex < ts.numBuckets && srcStart.Before(dstEnd) {
420srcEnd := srcStart.Add(srcInterval)
421if srcEnd.After(ts.lastAdd) {
422srcEnd = ts.lastAdd
423}
424
425if !srcEnd.Before(dstStart) {
426srcValue := l.buckets[(srcIndex+l.oldest)%ts.numBuckets]
427if !srcStart.Before(dstStart) && !srcEnd.After(dstEnd) {
428// dst completely contains src.
429if srcValue != nil {
430results[i].Add(srcValue)
431}
432} else {
433// dst partially overlaps src.
434overlapStart := maxTime(srcStart, dstStart)
435overlapEnd := minTime(srcEnd, dstEnd)
436base := srcEnd.Sub(srcStart)
437fraction := overlapEnd.Sub(overlapStart).Seconds() / base.Seconds()
438
439used := ts.provider()
440if srcValue != nil {
441used.CopyFrom(srcValue)
442}
443used.Multiply(fraction)
444results[i].Add(used)
445}
446
447if srcEnd.After(dstEnd) {
448break
449}
450}
451srcIndex++
452srcStart = srcStart.Add(srcInterval)
453}
454dstStart = dstStart.Add(dstInterval)
455}
456}
457
458// resetObservation clears the content so the struct may be reused.
459func (ts *timeSeries) resetObservation(observation Observable) Observable {
460if observation == nil {
461observation = ts.provider()
462} else {
463observation.Clear()
464}
465return observation
466}
467
468// TimeSeries tracks data at granularities from 1 second to 16 weeks.
469type TimeSeries struct {
470timeSeries
471}
472
473// NewTimeSeries creates a new TimeSeries using the function provided for creating new Observable.
474func NewTimeSeries(f func() Observable) *TimeSeries {
475return NewTimeSeriesWithClock(f, defaultClockInstance)
476}
477
478// NewTimeSeriesWithClock creates a new TimeSeries using the function provided for creating new Observable and the clock for
479// assigning timestamps.
480func NewTimeSeriesWithClock(f func() Observable, clock Clock) *TimeSeries {
481ts := new(TimeSeries)
482ts.timeSeries.init(timeSeriesResolutions, f, timeSeriesNumBuckets, clock)
483return ts
484}
485
486// MinuteHourSeries tracks data at granularities of 1 minute and 1 hour.
487type MinuteHourSeries struct {
488timeSeries
489}
490
491// NewMinuteHourSeries creates a new MinuteHourSeries using the function provided for creating new Observable.
492func NewMinuteHourSeries(f func() Observable) *MinuteHourSeries {
493return NewMinuteHourSeriesWithClock(f, defaultClockInstance)
494}
495
496// NewMinuteHourSeriesWithClock creates a new MinuteHourSeries using the function provided for creating new Observable and the clock for
497// assigning timestamps.
498func NewMinuteHourSeriesWithClock(f func() Observable, clock Clock) *MinuteHourSeries {
499ts := new(MinuteHourSeries)
500ts.timeSeries.init(minuteHourSeriesResolutions, f,
501minuteHourSeriesNumBuckets, clock)
502return ts
503}
504
505func (ts *MinuteHourSeries) Minute() Observable {
506return ts.timeSeries.Latest(0, 60)
507}
508
509func (ts *MinuteHourSeries) Hour() Observable {
510return ts.timeSeries.Latest(1, 60)
511}
512
513func minTime(a, b time.Time) time.Time {
514if a.Before(b) {
515return a
516}
517return b
518}
519
520func maxTime(a, b time.Time) time.Time {
521if a.After(b) {
522return a
523}
524return b
525}
526