forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
103 lines (86 loc) · 2.5 KB
/
error.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
package physical
import (
"context"
"errors"
"math/rand"
"time"
log "github.com/hashicorp/go-hclog"
)
const (
// DefaultErrorPercent is used to determin how often we error
DefaultErrorPercent = 20
)
// ErrorInjector is used to add errors into underlying physical requests
type ErrorInjector struct {
backend Backend
errorPercent int
random *rand.Rand
}
// TransactionalErrorInjector is the transactional version of the error
// injector
type TransactionalErrorInjector struct {
*ErrorInjector
Transactional
}
// Verify ErrorInjector satisfies the correct interfaces
var _ Backend = (*ErrorInjector)(nil)
var _ Transactional = (*TransactionalErrorInjector)(nil)
// NewErrorInjector returns a wrapped physical backend to inject error
func NewErrorInjector(b Backend, errorPercent int, logger log.Logger) *ErrorInjector {
if errorPercent < 0 || errorPercent > 100 {
errorPercent = DefaultErrorPercent
}
logger.Info("creating error injector")
return &ErrorInjector{
backend: b,
errorPercent: errorPercent,
random: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))),
}
}
// NewTransactionalErrorInjector creates a new transactional ErrorInjector
func NewTransactionalErrorInjector(b Backend, errorPercent int, logger log.Logger) *TransactionalErrorInjector {
return &TransactionalErrorInjector{
ErrorInjector: NewErrorInjector(b, errorPercent, logger),
Transactional: b.(Transactional),
}
}
func (e *ErrorInjector) SetErrorPercentage(p int) {
e.errorPercent = p
}
func (e *ErrorInjector) addError() error {
roll := e.random.Intn(100)
if roll < e.errorPercent {
return errors.New("random error")
}
return nil
}
func (e *ErrorInjector) Put(ctx context.Context, entry *Entry) error {
if err := e.addError(); err != nil {
return err
}
return e.backend.Put(ctx, entry)
}
func (e *ErrorInjector) Get(ctx context.Context, key string) (*Entry, error) {
if err := e.addError(); err != nil {
return nil, err
}
return e.backend.Get(ctx, key)
}
func (e *ErrorInjector) Delete(ctx context.Context, key string) error {
if err := e.addError(); err != nil {
return err
}
return e.backend.Delete(ctx, key)
}
func (e *ErrorInjector) List(ctx context.Context, prefix string) ([]string, error) {
if err := e.addError(); err != nil {
return nil, err
}
return e.backend.List(ctx, prefix)
}
func (e *TransactionalErrorInjector) Transaction(ctx context.Context, txns []*TxnEntry) error {
if err := e.addError(); err != nil {
return err
}
return e.Transactional.Transaction(ctx, txns)
}