-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathplan.go
245 lines (204 loc) · 5.16 KB
/
plan.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
package redfi
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
)
var (
// ErrNotFound is returned iff SelectRule can't find a Rule that applies
ErrNotFound = errors.New("no matching rule found")
)
// Plan defines a set of rules to be applied by the proxy
type Plan struct {
Rules []*Rule `json:"rules,omitempty"`
// a lookup table mapping rule name to index in the array
rulesMap map[string]int
m sync.RWMutex
}
// Rule is what get's applied on every client message iff it matches it
type Rule struct {
Name string `json:"name,omiempty"`
Delay int `json:"delay,omitempty"`
Drop bool `json:"drop,omitempty"`
ReturnEmpty bool `json:"return_empty,omitempty"`
ReturnErr string `json:"return_err,omitempty"`
Percentage int `json:"percentage,omitempty"`
// SelectRule does prefix matching on this value
ClientAddr string `json:"client_addr,omitempty"`
Command string `json:"command,omitempty"`
// filled by marshalCommand
marshaledCmd []byte
hits uint64
}
func (r Rule) String() string {
buf := []string{}
buf = append(buf, r.Name)
// count hits
hits := atomic.LoadUint64(&r.hits)
buf = append(buf, fmt.Sprintf("hits=%d", hits))
if r.Delay > 0 {
buf = append(buf, fmt.Sprintf("delay=%d", r.Delay))
}
if r.Drop {
buf = append(buf, fmt.Sprintf("drop=%t", r.Drop))
}
if r.ReturnEmpty {
buf = append(buf, fmt.Sprintf("return_empty=%t", r.ReturnEmpty))
}
if len(r.ReturnErr) > 0 {
buf = append(buf, fmt.Sprintf("return_err=%s", r.ReturnErr))
}
if len(r.ClientAddr) > 0 {
buf = append(buf, fmt.Sprintf("client_addr=%s", r.ClientAddr))
}
if r.Percentage > 0 {
buf = append(buf, fmt.Sprintf("percentage=%d", r.Percentage))
}
return strings.Join(buf, " ")
}
// Parse the plan.json file
func Parse(planPath string) (*Plan, error) {
fullPath, err := filepath.Abs(planPath)
if err != nil {
return nil, err
}
fd, err := os.Open(fullPath)
if err != nil {
return nil, err
}
buf, err := ioutil.ReadAll(fd)
if err != nil {
return nil, err
}
// this is the plan we will use
plan := &Plan{rulesMap: map[string]int{}}
// this is a draft of the plan
// we use to parse the json file,
// then copy its rules to the real plan
pd := &Plan{}
err = json.Unmarshal(buf, pd)
if err != nil {
return nil, err
}
for i, rule := range pd.Rules {
if rule == nil {
continue
}
err := plan.AddRule(*rule)
if err != nil {
return plan, fmt.Errorf("encountered error when adding rule #%d: %s", i, err)
}
}
return plan, nil
}
func NewPlan() *Plan {
return &Plan{
Rules: []*Rule{},
rulesMap: map[string]int{},
}
}
func (p *Plan) check() error {
for idx, rule := range p.Rules {
if rule.Percentage < 0 || rule.Percentage > 100 {
return fmt.Errorf("Percentage in rule #%d is malformed. it must within 0-100", idx)
}
}
return nil
}
func (p *Plan) MarshalCommands() {
for _, rule := range p.Rules {
if rule == nil {
continue
}
if len(rule.Command) > 0 {
rule.marshaledCmd = marshalCommand(rule.Command)
}
}
}
func marshalCommand(cmd string) []byte {
return []byte(fmt.Sprintf("\r\n%s\r\n", strings.ToUpper(cmd)))
}
// SelectRule finds the first rule that applies to the given variables
func (p *Plan) SelectRule(clientAddr string, buf []byte) *Rule {
var chosenRule *Rule
for _, rule := range p.Rules {
if len(rule.ClientAddr) > 0 && strings.HasPrefix(clientAddr, rule.ClientAddr) {
continue
}
if len(rule.Command) > 0 && !bytes.Contains(buf, rule.marshaledCmd) {
continue
}
chosenRule = rule
break
}
if chosenRule == nil {
return nil
}
if chosenRule.Percentage > 0 && rand.Intn(100) > chosenRule.Percentage {
return nil
}
atomic.AddUint64(&chosenRule.hits, 1)
return chosenRule
}
// AddRule adds a rule to the current working plan
func (p *Plan) AddRule(r Rule) error {
if r.Percentage < 0 || r.Percentage > 100 {
return fmt.Errorf("Percentage in rule #%s is malformed. it must within 0-100", r.Name)
}
if len(r.Name) <= 0 {
return fmt.Errorf("Name of rule is required")
}
if len(r.Command) > 0 {
r.marshaledCmd = marshalCommand(r.Command)
}
p.m.Lock()
defer p.m.Unlock()
if _, ok := p.rulesMap[r.Name]; ok {
return fmt.Errorf("a rule by the same name exists")
}
p.Rules = append(p.Rules, &r)
p.rulesMap[r.Name] = len(p.Rules) - 1
return nil
}
// DeleteRule deletes the given ruleName if found
// otherwise it returns ErrNotFound
func (p *Plan) DeleteRule(name string) error {
p.m.Lock()
defer p.m.Unlock()
idx, ok := p.rulesMap[name]
if !ok {
return ErrNotFound
}
p.Rules = append(p.Rules[:idx], p.Rules[idx+1:]...)
delete(p.rulesMap, name)
return nil
}
// GetRule returns the rule that matches the given name
func (p *Plan) GetRule(name string) (Rule, error) {
p.m.RLock()
defer p.m.RUnlock()
idx, ok := p.rulesMap[name]
if !ok {
return Rule{}, ErrNotFound
}
return *p.Rules[idx], nil
}
// ListRules returns a slice of all the existing rules
// the slice will be empty if Plan has no rules
func (p *Plan) ListRules() []Rule {
p.m.RLock()
defer p.m.RUnlock()
rules := []Rule{}
for _, rule := range p.Rules {
rules = append(rules, *rule)
}
return rules
}