...

Source file src/github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/tc/tc.go

Documentation: github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/tc

     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 tc
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  
    22  	"github.com/pkg/errors"
    23  	v1 "k8s.io/api/core/v1"
    24  	ctrl "sigs.k8s.io/controller-runtime"
    25  
    26  	"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
    27  	chaosdaemonclient "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/client"
    28  	"github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
    29  )
    30  
    31  var log = ctrl.Log.WithName("tc")
    32  
    33  // SetTcs makes grpc call to chaosdaemon to flush traffic control rules
    34  func SetTcs(ctx context.Context, pbClient chaosdaemonclient.ChaosDaemonClientInterface, pod *v1.Pod, tcs []*pb.Tc) error {
    35  	var err error
    36  
    37  	if len(pod.Status.ContainerStatuses) == 0 {
    38  		err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
    39  
    40  		return err
    41  	}
    42  
    43  	log.Info("Settings Tcs...")
    44  	for _, containerStatus := range pod.Status.ContainerStatuses {
    45  		containerName := containerStatus.Name
    46  		containerID := containerStatus.ContainerID
    47  		log.Info("attempting to set tcs", "containerName", containerName, "containerID", containerID)
    48  
    49  		_, err = pbClient.SetTcs(ctx, &pb.TcsRequest{
    50  			Tcs:         tcs,
    51  			ContainerId: containerID,
    52  			EnterNS:     true,
    53  		})
    54  
    55  		if err != nil {
    56  			log.Error(err, fmt.Sprintf("error while setting tcs for container %s, id %s", containerName, containerID))
    57  		} else {
    58  			log.Info("Successfully set tcs")
    59  			return nil
    60  		}
    61  	}
    62  
    63  	return errors.Errorf("unable to set tcs for pod %s", pod.Name)
    64  }
    65