...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package iptable
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/api/v1alpha1"
27 "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
28 "github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils"
29 chaosdaemonclient "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/client"
30 pb "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
31 )
32
33 var log = ctrl.Log.WithName("iptable")
34
35
36 func SetIptablesChains(ctx context.Context, pbClient chaosdaemonclient.ChaosDaemonClientInterface, pod *v1.Pod, chains []*pb.Chain) error {
37 var err error
38
39 if len(pod.Status.ContainerStatuses) == 0 {
40 err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
41
42 return err
43 }
44
45 log.Info("Setting IP Tables Chains...")
46 for _, containerStatus := range pod.Status.ContainerStatuses {
47 containerName := containerStatus.Name
48 containerID := containerStatus.ContainerID
49 log.Info("attempting to set ip table chains", "containerName", containerName, "containerID", containerID)
50 _, err = pbClient.SetIptablesChains(ctx, &pb.IptablesChainsRequest{
51 Chains: chains,
52 ContainerId: containerID,
53 EnterNS: true,
54 })
55
56 if err != nil {
57 log.Error(err, fmt.Sprintf("error while setting ip tables chains for container %s, id %s", containerName, containerID))
58 } else {
59 log.Info("Successfully set ip table chains")
60 return nil
61 }
62 }
63
64 return errors.Errorf("unable to set ip tables chains for pod %s", pod.Name)
65 }
66
67
68 func GenerateName(direction pb.Chain_Direction, networkchaos *v1alpha1.NetworkChaos) (chainName string) {
69 switch direction {
70 case pb.Chain_INPUT:
71 chainName = "INPUT/" + netutils.CompressName(networkchaos.Name, 21, "")
72 case pb.Chain_OUTPUT:
73 chainName = "OUTPUT/" + netutils.CompressName(networkchaos.Name, 20, "")
74 }
75
76 return
77 }
78