@@ -13,24 +13,20 @@ import (
1313 "github.com/influxdata/influxdb-client-go/v2/api/write"
1414)
1515
16- //type Metric struct {
17- // Name string `json:"__name__"`
18- // Db string
19- //}
20-
2116type MetricLine struct {
22- //Metric Metric
23- //Values []float64
2417 Timestamps []int64
2518}
2619
27- func WriteMetrics (records []* ElectricUsage , config InfluxDB ) {
20+ func WriteMetrics (records []* ElectricUsage , config InfluxDB , existingPoints map [ int64 ] struct {} ) {
2821 client := influxdb2 .NewClient (config .Host , config .User + ":" + config .Password )
2922 writeApi := client .WriteAPIBlocking ("" , config .Database )
3023 points := make ([]* write.Point , 0 , 15 * 2 * len (records ))
3124 for _ , record := range records {
3225 divisor := record .EndTime .Sub (record .StartTime ).Minutes ()
3326 for t := record .StartTime ; record .EndTime .After (t ); t = t .Add (time .Minute ) {
27+ if _ , ok := existingPoints [t .Unix ()]; ok {
28+ continue
29+ }
3430 watts := influxdb2 .NewPointWithMeasurement ("electric" ).
3531 SetTime (t ).
3632 AddField ("usage" , float64 (record .WattHours )/ divisor )
@@ -45,18 +41,9 @@ func WriteMetrics(records []*ElectricUsage, config InfluxDB) {
4541 if err != nil {
4642 log .Fatal (err )
4743 }
48- // query VM for metrics that already exist in the range we're trying to insert?
49- // if that's too much work, then just maintain last-inserted-time and don't insert newer
50- log .Println (points )
5144}
5245
53- // the goal here is to not double write any metrics
54- // therefore, we should simply filter inserted points by any points that
55- // already exist.
56- // the algorithm for that is to run this query first, making a map[time]struct{}
57- // and discarding any point in WriteMetrics that exists in the map.
58-
59- func QueryPreviousMetrics (startTime time.Time , endTime time.Time , config InfluxDB ) map [int64 ]struct {} {
46+ func QueryPreviousMetrics (startTime time.Time , endTime time.Time , config InfluxDB ) (map [int64 ]struct {}, error ) {
6047 client := & http.Client {}
6148 v := url.Values {
6249 "match[]" : {"sensor_temperature" },
@@ -65,13 +52,13 @@ func QueryPreviousMetrics(startTime time.Time, endTime time.Time, config InfluxD
6552 }
6653 req , err := http .NewRequest ("POST" , config .Host + "/api/v1/export" , strings .NewReader (v .Encode ()))
6754 if err != nil {
68- log . Fatal ( err )
55+ return nil , err
6956 }
7057 req .Header .Add ("Content-Type" , "application/x-www-form-urlencoded" )
7158 req .SetBasicAuth (config .User , config .Password )
7259 resp , err := client .Do (req )
7360 if err != nil {
74- log . Fatal ( err )
61+ return nil , err
7562 }
7663 defer func () {
7764 err := resp .Body .Close ()
@@ -90,5 +77,5 @@ func QueryPreviousMetrics(startTime time.Time, endTime time.Time, config InfluxD
9077 existing [ts ] = struct {}{}
9178 }
9279 }
93- return existing
80+ return existing , nil
9481}
0 commit comments