bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/bosun/database/metric_metadata.go (about)

     1  package database
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/garyburd/redigo/redis"
     8  )
     9  
    10  /*
    11  Metric metadata is the fields associated with every metric: desc, rate and unit.
    12  They are stored as a simple hash structure:
    13  
    14  mmeta:{{metric}} -> {desc:"",unit:"",rate:"",lastTouched:123}
    15  
    16  lastTouched time is unix timestamp of last time this metric metadata was set.
    17  
    18  */
    19  
    20  func metricMetaKey(metric string) string {
    21  	return fmt.Sprintf("mmeta:%s", metric)
    22  }
    23  
    24  const metricMetaTTL = int((time.Hour * 24 * 7) / time.Second)
    25  
    26  func (d *dataAccess) Metadata() MetadataDataAccess {
    27  	return d
    28  }
    29  
    30  func (d *dataAccess) PutMetricMetadata(metric string, field string, value string) error {
    31  	if field != "desc" && field != "unit" && field != "rate" {
    32  		return fmt.Errorf("Unknown metric metadata field: %s", field)
    33  	}
    34  	conn := d.Get()
    35  	defer conn.Close()
    36  	_, err := conn.Do("HMSET", metricMetaKey(metric), field, value, "lastTouched", time.Now().UTC().Unix())
    37  	return err
    38  }
    39  
    40  func (d *dataAccess) GetMetricMetadata(metric string) (*MetricMetadata, error) {
    41  	conn := d.Get()
    42  	defer conn.Close()
    43  	v, err := redis.Values(conn.Do("HGETALL", metricMetaKey(metric)))
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	if len(v) == 0 {
    48  		return nil, nil
    49  	}
    50  	mm := &MetricMetadata{}
    51  	if err := redis.ScanStruct(v, mm); err != nil {
    52  		return nil, err
    53  	}
    54  	return mm, nil
    55  }