...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ipset
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("ipset")
31
32
33 func BuildIPSet(pods []v1.Pod, externalCidrs []string, networkchaos *v1alpha1.NetworkChaos, namePostFix string, source string) v1alpha1.RawIPSet {
34 name := GenerateIPSetName(networkchaos, namePostFix)
35 cidrs := externalCidrs
36
37 for _, pod := range pods {
38 if len(pod.Status.PodIP) > 0 {
39 cidrs = append(cidrs, netutils.IPToCidr(pod.Status.PodIP))
40 }
41 }
42
43 return v1alpha1.RawIPSet{
44 Name: name,
45 Cidrs: cidrs,
46 RawRuleSource: v1alpha1.RawRuleSource{
47 Source: source,
48 },
49 }
50 }
51
52
53 func GenerateIPSetName(networkchaos *v1alpha1.NetworkChaos, namePostFix string) string {
54 return netutils.CompressName(networkchaos.Name, 27, namePostFix)
55 }
56
57
58 func FlushIPSets(ctx context.Context, builder *chaosdaemon.ChaosDaemonClientBuilder, pod *v1.Pod, ipsets []*pb.IPSet) error {
59 pbClient, err := builder.Build(ctx, pod)
60 if err != nil {
61 return err
62 }
63 defer pbClient.Close()
64
65 if len(pod.Status.ContainerStatuses) == 0 {
66 return fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
67 }
68
69 log.Info("Flushing IP Sets....")
70 for _, containerStatus := range pod.Status.ContainerStatuses {
71 containerID := containerStatus.ContainerID
72 log.Info("attempting to flush ip set", "containerID", containerID)
73
74 _, err = pbClient.FlushIPSets(ctx, &pb.IPSetsRequest{
75 Ipsets: ipsets,
76 ContainerId: containerID,
77 EnterNS: true,
78 })
79
80 if err != nil {
81 log.Error(err, fmt.Sprintf("error while flushing ip sets for containerID %s", containerID))
82 } else {
83 log.Info("Successfully flushed ip set")
84 return nil
85 }
86 }
87
88 return fmt.Errorf("unable to flush ip sets for pod %s", pod.Name)
89 }
90