|
| 1 | +package collect |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "os/exec" |
| 9 | + |
| 10 | + "github.com/pkg/errors" |
| 11 | + troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2" |
| 12 | +) |
| 13 | + |
| 14 | +type ServiceInfo struct { |
| 15 | + Unit string `json:"Unit"` |
| 16 | + Load string `json:"Load"` |
| 17 | + Active string `json:"Active"` |
| 18 | + Sub string `json:"Sub"` |
| 19 | +} |
| 20 | + |
| 21 | +const systemctlFormat = `%s %s %s %s` // this leaves off the description |
| 22 | + |
| 23 | +type CollectHostServices struct { |
| 24 | + hostCollector *troubleshootv1beta2.HostServices |
| 25 | +} |
| 26 | + |
| 27 | +func (c *CollectHostServices) Title() string { |
| 28 | + return hostCollectorTitleOrDefault(c.hostCollector.HostCollectorMeta, "Block Devices") |
| 29 | +} |
| 30 | + |
| 31 | +func (c *CollectHostServices) IsExcluded() (bool, error) { |
| 32 | + return isExcluded(c.hostCollector.Exclude) |
| 33 | +} |
| 34 | + |
| 35 | +func (c *CollectHostServices) Collect(progressChan chan<- interface{}) (map[string][]byte, error) { |
| 36 | + var devices []ServiceInfo |
| 37 | + |
| 38 | + cmd := exec.Command("systemctl", "list-units", "--type=service", "--no-legend", "--all") |
| 39 | + stdout, err := cmd.Output() |
| 40 | + if err != nil { |
| 41 | + return nil, errors.Wrapf(err, "failed to execute systemctl") |
| 42 | + } |
| 43 | + buf := bytes.NewBuffer(stdout) |
| 44 | + scanner := bufio.NewScanner(buf) |
| 45 | + |
| 46 | + for scanner.Scan() { |
| 47 | + bdi := ServiceInfo{} |
| 48 | + fmt.Sscanf( |
| 49 | + scanner.Text(), |
| 50 | + systemctlFormat, |
| 51 | + &bdi.Unit, |
| 52 | + &bdi.Load, |
| 53 | + &bdi.Active, |
| 54 | + &bdi.Sub, |
| 55 | + ) |
| 56 | + |
| 57 | + devices = append(devices, bdi) |
| 58 | + } |
| 59 | + |
| 60 | + b, err := json.Marshal(devices) |
| 61 | + if err != nil { |
| 62 | + return nil, errors.Wrap(err, "failed to marshal systemctl service info") |
| 63 | + } |
| 64 | + |
| 65 | + return map[string][]byte{ |
| 66 | + "system/systemctl_services.json": b, |
| 67 | + }, nil |
| 68 | +} |
0 commit comments