...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package graph
17
18 import (
19 "context"
20 "fmt"
21 "strings"
22
23 "github.com/pkg/errors"
24 v1 "k8s.io/api/core/v1"
25
26 "github.com/chaos-mesh/chaos-mesh/pkg/ctrlserver/graph/model"
27 )
28
29
30 func (r *Resolver) GetPidFromPS(ctx context.Context, pod *v1.Pod) ([]*model.Process, error) {
31 cmd := "ps"
32 out, err := r.ExecBypass(ctx, pod, cmd)
33 if err != nil {
34 return nil, errors.Wrapf(err, "run command %s failed", cmd)
35 }
36 outLines := strings.Split(string(out), "\n")
37 if len(outLines) < 2 {
38 return nil, fmt.Errorf("ps returns empty")
39 }
40 titles := strings.Fields(outLines[0])
41 var pidColumn, cmdColumn int
42 for i, t := range titles {
43 if t == "PID" {
44 pidColumn = i
45 }
46 if t == "COMMAND" || t == "CMD" {
47 cmdColumn = i
48 }
49 }
50 if pidColumn == 0 && cmdColumn == 0 {
51 return nil, fmt.Errorf("parsing ps error: could not get PID and COMMAND column")
52 }
53
54 var processes []*model.Process
55 for _, line := range outLines[1:] {
56 item := strings.Fields(line)
57
58 if len(item) == 0 {
59 break
60 }
61 if item[cmdColumn] == cmd {
62 continue
63 }
64 processes = append(processes, &model.Process{
65 Pod: pod,
66 Pid: item[pidColumn],
67 Command: item[cmdColumn],
68 })
69 }
70 return processes, nil
71 }
72