1
2
3
4
5
6
7
8
9
10
11
12
13
14 package utils
15
16 import (
17 "context"
18 "math"
19
20 "google.golang.org/grpc"
21 v1 "k8s.io/api/core/v1"
22 "sigs.k8s.io/controller-runtime/pkg/client"
23
24 chaosdaemon "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
25 "github.com/chaos-mesh/chaos-mesh/pkg/mock"
26 )
27
28
29 type ChaosDaemonClientInterface interface {
30 chaosdaemon.ChaosDaemonClient
31 Close() error
32 }
33
34
35 type GrpcChaosDaemonClient struct {
36 chaosdaemon.ChaosDaemonClient
37 conn *grpc.ClientConn
38 }
39
40 func (c *GrpcChaosDaemonClient) Close() error {
41 return c.conn.Close()
42 }
43
44
45 func NewChaosDaemonClient(ctx context.Context, c client.Client, pod *v1.Pod, port int) (ChaosDaemonClientInterface, error) {
46 if cli := mock.On("MockChaosDaemonClient"); cli != nil {
47 return cli.(ChaosDaemonClientInterface), nil
48 }
49 if err := mock.On("NewChaosDaemonClientError"); err != nil {
50 return nil, err.(error)
51 }
52
53 cc, err := CreateGrpcConnection(ctx, c, pod, port)
54 if err != nil {
55 return nil, err
56 }
57 return &GrpcChaosDaemonClient{
58 ChaosDaemonClient: chaosdaemon.NewChaosDaemonClient(cc),
59 conn: cc,
60 }, nil
61 }
62
63
64 func NewChaosDaemonClientLocally(port int) (ChaosDaemonClientInterface, error) {
65 if cli := mock.On("MockChaosDaemonClient"); cli != nil {
66 return cli.(ChaosDaemonClientInterface), nil
67 }
68 if err := mock.On("NewChaosDaemonClientError"); err != nil {
69 return nil, err.(error)
70 }
71
72 cc, err := CreateGrpcConnectionWithAddress("localhost", port)
73 if err != nil {
74 return nil, err
75 }
76 return &GrpcChaosDaemonClient{
77 ChaosDaemonClient: chaosdaemon.NewChaosDaemonClient(cc),
78 conn: cc,
79 }, nil
80 }
81
82
83
84
85
86
87
88 func MergeNetem(a, b *chaosdaemon.Netem) *chaosdaemon.Netem {
89 if a == nil && b == nil {
90 return nil
91 }
92
93
94 if a == nil {
95 a = &chaosdaemon.Netem{}
96 }
97 if b == nil {
98 b = &chaosdaemon.Netem{}
99 }
100 return &chaosdaemon.Netem{
101 Time: maxu32(a.GetTime(), b.GetTime()),
102 Jitter: maxu32(a.GetJitter(), b.GetJitter()),
103 DelayCorr: maxf32(a.GetDelayCorr(), b.GetDelayCorr()),
104 Limit: maxu32(a.GetLimit(), b.GetLimit()),
105 Loss: maxf32(a.GetLoss(), b.GetLoss()),
106 LossCorr: maxf32(a.GetLossCorr(), b.GetLossCorr()),
107 Gap: maxu32(a.GetGap(), b.GetGap()),
108 Duplicate: maxf32(a.GetDuplicate(), b.GetDuplicate()),
109 DuplicateCorr: maxf32(a.GetDuplicateCorr(), b.GetDuplicateCorr()),
110 Reorder: maxf32(a.GetReorder(), b.GetReorder()),
111 ReorderCorr: maxf32(a.GetReorderCorr(), b.GetReorderCorr()),
112 Corrupt: maxf32(a.GetCorrupt(), b.GetCorrupt()),
113 CorruptCorr: maxf32(a.GetCorruptCorr(), b.GetCorruptCorr()),
114 }
115 }
116
117 func maxu32(a, b uint32) uint32 {
118 if a > b {
119 return a
120 }
121 return b
122 }
123
124 func maxf32(a, b float32) float32 {
125 return float32(math.Max(float64(a), float64(b)))
126 }
127