|
| 1 | +package collect |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "os/exec" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/pkg/errors" |
| 11 | + troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2" |
| 12 | +) |
| 13 | + |
| 14 | +type HostRunInfo struct { |
| 15 | + Command string `json:"command"` |
| 16 | + ExitCode string `json:"exitCode"` |
| 17 | + Error string `json:"error"` |
| 18 | +} |
| 19 | + |
| 20 | +type CollectHostRun struct { |
| 21 | + hostCollector *troubleshootv1beta2.HostRun |
| 22 | + BundlePath string |
| 23 | +} |
| 24 | + |
| 25 | +func (c *CollectHostRun) Title() string { |
| 26 | + return hostCollectorTitleOrDefault(c.hostCollector.HostCollectorMeta, "Run Host") |
| 27 | +} |
| 28 | + |
| 29 | +func (c *CollectHostRun) IsExcluded() (bool, error) { |
| 30 | + return isExcluded(c.hostCollector.Exclude) |
| 31 | +} |
| 32 | + |
| 33 | +func (c *CollectHostRun) Collect(progressChan chan<- interface{}) (map[string][]byte, error) { |
| 34 | + runHostCollector := c.hostCollector |
| 35 | + |
| 36 | + cmd := exec.Command(runHostCollector.Command, runHostCollector.Args...) |
| 37 | + |
| 38 | + var stdout, stderr bytes.Buffer |
| 39 | + cmd.Stdout = &stdout |
| 40 | + cmd.Stderr = &stderr |
| 41 | + |
| 42 | + runInfo := HostRunInfo{ |
| 43 | + Command: cmd.String(), |
| 44 | + ExitCode: "0", |
| 45 | + } |
| 46 | + |
| 47 | + err := cmd.Run() |
| 48 | + if err != nil { |
| 49 | + if werr, ok := err.(*exec.ExitError); ok { |
| 50 | + runInfo.ExitCode = strings.TrimPrefix(werr.Error(), "exit status ") |
| 51 | + runInfo.Error = stderr.String() |
| 52 | + } else { |
| 53 | + return nil, errors.Wrap(err, "failed to run") |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + collectorName := c.hostCollector.CollectorName |
| 58 | + if collectorName == "" { |
| 59 | + collectorName = "run-host" |
| 60 | + } |
| 61 | + resultInfo := filepath.Join("host-collectors/run-host", collectorName+"-info.json") |
| 62 | + result := filepath.Join("host-collectors/run-host", collectorName+".txt") |
| 63 | + |
| 64 | + b, err := json.Marshal(runInfo) |
| 65 | + if err != nil { |
| 66 | + return nil, errors.Wrap(err, "failed to marshal run host result") |
| 67 | + } |
| 68 | + |
| 69 | + output := NewResult() |
| 70 | + output.SaveResult(c.BundlePath, resultInfo, bytes.NewBuffer(b)) |
| 71 | + output.SaveResult(c.BundlePath, result, bytes.NewBuffer(stdout.Bytes())) |
| 72 | + |
| 73 | + runHostOutput := map[string][]byte{ |
| 74 | + resultInfo: b, |
| 75 | + result: stdout.Bytes(), |
| 76 | + } |
| 77 | + |
| 78 | + return runHostOutput, nil |
| 79 | +} |
0 commit comments