...

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

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

     1  // Copyright 2020 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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package iptable
    15  
    16  import (
    17  	"context"
    18  	"fmt"
    19  
    20  	v1 "k8s.io/api/core/v1"
    21  	"sigs.k8s.io/controller-runtime/pkg/client"
    22  
    23  	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    24  	"github.com/chaos-mesh/chaos-mesh/controllers/config"
    25  	"github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils"
    26  	pb "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
    27  
    28  	daemonClient "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/client"
    29  )
    30  
    31  // SetIptablesChains makes grpc call to chaosdaemon to flush iptable
    32  func SetIptablesChains(ctx context.Context, c client.Client, pod *v1.Pod, chains []*pb.Chain) error {
    33  	pbClient, err := daemonClient.NewChaosDaemonClient(ctx, c, pod, config.ControllerCfg.ChaosDaemonPort)
    34  	if err != nil {
    35  		return err
    36  	}
    37  	defer pbClient.Close()
    38  
    39  	if len(pod.Status.ContainerStatuses) == 0 {
    40  		return fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
    41  	}
    42  
    43  	containerID := pod.Status.ContainerStatuses[0].ContainerID
    44  
    45  	_, err = pbClient.SetIptablesChains(ctx, &pb.IptablesChainsRequest{
    46  		Chains:      chains,
    47  		ContainerId: containerID,
    48  		EnterNS:     true,
    49  	})
    50  	return err
    51  }
    52  
    53  // GenerateName generates chain name for network chaos
    54  func GenerateName(direction pb.Chain_Direction, networkchaos *v1alpha1.NetworkChaos) (chainName string) {
    55  	switch direction {
    56  	case pb.Chain_INPUT:
    57  		chainName = "INPUT/" + netutils.CompressName(networkchaos.Name, 21, "")
    58  	case pb.Chain_OUTPUT:
    59  		chainName = "OUTPUT/" + netutils.CompressName(networkchaos.Name, 20, "")
    60  	}
    61  
    62  	return
    63  }
    64