github.com/google/cloudprober@v0.11.3/metrics/metrics.go (about)

     1  // Copyright 2017 The Cloudprober 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 metrics implements data types for probes generated data.
    16  package metrics
    17  
    18  import (
    19  	"errors"
    20  	"strconv"
    21  	"strings"
    22  )
    23  
    24  // Value represents any metric value
    25  type Value interface {
    26  	Clone() Value
    27  	Add(delta Value) error
    28  	AddInt64(i int64)
    29  	AddFloat64(f float64)
    30  	String() string
    31  
    32  	// SubtractCounter subtracts the provided "lastVal", assuming that value
    33  	// represents a counter, i.e. if "value" is less than the "lastVal", we
    34  	// assume that counter has been reset and don't subtract.
    35  	SubtractCounter(last Value) (wasReset bool, err error)
    36  }
    37  
    38  // NumValue represents any numerical metric value, e.g. Int, Float.
    39  // It's a superset of Value interface.
    40  type NumValue interface {
    41  	Value
    42  	Inc()
    43  	Int64() int64
    44  	Float64() float64
    45  	IncBy(delta NumValue)
    46  }
    47  
    48  // ParseValueFromString parses a value from its string representation
    49  func ParseValueFromString(val string) (Value, error) {
    50  	c := val[0]
    51  	switch {
    52  	// A float value
    53  	case '0' <= c && c <= '9':
    54  		f, err := strconv.ParseFloat(val, 64)
    55  		if err != nil {
    56  			return nil, err
    57  		}
    58  		return NewFloat(f), nil
    59  
    60  	// A map value
    61  	case c == 'm':
    62  		if !strings.HasPrefix(val, "map") {
    63  			break
    64  		}
    65  		return ParseMapFromString(val)
    66  
    67  	// A string value
    68  	case c == '"':
    69  		return NewString(strings.Trim(val, "\"")), nil
    70  
    71  	// A distribution value
    72  	case c == 'd':
    73  		if !strings.HasPrefix(val, "dist") {
    74  			break
    75  		}
    76  		distVal, err := ParseDistFromString(val)
    77  		if err != nil {
    78  			return nil, err
    79  		}
    80  		return distVal, nil
    81  	}
    82  
    83  	return nil, errors.New("unknown value type")
    84  }