generated from xmidt-org/.go-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
queueTimer.go
103 lines (81 loc) · 2.54 KB
/
queueTimer.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// SPDX-FileCopyrightText: 2020 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"github.com/xmidt-org/webpa-common/v2/logging" // nolint: staticcheck
)
type Content struct {
Status string
Data Data
}
type Data struct {
ResultType string
Result []Result
}
type Result struct {
Metric Metric
Value []interface{}
}
type Metric struct {
Url string
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func (app *App) calculateDuration(cutoffTime time.Time) {
logging.Info(app.logger).Log(logging.MessageKey(), "entered duration function")
var client = &http.Client{
Timeout: app.timeoutPrometheus,
}
encodedQuery := url.QueryEscape(app.queryExpression)
req, err := http.NewRequest("GET", fmt.Sprintf("%s?query=%s", app.queryURL, encodedQuery), nil)
if err != nil {
logging.Error(app.logger).Log(logging.MessageKey(), "failed to get prometheus url", logging.ErrorKey(), err.Error())
}
req.Header.Add("Authorization", app.prometheusAuth)
logging.Info(app.logger).Log(logging.MessageKey(), "added authorization")
for {
currentTime := time.Now()
res, err := client.Do(req)
if err != nil {
logging.Error(app.logger).Log(logging.MessageKey(), "failed to query prometheus", logging.ErrorKey(), err.Error())
return
} else {
defer res.Body.Close()
contents, err := io.ReadAll(res.Body)
if err != nil {
logging.Error(app.logger).Log(logging.MessageKey(), "failed to read body", logging.ErrorKey(), err.Error())
}
var content Content
if err := json.Unmarshal(contents, &content); err != nil {
logging.Error(app.logger).Log(logging.MessageKey(), "unable to unmarshal prometheus query body", logging.ErrorKey(), err, "contents", string(contents))
return
}
if content.Data.ResultType == "vector" {
for _, results := range content.Data.Result {
// only calculating duration once queue size reaches 0
val, _ := strconv.Atoi(results.Value[1].(string))
if contains(app.webhookURLs, results.Metric.Url) && val <= 500 {
// putting calculated duration into histogram metric
app.measures.TrackTime(currentTime.Sub(cutoffTime))
logging.Info(app.logger).Log(logging.MessageKey(), "time queue is 0: "+currentTime.String())
logging.Info(app.logger).Log(logging.MessageKey(), "sent histogram metric to prometheus: "+currentTime.Sub(cutoffTime).String())
return
}
}
}
}
}
}