Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/metrics/http.go
4093 views
1
package metrics
2
3
import (
4
"fmt"
5
"net/http"
6
"net/url"
7
"sort"
8
"time"
9
10
"github.com/go-kit/log/level"
11
"github.com/gorilla/mux"
12
"github.com/grafana/agent/pkg/metrics/cluster/configapi"
13
"github.com/prometheus/common/model"
14
"github.com/prometheus/prometheus/model/labels"
15
"github.com/prometheus/prometheus/scrape"
16
"github.com/prometheus/prometheus/storage/remote"
17
)
18
19
// WireAPI adds API routes to the provided mux router.
20
func (a *Agent) WireAPI(r *mux.Router) {
21
a.cluster.WireAPI(r)
22
23
// Backwards compatible endpoints. Use endpoints with `metrics` prefix instead
24
r.HandleFunc("/agent/api/v1/instances", a.ListInstancesHandler).Methods("GET")
25
r.HandleFunc("/agent/api/v1/targets", a.ListTargetsHandler).Methods("GET")
26
27
r.HandleFunc("/agent/api/v1/metrics/instances", a.ListInstancesHandler).Methods("GET")
28
r.HandleFunc("/agent/api/v1/metrics/targets", a.ListTargetsHandler).Methods("GET")
29
r.HandleFunc("/agent/api/v1/metrics/instance/{instance}/write", a.PushMetricsHandler).Methods("POST")
30
}
31
32
// ListInstancesHandler writes the set of currently running instances to the http.ResponseWriter.
33
func (a *Agent) ListInstancesHandler(w http.ResponseWriter, _ *http.Request) {
34
cfgs := a.mm.ListConfigs()
35
instanceNames := make([]string, 0, len(cfgs))
36
for k := range cfgs {
37
instanceNames = append(instanceNames, k)
38
}
39
sort.Strings(instanceNames)
40
41
err := configapi.WriteResponse(w, http.StatusOK, instanceNames)
42
if err != nil {
43
level.Error(a.logger).Log("msg", "failed to write response", "err", err)
44
}
45
}
46
47
// ListTargetsHandler retrieves the full set of targets across all instances and shows
48
// information on them.
49
func (a *Agent) ListTargetsHandler(w http.ResponseWriter, r *http.Request) {
50
instances := a.mm.ListInstances()
51
allTagets := make(map[string]TargetSet, len(instances))
52
for instName, inst := range instances {
53
allTagets[instName] = inst.TargetsActive()
54
}
55
ListTargetsHandler(allTagets).ServeHTTP(w, r)
56
}
57
58
// ListTargetsHandler renders a mapping of instance to target set.
59
func ListTargetsHandler(targets map[string]TargetSet) http.Handler {
60
return http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
61
resp := ListTargetsResponse{}
62
63
for instance, tset := range targets {
64
for key, targets := range tset {
65
for _, tgt := range targets {
66
var lastError string
67
if scrapeError := tgt.LastError(); scrapeError != nil {
68
lastError = scrapeError.Error()
69
}
70
71
resp = append(resp, TargetInfo{
72
InstanceName: instance,
73
TargetGroup: key,
74
75
Endpoint: tgt.URL().String(),
76
State: string(tgt.Health()),
77
DiscoveredLabels: tgt.DiscoveredLabels(),
78
Labels: tgt.Labels(),
79
LastScrape: tgt.LastScrape(),
80
ScrapeDuration: tgt.LastScrapeDuration().Milliseconds(),
81
ScrapeError: lastError,
82
})
83
}
84
}
85
}
86
87
sort.Slice(resp, func(i, j int) bool {
88
// sort by instance, then target group, then job label, then instance label
89
var (
90
iInstance = resp[i].InstanceName
91
iTargetGroup = resp[i].TargetGroup
92
iJobLabel = resp[i].Labels.Get(model.JobLabel)
93
iInstanceLabel = resp[i].Labels.Get(model.InstanceLabel)
94
95
jInstance = resp[j].InstanceName
96
jTargetGroup = resp[j].TargetGroup
97
jJobLabel = resp[j].Labels.Get(model.JobLabel)
98
jInstanceLabel = resp[j].Labels.Get(model.InstanceLabel)
99
)
100
101
switch {
102
case iInstance != jInstance:
103
return iInstance < jInstance
104
case iTargetGroup != jTargetGroup:
105
return iTargetGroup < jTargetGroup
106
case iJobLabel != jJobLabel:
107
return iJobLabel < jJobLabel
108
default:
109
return iInstanceLabel < jInstanceLabel
110
}
111
})
112
113
_ = configapi.WriteResponse(rw, http.StatusOK, resp)
114
})
115
}
116
117
// TargetSet is a set of targets for an individual scraper.
118
type TargetSet map[string][]*scrape.Target
119
120
// ListTargetsResponse is returned by the ListTargetsHandler.
121
type ListTargetsResponse []TargetInfo
122
123
// TargetInfo describes a specific target.
124
type TargetInfo struct {
125
InstanceName string `json:"instance"`
126
TargetGroup string `json:"target_group"`
127
128
Endpoint string `json:"endpoint"`
129
State string `json:"state"`
130
Labels labels.Labels `json:"labels"`
131
DiscoveredLabels labels.Labels `json:"discovered_labels"`
132
LastScrape time.Time `json:"last_scrape"`
133
ScrapeDuration int64 `json:"scrape_duration_ms"`
134
ScrapeError string `json:"scrape_error"`
135
}
136
137
// PushMetricsHandler provides a way to POST data directly into
138
// an instance's WAL.
139
func (a *Agent) PushMetricsHandler(w http.ResponseWriter, r *http.Request) {
140
// Get instance name.
141
instanceName, err := getInstanceName(r)
142
if err != nil {
143
http.Error(w, err.Error(), http.StatusBadRequest)
144
return
145
}
146
147
// Get the metrics instance and serve the request.
148
managedInstance, err := a.InstanceManager().GetInstance(instanceName)
149
if err != nil || managedInstance == nil {
150
http.Error(w, err.Error(), http.StatusBadRequest)
151
return
152
}
153
154
handler := remote.NewWriteHandler(a.logger, managedInstance)
155
handler.ServeHTTP(w, r)
156
}
157
158
// getInstanceName uses gorilla/mux's route variables to extract the
159
// "instance" variable. If not found, getInstanceName will return an error.
160
func getInstanceName(r *http.Request) (string, error) {
161
vars := mux.Vars(r)
162
name := vars["instance"]
163
name, err := url.PathUnescape(name)
164
if err != nil {
165
return "", fmt.Errorf("could not decode instance name: %w", err)
166
}
167
return name, nil
168
}
169
170