github.com/GuanceCloud/cliutils@v1.1.21/point/new_point.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  package point
     7  
     8  import (
     9  	"sort"
    10  	"time"
    11  )
    12  
    13  func NewPointV2(name string, kvs KVs, opts ...Option) *Point {
    14  	c := GetCfg(opts...)
    15  	defer PutCfg(c)
    16  
    17  	return doNewPoint(name, kvs, c)
    18  }
    19  
    20  // NewPoint returns a new Point given name(measurement), tags, fields and optional options.
    21  //
    22  // If fields empty(or nil), error ErrNoField will returned.
    23  //
    24  // Values in fields only allowed for int/uint(8-bit/16-bit/32-bit/64-bit), string, bool,
    25  // float(32-bit/64-bit) and []byte, other types are ignored.
    26  //
    27  // Deprecated: use NewPointV2.
    28  func NewPoint(name string, tags map[string]string, fields map[string]any, opts ...Option) (*Point, error) {
    29  	if len(fields) == 0 {
    30  		return nil, ErrNoFields
    31  	}
    32  
    33  	kvs := NewKVs(fields)
    34  	for k, v := range tags {
    35  		kvs = kvs.MustAddTag(k, v) // force add these tags
    36  	}
    37  
    38  	c := GetCfg(opts...)
    39  	defer PutCfg(c)
    40  
    41  	return doNewPoint(name, kvs, c), nil
    42  }
    43  
    44  func doNewPoint(name string, kvs KVs, c *cfg) *Point {
    45  	var pt *Point
    46  
    47  	if defaultPTPool != nil {
    48  		pt = defaultPTPool.Get()
    49  
    50  		pt.SetName(name)
    51  		pt.pt.Fields = kvs
    52  		pt.SetFlag(Ppooled)
    53  	} else {
    54  		pt = &Point{
    55  			pt: &PBPoint{
    56  				Name:   name,
    57  				Fields: kvs,
    58  			},
    59  		}
    60  	}
    61  
    62  	// add extra tags
    63  	if len(c.extraTags) > 0 {
    64  		for _, kv := range c.extraTags {
    65  			pt.AddTag(kv.Key, kv.GetS()) // NOTE: do-not-override exist keys
    66  		}
    67  	}
    68  
    69  	if c.enc == Protobuf {
    70  		pt.SetFlag(Ppb)
    71  	}
    72  
    73  	if c.keySorted {
    74  		kvs := KVs(pt.pt.Fields)
    75  		sort.Sort(kvs)
    76  		pt.pt.Fields = kvs
    77  	}
    78  
    79  	if c.precheck {
    80  		chk := checker{cfg: c}
    81  		pt = chk.check(pt)
    82  		pt.SetFlag(Pcheck)
    83  	}
    84  
    85  	// sort again: during check, kv maybe update
    86  	if c.keySorted {
    87  		sort.Sort(KVs(pt.pt.Fields))
    88  	}
    89  
    90  	if c.timestamp >= 0 {
    91  		pt.pt.Time = c.timestamp
    92  	} else { // not set, use current time
    93  		pt.pt.Time = time.Now().Round(0).UnixNano() // trim monotonic clock
    94  	}
    95  
    96  	return pt
    97  }