Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/flow/flow_http.go
4094 views
1
package flow
2
3
import (
4
"encoding/json"
5
"fmt"
6
"io"
7
"net/http"
8
"path"
9
"strings"
10
11
"github.com/grafana/agent/pkg/river/encoding"
12
13
"github.com/gorilla/mux"
14
"github.com/grafana/agent/pkg/flow/internal/controller"
15
)
16
17
// ComponentHandler returns an http.HandlerFunc which will delegate all requests to
18
// a component named by the first path segment
19
func (f *Flow) ComponentHandler() http.HandlerFunc {
20
return func(w http.ResponseWriter, r *http.Request) {
21
vars := mux.Vars(r)
22
id := vars["id"]
23
24
// find node with ID
25
var node *controller.ComponentNode
26
for _, n := range f.loader.Components() {
27
if n.ID().String() == id {
28
node = n
29
break
30
}
31
}
32
if node == nil {
33
w.WriteHeader(http.StatusNotFound)
34
return
35
}
36
// TODO: potentially cache these handlers, and invalidate on component state change.
37
handler := node.HTTPHandler()
38
if handler == nil {
39
w.WriteHeader(http.StatusNotFound)
40
return
41
}
42
// Remove prefix from path, so each component can handle paths from their
43
// own root path.
44
r.URL.Path = strings.TrimPrefix(r.URL.Path, path.Join(f.opts.HTTPPathPrefix, id))
45
handler.ServeHTTP(w, r)
46
}
47
}
48
49
// ComponentJSON returns the json representation of the flow component.
50
func (f *Flow) ComponentJSON(w io.Writer, ci *ComponentInfo) error {
51
f.loadMut.RLock()
52
defer f.loadMut.RUnlock()
53
54
var foundComponent *controller.ComponentNode
55
for _, c := range f.loader.Components() {
56
if c.ID().String() == ci.ID {
57
foundComponent = c
58
break
59
}
60
}
61
if foundComponent == nil {
62
return fmt.Errorf("unable to find component named %q", ci.ID)
63
}
64
65
var err error
66
args, err := encoding.ConvertRiverBodyToJSON(foundComponent.Arguments())
67
if err != nil {
68
return err
69
}
70
ci.Arguments = args
71
72
exports, err := encoding.ConvertRiverBodyToJSON(foundComponent.Exports())
73
if err != nil {
74
return err
75
}
76
ci.Exports = exports
77
78
debugInfo, err := encoding.ConvertRiverBodyToJSON(foundComponent.DebugInfo())
79
if err != nil {
80
return err
81
}
82
ci.DebugInfo = debugInfo
83
84
bb, err := json.Marshal(ci)
85
if err != nil {
86
return err
87
}
88
_, err = w.Write(bb)
89
return err
90
}
91
92