-
Notifications
You must be signed in to change notification settings - Fork 479
/
config.go
251 lines (222 loc) · 6.37 KB
/
config.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Package config generates Grafana Agent configuration based on Kubernetes
// resources.
package config
import (
"embed"
"encoding/json"
"fmt"
"io/fs"
"path"
"github.com/fatih/structs"
jsonnet "github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
grafana "github.com/grafana/agent/pkg/operator/apis/monitoring/v1alpha1"
"github.com/grafana/agent/pkg/operator/assets"
prom "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
"gopkg.in/yaml.v3"
)
// Type is the type of Agent deployment that a config is being generated
// for.
type Type int
const (
// MetricsType generates a configuration for metrics.
MetricsType Type = iota + 1
// LogsType generates a configuration for logs.
LogsType
)
// String returns the string form of Type.
func (t Type) String() string {
switch t {
case MetricsType:
return "metrics"
case LogsType:
return "logs"
default:
return fmt.Sprintf("unknown (%d)", int(t))
}
}
//go:embed templates/*
var templates embed.FS
// Deployment is a set of resources used for one deployment of the Agent.
type Deployment struct {
// Agent is the root resource that the deployment represents.
Agent *grafana.GrafanaAgent
// Metrics is the set of metrics instances discovered from the root Agent resource.
Metrics []MetricsInstance
// Logs is the set of logging instances discovered from the root Agent
// resource.
Logs []LogInstance
// Secrets that can be referenced in the deployment.
Secrets assets.SecretStore
}
// DeepCopy creates a deep copy of d.
func (d *Deployment) DeepCopy() *Deployment {
p := make([]MetricsInstance, 0, len(d.Metrics))
for _, i := range d.Metrics {
var (
inst = i.Instance.DeepCopy()
sMons = make([]*prom.ServiceMonitor, 0, len(i.ServiceMonitors))
pMons = make([]*prom.PodMonitor, 0, len(i.PodMonitors))
probes = make([]*prom.Probe, 0, len(i.Probes))
)
for _, sMon := range i.ServiceMonitors {
sMons = append(sMons, sMon.DeepCopy())
}
for _, pMon := range i.PodMonitors {
pMons = append(pMons, pMon.DeepCopy())
}
for _, probe := range i.Probes {
probes = append(probes, probe.DeepCopy())
}
p = append(p, MetricsInstance{
Instance: inst,
ServiceMonitors: sMons,
PodMonitors: pMons,
Probes: probes,
})
}
l := make([]LogInstance, 0, len(d.Logs))
for _, i := range d.Logs {
var (
inst = i.Instance.DeepCopy()
pLogs = make([]*grafana.PodLogs, 0, len(i.PodLogs))
)
for _, pLog := range i.PodLogs {
pLogs = append(pLogs, pLog.DeepCopy())
}
l = append(l, LogInstance{
Instance: inst,
PodLogs: pLogs,
})
}
return &Deployment{
Agent: d.Agent.DeepCopy(),
Metrics: p,
Logs: l,
}
}
// TODO(rfratto): the "Optional" field of secrets is currently ignored.
// BuildConfig builds an Agent configuration file.
func (d *Deployment) BuildConfig(secrets assets.SecretStore, ty Type) (string, error) {
vm, err := createVM(secrets)
if err != nil {
return "", err
}
bb, err := jsonnetMarshal(d)
if err != nil {
return "", err
}
vm.TLACode("ctx", string(bb))
switch ty {
case MetricsType:
return vm.EvaluateFile("./agent-metrics.libsonnet")
case LogsType:
return vm.EvaluateFile("./agent-logs.libsonnet")
default:
panic(fmt.Sprintf("unexpected config type %v", ty))
}
}
func createVM(secrets assets.SecretStore) (*jsonnet.VM, error) {
vm := jsonnet.MakeVM()
vm.StringOutput = true
templatesContents, err := fs.Sub(templates, "templates")
if err != nil {
return nil, err
}
vm.Importer(NewFSImporter(templatesContents, []string{"./"}))
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "marshalYAML",
Params: ast.Identifiers{"object"},
Func: func(i []interface{}) (interface{}, error) {
bb, err := yaml.Marshal(i[0])
if err != nil {
return nil, jsonnet.RuntimeError{Msg: err.Error()}
}
return string(bb), nil
},
})
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "unmarshalYAML",
Params: ast.Identifiers{"text"},
Func: unmarshalYAML,
})
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "intoStages",
Params: ast.Identifiers{"text"},
Func: intoStages,
})
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "trimOptional",
Params: ast.Identifiers{"value"},
Func: func(i []interface{}) (interface{}, error) {
m := i[0].(map[string]interface{})
trimMap(m)
return m, nil
},
})
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "secretLookup",
Params: ast.Identifiers{"key"},
Func: func(i []interface{}) (interface{}, error) {
if i[0] == nil {
return nil, nil
}
k := assets.Key(i[0].(string))
val, ok := secrets[k]
if !ok {
return nil, jsonnet.RuntimeError{Msg: fmt.Sprintf("key not provided: %s", k)}
}
return val, nil
},
})
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "secretPath",
Params: ast.Identifiers{"key"},
Func: func(i []interface{}) (interface{}, error) {
if i[0] == nil {
return nil, nil
}
key := SanitizeLabelName(i[0].(string))
return path.Join("/var/lib/grafana-agent/secrets", key), nil
},
})
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "sanitize",
Params: ast.Identifiers{"text"},
Func: func(i []interface{}) (interface{}, error) {
if len(i) != 1 {
return nil, jsonnet.RuntimeError{Msg: "inappropriate number of arguments"}
}
s, ok := i[0].(string)
if !ok {
return nil, jsonnet.RuntimeError{Msg: "text must be a string"}
}
return SanitizeLabelName(s), nil
},
})
return vm, nil
}
// jsonnetMarshal marshals a value for passing to Jsonnet. This marshals to a
// JSON representation of the Go value, ignoring all json struct tags. Fields
// must be access as they would from Go, with the exception of embedded fields,
// which must be accessed through the embedded type name (a.Embedded.Field).
func jsonnetMarshal(v interface{}) ([]byte, error) {
if structs.IsStruct(v) {
return json.Marshal(structs.Map(v))
}
return json.Marshal(v)
}
// MetricsInstance is an instance with a set of associated service monitors,
// pod monitors, and probes, which compose the final configuration of the
// generated Metrics instance.
type MetricsInstance struct {
Instance *grafana.MetricsInstance
ServiceMonitors []*prom.ServiceMonitor
PodMonitors []*prom.PodMonitor
Probes []*prom.Probe
}
// LogInstance is an instance with a set of associated PodLogs.
type LogInstance struct {
Instance *grafana.LogsInstance
PodLogs []*grafana.PodLogs
}