-
Notifications
You must be signed in to change notification settings - Fork 449
/
toxic_collection.go
299 lines (256 loc) · 6.68 KB
/
toxic_collection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package toxiproxy
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"sync"
"github.com/rs/zerolog"
"github.com/Shopify/toxiproxy/v2/stream"
"github.com/Shopify/toxiproxy/v2/toxics"
)
// ToxicCollection contains a list of toxics that are chained together. Each proxy
// has its own collection. A hidden noop toxic is always maintained at the beginning
// of each chain so toxics have a method of pausing incoming data (by interrupting
// the preceding toxic).
type ToxicCollection struct {
sync.Mutex
noop *toxics.ToxicWrapper
proxy *Proxy
chain [][]*toxics.ToxicWrapper
links map[string]*ToxicLink
}
func NewToxicCollection(proxy *Proxy) *ToxicCollection {
collection := &ToxicCollection{
noop: &toxics.ToxicWrapper{
Toxic: new(toxics.NoopToxic),
Type: "noop",
},
proxy: proxy,
chain: make([][]*toxics.ToxicWrapper, stream.NumDirections),
links: make(map[string]*ToxicLink),
}
for dir := range collection.chain {
collection.chain[dir] = make([]*toxics.ToxicWrapper, 1, toxics.Count()+1)
collection.chain[dir][0] = collection.noop
}
return collection
}
func (c *ToxicCollection) ResetToxics(ctx context.Context) {
c.Lock()
defer c.Unlock()
// Remove all but the first noop toxic
for dir := range c.chain {
for len(c.chain[dir]) > 1 {
c.chainRemoveToxic(ctx, c.chain[dir][1])
}
}
}
func (c *ToxicCollection) GetToxic(name string) *toxics.ToxicWrapper {
c.Lock()
defer c.Unlock()
return c.findToxicByName(name)
}
func (c *ToxicCollection) GetToxicArray() []toxics.Toxic {
c.Lock()
defer c.Unlock()
result := make([]toxics.Toxic, 0)
for dir := range c.chain {
for i, toxic := range c.chain[dir] {
if i == 0 {
// Skip the first noop toxic, it should not be visible
continue
}
result = append(result, toxic)
}
}
return result
}
func (c *ToxicCollection) AddToxicJson(data io.Reader) (*toxics.ToxicWrapper, error) {
c.Lock()
defer c.Unlock()
var buffer bytes.Buffer
// Default to a downstream toxic with a toxicity of 1.
wrapper := &toxics.ToxicWrapper{
Stream: "downstream",
Toxicity: 1.0,
Toxic: new(toxics.NoopToxic),
}
err := json.NewDecoder(io.TeeReader(data, &buffer)).Decode(wrapper)
if err != nil {
return nil, joinError(err, ErrBadRequestBody)
}
wrapper.Direction, err = stream.ParseDirection(wrapper.Stream)
if err != nil {
return nil, ErrInvalidStream
}
if wrapper.Name == "" {
wrapper.Name = fmt.Sprintf("%s_%s", wrapper.Type, wrapper.Stream)
}
if toxics.New(wrapper) == nil {
return nil, ErrInvalidToxicType
}
found := c.findToxicByName(wrapper.Name)
if found != nil {
return nil, ErrToxicAlreadyExists
}
// Parse attributes because we now know the toxics type.
attrs := &struct {
Attributes interface{} `json:"attributes"`
}{
wrapper.Toxic,
}
err = json.NewDecoder(&buffer).Decode(attrs)
if err != nil {
return nil, joinError(err, ErrBadRequestBody)
}
c.chainAddToxic(wrapper)
return wrapper, nil
}
func (c *ToxicCollection) UpdateToxicJson(
name string,
data io.Reader,
) (*toxics.ToxicWrapper, error) {
c.Lock()
defer c.Unlock()
toxic := c.findToxicByName(name)
if toxic != nil {
attrs := &struct {
Attributes interface{} `json:"attributes"`
Toxicity float32 `json:"toxicity"`
}{
toxic.Toxic,
toxic.Toxicity,
}
err := json.NewDecoder(data).Decode(attrs)
if err != nil {
return nil, joinError(err, ErrBadRequestBody)
}
toxic.Toxicity = attrs.Toxicity
c.chainUpdateToxic(toxic)
return toxic, nil
}
return nil, ErrToxicNotFound
}
func (c *ToxicCollection) RemoveToxic(ctx context.Context, name string) error {
log := zerolog.Ctx(ctx).
With().
Str("component", "ToxicCollection").
Str("method", "RemoveToxic").
Str("toxic", name).
Str("proxy", c.proxy.Name).
Logger()
log.Trace().Msg("Acquire locking...")
c.Lock()
defer c.Unlock()
log.Trace().Msg("Getting toxic by name...")
toxic := c.findToxicByName(name)
if toxic == nil {
log.Trace().Msg("Could not find toxic by name")
return ErrToxicNotFound
}
c.chainRemoveToxic(ctx, toxic)
log.Trace().Msg("Finished")
return nil
}
func (c *ToxicCollection) StartLink(
server *ApiServer,
name string,
input io.Reader,
output io.WriteCloser,
direction stream.Direction,
) {
c.Lock()
defer c.Unlock()
var logger zerolog.Logger
if c.proxy.Logger != nil {
logger = *c.proxy.Logger
} else {
logger = zerolog.Nop()
}
link := NewToxicLink(c.proxy, c, direction, logger)
link.Start(server, name, input, output)
c.links[name] = link
}
func (c *ToxicCollection) RemoveLink(name string) {
c.Lock()
defer c.Unlock()
delete(c.links, name)
}
// All following functions assume the lock is already grabbed.
func (c *ToxicCollection) findToxicByName(name string) *toxics.ToxicWrapper {
for dir := range c.chain {
// Skip the first noop toxic, it has no name
for _, toxic := range c.chain[dir][1:] {
if toxic.Name == name {
return toxic
}
}
}
return nil
}
func (c *ToxicCollection) chainAddToxic(toxic *toxics.ToxicWrapper) {
dir := toxic.Direction
toxic.Index = len(c.chain[dir])
c.chain[dir] = append(c.chain[dir], toxic)
// Asynchronously add the toxic to each link
wg := sync.WaitGroup{}
for _, link := range c.links {
if link.direction == dir {
wg.Add(1)
go func(link *ToxicLink, wg *sync.WaitGroup) {
defer wg.Done()
link.AddToxic(toxic)
}(link, &wg)
}
}
wg.Wait()
}
func (c *ToxicCollection) chainUpdateToxic(toxic *toxics.ToxicWrapper) {
c.chain[toxic.Direction][toxic.Index] = toxic
// Asynchronously update the toxic in each link
group := sync.WaitGroup{}
for _, link := range c.links {
if link.direction == toxic.Direction {
group.Add(1)
go func(link *ToxicLink) {
defer group.Done()
link.UpdateToxic(toxic)
}(link)
}
}
group.Wait()
}
func (c *ToxicCollection) chainRemoveToxic(ctx context.Context, toxic *toxics.ToxicWrapper) {
log := zerolog.Ctx(ctx).
With().
Str("component", "ToxicCollection").
Str("method", "chainRemoveToxic").
Str("toxic", toxic.Name).
Str("direction", toxic.Direction.String()).
Logger()
dir := toxic.Direction
c.chain[dir] = append(c.chain[dir][:toxic.Index], c.chain[dir][toxic.Index+1:]...)
for i := toxic.Index; i < len(c.chain[dir]); i++ {
c.chain[dir][i].Index = i
}
// Asynchronously remove the toxic from each link
wg := sync.WaitGroup{}
event_array := zerolog.Arr()
for _, link := range c.links {
if link.direction == dir {
event_array = event_array.Str(fmt.Sprintf("Link[%p] %s", link, link.Direction()))
wg.Add(1)
go func(ctx context.Context, link *ToxicLink, log zerolog.Logger) {
defer wg.Done()
link.RemoveToxic(ctx, toxic)
}(ctx, link, log)
}
}
log.Trace().
Array("links", event_array).
Msg("Waiting to update links")
wg.Wait()
toxic.Index = -1
}