...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/chaosctl/recover/recover.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/chaosctl/recover

     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 recover
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"strings"
    22  
    23  	"github.com/pkg/errors"
    24  
    25  	ctrlclient "github.com/chaos-mesh/chaos-mesh/pkg/ctrl/client"
    26  )
    27  
    28  // PartialPod is a subset of the Pod type.
    29  // It contains necessary information for forced recovery.
    30  type PartialPod struct {
    31  	Namespace string
    32  	Name      string
    33  	Processes []struct {
    34  		Pid, Command string
    35  	}
    36  	TcQdisc  []string
    37  	Iptables []string
    38  }
    39  
    40  type Recoverer interface {
    41  	// Recover target pod forcedly
    42  	Recover(ctx context.Context, pod *PartialPod) error
    43  }
    44  
    45  type RecovererBuilder func(client *ctrlclient.CtrlClient) Recoverer
    46  
    47  type cleanProcessRecoverer struct {
    48  	client  *ctrlclient.CtrlClient
    49  	process string
    50  }
    51  
    52  func newCleanProcessRecoverer(client *ctrlclient.CtrlClient, process string) Recoverer {
    53  	return &cleanProcessRecoverer{
    54  		client:  client,
    55  		process: process,
    56  	}
    57  }
    58  
    59  func (r *cleanProcessRecoverer) Recover(ctx context.Context, pod *PartialPod) error {
    60  	var pids []string
    61  	for _, process := range pod.Processes {
    62  		if process.Command == r.process {
    63  			pids = append(pids, process.Pid)
    64  		}
    65  	}
    66  
    67  	if len(pids) == 0 {
    68  		printStep(fmt.Sprintf("all %s processes are cleaned up", r.process))
    69  		return nil
    70  	}
    71  	printStep(fmt.Sprintf("cleaning %s processes: %v", r.process, pids))
    72  
    73  	killedPids, err := r.client.KillProcesses(ctx, pod.Namespace, pod.Name, pids)
    74  	if err != nil {
    75  		return errors.Wrapf(err, "kill %s processes", r.process)
    76  	}
    77  	if len(killedPids) != 0 {
    78  		printStep(fmt.Sprintf("%s processes(%s) are cleaned up", r.process, strings.Join(killedPids, ", ")))
    79  	}
    80  
    81  	return nil
    82  }
    83