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