istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/loadbalancersim/timeseries/instance.go (about)

     1  //  Copyright Istio Authors
     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 timeseries
    16  
    17  import (
    18  	"sync"
    19  	"time"
    20  )
    21  
    22  type Instance struct {
    23  	data  Data
    24  	times times
    25  	mutex sync.Mutex
    26  }
    27  
    28  func (ts *Instance) AddObservation(val float64, t time.Time) {
    29  	ts.mutex.Lock()
    30  	defer ts.mutex.Unlock()
    31  	ts.data = append(ts.data, val)
    32  	ts.times = append(ts.times, t)
    33  }
    34  
    35  func (ts *Instance) AddAll(o *Instance) {
    36  	ts.mutex.Lock()
    37  	defer ts.mutex.Unlock()
    38  
    39  	oData, oTimes := o.Series()
    40  	ts.data = append(ts.data, oData...)
    41  	ts.times = append(ts.times, oTimes...)
    42  }
    43  
    44  func (ts *Instance) Data() Data {
    45  	ts.mutex.Lock()
    46  	defer ts.mutex.Unlock()
    47  	return ts.data.Copy()
    48  }
    49  
    50  func (ts *Instance) Series() (Data, []time.Time) {
    51  	ts.mutex.Lock()
    52  	defer ts.mutex.Unlock()
    53  	return ts.data.Copy(), ts.times.copy()
    54  }
    55  
    56  func (ts *Instance) SeriesAsDurationSinceEpoch(epoch time.Time) (Data, []time.Duration) {
    57  	ts.mutex.Lock()
    58  	defer ts.mutex.Unlock()
    59  	return ts.data.Copy(), ts.times.asDurationSinceEpoch(epoch)
    60  }
    61  
    62  type times []time.Time
    63  
    64  func (t times) copy() times {
    65  	out := make(times, 0, len(t))
    66  	out = append(out, t...)
    67  	return out
    68  }
    69  
    70  func (t times) asDurationSinceEpoch(epoch time.Time) []time.Duration {
    71  	out := make([]time.Duration, 0, len(t))
    72  	for _, tm := range t {
    73  		out = append(out, tm.Sub(epoch))
    74  	}
    75  	return out
    76  }