-
Notifications
You must be signed in to change notification settings - Fork 0
/
metric.go
64 lines (51 loc) · 1.29 KB
/
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
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"time"
"github.com/openfaas/faas/gateway/metrics"
)
type MetricConfig struct {
Host string
Port int
InactivityDuration uint32
}
func NewMetric(host string, port int, inactivityDuration uint32) (*MetricConfig, error) {
return &MetricConfig{
Host: host,
Port: port,
InactivityDuration: inactivityDuration,
}, nil
}
func (c *MetricConfig) Get(functionName string) (float64, error) {
var metric float64
duration := fmt.Sprintf("%dm", c.InactivityDuration)
queryStr := url.QueryEscape(`sum(rate(gateway_function_invocation_total{function_name="` + functionName + `"}[` + duration + `]))`)
client := &http.Client{
Timeout: time.Second * 10,
}
query := metrics.NewPrometheusQuery(c.Host, c.Port, client)
response, err := query.Fetch(queryStr)
if err != nil {
return -1.0, err
}
for _, v := range response.Data.Result {
if v.Metric.FunctionName == functionName {
metricValue := v.Value[1]
switch metricValue.(type) {
case string:
f, err := strconv.ParseFloat(metricValue.(string), 64)
if err != nil {
log.Printf("unable to convert value for metric: %s\n", err)
continue
}
metric = f
break
}
}
}
return metric, nil
}