forked from sensu/sensu-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keepalive_store.go
74 lines (63 loc) · 2.02 KB
/
keepalive_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
package etcd
import (
"context"
"fmt"
"path"
"github.com/coreos/etcd/clientv3"
"github.com/gogo/protobuf/proto"
"github.com/sensu/sensu-go/types"
)
const (
keepalivesPathPrefix = "keepalives"
)
func getKeepalivePath(keepalivesPath string, entity *types.Entity) string {
return path.Join(keepalivesPath, entity.Namespace, entity.Name)
}
// DeleteFailingKeepalive deletes a failing KeepaliveRecord.
func (s *Store) DeleteFailingKeepalive(ctx context.Context, entity *types.Entity) error {
_, err := s.client.Delete(ctx, getKeepalivePath(s.keepalivesPath, entity))
return err
}
// GetFailingKeepalives gets all of the failing KeepaliveRecords.
func (s *Store) GetFailingKeepalives(ctx context.Context) ([]*types.KeepaliveRecord, error) {
resp, err := s.client.Get(ctx, s.keepalivesPath, clientv3.WithPrefix())
if err != nil {
return nil, err
}
keepalives := []*types.KeepaliveRecord{}
for _, kv := range resp.Kvs {
keepalive := &types.KeepaliveRecord{}
if err := unmarshal(kv.Value, keepalive); err != nil {
// if we have a problem deserializing a keepalive record, delete that record
// ignoring any errors we have along the way.
if _, err := s.client.Delete(ctx, string(kv.Key)); err != nil {
logger.Debug(err)
}
continue
}
keepalives = append(keepalives, keepalive)
}
return keepalives, nil
}
// UpdateFailingKeepalive updates a failing KeepaliveRecord.
func (s *Store) UpdateFailingKeepalive(ctx context.Context, entity *types.Entity, expiration int64) error {
kr := types.NewKeepaliveRecord(entity, expiration)
krBytes, err := proto.Marshal(kr)
if err != nil {
return err
}
cmp := clientv3.Compare(clientv3.Version(getNamespacePath(entity.Namespace)), ">", 0)
req := clientv3.OpPut(getKeepalivePath(s.keepalivesPath, entity), string(krBytes))
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 keepalive for entity %s in namespace %s",
entity.Name,
entity.Namespace,
)
}
return err
}