/
consul_txn.go
322 lines (292 loc) · 10.2 KB
/
consul_txn.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
/*
Copyright 2021 Shlomi Noach, GitHub Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kv
import (
"crypto/tls"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"github.com/openark/orchestrator/go/config"
consulapi "github.com/hashicorp/consul/api"
"github.com/patrickmn/go-cache"
"github.com/openark/golib/log"
)
// groupKVPairsByKeyPrefix groups Consul Transaction operations by KV key prefix. This
// ensures KVs for a single cluster are grouped into a single transaction
func groupKVPairsByKeyPrefix(kvPairs consulapi.KVPairs) (groups []consulapi.KVPairs) {
maxOpsPerTxn := config.Config.ConsulMaxKVsPerTransaction
clusterMasterPrefix := config.Config.KVClusterMasterPrefix + "/"
groupsMap := map[string]consulapi.KVPairs{}
for _, pair := range kvPairs {
prefix := pair.Key
if strings.HasPrefix(prefix, clusterMasterPrefix) {
prefix = strings.Replace(prefix, clusterMasterPrefix, "", 1)
if path := strings.Split(prefix, "/"); len(path) > 0 {
prefix = path[0]
}
}
if _, found := groupsMap[prefix]; found {
groupsMap[prefix] = append(groupsMap[prefix], pair)
} else {
groupsMap[prefix] = consulapi.KVPairs{pair}
}
}
pairsBuf := consulapi.KVPairs{}
for _, group := range groupsMap {
groupLen := len(group)
pairsBufLen := len(pairsBuf)
if (pairsBufLen + groupLen) > maxOpsPerTxn {
groups = append(groups, pairsBuf)
pairsBuf = consulapi.KVPairs{}
}
pairsBuf = append(pairsBuf, group...)
}
if len(pairsBuf) > 0 {
groups = append(groups, pairsBuf)
}
return groups
}
// A Consul store based on config's `ConsulAddress`, `ConsulScheme`, and `ConsulKVPrefix`
type consulTxnStore struct {
client *consulapi.Client
kvCache *cache.Cache
pairsDistributionSuccessMutex sync.Mutex
distributionReentry int64
}
// NewConsulTxnStore creates a new consul store that uses Consul Transactions to read/write multiple KVPairs.
// It is possible that the client for this store is nil, which is the case if no consul config is provided
func NewConsulTxnStore() KVStore {
store := &consulTxnStore{
kvCache: cache.New(cache.NoExpiration, cache.DefaultExpiration),
}
if config.Config.ConsulAddress != "" {
consulConfig := consulapi.DefaultConfig()
consulConfig.Address = config.Config.ConsulAddress
consulConfig.Scheme = config.Config.ConsulScheme
if config.Config.ConsulScheme == "https" {
consulConfig.HttpClient = &http.Client{
Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
}
}
// ConsulAclToken defaults to ""
consulConfig.Token = config.Config.ConsulAclToken
if client, err := consulapi.NewClient(consulConfig); err != nil {
log.Errore(err)
} else {
store.client = client
}
}
return store
}
// doWriteTxn performs one or many of write operations using a Consul Transaction and handles any client/server
// or transaction-level errors. Updates are all-or-nothing - all operations are rolled-back on any txn error
func (this *consulTxnStore) doWriteTxn(txnOps consulapi.TxnOps, queryOptions *consulapi.QueryOptions) (err error) {
ok, resp, _, err := this.client.Txn().Txn(txnOps, queryOptions)
if err != nil {
log.Errorf("consulTxnStore.doWriteTxn(): %v", err)
return err
} else if !ok {
for _, terr := range resp.Errors {
txnOp := txnOps[terr.OpIndex]
log.Errorf("consulTxnStore.doWriteTxn(): transaction error %q for KV %s on %s", terr.What, txnOp.KV.Verb, txnOp.KV.Key)
err = fmt.Errorf("%v", terr.What)
}
}
return err
}
// updateDatacenterKVPairsResponse contains a response from .updateDatacenterKVPairs()
type updateDatacenterKVPairsResponse struct {
err error
existing int
failed int
skipped int
written int
getTxns int
setTxns int
}
// updateDatacenterKVPairs handles updating a list of Consul KV pairs for a single datacenter. Current values are
// read from the server in a single transaction and any necessary updates are made in a second transaction. If a
// KVPair from a group is missing on the server all KVPairs will be updated.
func (this *consulTxnStore) updateDatacenterKVPairs(wg *sync.WaitGroup, dc string, kvPairs []*consulapi.KVPair, responses chan updateDatacenterKVPairsResponse) {
defer wg.Done()
queryOptions := &consulapi.QueryOptions{Datacenter: dc}
kcCacheKeys := make([]string, 0)
// get the current key-values in a single transaction
resp := updateDatacenterKVPairsResponse{}
var terr error
var getTxnOps consulapi.TxnOps
var getTxnResp *consulapi.TxnResponse
var possibleSetKVPairs []*consulapi.KVPair
for _, kvPair := range kvPairs {
val := string(kvPair.Value)
kcCacheKey := getConsulKVCacheKey(dc, kvPair.Key)
kcCacheKeys = append(kcCacheKeys, kcCacheKey)
if value, found := this.kvCache.Get(kcCacheKey); found && val == value {
resp.skipped++
continue
}
getTxnOps = append(getTxnOps, &consulapi.TxnOp{
KV: &consulapi.KVTxnOp{
Verb: consulapi.KVGet,
Key: kvPair.Key,
},
})
possibleSetKVPairs = append(possibleSetKVPairs, kvPair)
}
if len(getTxnOps) > 0 {
_, getTxnResp, _, terr = this.client.Txn().Txn(getTxnOps, queryOptions)
if terr != nil {
log.Errorf("consulTxnStore.DistributePairs(): %v", terr)
}
resp.getTxns++
}
// find key-value pairs that need updating, add pairs that need updating to set transaction
var setTxnOps consulapi.TxnOps
for _, pair := range possibleSetKVPairs {
var kvExistsAndEqual bool
if getTxnResp != nil {
for _, result := range getTxnResp.Results {
if pair.Key == result.KV.Key && string(pair.Value) == string(result.KV.Value) {
this.kvCache.SetDefault(getConsulKVCacheKey(dc, pair.Key), string(pair.Value))
kvExistsAndEqual = true
resp.existing++
break
}
}
}
if !kvExistsAndEqual {
setTxnOps = append(setTxnOps, &consulapi.TxnOp{
KV: &consulapi.KVTxnOp{
Verb: consulapi.KVSet,
Key: pair.Key,
Value: pair.Value,
},
})
}
}
// update key-value pairs in a single Consul Transaction
if len(setTxnOps) > 0 {
if resp.err = this.doWriteTxn(setTxnOps, queryOptions); resp.err != nil {
log.Errorf("consulTxnStore.DistributePairs(): failed %v, error %v", kcCacheKeys, resp.err)
resp.failed = len(setTxnOps)
} else {
for _, txnOp := range setTxnOps {
this.kvCache.SetDefault(getConsulKVCacheKey(dc, txnOp.KV.Key), string(txnOp.KV.Value))
resp.written++
}
}
resp.setTxns++
}
responses <- resp
}
// GetKeyValue returns the value of a Consul KV if it exists
func (this *consulTxnStore) GetKeyValue(key string) (value string, found bool, err error) {
if this.client == nil {
return value, found, nil
}
pair, _, err := this.client.KV().Get(key, nil)
if err != nil {
return value, found, err
}
return string(pair.Value), (pair != nil), nil
}
// PutKeyValue performs a Consul KV put operation for a key/value
func (this *consulTxnStore) PutKeyValue(key string, value string) (err error) {
if this.client == nil {
return nil
}
pair := &consulapi.KVPair{Key: key, Value: []byte(value)}
_, err = this.client.KV().Put(pair, nil)
return err
}
// PutKVPairs updates one or more KV pairs in a single, atomic Consul operation.
// If a single KV pair is provided PutKeyValue is used to update the pair
func (this *consulTxnStore) PutKVPairs(kvPairs []*KVPair) (err error) {
if this.client == nil {
return nil
}
// use .PutKeyValue for single KVPair puts
if len(kvPairs) == 1 {
return this.PutKeyValue(kvPairs[0].Key, kvPairs[0].Value)
}
var txnOps consulapi.TxnOps
for _, pair := range kvPairs {
txnOps = append(txnOps, &consulapi.TxnOp{
KV: &consulapi.KVTxnOp{
Verb: consulapi.KVSet,
Key: pair.Key,
Value: []byte(pair.Value),
},
})
}
return this.doWriteTxn(txnOps, nil)
}
// DistributePairs updates all known Consul Datacenters with one or more KV pairs
func (this *consulTxnStore) DistributePairs(kvPairs [](*KVPair)) (err error) {
// This function is non re-entrant (it can only be running once at any point in time)
if atomic.CompareAndSwapInt64(&this.distributionReentry, 0, 1) {
defer atomic.StoreInt64(&this.distributionReentry, 0)
} else {
return
}
if !config.Config.ConsulCrossDataCenterDistribution {
return nil
}
datacenters, err := this.client.Catalog().Datacenters()
if err != nil {
return err
}
log.Debugf("consulTxnStore.DistributePairs(): distributing %d pairs to %d datacenters", len(kvPairs), len(datacenters))
consulPairs := []*consulapi.KVPair{}
for _, kvPair := range kvPairs {
consulPairs = append(consulPairs, &consulapi.KVPair{Key: kvPair.Key, Value: []byte(kvPair.Value)})
}
var wg sync.WaitGroup
for _, datacenter := range datacenters {
datacenter := datacenter
responses := make(chan updateDatacenterKVPairsResponse)
wg.Add(1)
go func() {
defer wg.Done()
// receive responses from .updateDatacenterKVPairs()
// goroutines, log a summary when channel is closed
go func() {
sum := updateDatacenterKVPairsResponse{}
for resp := range responses {
sum.existing += resp.existing
sum.failed += resp.failed
sum.skipped += resp.skipped
sum.written += resp.written
sum.getTxns += resp.getTxns
sum.setTxns += resp.setTxns
}
log.Debugf("consulTxnStore.DistributePairs(): datacenter: %s; getTxns: %d, setTxns: %d, skipped: %d, existing: %d, written: %d, failed: %d",
datacenter, sum.getTxns, sum.setTxns, sum.skipped, sum.existing, sum.written, sum.failed,
)
}()
// launch an .updateDatacenterKVPairs() goroutine
// for each grouping of consul KV pairs and wait
var dcWg sync.WaitGroup
for _, kvPairGroup := range groupKVPairsByKeyPrefix(consulPairs) {
dcWg.Add(1)
go this.updateDatacenterKVPairs(&dcWg, datacenter, kvPairGroup, responses)
}
dcWg.Wait()
close(responses)
}()
}
wg.Wait()
return err
}