yats.git

ref: a87c1c994f12dc502708a4722f5887ca802a16b2

server/db/metric.go


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package db

import (
	"fmt"
	"time"
	"yats-server/model"

	"github.com/gocql/gocql"
)

type MetricModel struct {
	ID_client string    `json:"id_client"`
	Mtime     time.Time `json:"mtime"`
	Name      string    `json:"name"`
	Value     string    `json:"value"`
}

func PrintMetrics(metrics []model.MetricRequest) {
	for _, metric := range metrics {
		fmt.Printf("%s\n", metric.Name)
	}
}

func LoadMetrics(session *gocql.Session) []model.MetricRequest {
	var metrics []model.MetricRequest
	m := map[string]interface{}{}

	iter := session.Query("SELECT  id_client, mtime, name, value FROM metric").Iter()
	for iter.MapScan(m) {
		metrics = append(metrics, model.MetricRequest{
			ID_client: m["id_client"].(string),
			Mtime:     m["mtime"].(time.Time).UnixMilli(),
			Name:      m["name"].(string),
			Value:     m["value"].(string),
		})

		m = map[string]interface{}{}
	}
	return metrics
}

func OLDLoadMetrics(session *gocql.Session) []MetricModel {
	var metrics []MetricModel
	m := map[string]interface{}{}

	iter := session.Query("SELECT  id_client, mtime, name, value FROM metric").Iter()
	for iter.MapScan(m) {
		metrics = append(metrics, MetricModel{
			ID_client: m["id_client"].(string),
			Mtime:     m["mtime"].(time.Time),
			Name:      m["name"].(string),
			Value:     m["value"].(string),
		})

		m = map[string]interface{}{}
	}
	return metrics
}

func SaveMetric(idClient string, metricName string, metricValue string) {
	q := fmt.Sprintf("insert into metric ( id_client, mtime, name, value) values ('%s',toTimestamp(now()),'%s','%s');", idClient, metricName, metricValue)
	Session.Query(q).Exec()
}

func SaveMetricAt(idClient string, tstamp time.Time, metricName string, metricValue string) {
	timeAsBytes, _ := tstamp.UTC().MarshalText()
	q := fmt.Sprintf("insert into metric ( id_client, mtime, name, value) values ('%s','%s','%s','%s');", idClient, string(timeAsBytes), metricName, metricValue)
	Session.Query(q).Exec()
}