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