-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathdiagnostics.go
616 lines (561 loc) · 17.6 KB
/
diagnostics.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.
package diagnostics
import (
"archive/zip"
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"reflect"
"runtime/pprof"
"strings"
"time"
"github.com/elastic/elastic-agent/pkg/control/v2/client"
"github.com/elastic/go-ucfg"
"gopkg.in/yaml.v3"
"github.com/elastic/elastic-agent/internal/pkg/agent/application/paths"
"github.com/elastic/elastic-agent/internal/pkg/config"
"github.com/elastic/elastic-agent/internal/pkg/release"
"github.com/elastic/elastic-agent/pkg/component"
"github.com/elastic/elastic-agent/version"
)
const (
// ContentTypeDirectory should be used to indicate that a directory should be made in the resulting bundle
ContentTypeDirectory = "directory"
// REDACTED is used to replace sensative fields
REDACTED = "<REDACTED>"
agentName = "elastic-agent"
)
// DiagCPU* are contstants to describe the CPU profile that is collected when the --cpu-profile flag is used with the diagnostics command, or the diagnostics action contains "CPU" in the additional_metrics list.
const (
DiagCPUName = "cpuprofile"
DiagCPUFilename = "cpu.pprof"
DiagCPUDescription = "CPU profile"
DiagCPUContentType = "application/octet-stream"
DiagCPUDuration = 30 * time.Second
)
// Hook is a hook that gets used when diagnostic information is requested from the Elastic Agent.
type Hook struct {
Name string
Filename string
Description string
ContentType string
Hook func(ctx context.Context) []byte
}
// Hooks is a set of diagnostic hooks.
type Hooks []Hook
// GlobalHooks returns the global hooks that can be used at anytime with no other references.
func GlobalHooks() Hooks {
return Hooks{
{
Name: "version",
Filename: "version.txt",
Description: "version information",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
v := release.Info()
o, err := yaml.Marshal(v)
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "package version",
Filename: "package.version",
Description: "Package Version",
ContentType: "text/plain",
Hook: func(_ context.Context) []byte {
pkgVersionPath, err := version.GetAgentPackageVersionFilePath()
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
fileBytes, err := os.ReadFile(pkgVersionPath)
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return fileBytes
},
},
{
Name: "goroutine",
Filename: "goroutine.pprof.gz",
Description: "stack traces of all current goroutines",
ContentType: "application/octet-stream",
Hook: pprofDiag("goroutine", 0),
},
{
Name: "heap",
Filename: "heap.pprof.gz",
Description: "a sampling of memory allocations of live objects",
ContentType: "application/octet-stream",
Hook: pprofDiag("heap", 0),
},
{
Name: "allocs",
Filename: "allocs.pprof.gz",
Description: "a sampling of all past memory allocations",
ContentType: "application/octet-stream",
Hook: pprofDiag("allocs", 0),
},
{
Name: "threadcreate",
Filename: "threadcreate.pprof.gz",
Description: "stack traces that led to the creation of new OS threads",
ContentType: "application/octet-stream",
Hook: pprofDiag("threadcreate", 0),
},
{
Name: "block",
Filename: "block.pprof.gz",
Description: "stack traces that led to blocking on synchronization primitives",
ContentType: "application/octet-stream",
Hook: pprofDiag("block", 0),
},
{
Name: "mutex",
Filename: "mutex.pprof.gz",
Description: "stack traces of holders of contended mutexes",
ContentType: "application/octet-stream",
Hook: pprofDiag("mutex", 0),
},
}
}
func pprofDiag(name string, debug int) func(context.Context) []byte {
return func(_ context.Context) []byte {
var w bytes.Buffer
err := pprof.Lookup(name).WriteTo(&w, debug)
if err != nil {
// error is returned as the content
return []byte(fmt.Sprintf("failed to write pprof to bytes buffer: %s", err))
}
return w.Bytes()
}
}
// CreateCPUProfile will gather a CPU profile over a given time duration.
func CreateCPUProfile(ctx context.Context, period time.Duration) ([]byte, error) {
var writeBuf bytes.Buffer
err := pprof.StartCPUProfile(&writeBuf)
if err != nil {
return nil, fmt.Errorf("error starting CPU profile: %w", err)
}
tc := time.After(period)
select {
case <-ctx.Done():
pprof.StopCPUProfile()
return nil, ctx.Err()
case <-tc:
break
}
pprof.StopCPUProfile()
return writeBuf.Bytes(), nil
}
// ZipArchive creates a zipped diagnostics bundle using the passed writer with the passed diagnostics and local logs.
// If any error is encountered when writing the contents of the archive it is returned.
func ZipArchive(
errOut,
w io.Writer,
topPath string,
agentDiag []client.DiagnosticFileResult,
unitDiags []client.DiagnosticUnitResult,
compDiags []client.DiagnosticComponentResult,
excludeEvents bool) error {
ts := time.Now().UTC()
zw := zip.NewWriter(w)
defer zw.Close()
// Write agent diagnostics content
for _, ad := range agentDiag {
zf, err := zw.CreateHeader(&zip.FileHeader{
Name: ad.Filename,
Method: zip.Deflate,
Modified: ad.Generated,
})
if err != nil {
return fmt.Errorf("error creating header for agent diagnostics: %w", err)
}
err = writeRedacted(errOut, zf, ad.Filename, ad)
if err != nil {
return fmt.Errorf("error writing file for agent diagnostics: %w", err)
}
}
// Handle unit diagnostics
// structure each unit into its own component directory
compDirs := make(map[string][]client.DiagnosticUnitResult)
for _, ud := range unitDiags {
compDir := strings.ReplaceAll(ud.ComponentID, "/", "-")
compDirs[compDir] = append(compDirs[compDir], ud)
}
componentResults := map[string]client.DiagnosticComponentResult{}
// handle component diagnostics
for _, comp := range compDiags {
compDir := strings.ReplaceAll(comp.ComponentID, "/", "-")
componentResults[compDir] = comp
}
// write each units diagnostics into its own directory
// layout becomes components/<component-id>/<unit-id>/<filename>
_, err := zw.CreateHeader(&zip.FileHeader{
Name: "components/",
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return fmt.Errorf("error creating .zip header for components/ directory: %w", err)
}
// iterate over components
for dirName, units := range compDirs {
_, err := zw.CreateHeader(&zip.FileHeader{
Name: fmt.Sprintf("components/%s/", dirName),
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return fmt.Errorf("error creating .zip header for component directory: %w", err)
}
// create component diags
if comp, ok := componentResults[dirName]; ok {
// check for component-level errors
if comp.Err != nil {
err = writeErrorResult(zw, fmt.Sprintf("components/%s/error.txt", dirName), comp.Err.Error())
if err != nil {
return fmt.Errorf("error while writing error result for component %s: %w", comp.ComponentID, err)
}
} else {
for _, res := range comp.Results {
filePath := fmt.Sprintf("components/%s/%s", dirName, res.Filename)
resFileWriter, err := zw.CreateHeader(&zip.FileHeader{
Name: filePath,
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return fmt.Errorf("error creating .zip header for %s: %w", res.Filename, err)
}
err = writeRedacted(errOut, resFileWriter, filePath, res)
if err != nil {
return fmt.Errorf("error writing %s in zip file: %w", res.Filename, err)
}
}
}
}
// create unit diags
for _, ud := range units {
unitDir := strings.ReplaceAll(strings.TrimPrefix(ud.UnitID, ud.ComponentID+"-"), "/", "-")
_, err := zw.CreateHeader(&zip.FileHeader{
Name: fmt.Sprintf("components/%s/%s/", dirName, unitDir),
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return fmt.Errorf("error creating .zip header for unit directory: %w", err)
}
// check for unit-level errors
if ud.Err != nil {
err = writeErrorResult(zw, fmt.Sprintf("components/%s/%s/error.txt", dirName, unitDir), ud.Err.Error())
if err != nil {
return fmt.Errorf("error while writing error result for unit %s: %w", ud.UnitID, err)
}
continue
}
for _, fr := range ud.Results {
filePath := fmt.Sprintf("components/%s/%s/%s", dirName, unitDir, fr.Filename)
w, err := zw.CreateHeader(&zip.FileHeader{
Name: filePath,
Method: zip.Deflate,
Modified: fr.Generated,
})
if err != nil {
return err
}
err = writeRedacted(errOut, w, filePath, fr)
if err != nil {
return err
}
}
}
}
// Gather Logs:
return zipLogs(zw, ts, topPath, excludeEvents)
}
func writeErrorResult(zw *zip.Writer, path string, errBody string) error {
ts := time.Now().UTC()
w, err := zw.CreateHeader(&zip.FileHeader{
Name: path,
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return fmt.Errorf("error writing header for error.txt file for component: %w", err)
}
_, err = w.Write([]byte(fmt.Sprintf("%s\n", errBody)))
if err != nil {
return fmt.Errorf("error writing error.txt file for component: %w", err)
}
return nil
}
func writeRedacted(errOut, resultWriter io.Writer, fullFilePath string, fileResult client.DiagnosticFileResult) error {
out := &fileResult.Content
// Should we support json too?
if fileResult.ContentType == "application/yaml" {
unmarshalled := map[string]interface{}{}
err := yaml.Unmarshal(fileResult.Content, &unmarshalled)
if err != nil {
// Best effort, output a warning but still include the file
fmt.Fprintf(errOut, "[WARNING] Could not redact %s due to unmarshalling error: %s\n", fullFilePath, err)
} else {
unmarshalled = RedactSecretPaths(unmarshalled, errOut)
redacted, err := yaml.Marshal(redactMap(errOut, unmarshalled))
if err != nil {
// Best effort, output a warning but still include the file
fmt.Fprintf(errOut, "[WARNING] Could not redact %s due to marshalling error: %s\n", fullFilePath, err)
} else {
out = &redacted
}
}
}
_, err := resultWriter.Write(*out)
return err
}
// redactMap sensitive values from the underlying map
// the whole generic function here is out of paranoia. Although extremely unlikely,
// we have no way of guaranteeing we'll get a "normal" map[string]interface{},
// since the diagnostic interface is a bit of a free-for-all
func redactMap[K comparable](errOut io.Writer, inputMap map[K]interface{}) map[K]interface{} {
if inputMap == nil {
return nil
}
for rootKey, rootValue := range inputMap {
if rootValue != nil {
switch cast := rootValue.(type) {
case map[string]interface{}:
rootValue = redactMap(errOut, cast)
case map[interface{}]interface{}:
rootValue = redactMap(errOut, cast)
case map[int]interface{}:
rootValue = redactMap(errOut, cast)
case string:
if keyString, ok := any(rootKey).(string); ok {
if redactKey(keyString) {
rootValue = REDACTED
}
}
default:
// in cases where we got some weird kind of map we couldn't parse, print a warning
if reflect.TypeOf(rootValue).Kind() == reflect.Map {
fmt.Fprintf(errOut, "[WARNING]: file may be partly redacted, could not cast value %v of type %T", rootKey, rootValue)
}
}
}
inputMap[rootKey] = rootValue
}
return inputMap
}
func redactKey(k string) bool {
// "routekey" shouldn't be redacted.
// Add any other exceptions here.
if k == "routekey" {
return false
}
k = strings.ToLower(k)
return strings.Contains(k, "certificate") ||
strings.Contains(k, "passphrase") ||
strings.Contains(k, "password") ||
strings.Contains(k, "token") ||
strings.Contains(k, "key") ||
strings.Contains(k, "secret")
}
func zipLogs(zw *zip.Writer, ts time.Time, topPath string, excludeEvents bool) error {
homePath := paths.HomeFrom(topPath)
dataPath := paths.DataFrom(topPath)
currentDir := filepath.Base(homePath)
if !paths.IsVersionHome() {
// running in a container with custom top path set
// logs are directly under top path
return zipLogsWithPath(homePath, currentDir, true, excludeEvents, zw, ts)
}
dataDir, err := os.Open(dataPath)
if err != nil {
return err
}
defer dataDir.Close()
subdirs, err := dataDir.Readdirnames(0)
if err != nil {
return err
}
dirPrefix := fmt.Sprintf("%s-", agentName)
for _, dir := range subdirs {
if !strings.HasPrefix(dir, dirPrefix) {
continue
}
collectServices := dir == currentDir
path := filepath.Join(dataPath, dir)
if err := zipLogsWithPath(path, dir, collectServices, excludeEvents, zw, ts); err != nil {
return err
}
}
return nil
}
// zipLogs walks paths.Logs() and copies the file structure into zw in "logs/"
func zipLogsWithPath(pathsHome, commitName string, collectServices, excludeEvents bool, zw *zip.Writer, ts time.Time) error {
_, err := zw.CreateHeader(&zip.FileHeader{
Name: "logs/",
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return err
}
if collectServices {
if err := collectServiceComponentsLogs(zw); err != nil {
return fmt.Errorf("failed to collect endpoint-security logs: %w", err)
}
}
_, err = zw.CreateHeader(&zip.FileHeader{
Name: "logs/" + commitName + "/",
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return err
}
// using Data() + "/logs", for some reason default paths/Logs() is the home dir...
logPath := filepath.Join(pathsHome, "logs") + string(filepath.Separator)
return filepath.WalkDir(logPath, func(path string, d fs.DirEntry, fErr error) error {
if errors.Is(fErr, fs.ErrNotExist) {
return nil
}
if fErr != nil {
return fmt.Errorf("unable to walk log dir: %w", fErr)
}
// name is the relative dir/file name replacing any filepath seperators with /
// this will clean log names on windows machines and will nop on *nix
name := filepath.ToSlash(strings.TrimPrefix(path, logPath))
if name == "" {
return nil
}
// Skip events logs, if necessary
// name can either be the folder name 'events' or the folder plus
// the file name like 'events/elastic-agent-events-log.ndjson'
// we need to skip both.
if excludeEvents && strings.HasPrefix(name, "events") {
return nil
}
name = filepath.Join(commitName, name)
if d.IsDir() {
_, err := zw.CreateHeader(&zip.FileHeader{
Name: "logs/" + filepath.ToSlash(name) + "/",
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return fmt.Errorf("unable to create log directory in archive: %w", err)
}
return nil
}
return saveLogs(name, path, zw)
})
}
func collectServiceComponentsLogs(zw *zip.Writer) error {
platform, err := component.LoadPlatformDetail()
if err != nil {
return fmt.Errorf("failed to gather system information: %w", err)
}
specs, err := component.LoadRuntimeSpecs(paths.Components(), platform)
if err != nil {
return fmt.Errorf("failed to detect inputs and outputs: %w", err)
}
for _, spec := range specs.ServiceSpecs() {
if spec.Spec.Service.Log == nil || spec.Spec.Service.Log.Path == "" {
// no log path set in specification
continue
}
logPath := filepath.Dir(spec.Spec.Service.Log.Path) + string(filepath.Separator)
err = filepath.WalkDir(logPath, func(path string, d fs.DirEntry, fErr error) error {
if fErr != nil {
if errors.Is(fErr, fs.ErrNotExist) {
return nil
}
return fmt.Errorf("unable to walk log directory %q for service input %s: %w", logPath, spec.InputType, fErr)
}
name := filepath.ToSlash(strings.TrimPrefix(path, logPath))
if name == "" {
return nil
}
if d.IsDir() {
return nil
}
return saveLogs("services/"+name, path, zw)
})
if err != nil {
return err
}
}
return nil
}
func saveLogs(name string, logPath string, zw *zip.Writer) error {
ts := time.Now().UTC()
lf, err := os.Open(logPath)
if err != nil {
return fmt.Errorf("unable to open log file: %w", err)
}
defer lf.Close()
if li, err := lf.Stat(); err == nil {
ts = li.ModTime()
}
zf, err := zw.CreateHeader(&zip.FileHeader{
Name: "logs/" + filepath.ToSlash(name),
Method: zip.Deflate,
Modified: ts,
})
if err != nil {
return err
}
_, err = io.Copy(zf, lf)
if err != nil {
return err
}
return nil
}
// RedactSecretPaths will check the passed mapStr input for a secret_paths attribute.
// If found it will replace the value for every key in the paths list with <REDACTED> and return the resulting map.
// Any issues or errors will be written to the errOut writer.
func RedactSecretPaths(mapStr map[string]any, errOut io.Writer) map[string]any {
v, ok := mapStr["secret_paths"]
if !ok {
return mapStr
}
arr, ok := v.([]interface{})
if !ok {
fmt.Fprintln(errOut, "No output redaction: secret_paths attribute is not a list.")
return mapStr
}
cfg := ucfg.MustNewFrom(mapStr, ucfg.PathSep("."))
for _, v := range arr {
key, ok := v.(string)
if !ok {
fmt.Fprintf(errOut, "No output redaction for %q: expected type string, is type %T.\n", v, v)
continue
}
if ok, err := cfg.Has(key, -1, ucfg.PathSep(".")); err != nil {
fmt.Fprintf(errOut, "Error redacting secret path %q: %v.\n", key, err)
} else if ok {
err := cfg.SetString(key, -1, REDACTED, ucfg.PathSep("."))
if err != nil {
fmt.Fprintf(errOut, "No output redaction for %q: %v.\n", key, err)
}
} else {
fmt.Fprintf(errOut, "Unable to find secret path %q for redaction.\n", key)
}
}
result, err := config.MustNewConfigFrom(cfg).ToMapStr()
if err != nil {
return mapStr
}
return result
}