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