...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package podnetworkchaosmanager
17
18 import (
19 "fmt"
20
21 "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
22 )
23
24
25 type PodNetworkTransaction struct {
26 Steps []Step
27 }
28
29
30 type Step interface {
31
32 Apply(chaos *v1alpha1.PodNetworkChaos) error
33 }
34
35
36 type Clear struct {
37 Source string
38 }
39
40
41 func (s *Clear) Apply(chaos *v1alpha1.PodNetworkChaos) error {
42 ipsets := []v1alpha1.RawIPSet{}
43 for _, ipset := range chaos.Spec.IPSets {
44 if ipset.Source != s.Source {
45 ipsets = append(ipsets, ipset)
46 }
47 }
48 chaos.Spec.IPSets = ipsets
49
50 chains := []v1alpha1.RawIptables{}
51 for _, chain := range chaos.Spec.Iptables {
52 if chain.Source != s.Source {
53 chains = append(chains, chain)
54 }
55 }
56 chaos.Spec.Iptables = chains
57
58 qdiscs := []v1alpha1.RawTrafficControl{}
59 for _, qdisc := range chaos.Spec.TrafficControls {
60 if qdisc.Source != s.Source {
61 qdiscs = append(qdiscs, qdisc)
62 }
63 }
64 chaos.Spec.TrafficControls = qdiscs
65
66 return nil
67 }
68
69
70 type Append struct {
71 Item interface{}
72 }
73
74
75 func (a *Append) Apply(chaos *v1alpha1.PodNetworkChaos) error {
76 switch item := a.Item.(type) {
77 case v1alpha1.RawIPSet:
78 chaos.Spec.IPSets = append(chaos.Spec.IPSets, item)
79 case v1alpha1.RawIptables:
80 chaos.Spec.Iptables = append(chaos.Spec.Iptables, item)
81 case v1alpha1.RawTrafficControl:
82 chaos.Spec.TrafficControls = append(chaos.Spec.TrafficControls, item)
83 default:
84 return fmt.Errorf("unknown type of item")
85 }
86
87 return nil
88 }
89
90
91 func (t *PodNetworkTransaction) Clear(source string) {
92 t.Steps = append(t.Steps, &Clear{
93 Source: source,
94 })
95 }
96
97
98 func (t *PodNetworkTransaction) Append(item interface{}) error {
99 switch item.(type) {
100 case v1alpha1.RawIPSet, v1alpha1.RawIptables, v1alpha1.RawTrafficControl:
101 t.Steps = append(t.Steps, &Append{
102 Item: item,
103 })
104 return nil
105 default:
106 return fmt.Errorf("unknown type of item")
107 }
108 }
109
110
111 func (t *PodNetworkTransaction) Apply(chaos *v1alpha1.PodNetworkChaos) error {
112 for _, s := range t.Steps {
113 err := s.Apply(chaos)
114 if err != nil {
115 return err
116 }
117 }
118
119 return nil
120 }
121