Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/web/api/api.go
4096 views
1
// Package api implements the HTTP API used for the Grafana Agent Flow UI.
2
//
3
// The API is internal only; it is not stable and shouldn't be relied on
4
// externally.
5
package api
6
7
import (
8
"bytes"
9
"encoding/json"
10
"net/http"
11
"path"
12
13
"github.com/prometheus/prometheus/util/httputil"
14
15
"github.com/gorilla/mux"
16
"github.com/grafana/agent/pkg/flow"
17
)
18
19
// FlowAPI is a wrapper around the component API.
20
type FlowAPI struct {
21
flow *flow.Flow
22
}
23
24
// NewFlowAPI instantiates a new Flow API.
25
func NewFlowAPI(flow *flow.Flow, r *mux.Router) *FlowAPI {
26
return &FlowAPI{flow: flow}
27
}
28
29
// RegisterRoutes registers all the API's routes.
30
func (f *FlowAPI) RegisterRoutes(urlPrefix string, r *mux.Router) {
31
r.Handle(path.Join(urlPrefix, "/components"), httputil.CompressionHandler{Handler: f.listComponentsHandler()})
32
r.Handle(path.Join(urlPrefix, "/components/{id}"), httputil.CompressionHandler{Handler: f.listComponentHandler()})
33
}
34
35
func (f *FlowAPI) listComponentsHandler() http.HandlerFunc {
36
return func(w http.ResponseWriter, _ *http.Request) {
37
infos := f.flow.ComponentInfos()
38
bb, err := json.Marshal(infos)
39
if err != nil {
40
http.Error(w, err.Error(), http.StatusInternalServerError)
41
return
42
}
43
_, _ = w.Write(bb)
44
}
45
}
46
47
func (f *FlowAPI) listComponentHandler() http.HandlerFunc {
48
return func(w http.ResponseWriter, r *http.Request) {
49
vars := mux.Vars(r)
50
infos := f.flow.ComponentInfos()
51
requestedComponent := vars["id"]
52
53
for _, info := range infos {
54
if requestedComponent == info.ID {
55
bb, err := f.json(info)
56
if err != nil {
57
http.Error(w, err.Error(), http.StatusInternalServerError)
58
return
59
}
60
_, _ = w.Write(bb)
61
return
62
}
63
}
64
65
http.NotFound(w, r)
66
}
67
}
68
69
// json returns the JSON representation of c.
70
func (f *FlowAPI) json(c *flow.ComponentInfo) ([]byte, error) {
71
var buf bytes.Buffer
72
err := f.flow.ComponentJSON(&buf, c)
73
if err != nil {
74
return nil, err
75
}
76
return buf.Bytes(), nil
77
}
78
79