forked from sensu/sensu-go
/
mutator_store.go
94 lines (78 loc) · 2.31 KB
/
mutator_store.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
package etcd
import (
"context"
"errors"
"fmt"
"github.com/coreos/etcd/clientv3"
"github.com/gogo/protobuf/proto"
"github.com/sensu/sensu-go/backend/store"
"github.com/sensu/sensu-go/types"
)
var (
mutatorsPathPrefix = "mutators"
mutatorKeyBuilder = store.NewKeyBuilder(mutatorsPathPrefix)
)
func getMutatorPath(mutator *types.Mutator) string {
return mutatorKeyBuilder.WithResource(mutator).Build(mutator.Name)
}
// GetMutatorsPath gets the path of the mutator store.
func GetMutatorsPath(ctx context.Context, name string) string {
return mutatorKeyBuilder.WithContext(ctx).Build(name)
}
// DeleteMutatorByName deletes a Mutator by name.
func (s *Store) DeleteMutatorByName(ctx context.Context, name string) error {
if name == "" {
return errors.New("must specify name of mutator")
}
_, err := s.client.Delete(ctx, GetMutatorsPath(ctx, name))
return err
}
// GetMutators gets the list of mutators for a namespace.
func (s *Store) GetMutators(ctx context.Context, pred *store.SelectionPredicate) ([]*types.Mutator, error) {
mutators := []*types.Mutator{}
err := List(ctx, s.client, GetMutatorsPath, &mutators, pred)
return mutators, err
}
// GetMutatorByName gets a Mutator by name.
func (s *Store) GetMutatorByName(ctx context.Context, name string) (*types.Mutator, error) {
if name == "" {
return nil, errors.New("must specify name of mutator")
}
resp, err := s.client.Get(ctx, GetMutatorsPath(ctx, name))
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return nil, nil
}
mutatorBytes := resp.Kvs[0].Value
mutator := &types.Mutator{}
if err := unmarshal(mutatorBytes, mutator); err != nil {
return nil, err
}
return mutator, nil
}
// UpdateMutator updates a Mutator.
func (s *Store) UpdateMutator(ctx context.Context, mutator *types.Mutator) error {
if err := mutator.Validate(); err != nil {
return err
}
mutatorBytes, err := proto.Marshal(mutator)
if err != nil {
return err
}
cmp := clientv3.Compare(clientv3.Version(getNamespacePath(mutator.Namespace)), ">", 0)
req := clientv3.OpPut(getMutatorPath(mutator), string(mutatorBytes))
res, err := s.client.Txn(ctx).If(cmp).Then(req).Commit()
if err != nil {
return err
}
if !res.Succeeded {
return fmt.Errorf(
"could not create the mutator %s in namespace %s",
mutator.Name,
mutator.Namespace,
)
}
return nil
}