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