blob: 453f2820b0004241032611150154a6ad709a0b4d [file] [log] [blame]
khenaidoocfee5f42018-07-19 22:47:38 -04001package kvstore
2
3import (
4 "context"
5 "errors"
6 "bytes"
7 "sync"
8 "time"
9 log "github.com/opencord/voltha-go/common/log"
10 //log "ciena.com/coordinator/common"
11 consulapi "github.com/hashicorp/consul/api"
12)
13
14type channelContextMap struct {
15 ctx context.Context
16 channel chan *Event
17 cancel context.CancelFunc
18}
19
20
21// ConsulClient represents the consul KV store client
22type ConsulClient struct {
23 session *consulapi.Session
24 sessionID string
25 consul *consulapi.Client
26 doneCh *chan int
27 keyReservations map[string]interface{}
28 watchedChannelsContext map[string][]*channelContextMap
29 writeLock sync.Mutex
30}
31
32// NewConsulClient returns a new client for the Consul KV store
33func NewConsulClient(addr string, timeout int) (*ConsulClient, error) {
34
35 duration := GetDuration(timeout)
36
37 config := consulapi.DefaultConfig()
38 config.Address = addr
39 config.WaitTime = duration
40 consul, err := consulapi.NewClient(config)
41 if err != nil {
42 log.Error(err)
43 return nil, err
44 }
45
46 doneCh := make(chan int, 1)
47 wChannelsContext := make(map[string][]*channelContextMap)
48 reservations := make(map[string]interface{})
49 return &ConsulClient{consul: consul, doneCh: &doneCh, watchedChannelsContext: wChannelsContext, keyReservations: reservations}, nil
50}
51
52// List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will
53// wait for a response
54func (c *ConsulClient) List(key string, timeout int) (map[string]*KVPair, error) {
55 duration := GetDuration(timeout)
56
57 kv := c.consul.KV()
58 var queryOptions consulapi.QueryOptions
59 queryOptions.WaitTime = duration
60 // For now we ignore meta data
61 kvps, _, err := kv.List(key, &queryOptions)
62 if err != nil {
63 log.Error(err)
64 return nil, err
65 }
66 m := make(map[string]*KVPair)
67 for _, kvp := range kvps {
68 m[string(kvp.Key)] = NewKVPair(string(kvp.Key), kvp.Value, string(kvp.Session), 0)
69 }
70 return m, nil
71}
72
73// Get returns a key-value pair for a given key. Timeout defines how long the function will
74// wait for a response
75func (c *ConsulClient) Get(key string, timeout int) (*KVPair, error) {
76
77 duration := GetDuration(timeout)
78
79 kv := c.consul.KV()
80 var queryOptions consulapi.QueryOptions
81 queryOptions.WaitTime = duration
82 // For now we ignore meta data
83 kvp, _, err := kv.Get(key, &queryOptions)
84 if err != nil {
85 log.Error(err)
86 return nil, err
87 }
88 if kvp != nil {
89 return NewKVPair(string(kvp.Key), kvp.Value, string(kvp.Session), 0), nil
90 }
91
92 return nil, nil
93}
94
95// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the consul API
96// accepts only a []byte as a value for a put operation. Timeout defines how long the function will
97// wait for a response
98func (c *ConsulClient) Put(key string, value interface{}, timeout int) error {
99
100 // Validate that we can create a byte array from the value as consul API expects a byte array
101 var val []byte
102 var er error
103 if val, er = ToByte(value); er != nil {
104 log.Error(er)
105 return er
106 }
107
108 // Create a key value pair
109 kvp := consulapi.KVPair{Key: key, Value: val}
110 kv := c.consul.KV()
111 var writeOptions consulapi.WriteOptions
112 c.writeLock.Lock()
113 defer c.writeLock.Unlock()
114 _, err := kv.Put(&kvp, &writeOptions)
115 if err != nil {
116 log.Error(err)
117 return err
118 }
119 return nil
120}
121
122// Delete removes a key from the KV store. Timeout defines how long the function will
123// wait for a response
124func (c *ConsulClient) Delete(key string, timeout int) error {
125 kv := c.consul.KV()
126 var writeOptions consulapi.WriteOptions
127 c.writeLock.Lock()
128 defer c.writeLock.Unlock()
129 _, err := kv.Delete(key, &writeOptions)
130 if err != nil {
131 log.Error(err)
132 return err
133 }
134 return nil
135}
136
137func (c *ConsulClient) deleteSession() {
138 if c.sessionID != "" {
139 log.Debug("cleaning-up-session")
140 session := c.consul.Session()
141 _, err := session.Destroy(c.sessionID, nil)
142 if err != nil {
143 log.Errorw("error-cleaning-session", log.Fields{"session":c.sessionID, "error":err})
144 }
145 }
146 c.sessionID = ""
147 c.session = nil
148}
149
150func (c *ConsulClient) createSession(ttl int64, retries int) (*consulapi.Session, string, error) {
151 session := c.consul.Session()
152 entry := &consulapi.SessionEntry{
153 Behavior: consulapi.SessionBehaviorDelete,
154 TTL: "10s", // strconv.FormatInt(ttl, 10) + "s", // disable ttl
155 }
156
157 for {
158 id, meta, err := session.Create(entry, nil)
159 if err != nil {
160 log.Errorw("create-session-error", log.Fields{"error":err})
161 if retries == 0 {
162 return nil, "", err
163 }
164 } else if meta.RequestTime == 0 {
165 log.Errorw("create-session-bad-meta-data", log.Fields{"meta-data":meta})
166 if retries == 0 {
167 return nil, "", errors.New("bad-meta-data")
168 }
169 } else if id == "" {
170 log.Error("create-session-nil-id")
171 if retries == 0 {
172 return nil, "", errors.New("ID-nil")
173 }
174 } else {
175 return session, id, nil
176 }
177 // If retry param is -1 we will retry indefinitely
178 if retries > 0 {
179 retries--
180 }
181 log.Debug("retrying-session-create-after-a-second-delay")
182 time.Sleep(time.Duration(1) * time.Second)
183 }
184}
185
186
187// Helper function to verify mostly whether the content of two interface types are the same. Focus is []byte and
188// string types
189func isEqual(val1 interface{}, val2 interface{}) bool {
190 b1, err := ToByte(val1)
191 b2, er := ToByte(val2)
192 if err == nil && er == nil {
193 return bytes.Equal(b1, b2)
194 }
195 return val1 == val2
196}
197
198// Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since
199// the consul API accepts only a []byte. Timeout defines how long the function will wait for a response. TTL
200// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
201// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
202// then the value assigned to that key will be returned.
203func (c *ConsulClient) Reserve(key string, value interface{}, ttl int64) (interface{}, error) {
204
205 // Validate that we can create a byte array from the value as consul API expects a byte array
206 var val []byte
207 var er error
208 if val, er = ToByte(value); er != nil {
209 log.Error(er)
210 return nil, er
211 }
212
213 // Cleanup any existing session and recreate new ones. A key is reserved against a session
214 if c.sessionID != "" {
215 c.deleteSession()
216 }
217
218 // Clear session if reservation is not successful
219 reservationSuccessful := false
220 defer func() {
221 if !reservationSuccessful {
222 log.Debug("deleting-session")
223 c.deleteSession()
224 }
225 }()
226
227 session, sessionID, err := c.createSession(ttl, -1)
228 if err != nil {
229 log.Errorw("no-session-created", log.Fields{"error":err})
230 return "", errors.New("no-session-created")
231 }
232 log.Debugw("session-created", log.Fields{"session-id":sessionID})
233 c.sessionID = sessionID
234 c.session = session
235
236 // Try to grap the Key using the session
237 kv := c.consul.KV()
238 kvp := consulapi.KVPair{Key: key, Value: val, Session: c.sessionID}
239 result, _, err := kv.Acquire(&kvp, nil)
240 if err != nil {
241 log.Errorw("error-acquiring-keys", log.Fields{"error":err})
242 return nil, err
243 }
244
245 log.Debugw("key-acquired", log.Fields{"key":key, "status":result})
246
247 // Irrespective whether we were successful in acquiring the key, let's read it back and see if it's us.
248 m, err := c.Get(key, defaultKVGetTimeout)
249 if err != nil {
250 return nil, err
251 }
252 if m != nil {
253 log.Debugw("response-received", log.Fields{"key":m.Key, "m.value":string(m.Value.([]byte)), "value":value})
254 if m.Key == key && isEqual(m.Value, value) {
255 // My reservation is successful - register it. For now, support is only for 1 reservation per key
256 // per session.
257 reservationSuccessful = true
258 c.writeLock.Lock()
259 c.keyReservations[key] = m.Value
260 c.writeLock.Unlock()
261 return m.Value, nil
262 }
263 // My reservation has failed. Return the owner of that key
264 return m.Value, nil
265 }
266 return nil, nil
267}
268
269// ReleaseAllReservations releases all key reservations previously made (using Reserve API)
270func (c *ConsulClient) ReleaseAllReservations() error {
271 kv := c.consul.KV()
272 var kvp consulapi.KVPair
273 var result bool
274 var err error
275
276 c.writeLock.Lock()
277 defer c.writeLock.Unlock()
278
279 for key, value := range c.keyReservations {
280 kvp = consulapi.KVPair{Key: key, Value: value.([]byte), Session: c.sessionID}
281 result, _, err = kv.Release(&kvp, nil)
282 if err != nil {
283 log.Errorw("cannot-release-reservation", log.Fields{"key":key, "error":err})
284 return err
285 }
286 if !result {
287 log.Errorw("cannot-release-reservation", log.Fields{"key":key})
288 }
289 delete(c.keyReservations, key)
290 }
291 return nil
292}
293
294// ReleaseReservation releases reservation for a specific key.
295func (c *ConsulClient) ReleaseReservation(key string) error {
296 var ok bool
297 var reservedValue interface{}
298 c.writeLock.Lock()
299 defer c.writeLock.Unlock()
300 if reservedValue, ok = c.keyReservations[key]; !ok {
301 return errors.New("key-not-reserved:" + key)
302 }
303 // Release the reservation
304 kv := c.consul.KV()
305 kvp := consulapi.KVPair{Key: key, Value: reservedValue.([]byte), Session: c.sessionID}
306
307 result, _, er := kv.Release(&kvp, nil)
308 if er != nil {
309 return er
310 }
311 // Remove that key entry on success
312 if result {
313 delete(c.keyReservations, key)
314 return nil
315 }
316 return errors.New("key-cannot-be-unreserved")
317}
318
319// RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live)
320// period specified when reserving the key
321func (c *ConsulClient) RenewReservation(key string) error {
322 // In the case of Consul, renew reservation of a reserve key only require renewing the client session.
323
324 c.writeLock.Lock()
325 defer c.writeLock.Unlock()
326
327 // Verify the key was reserved
328 if _, ok := c.keyReservations[key]; !ok {
329 return errors.New("key-not-reserved")
330 }
331
332 if c.session == nil {
333 return errors.New("no-session-exist")
334 }
335
336 var writeOptions consulapi.WriteOptions
337 if _, _, err := c.session.Renew(c.sessionID, &writeOptions); err != nil {
338 return err
339 }
340 return nil
341}
342
343// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
344// listen to receive Events.
345func (c *ConsulClient) Watch(key string) chan *Event {
346
347 // Create a new channel
348 ch := make(chan *Event, maxClientChannelBufferSize)
349
350 // Create a context to track this request
351 watchContext, cFunc := context.WithCancel(context.Background())
352
353 // Save the channel and context reference for later
354 c.writeLock.Lock()
355 defer c.writeLock.Unlock()
356 ccm := channelContextMap{channel: ch, ctx: watchContext, cancel: cFunc}
357 c.watchedChannelsContext[key] = append(c.watchedChannelsContext[key], &ccm)
358
359 // Launch a go routine to listen for updates
360 go c.listenForKeyChange(watchContext, key, ch)
361
362 return ch
363}
364
365// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
366// may be multiple listeners on the same key. The previously created channel serves as a key
367func (c *ConsulClient) CloseWatch(key string, ch chan *Event) {
368 // First close the context
369 var ok bool
370 var watchedChannelsContexts []*channelContextMap
371 c.writeLock.Lock()
372 defer c.writeLock.Unlock()
373 if watchedChannelsContexts, ok = c.watchedChannelsContext[key]; !ok {
374 log.Errorw("key-has-no-watched-context-or-channel", log.Fields{"key":key})
375 return
376 }
377 // Look for the channels
378 var pos = -1
379 for i, chCtxMap := range watchedChannelsContexts {
380 if chCtxMap.channel == ch {
381 log.Debug("channel-found")
382 chCtxMap.cancel()
383 //close the channel
384 close(ch)
385 pos = i
386 break
387 }
388 }
389 // Remove that entry if present
390 if pos >= 0 {
391 c.watchedChannelsContext[key] = append(c.watchedChannelsContext[key][:pos], c.watchedChannelsContext[key][pos+1:]...)
392 }
393 log.Debugw("watched-channel-exiting", log.Fields{"key":key, "channel":c.watchedChannelsContext[key]})
394}
395
396func (c *ConsulClient) isKVEqual(kv1 *consulapi.KVPair, kv2 *consulapi.KVPair) bool {
397 if (kv1 == nil) && (kv2 == nil) {
398 return true
399 } else if (kv1 == nil) || (kv2 == nil) {
400 return false
401 }
402 // Both the KV should be non-null here
403 if kv1.Key != kv2.Key ||
404 !bytes.Equal(kv1.Value, kv2.Value) ||
405 kv1.Session != kv2.Session ||
406 kv1.LockIndex != kv2.LockIndex ||
407 kv1.ModifyIndex != kv2.ModifyIndex {
408 return false
409 }
410 return true
411}
412
413func (c *ConsulClient) listenForKeyChange(watchContext context.Context, key string, ch chan *Event) {
414 log.Debugw("start-watching-channel", log.Fields{"key":key, "channel":ch})
415
416 defer c.CloseWatch(key, ch)
417 duration := GetDuration(defaultKVGetTimeout)
418 kv := c.consul.KV()
419 var queryOptions consulapi.QueryOptions
420 queryOptions.WaitTime = duration
421
422 // Get the existing value, if any
423 previousKVPair, meta, err := kv.Get(key, &queryOptions)
424 if err != nil {
425 log.Debug(err)
426 }
427 lastIndex := meta.LastIndex
428
429 // Wait for change. Push any change onto the channel and keep waiting for new update
430 //var waitOptions consulapi.QueryOptions
431 var pair *consulapi.KVPair
432 //watchContext, _ := context.WithCancel(context.Background())
433 waitOptions := queryOptions.WithContext(watchContext)
434 for {
435 //waitOptions = consulapi.QueryOptions{WaitIndex: lastIndex}
436 waitOptions.WaitIndex = lastIndex
437 pair, meta, err = kv.Get(key, waitOptions)
438 select {
439 case <-watchContext.Done():
440 log.Debug("done-event-received-exiting")
441 return
442 default:
443 if err != nil {
444 log.Warnw("error-from-watch", log.Fields{"error":err})
445 ch <- NewEvent(CONNECTIONDOWN, key, []byte(""))
446 } else {
447 log.Debugw("index-state", log.Fields{"lastindex":lastIndex, "newindex":meta.LastIndex, "key":key})
448 }
449 }
450 if err != nil {
451 log.Debug(err)
452 // On error, block for 10 milliseconds to prevent endless loop
453 time.Sleep(10 * time.Millisecond)
454 } else if meta.LastIndex <= lastIndex {
455 log.Info("no-index-change-or-negative")
456 } else {
457 log.Debugw("update-received", log.Fields{"pair":pair})
458 if pair == nil {
459 ch <- NewEvent(DELETE, key, []byte(""))
460 } else if !c.isKVEqual(pair, previousKVPair) {
461 // Push the change onto the channel if the data has changed
462 // For now just assume it's a PUT change
463 log.Debugw("pair-details", log.Fields{"session":pair.Session, "key":pair.Key, "value":pair.Value})
464 ch <- NewEvent(PUT, pair.Key, pair.Value)
465 }
466 previousKVPair = pair
467 lastIndex = meta.LastIndex
468 }
469 }
470}
471
472// Close closes the KV store client
473func (c *ConsulClient) Close() {
474 var writeOptions consulapi.WriteOptions
475 // Inform any goroutine it's time to say goodbye.
476 c.writeLock.Lock()
477 defer c.writeLock.Unlock()
478 if c.doneCh != nil {
479 close(*c.doneCh)
480 }
481
482 // Clear the sessionID
483 if _, err := c.consul.Session().Destroy(c.sessionID, &writeOptions); err != nil {
484 log.Errorw("error-closing-client", log.Fields{"error":err})
485 }
486}