-
Notifications
You must be signed in to change notification settings - Fork 13
/
kv_consul.go
1281 lines (1138 loc) · 30.6 KB
/
kv_consul.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package consul implements the KVDB interface based on consul.
// Code from docker/libkv was leveraged to build parts of this module.
package consul
import (
"bytes"
"encoding/json"
"fmt"
"math/rand"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/consul/api"
"github.com/portworx/kvdb"
"github.com/portworx/kvdb/common"
"github.com/portworx/kvdb/mem"
"github.com/sirupsen/logrus"
)
const (
// Name is the name of this kvdb implementation.
Name = "consul-kv"
bootstrap = "kvdb/bootstrap"
// MaxRenewRetries to renew TTL.
MaxRenewRetries = 5
// refreshDelay is the wait to wait before testing connection with a machine
refreshDelay = 5 * time.Second
)
const (
// session ttl limits for consul
ttlLowerLimit = 10 // 10 seconds
ttlUpperLimit = 60 * 60 * 24 // 1 days
)
var (
// an incorrect is added to check failover
defaultMachines = []string{"3.1.4.1:5926", "127.0.0.1:8500"}
)
// connectionParam stores connection paramaters for consul kv.
type connectionParams struct {
// machines is list of consul servers
machines []string
// options is consul specific options
options map[string]string
// fatalErrorCb callback to invoke in case of errors
fatalErrorCb kvdb.FatalErrorCB
}
// CKVPairs sortable KVPairs
type CKVPairs api.KVPairs
func (c CKVPairs) Len() int {
return len(c)
}
func (c CKVPairs) Less(i, j int) bool {
return c[i].ModifyIndex < c[j].ModifyIndex
}
func (c CKVPairs) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
func init() {
if err := kvdb.Register(Name, New, Version); err != nil {
panic(err.Error())
}
}
func stripConsecutiveForwardslash(key string) string {
// Replace consecutive occurences of forward slash with single occurrence
re := regexp.MustCompile("(//*)")
return re.ReplaceAllString(key, "/")
}
type consulKV struct {
common.BaseKvdb
// client is an instance of clientConsuler, which is a px defined interface.
// clientConsuler wraps pointer to client from consul api but also provides
// methods to refresh it during failover.
client consulClient
domain string
kvdb.Controller
mu sync.Mutex
}
type consulLock struct {
lock *api.Lock
doneCh chan struct{}
tag interface{}
}
// shuffle list of input strings
func shuffle(input []string) []string {
tmp := make([]string, len(input))
r := rand.New(rand.NewSource(time.Now().Unix()))
for i, j := range r.Perm(len(input)) {
tmp[i] = input[j]
}
return tmp
}
// New constructs a new kvdb.Kvdb given a list of end points to conntect to.
func New(
domain string,
servers []string,
options map[string]string,
fatalErrorCb kvdb.FatalErrorCB,
) (kvdb.Kvdb, error) {
// check for unsupported options
for _, opt := range []string{kvdb.UsernameKey, kvdb.PasswordKey} {
// Check if username provided
if _, ok := options[opt]; ok {
return nil, kvdb.ErrAuthNotSupported
}
}
if domain != "" && !strings.HasSuffix(domain, "/") {
domain = domain + "/"
}
hasHttpsPrefix := false
for _, machine := range servers {
if strings.HasPrefix(machine, "https://") {
hasHttpsPrefix = true
break
}
}
if options == nil {
options = make(map[string]string)
}
if hasHttpsPrefix {
options[kvdb.TransportScheme] = "https"
} else {
options[kvdb.TransportScheme] = "http"
}
connParams := connectionParams{
machines: shuffle(servers),
options: options,
fatalErrorCb: fatalErrorCb,
}
if len(connParams.machines) == 0 {
connParams.machines = defaultMachines
}
var err error
var config *api.Config
var client *api.Client
for _, machine := range connParams.machines {
if strings.HasPrefix(machine, "http://") {
machine = strings.TrimPrefix(machine, "http://")
} else if strings.HasPrefix(machine, "https://") {
machine = strings.TrimPrefix(machine, "https://")
}
if config, client, err = newKvClient(machine, connParams); err == nil {
return &consulKV{
BaseKvdb: common.BaseKvdb{FatalCb: connParams.fatalErrorCb, LockTryDuration: kvdb.DefaultLockTryDuration},
domain: domain,
Controller: kvdb.ControllerNotSupported,
client: newConsulClient(config, client, refreshDelay, connParams),
}, nil
}
}
return nil, err
}
// Version returns the supported version for consul api
func Version(url string, kvdbOptions map[string]string) (string, error) {
// Currently we support only v1
return kvdb.ConsulVersion1, nil
}
func (kv *consulKV) String() string {
return Name
}
func (kv *consulKV) Capabilities() int {
return 0
}
func (kv *consulKV) Get(key string) (*kvdb.KVPair, error) {
options := &api.QueryOptions{
AllowStale: false,
RequireConsistent: true,
}
key = kv.domain + key
key = stripConsecutiveForwardslash(key)
pair, meta, err := kv.client.Get(key, options)
if err != nil {
return nil, err
}
if pair == nil {
return nil, kvdb.ErrNotFound
}
return kv.pairToKv("get", pair, meta), nil
}
func (kv *consulKV) GetVal(key string, val interface{}) (*kvdb.KVPair, error) {
kvp, err := kv.Get(key)
if err != nil {
return nil, err
}
return kvp, json.Unmarshal(kvp.Value, val)
}
func (kv *consulKV) createTTLSession(
key string,
val interface{},
ttl uint64,
noCreate bool,
) (*api.KVPair, error) {
pathKey := kv.domain + key
pathKey = stripConsecutiveForwardslash(pathKey)
b, err := common.ToBytes(val)
if err != nil {
return nil, err
}
pair := &api.KVPair{
Key: pathKey,
Value: b,
}
if ttl > 0 {
if ttl < ttlLowerLimit*2 { // multiply by 2 because we divide ttl values later by 2
return nil, kvdb.ErrTTLNotSupported
}
if ttl > ttlUpperLimit*2 {
return nil, kvdb.ErrTTLNotSupported
}
// Future Use : To Support TTL values
for retries := 1; retries <= MaxRenewRetries; retries++ {
// Consul doubles the ttl value. Hence we divide it by 2
// Consul does not support ttl values less than 10.
// Hence we set our lower limit to 20.
// Consul does not support ttl values more than 1 day.
// Hence we set our upper limit to 2 days.
session, err := kv.renewSession(pair, ttl/2, noCreate)
if err == nil {
pair.Session = session
break
}
if retries == MaxRenewRetries {
return nil, kvdb.ErrSetTTLFailed
}
}
}
return pair, nil
}
func (kv *consulKV) Put(
key string,
val interface{},
ttl uint64,
) (*kvdb.KVPair, error) {
pair, err := kv.createTTLSession(key, val, ttl, false)
if err != nil {
return nil, err
}
if ttl == 0 {
if _, err := kv.client.Put(pair, nil); err != nil {
return nil, err
}
} else {
// It is unclear why err == nil but ok == false. We always
// delete any existing sessions on Put, so this should work fine.
if _, err := kv.client.Acquire(pair, nil); err != nil {
return nil, err
}
}
kvPair, err := kv.Get(key)
if err != nil {
return nil, err
}
kvPair.Action = kvdb.KVSet
return kvPair, nil
}
func (kv *consulKV) Create(
key string,
val interface{},
ttl uint64,
) (*kvdb.KVPair, error) {
sessionPair, err := kv.createTTLSession(key, val, ttl, true)
if err != nil {
return nil, err
}
kvPair := &kvdb.KVPair{Key: key, Value: sessionPair.Value}
kvPair, err = kv.CompareAndSet(kvPair, kvdb.KVModifiedIndex, nil)
if err == nil {
kvPair.Action = kvdb.KVCreate
if ttl > 0 {
if _, ok, err := kv.client.CreateMeta(key, sessionPair, nil); ok && err == nil {
return kvPair, err
} else if err != nil {
return nil, err
}
}
}
if err == kvdb.ErrModified {
// key already exists since compare and set with index 0 failed.
err = kvdb.ErrExist
}
return kvPair, err
}
func (kv *consulKV) Update(
key string,
val interface{},
ttl uint64,
) (*kvdb.KVPair, error) {
if _, err := kv.Get(key); err != nil {
return nil, err
}
kvPair, err := kv.Put(key, val, ttl)
if err != nil {
return nil, err
}
kvPair.Action = kvdb.KVSet
return kvPair, nil
}
func (kv *consulKV) Enumerate(prefix string) (kvdb.KVPairs, error) {
prefix = kv.domain + prefix
prefix = stripConsecutiveForwardslash(prefix)
pairs, meta, err := kv.client.List(prefix, nil)
if err != nil {
return nil, err
}
return kv.pairToKvs("enumerate", pairs, meta), nil
}
func (kv *consulKV) Delete(key string) (*kvdb.KVPair, error) {
pair, err := kv.Get(key)
if err != nil {
return nil, err
}
key = kv.domain + key
key = stripConsecutiveForwardslash(key)
if _, err := kv.client.Delete(key, nil); err != nil {
return nil, err
}
return pair, nil
}
func (kv *consulKV) DeleteTree(key string) error {
key = kv.domain + key
key = stripConsecutiveForwardslash(key)
if !strings.HasSuffix(key, kvdb.DefaultSeparator) {
key += kvdb.DefaultSeparator
}
_, err := kv.client.DeleteTree(key, nil)
return err
}
func (kv *consulKV) Keys(prefix, sep string) ([]string, error) {
if "" == sep {
sep = "/"
}
prefix = kv.domain + prefix
prefix = stripConsecutiveForwardslash(prefix)
lenPrefix := len(prefix)
lenSep := len(sep)
if prefix[lenPrefix-lenSep:] != sep {
prefix += sep
lenPrefix += lenSep
}
list, _, err := kv.client.Keys(prefix, sep, nil)
if err != nil {
return nil, err
}
var retList []string
if len(list) > 0 {
retList = make([]string, len(list))
for i, key := range list {
if strings.HasPrefix(key, prefix) {
key = key[lenPrefix:]
}
if lky := len(key); lky > lenSep && key[lky-lenSep:] == sep {
key = key[0 : lky-lenSep]
}
retList[i] = key
}
}
return retList, nil
}
func (kv *consulKV) CompareAndSet(
kvp *kvdb.KVPair,
flags kvdb.KVFlags,
prevValue []byte,
) (*kvdb.KVPair, error) {
key := kv.domain + kvp.Key
key = stripConsecutiveForwardslash(key)
pair := &api.KVPair{
Key: key,
Value: kvp.Value,
Flags: api.LockFlagValue,
}
if (flags & kvdb.KVModifiedIndex) != 0 {
pair.ModifyIndex = kvp.ModifiedIndex
} else if (flags&kvdb.KVModifiedIndex) == 0 && prevValue != nil {
kvPair, err := kv.Get(kvp.Key)
if err != nil {
return nil, err
}
// Prev Value not equal to current value in etcd
if bytes.Compare(kvPair.Value, prevValue) != 0 {
return nil, kvdb.ErrValueMismatch
}
pair.ModifyIndex = kvPair.ModifiedIndex
} else {
pair.ModifyIndex = 0
}
ok, _, err := kv.client.CompareAndSet(kvp.Key, kvp.Value, pair, nil)
if err != nil {
return nil, err
}
if !ok {
kvp, getErr := kv.Get(pair.Key)
if getErr == nil {
if bytes.Compare(kvp.Value, pair.Value) == 0 {
return kvp, nil
}
}
if (flags & kvdb.KVModifiedIndex) == 0 {
return nil, kvdb.ErrValueMismatch
}
return nil, kvdb.ErrModified
}
kvPair, err := kv.Get(kvp.Key)
if err != nil {
return nil, err
}
return kvPair, nil
}
func (kv *consulKV) CompareAndDelete(
kvp *kvdb.KVPair,
flags kvdb.KVFlags,
) (*kvdb.KVPair, error) {
key := kv.domain + kvp.Key
key = stripConsecutiveForwardslash(key)
pair := &api.KVPair{
Key: key,
Value: kvp.Value,
Flags: api.LockFlagValue,
}
if (flags & kvdb.KVModifiedIndex) == 0 {
// Use value for comparison
kvPair, err := kv.Get(kvp.Key)
if err != nil {
return nil, err
}
// Prev Value not equal to current value in etcd
if bytes.Compare(kvPair.Value, kvp.Value) != 0 {
return nil, kvdb.ErrValueMismatch
}
pair.ModifyIndex = kvPair.ModifiedIndex
} else {
// Use index for comparison
pair.ModifyIndex = kvp.ModifiedIndex
}
ok, _, err := kv.client.CompareAndDelete(kvp.Key, kvp.Value, pair, nil)
if err != nil {
return nil, err
}
if !ok {
return nil, kvdb.ErrModified
}
return kvp, nil
}
func (kv *consulKV) WatchKey(
key string,
waitIndex uint64,
opaque interface{},
cb kvdb.WatchCB,
) error {
var keyExist bool
kvp, err := kv.Get(key)
if err == kvdb.ErrNotFound {
keyExist = false
} else if err != nil {
return err
} else {
keyExist = true
}
if waitIndex == 0 && kvp != nil {
waitIndex = kvp.KVDBIndex
}
key = kv.domain + key
go kv.watchKeyStart(key, keyExist, waitIndex, opaque, cb)
return nil
}
func (kv *consulKV) WatchTree(prefix string, waitIndex uint64, opaque interface{}, cb kvdb.WatchCB) error {
var prefixExist bool
kvps, err := kv.Enumerate(prefix)
if err == kvdb.ErrNotFound {
prefixExist = false
} else if err != nil {
return err
} else {
prefixExist = true
}
if waitIndex == 0 && kvps != nil && len(kvps) != 0 {
waitIndex = kvps[0].KVDBIndex
}
prefix = kv.domain + prefix
go kv.watchTreeStart(prefix, prefixExist, waitIndex, opaque, cb)
return nil
}
func (kv *consulKV) Compact(index uint64) error {
return kvdb.ErrNotSupported
}
func (kv *consulKV) Lock(key string) (*kvdb.KVPair, error) {
return kv.LockWithID(key, "locked")
}
func (kv *consulKV) LockWithID(key string, lockerID string) (
*kvdb.KVPair,
error,
) {
return kv.LockWithTimeout(key, lockerID, kv.LockTryDuration, kv.GetLockHoldDuration())
}
func (kv *consulKV) LockWithTimeout(
key string,
lockerID string,
lockTryDuration time.Duration,
lockHoldDuration time.Duration,
) (*kvdb.KVPair, error) {
key = stripConsecutiveForwardslash(key)
// Strip of the leading slash or else consul throws error
if key[0] == '/' {
key = key[1:]
}
timeout := time.After(lockTryDuration)
var l *consulLock
err := fmt.Errorf("Timeout acquiring lock")
done := false
for !done {
select {
case <-timeout:
return nil, err
default:
l, err = kv.getLock(key, lockerID, lockHoldDuration)
if err == nil {
done = true
} else {
time.Sleep(time.Second)
}
}
}
return &kvdb.KVPair{
Key: key,
Lock: l,
}, nil
}
func (kv *consulKV) IsKeyLocked(key string) (bool, string, error) {
kvPair, err := kv.Get(key)
if err == kvdb.ErrNotFound {
return false, "", nil
} else if err != nil {
return false, "", err
}
lockerID := string(kvPair.Value)
return true, lockerID, nil
}
func (kv *consulKV) Unlock(kvp *kvdb.KVPair) error {
l, ok := kvp.Lock.(*consulLock)
if !ok {
return fmt.Errorf("Invalid lock structure for key: %v", string(kvp.Key))
}
_, err := kv.Delete(kvp.Key)
if err == nil || isConsulErrNeedingRetry(err) {
_ = l.lock.Unlock()
// stop refreshing the lock, this will automatically release the lock
if l.doneCh != nil {
close(l.doneCh)
}
return nil
}
logrus.Errorf("Unlock failed for key: %s, tag: %s, error: %s", kvp.Key,
l.tag, err.Error())
return err
}
func (kv *consulKV) TxNew() (kvdb.Tx, error) {
return nil, kvdb.ErrNotSupported
}
func (kv *consulKV) Snapshot(prefixes []string, consistent bool) (kvdb.Kvdb, uint64, error) {
if len(prefixes) == 0 {
prefixes = []string{""}
} else {
prefixes = append(prefixes, bootstrap)
prefixes = common.PrunePrefixes(prefixes)
}
// Create a new bootstrap key : lowest index
r := rand.New(rand.NewSource(time.Now().UnixNano())).Int63()
bootStrapKeyLow := bootstrap + strconv.FormatInt(r, 10) +
strconv.FormatInt(time.Now().UnixNano(), 10)
val, _ := common.ToBytes(time.Now().UnixNano())
kvPair, err := kv.Put(bootStrapKeyLow, val, 0)
if err != nil {
return nil, 0, fmt.Errorf("Failed to create snap bootstrap key %v, "+
"err: %v", bootStrapKeyLow, err)
}
lowestKvdbIndex := kvPair.ModifiedIndex
options := &api.QueryOptions{
AllowStale: false,
RequireConsistent: true,
}
var (
kvPairs kvdb.KVPairs
)
for _, prefix := range prefixes {
listKey := kv.domain + prefix
listKey = stripConsecutiveForwardslash(listKey)
pairs, _, err := kv.client.List(listKey, options)
if err != nil {
return nil, 0, err
}
kvps := kv.pairToKvs("enumerate", pairs, nil)
kvPairs = append(kvPairs, kvps...)
}
snapDb, err := mem.New(
kv.domain,
nil,
map[string]string{mem.KvSnap: "true"},
kv.FatalCb,
)
if err != nil {
return nil, 0, err
}
for _, kvPair := range kvPairs {
_, err := snapDb.SnapPut(kvPair)
if err != nil {
return nil, 0, fmt.Errorf("Failed creating snap: %v", err)
}
}
if !consistent {
// A consistent snapshot is not required
// return all the enumerated keys
return snapDb, 0, nil
}
// Create bootrap key : highest index
bootStrapKeyHigh := bootstrap + strconv.FormatInt(r, 10) +
strconv.FormatInt(time.Now().UnixNano(), 10)
val, _ = common.ToBytes(time.Now().UnixNano())
kvPair, err = kv.Put(bootStrapKeyHigh, val, 0)
if err != nil {
return nil, 0, fmt.Errorf("Failed to create snap bootstrap key %v, "+
"err: %v", bootStrapKeyHigh, err)
}
highestKvdbIndex := kvPair.ModifiedIndex
// In consul Delete does not increment kvdb index.
// Hence the put (bootstrap) key and delete both return the same index
if lowestKvdbIndex+1 != highestKvdbIndex {
// create a watch to get all changes
// between lowestKvdbIndex and highestKvdbIndex
done := make(chan error)
watchClosed := false
mutex := &sync.Mutex{}
cb := func(
prefix string,
opaque interface{},
kvp *kvdb.KVPair,
err error,
) error {
var watchErr error
var sendErr error
var m *sync.Mutex
var found, ok bool
if err != nil {
if err == kvdb.ErrWatchStopped && watchClosed {
return nil
}
watchErr = err
sendErr = err
goto errordone
}
if kvp == nil {
watchErr = fmt.Errorf("kvp is nil")
sendErr = watchErr
goto errordone
}
m, ok = opaque.(*sync.Mutex)
if !ok {
watchErr = fmt.Errorf("Failed to get mutex")
sendErr = watchErr
goto errordone
}
for _, prefix := range prefixes {
if strings.HasPrefix(kvp.Key, prefix) {
found = true
break
}
}
if !found {
return nil
}
m.Lock()
defer m.Unlock()
if kvp.ModifiedIndex > highestKvdbIndex {
// done applying changes, just return
watchErr = fmt.Errorf("done")
sendErr = nil
goto errordone
} else if kvp.ModifiedIndex == highestKvdbIndex {
// last update that we needed. Put it inside snap db
// and return
_, err = snapDb.SnapPut(kvp)
if err != nil {
watchErr = fmt.Errorf("Failed to apply update to snap: %v", err)
sendErr = watchErr
} else {
watchErr = fmt.Errorf("done")
sendErr = nil
}
goto errordone
} else {
if kvp.Action == kvdb.KVDelete {
_, err = snapDb.Delete(kvp.Key)
// A Delete key was issued between our first lowestKvdbIndex Put
// and Enumerate APIs in this function
if err == kvdb.ErrNotFound {
err = nil
}
} else {
_, err = snapDb.SnapPut(kvp)
}
if err != nil {
watchErr = fmt.Errorf("Failed to apply update to snap: %v", err)
sendErr = watchErr
goto errordone
}
}
return nil
errordone:
watchClosed = true
done <- sendErr
return watchErr
}
if err := kv.WatchTree("", lowestKvdbIndex, mutex,
cb); err != nil {
return nil, 0, fmt.Errorf("Failed to start watch: %v", err)
}
err = <-done
if err != nil {
return nil, 0, err
}
}
_, err = kv.Delete(bootStrapKeyLow)
if err != nil {
return nil, 0, fmt.Errorf("Failed to delete snap bootstrap key: %v, "+
"err: %v", bootStrapKeyLow, err)
}
_, err = kv.Delete(bootStrapKeyHigh)
if err != nil {
return nil, 0, fmt.Errorf("Failed to delete snap bootstrap key: %v, "+
"err: %v", bootStrapKeyHigh, err)
}
return snapDb, highestKvdbIndex, nil
}
func (kv *consulKV) createKv(pair *api.KVPair) *kvdb.KVPair {
kvp := &kvdb.KVPair{
Value: []byte(pair.Value),
ModifiedIndex: pair.ModifyIndex,
CreatedIndex: pair.CreateIndex,
}
// Strip out the leading '/'
if len(pair.Key) != 0 {
kvp.Key = pair.Key[1:]
} else {
kvp.Key = pair.Key
}
kvp.Key = strings.TrimPrefix(pair.Key, kv.domain)
return kvp
}
func (kv *consulKV) EnumerateWithSelect(
prefix string,
enumerateSelect kvdb.EnumerateSelect,
copySelect kvdb.CopySelect,
) ([]interface{}, error) {
return nil, kvdb.ErrNotSupported
}
func (kv *consulKV) EnumerateKVPWithSelect(
prefix string,
enumerateSelect kvdb.EnumerateKVPSelect,
copySelect kvdb.CopyKVPSelect,
) (kvdb.KVPairs, error) {
return nil, kvdb.ErrNotSupported
}
func (kv *consulKV) GetWithCopy(
key string,
copySelect kvdb.CopySelect,
) (interface{}, error) {
return nil, kvdb.ErrNotSupported
}
func (kv *consulKV) pairToKv(action string, pair *api.KVPair, meta *api.QueryMeta) *kvdb.KVPair {
kvp := kv.createKv(pair)
switch action {
case "create":
kvp.Action = kvdb.KVCreate
case "set", "update", "put":
kvp.Action = kvdb.KVSet
case "delete":
kvp.Action = kvdb.KVDelete
case "get":
kvp.Action = kvdb.KVGet
default:
kvp.Action = kvdb.KVUknown
}
if meta != nil {
kvp.KVDBIndex = meta.LastIndex
}
return kvp
}
func isHidden(key string) bool {
tokens := strings.Split(key, "/")
keySuffix := tokens[len(tokens)-1]
return keySuffix != "" && keySuffix[0] == '_'
}
func (kv *consulKV) pairToKvs(
action string,
pairs []*api.KVPair,
meta *api.QueryMeta,
) kvdb.KVPairs {
kvs := []*kvdb.KVPair{}
for _, pair := range pairs {
// Ignore hidden keys.
if isHidden(pair.Key) {
continue
}
kvs = append(kvs, kv.pairToKv(action, pair, meta))
}
return kvs
}
func (kv *consulKV) renewLockSession(
key string,
initialTTL string,
lockTimeout time.Duration,
session string,
doneCh chan struct{},
tag interface{},
) {
go func() {
kv.client.RenewPeriodic(initialTTL, session, nil, doneCh)
}()
if lockTimeout > 0 {
go func() {
timeout := time.After(lockTimeout)
for {
select {
case <-timeout:
kv.LockTimedout(fmt.Sprintf("Key:%s,Tag:%v", key, tag), lockTimeout)
case <-doneCh:
return
}
}
}()
}
}
func (kv *consulKV) getLock(
key string,
tag interface{},
lockHoldDuration time.Duration,
) (*consulLock, error) {
key = kv.domain + key
tagValue, err := common.ToBytes(tag)
if err != nil {
return nil, fmt.Errorf("Failed to convert tag: %v, error: %v", tag,
err)
}
// Since we need to extend lock hold time, we create a session
// which is refreshed every so often until we hit lockHoldDuration,
// when we run the FatalCb. Set the TTL to a smaller value so that
// the lock is released in case the locking process exits.
entry := &api.SessionEntry{
Behavior: api.SessionBehaviorRelease, // Release the lock when the session expires
TTL: (10 * time.Second).String(), // Consul multiplies the TTL by 2x
LockDelay: 0, // Virtually disable lock delay
}
session, _, err := kv.client.Create(entry, nil)
// create a lock handle
lockOpts := &api.LockOptions{
Key: key,
Value: tagValue,
LockTryOnce: true, // give up if lock already exists
Session: session,
LockWaitTime: time.Microsecond, // zero means default, so give a very small value
}
l, err := kv.client.LockOpts(lockOpts)
if err != nil {
return nil, err
}
if lockChan, err := l.Lock(nil); err != nil || lockChan == nil {
kv.client.Destroy(session, nil)
return nil, kvdb.ErrExist
}
lock := &consulLock{
doneCh: make(chan struct{}),
tag: tag,
lock: l,
}
kv.renewLockSession(key, entry.TTL, lockHoldDuration, session, lock.doneCh, tag)
return lock, nil
}
func (kv *consulKV) watchTreeStart(
prefix string,
prefixExisted bool,
waitIndex uint64,
opaque interface{},
cb kvdb.WatchCB,
) {
prefix = stripConsecutiveForwardslash(prefix)
opts := &api.QueryOptions{
WaitIndex: waitIndex,