-
-
Notifications
You must be signed in to change notification settings - Fork 517
/
cmd_gatherlogs.go
497 lines (452 loc) · 16.1 KB
/
cmd_gatherlogs.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
package cli
import (
"archive/zip"
"bufio"
"context"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/telepresenceio/telepresence/rpc/v2/connector"
"github.com/telepresenceio/telepresence/rpc/v2/daemon"
"github.com/telepresenceio/telepresence/rpc/v2/manager"
"github.com/telepresenceio/telepresence/v2/pkg/client/cli/cliutil"
"github.com/telepresenceio/telepresence/v2/pkg/client/errcat"
"github.com/telepresenceio/telepresence/v2/pkg/client/scout"
"github.com/telepresenceio/telepresence/v2/pkg/filelocation"
"github.com/telepresenceio/telepresence/v2/pkg/log"
)
type gatherLogsArgs struct {
outputFile string
daemons string
trafficAgents string
trafficManager bool
anon bool
podYaml bool
}
func gatherLogsCommand() *cobra.Command {
gl := &gatherLogsArgs{}
cmd := &cobra.Command{
Use: "gather-logs",
Args: cobra.NoArgs,
Short: "Gather logs from traffic-manager, traffic-agent, user and root daemons, and export them into a zip file.",
Long: `Gather logs from traffic-manager, traffic-agent, user and root daemons,
and export them into a zip file. Useful if you are opening a Github issue or asking
someone to help you debug Telepresence.`,
Example: `Here are a few examples of how you can use this command:
# Get all logs and export to a given file
telepresence gather-logs -o /tmp/telepresence_logs.zip
# Get all logs and pod yaml manifests for components in the kubernetes cluster
telepresence gather-logs -o /tmp/telepresence_logs.zip --get-pod-yaml
# Get all logs for the daemons only
telepresence gather-logs --traffic-agents=None --traffic-manager=False
# Get all logs for pods that have "echo-easy" in the name, useful if you have multiple replicas
telepresence gather-logs --traffic-manager=False --traffic-agents=echo-easy
# Get all logs for a specific pod
telepresence gather-logs --traffic-manager=False --traffic-agents=echo-easy-6848967857-tw4jw
# Get logs from everything except the daemons
telepresence gather-logs --daemons=None
`,
RunE: func(cmd *cobra.Command, _ []string) error {
return gl.gatherLogs(cmd.Context(), cmd, cmd.OutOrStdout(), cmd.ErrOrStderr())
},
}
flags := cmd.Flags()
flags.StringVarP(&gl.outputFile, "output-file", "o", "", "The file you want to output the logs to.")
flags.StringVar(&gl.daemons, "daemons", "all", "The daemons you want logs from: all, root, user, None")
flags.BoolVar(&gl.trafficManager, "traffic-manager", true, "If you want to collect logs from the traffic-manager")
flags.StringVar(&gl.trafficAgents, "traffic-agents", "all", "Traffic-agents to collect logs from: all, name substring, None")
flags.BoolVarP(&gl.anon, "anonymize", "a", false, "To anonymize pod names + namespaces from the logs")
flags.BoolVarP(&gl.podYaml, "get-pod-yaml", "y", false, "Get the yaml of any pods you are getting logs for")
return cmd
}
// anonymizer contains the mappings between things we want to anonymize
// and their new, anonymized name. Using a map instead of simply redacting
// makes it easier for us to maintain certain relationships in the logs (e.g.
// namespaces things are in) which may be helpful in troubleshooting.
type anonymizer struct {
namespaces map[string]string
podNames map[string]string
}
// gatherLogs gets the logs from the daemons (daemon + connector) and creates a zip
func (gl *gatherLogsArgs) gatherLogs(ctx context.Context, cmd *cobra.Command, stdout, stderr io.Writer) error {
scout := scout.NewScout(ctx, "cli")
// Get the log directory and return the error if we can't get it
logDir, err := filelocation.AppUserLogDir(ctx)
if err != nil {
return errcat.User.New(err)
}
anonymizer := &anonymizer{
namespaces: make(map[string]string),
podNames: make(map[string]string),
}
// If the user did not provide an outputFile, we'll use their current working directory
if gl.outputFile == "" {
pwd, err := os.Getwd()
if err != nil {
return errcat.User.New(err)
}
gl.outputFile = fmt.Sprintf("%s/telepresence_logs.zip", pwd)
} else if !strings.HasSuffix(gl.outputFile, ".zip") {
return errcat.User.New("output file must end in .zip")
}
// Create a temporary directory where we will store the logs before we zip
// them for export
exportDir, err := os.MkdirTemp("", "logexp-")
if err != nil {
return errcat.User.New(err)
}
defer func() {
if err := os.RemoveAll(exportDir); err != nil {
fmt.Fprintf(stderr, "Failed to remove temp directory %s: %s", exportDir, err)
}
}()
// First we add the daemonLogs to the export directory
var daemonLogs []string
switch gl.daemons {
case "all":
daemonLogs = append(daemonLogs, "connector", "daemon")
case "root":
daemonLogs = append(daemonLogs, "daemon")
case "user":
daemonLogs = append(daemonLogs, "connector")
case "None":
default:
return errcat.User.New("Options for --daemons are: all, root, user, or None")
}
// Add metadata about the request so we can track usage + see which
// types of logs people are requesting more frequently.
// This also gives us an idea about how much usage this command is
// getting.
scout.SetMetadatum("daemon_logs", daemonLogs)
scout.SetMetadatum("traffic_manager_logs", gl.trafficManager)
scout.SetMetadatum("traffic_agent_logs", gl.trafficAgents)
scout.SetMetadatum("get_pod_yaml", gl.podYaml)
scout.SetMetadatum("anonymized_logs", gl.anon)
scout.Report(log.WithDiscardingLogger(ctx), "used_gather_logs")
// Get all logs from the logdir that match the daemons the user cares about.
logFiles, err := os.ReadDir(logDir)
if err != nil {
return errcat.User.New(err)
}
for _, entry := range logFiles {
if entry.IsDir() {
continue
}
for _, logType := range daemonLogs {
if strings.Contains(entry.Name(), logType) {
srcFile := fmt.Sprintf("%s/%s", logDir, entry.Name())
dstFile := fmt.Sprintf("%s/%s", exportDir, entry.Name())
if err := copyFiles(dstFile, srcFile); err != nil {
// We don't want to fail / exit abruptly if we can't copy certain
// files, but we do want the user to know we were unsuccessful
fmt.Fprintf(stderr, "failed exporting %s: %s\n", entry.Name(), err)
continue
}
}
}
}
// Since getting the logs from k8s requires the connector, let's only do this
// work if we know the user wants to get logs from k8s.
if gl.trafficManager || gl.trafficAgents != "None" {
// To get logs from the components in the kubernetes cluster, we ask the
// traffic-manager.
rq := &manager.GetLogsRequest{
TrafficManager: gl.trafficManager,
Agents: gl.trafficAgents,
GetPodYaml: gl.podYaml,
}
err = withConnector(cmd, false, func(_ context.Context, _ connector.ConnectorClient, _ *connector.ConnectInfo, _ daemon.DaemonClient) error {
err = cliutil.WithManager(ctx, func(ctx context.Context, managerClient manager.ManagerClient) error {
lr, err := managerClient.GetLogs(ctx, rq)
if err != nil {
return err
}
if err := writeResponseToFiles(lr, anonymizer, exportDir, gl.anon); err != nil {
return err
}
return nil
})
if err != nil {
return err
}
return nil
})
// We let the user know we were unable to get logs from the kubernetes components,
// and why, but this shouldn't block the command returning successful with the logs
// it was able to get.
if err != nil {
fmt.Fprintf(stdout, "error getting logs from kubernetes components: %s\n", err)
}
}
// Zip up all the files we've created in the zip directory and return that to the user
dirEntries, err := os.ReadDir(exportDir)
files := make([]string, len(dirEntries))
if err != nil {
return errcat.User.New(err)
}
for i, entry := range dirEntries {
if entry.IsDir() {
files = files[:len(files)-1]
continue
}
fullFileName := fmt.Sprintf("%s/%s", exportDir, entry.Name())
// anonymize the log if necessary
if gl.anon {
if err := anonymizeLog(stdout, fullFileName, anonymizer); err != nil {
fmt.Fprintf(stdout, "error anonymizing %s: %s\n", fullFileName, err)
}
}
files[i] = fullFileName
}
if err := zipFiles(files, gl.outputFile); err != nil {
return errcat.User.New(err)
}
fmt.Fprintf(stdout, "Logs have been exported to %s\n", gl.outputFile)
return nil
}
// writeResponseToFiles contains the logic for parsing the response from the
// manager and writing its components into logical files.
func writeResponseToFiles(lr *manager.LogsResponse, anonymizer *anonymizer, exportDir string, anonymize bool) error {
createFileWithContent := func(fileName, content string) error {
fd, err := os.Create(fileName)
if err != nil {
return err
}
defer fd.Close()
fdWriter := bufio.NewWriter(fd)
_, err = fdWriter.WriteString(content)
if err != nil {
return err
}
fdWriter.Flush()
return nil
}
// Write the logs for each pod to files
for podName, log := range lr.PodLogs {
podName = getPodName(podName, anonymize, anonymizer)
agentLogFile := fmt.Sprintf("%s/%s.log", exportDir, podName)
if err := createFileWithContent(agentLogFile, log); err != nil {
return err
}
}
// Write the pod yaml to files
for podName, yaml := range lr.PodYaml {
podName = getPodName(podName, anonymize, anonymizer)
podYamlFile := fmt.Sprintf("%s/%s.yaml", exportDir, podName)
if err := createFileWithContent(podYamlFile, yaml); err != nil {
return err
}
}
return nil
}
// copyFiles copies files from one location into another.
func copyFiles(dstFile, srcFile string) error {
srcWriter, err := os.Open(srcFile)
if err != nil {
return err
}
defer srcWriter.Close()
dstWriter, err := os.Create(dstFile)
if err != nil {
return err
}
defer dstWriter.Close()
if _, err := io.Copy(dstWriter, srcWriter); err != nil {
return err
}
return nil
}
// zipFiles creates a zip file with the contents of all the files passed in.
// If some of the files do not exist, it will include that in the error message
// but it will still create a zip file with as many files as it can.
func zipFiles(files []string, zipFileName string) error {
zipFile, err := os.Create(zipFileName)
if err != nil {
return err
}
defer zipFile.Close()
zipWriter := zip.NewWriter(zipFile)
defer zipWriter.Close()
addFileToZip := func(file string) error {
fd, err := os.Open(file)
if err != nil {
return err
}
defer fd.Close()
// Get the header information from the original file
fileInfo, err := os.Stat(file)
if err != nil {
return err
}
fileHeader, err := zip.FileInfoHeader(fileInfo)
if err != nil {
return err
}
fileHeader.Method = zip.Deflate
if err != nil {
return err
}
// Get the basename of the file since that's all we want
// to include in the zip
baseName := filepath.Base(file)
fileHeader.Name = baseName
zfd, err := zipWriter.CreateHeader(fileHeader)
if err != nil {
return err
}
if _, err := io.Copy(zfd, fd); err != nil {
return err
}
return nil
}
// Make a note of the files we fail to add to the zip so users know if the
// zip is incomplete
errMsg := ""
for _, file := range files {
// If the file doesn't have a name, then we obviously can't add it to
// the zip. We have handling elsewhere to prevent files like this from
// getting here but are extra cautious.
if file == "" {
continue
}
if err := addFileToZip(file); err != nil {
errMsg += fmt.Sprintf("failed adding %s to zip file: %s ", file, err)
}
}
if errMsg != "" {
return errors.New(errMsg)
}
return nil
}
// getPodName either returns the podName passed in or gets the anonymized
// name of the pod. If the podName has not been yet anonymized in the
// anonymizer, then it will create the anonymized name and store it in
// the anonymizer.
func getPodName(podName string, anon bool, anonymizer *anonymizer) string {
// If we aren't anonymizing the logs, just return the podName
if !anon {
return podName
}
// If this pod name has already been mapped, return that
if anonName, ok := anonymizer.podNames[podName]; ok {
return anonName
}
// the podName hasn't been anonymized yet so we split it up
// so we can anonymize the namespace
nameComponents := strings.SplitN(podName, ".", 2)
if len(nameComponents) != 2 {
// Note: the ordinal here is based on the total number of
// pods, not the number of anonPods that are found. This
// shouldn't be a problem because the main goal of this
// is to make them distinct, but should we ever want the
// ordinals to be strictly for anonPods, we'll need to
// make a change here.
unknownPodName := fmt.Sprintf("anonPod-%d.anonNamespace",
len(anonymizer.podNames)+1)
anonymizer.podNames[podName] = unknownPodName
return unknownPodName
}
var anonPodName, anonNamespace string
name, namespace := nameComponents[0], nameComponents[1]
if val, ok := anonymizer.namespaces[namespace]; ok {
anonNamespace = val
} else {
anonNamespace = fmt.Sprintf("namespace-%d", len(anonymizer.namespaces)+1)
anonymizer.namespaces[namespace] = anonNamespace
}
// we want to special case the traffic-manager so we can easily distinguish
// between that and the traffic-agents
if strings.Contains(name, "traffic-manager") {
anonPodName = fmt.Sprintf("traffic-manager.%s", anonNamespace)
} else {
anonPodName = fmt.Sprintf("pod-%d.%s", len(anonymizer.podNames)+1, anonNamespace)
}
// Store the anonPodName in the map
anonymizer.podNames[podName] = anonPodName
return anonPodName
}
// anonymizeLog is a helper function that replaces the namespace + podName
// used in the log with its anonymized version, provided by the anonymizer.
// It overwrites the file with the anonymized version.
func anonymizeLog(stdout io.Writer, logFile string, anonymizer *anonymizer) error {
// Read the contents we are going to overwrite from the file
content, err := os.ReadFile(logFile)
if err != nil {
return err
}
// Open the file with write so we can overwrite it
stringContent := string(content)
f, err := os.OpenFile(logFile, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
// First we replace the actual namespace with the anonymized
// version.
for namespace, anonNamespace := range anonymizer.namespaces {
stringContent = strings.ReplaceAll(stringContent, namespace, anonNamespace)
}
// Now we do pod name which is a little bit more complicated
for fullPodName, fullAnonPodName := range anonymizer.podNames {
// strip the namespace off of the anonymized name
anonPodParts := strings.Split(fullAnonPodName, ".")
anonPodName := anonPodParts[0]
// Strip the namespace off of the podName
podParts := strings.Split(fullPodName, ".")
for _, name := range getSignificantPodNames(podParts[0]) {
stringContent = strings.ReplaceAll(stringContent, name, anonPodName)
}
}
// Overwrite the file with the anonymized log
err = f.Truncate(0)
if err != nil {
return err
}
_, err = f.Seek(0, 0)
if err != nil {
return err
}
fdWriter := bufio.NewWriter(f)
_, err = fdWriter.WriteString(stringContent)
if err != nil {
return err
}
fdWriter.Flush()
return nil
}
// getSignificantPodNames is a helper function that takes in a
// pod's name and returns the significant subnames that we want
// to anonymize. It currently works for pods owned by StatefulSets,
// ReplicaSets, and Deployments.
func getSignificantPodNames(podName string) []string {
// if the pods ends in an ordinal we can be pretty sure it's
// coming from a StatefulSet.
statefulSetRegex := regexp.MustCompile("(.*)-([0-9]+)$")
// ReplicasSets, and therefore Deployments because they create
// ReplicaSets, have a hash followed by a 5 character identity
// string attached to the end.
replicaSetRegex := regexp.MustCompile("(.*)-([0-9a-f]+)-([0-9a-z]{5})$")
sigNames := []string{}
switch {
case statefulSetRegex.MatchString(podName):
match := statefulSetRegex.FindStringSubmatch(podName)
appName := match[1]
// Add the pod name with and without the ordinal
sigNames = append(sigNames, podName, appName)
case replicaSetRegex.MatchString(podName):
match := replicaSetRegex.FindStringSubmatch(podName)
appName := match[1]
rsName := fmt.Sprintf("%s-%s", appName, match[2])
// add the app name with and without generated ReplicaSet hash
sigNames = append(sigNames, podName, rsName, appName)
default:
// For default we don't do anything and will leave sigNames
// as an empty slice
}
return sigNames
}