...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/ctrlserver/graph/process.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/ctrlserver/graph

     1  // Copyright 2021 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    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  // GetPidFromPS returns pid-command pairs
    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  		// break when got empty line
    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