...
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 "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/podnetworkchaos/netutils"
25 "github.com/chaos-mesh/chaos-mesh/controllers/utils"
26 pb "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
27 )
28
29
30 func BuildIPSet(pods []v1.Pod, externalCidrs []string, networkchaos *v1alpha1.NetworkChaos, namePostFix string, source string) v1alpha1.RawIPSet {
31 name := GenerateIPSetName(networkchaos, namePostFix)
32 cidrs := externalCidrs
33
34 for _, pod := range pods {
35 if len(pod.Status.PodIP) > 0 {
36 cidrs = append(cidrs, netutils.IPToCidr(pod.Status.PodIP))
37 }
38 }
39
40 return v1alpha1.RawIPSet{
41 Name: name,
42 Cidrs: cidrs,
43 RawRuleSource: v1alpha1.RawRuleSource{
44 Source: source,
45 },
46 }
47 }
48
49
50 func GenerateIPSetName(networkchaos *v1alpha1.NetworkChaos, namePostFix string) string {
51 return netutils.CompressName(networkchaos.Name, 27, namePostFix)
52 }
53
54
55 func FlushIPSets(ctx context.Context, c client.Client, pod *v1.Pod, ipsets []*pb.IPSet) error {
56 pbClient, err := utils.NewChaosDaemonClient(ctx, c, pod)
57 if err != nil {
58 return err
59 }
60 defer pbClient.Close()
61
62 if len(pod.Status.ContainerStatuses) == 0 {
63 return fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
64 }
65
66 containerID := pod.Status.ContainerStatuses[0].ContainerID
67
68 _, err = pbClient.FlushIPSets(ctx, &pb.IPSetsRequest{
69 Ipsets: ipsets,
70 ContainerId: containerID,
71 EnterNS: true,
72 })
73 return err
74 }
75