This repository has been archived by the owner on Jan 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathmain.go
354 lines (323 loc) · 10.3 KB
/
main.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"time"
"github.com/pkg/errors"
)
func main() {
// setup APM package and add it to default policy
if err := setupManagedAPM(); err != nil {
log.Fatal(err)
}
// create a reverse proxy to the APM Server running via Elastic Agent,
// headers are not rewritten, as not considered important right now.
target, _ := url.Parse("http://elastic-agent:8200")
http.Handle("/", httputil.NewSingleHostReverseProxy(target))
if err := http.ListenAndServe(":8200", nil); err != nil {
log.Fatal(err)
}
}
func setupManagedAPM() error {
client := newKibanaClient()
policy, err := fetchDefaultPolicy(client)
if err != nil {
return err
}
fmt.Println("default policy fetched")
// fetch the available apm package
apmPkg, err := client.getAPMPackage()
if err != nil {
return err
}
fmt.Println("apm package fetched")
// define expected APM package policy
expectedAPMPackagePolicy, err := apmPackagePolicy(policy.ID, apmPkg)
if err != nil {
return err
}
fmt.Println("apm package policy defined")
// fetch apm package installed to default policy and verify if it is aligned with
// expected setup
defaultPolicyPackages, err := client.getPackagePolicies(fmt.Sprintf("kuery=ingest-package-policies.policy_id:%s", policy.ID))
if err != nil {
log.Fatal(err)
}
var apmPackagePolicies []packagePolicy
for _, p := range defaultPolicyPackages {
for _, input := range p.Inputs {
if input.Type == "apm" {
apmPackagePolicies = append(apmPackagePolicies, p)
break
}
}
}
var requiresSetup bool
switch len(apmPackagePolicies) {
case 0:
requiresSetup = true
fmt.Println("agent policy has no apm integration")
case 1:
// apm package is defined to always only have 1 Input
fmt.Println("agent policy has existing apm integration")
existing := apmPackagePolicies[0]
// verify that package is enabled, has default namespace and expected package properties
if !existing.Enabled ||
existing.Namespace != expectedAPMPackagePolicy.Namespace ||
existing.Package != expectedAPMPackagePolicy.Package {
requiresSetup = true
} else {
// verify that variables are configured as expected
for k, expected := range expectedAPMPackagePolicy.Inputs[0].Vars {
configured, ok := existing.Inputs[0].Vars[k]
if !ok || configured["type"] != expected["type"] || configured["value"] != expected["value"] {
requiresSetup = true
break
}
}
}
default:
// multiple apm package policies lead to issues,
// delete them and create a new setup
fmt.Println("agent policy has multiple existing apm integration")
requiresSetup = true
}
if !requiresSetup {
fmt.Println("apm integration does not require setup")
return nil
}
fmt.Println("apm integration requires setup")
if err := client.deletePackagePolicies(apmPackagePolicies); err != nil {
return err
}
if err := client.addPackagePolicy(expectedAPMPackagePolicy); err != nil {
return err
}
fmt.Println("apm integration succesfully added to agent policy")
return nil
}
func fetchDefaultPolicy(client *kibanaClient) (agentPolicy, error) {
fleetServer := ""
if enable, err := strconv.ParseBool(os.Getenv("FLEET_SERVER_ENABLE")); err == nil && enable {
fleetServer = "_fleet_server"
}
kuery := fmt.Sprintf("kuery=ingest-agent-policies.is_default%s:true", fleetServer)
for ct := 0; ct < 20; ct++ {
agentPolicies, err := client.getAgentPolicies(kuery)
if err != nil {
return agentPolicy{}, err
}
if len(agentPolicies) > 0 {
// there's supposed to only be one default policy,
// in case there are more, there is a bug in the agent integrations logic
return agentPolicies[0], nil
}
time.Sleep(5 * time.Second)
}
return agentPolicy{}, errors.New("no default agent policy found")
}
// apmPackagePolicy defines the expected APM package policy
func apmPackagePolicy(policyID string, pkg *eprPackage) (packagePolicy, error) {
p := packagePolicy{
Name: "apm-integration-testing",
Namespace: "default",
Enabled: true,
AgentPolicyID: policyID,
Package: packagePolicyPackage{
Name: pkg.Name,
Version: pkg.Version,
Title: pkg.Title,
},
}
if len(pkg.PolicyTemplates) != 1 || len(pkg.PolicyTemplates[0].Inputs) != 1 {
return p, fmt.Errorf("apm package policy input missing: %+v", pkg)
}
input := pkg.PolicyTemplates[0].Inputs[0]
vars := make(map[string]map[string]interface{})
for _, inputVar := range input.Vars {
varMap := map[string]interface{}{"type": inputVar.Type}
switch inputVar.Name {
case "host":
varMap["value"] = "0.0.0.0:8200"
case "enable_rum":
varMap["value"] = true
case "secret_token":
varMap["value"] = os.Getenv("APM_SERVER_SECRET_TOKEN")
}
vars[inputVar.Name] = varMap
}
p.Inputs = append(p.Inputs, packagePolicyInput{
Type: input.Type,
Enabled: true,
Streams: []interface{}{},
Vars: vars,
})
return p, nil
}
type kibanaClient struct {
fleetURL string
}
func newKibanaClient() *kibanaClient {
host := os.Getenv("KIBANA_HOST")
if host == "" {
host = "http://admin:changeme@kibana:5601"
}
return &kibanaClient{fleetURL: fmt.Sprintf("%s/api/fleet", host)}
}
func (client *kibanaClient) getAPMPackage() (*eprPackage, error) {
url := fmt.Sprintf("%s/epm/packages?experimental=true", client.fleetURL)
var pkgs eprPackagesResponse
if err := makeRequest(http.MethodGet, url, nil, &pkgs); err != nil {
return nil, err
}
for _, p := range pkgs.Packages {
if p.Name != "apm" {
continue
}
var apm eprPackageResponse
url := fmt.Sprintf("%s/epm/packages/%s-%s", client.fleetURL, p.Name, p.Version)
err := makeRequest(http.MethodGet, url, nil, &apm)
return &apm.Package, err
}
return nil, errors.New("no apm package found")
}
func (client *kibanaClient) getAgentPolicies(query string) ([]agentPolicy, error) {
url := fmt.Sprintf("%s/agent_policies?%s", client.fleetURL, query)
var result struct {
Items []agentPolicy `json:"items"`
}
if err := makeRequest(http.MethodGet, url, nil, &result); err != nil {
return result.Items, errors.Wrap(err, "getAgentPolicies")
}
return result.Items, nil
}
func (client *kibanaClient) addPackagePolicy(policy packagePolicy) error {
url := fmt.Sprintf("%s/package_policies", client.fleetURL)
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(&policy); err != nil {
return err
}
var result interface{}
if err := makeRequest(http.MethodPost, url, &buf, &result); err != nil {
return errors.Wrap(err, "addPackagePolicies")
}
return nil
}
func (client *kibanaClient) getPackagePolicies(query string) ([]packagePolicy, error) {
url := fmt.Sprintf("%s/package_policies?%s", client.fleetURL, query)
var result struct {
Items []packagePolicy `json:"items"`
}
if err := makeRequest(http.MethodGet, url, nil, &result); err != nil {
return result.Items, errors.Wrap(err, "getPackagePolicies")
}
return result.Items, nil
}
// deletePackagePolicy deletes one or more package policies.
func (client *kibanaClient) deletePackagePolicies(policies []packagePolicy) error {
if len(policies) == 0 {
return nil
}
var ids []string
for _, p := range policies {
ids = append(ids, p.ID)
}
var params struct {
PackagePolicyIDs []string `json:"packagePolicyIds"`
}
params.PackagePolicyIDs = ids
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(params); err != nil {
return err
}
var result interface{}
if err := makeRequest(http.MethodPost, client.fleetURL+"/package_policies/delete", &body, &result); err != nil {
return errors.Wrap(err, "deletePackagePolicies")
}
return nil
}
func makeRequest(method string, url string, body io.Reader, out interface{}) error {
req, err := http.NewRequest(method, url, body)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("kbn-xsrf", "1")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("request failed (%s): %s", resp.Status, body)
}
return json.NewDecoder(resp.Body).Decode(&out)
}
// agentPolicy holds details of a Fleet Agent Policy.
type agentPolicy struct {
ID string `json:"id"`
}
type eprPackage struct {
Name string `json:"name"`
Version string `json:"version"`
Release string `json:"release"`
Type string `json:"type"`
Title string `json:"title"`
Description string `json:"description"`
Download string `json:"download"`
Path string `json:"path"`
Status string `json:"status"`
PolicyTemplates []packagePolicyTemplate `json:"policy_templates"`
}
// packagePolicy holds details of a Fleet Package Policy.
type packagePolicy struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Namespace string `json:"namespace"`
Enabled bool `json:"enabled"`
AgentPolicyID string `json:"policy_id"`
OutputID string `json:"output_id"`
Inputs []packagePolicyInput `json:"inputs"`
Package packagePolicyPackage `json:"package"`
}
type packagePolicyPackage struct {
Name string `json:"name"`
Version string `json:"version"`
Title string `json:"title"`
}
type packagePolicyInput struct {
Type string `json:"type"`
Enabled bool `json:"enabled"`
Streams []interface{} `json:"streams"`
Vars map[string]map[string]interface{} `json:"vars,omitempty"`
}
type packagePolicyTemplate struct {
Inputs []packagePolicyTemplateInput `json:"inputs"`
}
type packagePolicyTemplateInput struct {
Type string `json:"type"`
Title string `json:"title"`
TemplatePath string `json:"template_path"`
Description string `json:"description"`
Vars []packagePolicyTemplateInputVar `json:"vars"`
}
type packagePolicyTemplateInputVar struct {
Name string `json:"name"`
Type string `json:"type"`
}
type eprPackageResponse struct {
Package eprPackage `json:"response"`
}
type eprPackagesResponse struct {
Packages []eprPackage `json:"response"`
}