1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package netem
17
18 import (
19 "math"
20 "strconv"
21 "strings"
22
23 chaosdaemon "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
24 )
25
26
27
28
29
30
31
32 func MergeNetem(a, b *chaosdaemon.Netem) *chaosdaemon.Netem {
33 if a == nil && b == nil {
34 return nil
35 }
36
37
38 if a == nil {
39 a = &chaosdaemon.Netem{}
40 }
41 if b == nil {
42 b = &chaosdaemon.Netem{}
43 }
44 return &chaosdaemon.Netem{
45 Time: maxu32(a.GetTime(), b.GetTime()),
46 Jitter: maxu32(a.GetJitter(), b.GetJitter()),
47 DelayCorr: maxf32(a.GetDelayCorr(), b.GetDelayCorr()),
48 Limit: maxu32(a.GetLimit(), b.GetLimit()),
49 Loss: maxf32(a.GetLoss(), b.GetLoss()),
50 LossCorr: maxf32(a.GetLossCorr(), b.GetLossCorr()),
51 Gap: maxu32(a.GetGap(), b.GetGap()),
52 Duplicate: maxf32(a.GetDuplicate(), b.GetDuplicate()),
53 DuplicateCorr: maxf32(a.GetDuplicateCorr(), b.GetDuplicateCorr()),
54 Reorder: maxf32(a.GetReorder(), b.GetReorder()),
55 ReorderCorr: maxf32(a.GetReorderCorr(), b.GetReorderCorr()),
56 Corrupt: maxf32(a.GetCorrupt(), b.GetCorrupt()),
57 CorruptCorr: maxf32(a.GetCorruptCorr(), b.GetCorruptCorr()),
58 Rate: maxRateString(a.GetRate(), b.GetRate()),
59 }
60 }
61
62 func maxu32(a, b uint32) uint32 {
63 if a > b {
64 return a
65 }
66 return b
67 }
68
69 func maxf32(a, b float32) float32 {
70 return float32(math.Max(float64(a), float64(b)))
71 }
72
73 func parseRate(nu string) uint64 {
74
75 s := strings.ToLower(strings.TrimSpace(nu))
76
77 for i, u := range []string{"tbps", "gbps", "mbps", "kbps", "bps"} {
78 if strings.HasSuffix(s, u) {
79 ts := strings.TrimSuffix(s, u)
80 s := strings.TrimSpace(ts)
81
82 n, err := strconv.ParseUint(s, 10, 64)
83
84 if err != nil {
85 return 0
86 }
87
88
89 for j := 4 - i; j > 0; j-- {
90 n = n * 1024
91 }
92
93 return n
94 }
95 }
96
97 for i, u := range []string{"tbit", "gbit", "mbit", "kbit", "bit"} {
98 if strings.HasSuffix(s, u) {
99 ts := strings.TrimSuffix(s, u)
100 s := strings.TrimSpace(ts)
101
102 n, err := strconv.ParseUint(s, 10, 64)
103
104 if err != nil {
105 return 0
106 }
107
108
109 for j := 4 - i; j > 0; j-- {
110 n = n * 1000
111 }
112 n = n / 8
113
114 return n
115 }
116 }
117
118 return 0
119 }
120
121 func maxRateString(a, b string) string {
122 if parseRate(a) > parseRate(b) {
123 return a
124 }
125 return b
126 }
127