|
| 1 | +package diagnostic |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "os/exec" |
| 9 | + "path/filepath" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +type DockerLogCollector struct { |
| 14 | + containerID string // This member identifies the container by identifier or name |
| 15 | +} |
| 16 | + |
| 17 | +func NewDockerLogCollector(containerID string) *DockerLogCollector { |
| 18 | + return &DockerLogCollector{ |
| 19 | + containerID, |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +func (collector *DockerLogCollector) Collect(ctx context.Context) (*LogInformation, error) { |
| 24 | + tmp := os.TempDir() |
| 25 | + |
| 26 | + outputHandle, err := os.Create(filepath.Join(tmp, logFilename)) |
| 27 | + if err != nil { |
| 28 | + return nil, fmt.Errorf("error opening output file: %w", err) |
| 29 | + } |
| 30 | + |
| 31 | + defer outputHandle.Close() |
| 32 | + |
| 33 | + // Calculate 2 weeks ago |
| 34 | + since := time.Now().Add(twoWeeksOffset).Format(time.RFC3339) |
| 35 | + |
| 36 | + command := exec.CommandContext( |
| 37 | + ctx, |
| 38 | + "docker", |
| 39 | + "logs", |
| 40 | + "--tail", |
| 41 | + tailMaxNumberOfLines, |
| 42 | + "--since", |
| 43 | + since, |
| 44 | + collector.containerID, |
| 45 | + ) |
| 46 | + |
| 47 | + stdoutReader, err := command.StdoutPipe() |
| 48 | + if err != nil { |
| 49 | + return nil, fmt.Errorf( |
| 50 | + "error retrieving output from command '%s': %w", |
| 51 | + command.String(), |
| 52 | + err, |
| 53 | + ) |
| 54 | + } |
| 55 | + |
| 56 | + if err := command.Start(); err != nil { |
| 57 | + return nil, fmt.Errorf( |
| 58 | + "error running command '%s': %w", |
| 59 | + command.String(), |
| 60 | + err, |
| 61 | + ) |
| 62 | + } |
| 63 | + |
| 64 | + _, err = io.Copy(outputHandle, stdoutReader) |
| 65 | + if err != nil { |
| 66 | + return nil, fmt.Errorf( |
| 67 | + "error copying output from %s to file %s: %w", |
| 68 | + command.String(), |
| 69 | + outputHandle.Name(), |
| 70 | + err, |
| 71 | + ) |
| 72 | + } |
| 73 | + |
| 74 | + if err := command.Wait(); err != nil { |
| 75 | + return nil, fmt.Errorf( |
| 76 | + "error waiting from command '%s': %w", |
| 77 | + command.String(), |
| 78 | + err, |
| 79 | + ) |
| 80 | + } |
| 81 | + |
| 82 | + return NewLogInformation(outputHandle.Name(), true, false), nil |
| 83 | +} |
0 commit comments