blob: f595dc1b7deed61a0cc009abf473b46c9f75153f [file] [log] [blame]
khenaidoobf6e7bb2018-08-14 22:27:29 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Stephane Barbariedc5022d2018-11-19 15:21:44 -050016
sbarbari17d7e222019-11-05 10:02:29 -050017package db
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040018
19import (
Scott Baker973f8ba2019-11-19 15:00:22 -080020 "context"
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040021 "errors"
22 "fmt"
Scott Baker973f8ba2019-11-19 15:00:22 -080023 "time"
serkant.uluderya2ae470f2020-01-21 11:13:09 -080024
25 "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
26 "github.com/opencord/voltha-lib-go/v3/pkg/log"
27 "google.golang.org/grpc/codes"
28 "google.golang.org/grpc/status"
Scott Baker973f8ba2019-11-19 15:00:22 -080029)
30
31const (
32 // Default Minimal Interval for posting alive state of backend kvstore on Liveness Channel
33 DefaultLivenessChannelInterval = time.Second * 30
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040034)
35
Stephane Barbariedc5022d2018-11-19 15:21:44 -050036// Backend structure holds details for accessing the kv store
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040037type Backend struct {
Scott Baker973f8ba2019-11-19 15:00:22 -080038 Client kvstore.Client
39 StoreType string
Neha Sharma7d6f3a92020-04-14 15:26:22 +000040 Timeout time.Duration
Neha Sharmad1387da2020-05-07 20:07:28 +000041 Address string
Scott Baker973f8ba2019-11-19 15:00:22 -080042 PathPrefix string
43 alive bool // Is this backend connection alive?
44 liveness chan bool // channel to post alive state
45 LivenessChannelInterval time.Duration // regularly push alive state beyond this interval
46 lastLivenessTime time.Time // Instant of last alive state push
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040047}
48
Stephane Barbariedc5022d2018-11-19 15:21:44 -050049// NewBackend creates a new instance of a Backend structure
Rohan Agrawal31f21802020-06-12 05:38:46 +000050func NewBackend(ctx context.Context, storeType string, address string, timeout time.Duration, pathPrefix string) *Backend {
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040051 var err error
52
53 b := &Backend{
Scott Baker973f8ba2019-11-19 15:00:22 -080054 StoreType: storeType,
Neha Sharmad1387da2020-05-07 20:07:28 +000055 Address: address,
Scott Baker973f8ba2019-11-19 15:00:22 -080056 Timeout: timeout,
57 LivenessChannelInterval: DefaultLivenessChannelInterval,
58 PathPrefix: pathPrefix,
59 alive: false, // connection considered down at start
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040060 }
61
Rohan Agrawal31f21802020-06-12 05:38:46 +000062 if b.Client, err = b.newClient(ctx, address, timeout); err != nil {
63 logger.Errorw(ctx, "failed-to-create-kv-client",
Stephane Barbariee0a4c792019-01-16 11:26:29 -050064 log.Fields{
Neha Sharmad1387da2020-05-07 20:07:28 +000065 "type": storeType, "address": address,
Stephane Barbariee0a4c792019-01-16 11:26:29 -050066 "timeout": timeout, "prefix": pathPrefix,
67 "error": err.Error(),
68 })
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040069 }
70
71 return b
72}
73
Rohan Agrawal31f21802020-06-12 05:38:46 +000074func (b *Backend) newClient(ctx context.Context, address string, timeout time.Duration) (kvstore.Client, error) {
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040075 switch b.StoreType {
76 case "consul":
Rohan Agrawal31f21802020-06-12 05:38:46 +000077 return kvstore.NewConsulClient(ctx, address, timeout)
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040078 case "etcd":
Rohan Agrawal31f21802020-06-12 05:38:46 +000079 return kvstore.NewEtcdClient(ctx, address, timeout, log.WarnLevel)
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040080 }
Stephane Barbariee0a4c792019-01-16 11:26:29 -050081 return nil, errors.New("unsupported-kv-store")
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040082}
83
Rohan Agrawal31f21802020-06-12 05:38:46 +000084func (b *Backend) makePath(ctx context.Context, key string) string {
Stephane Barbarieec0919b2018-09-05 14:14:29 -040085 path := fmt.Sprintf("%s/%s", b.PathPrefix, key)
Stephane Barbarieec0919b2018-09-05 14:14:29 -040086 return path
87}
Stephane Barbariedc5022d2018-11-19 15:21:44 -050088
Rohan Agrawal31f21802020-06-12 05:38:46 +000089func (b *Backend) updateLiveness(ctx context.Context, alive bool) {
Scott Baker973f8ba2019-11-19 15:00:22 -080090 // Periodically push stream of liveness data to the channel,
91 // so that in a live state, the core does not timeout and
92 // send a forced liveness message. Push alive state if the
93 // last push to channel was beyond livenessChannelInterval
94 if b.liveness != nil {
95
96 if b.alive != alive {
Rohan Agrawal31f21802020-06-12 05:38:46 +000097 logger.Debug(ctx, "update-liveness-channel-reason-change")
Scott Baker973f8ba2019-11-19 15:00:22 -080098 b.liveness <- alive
99 b.lastLivenessTime = time.Now()
Rohan Agrawal7f72f0c2020-01-14 12:05:51 +0000100 } else if time.Since(b.lastLivenessTime) > b.LivenessChannelInterval {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000101 logger.Debug(ctx, "update-liveness-channel-reason-interval")
Scott Baker973f8ba2019-11-19 15:00:22 -0800102 b.liveness <- alive
103 b.lastLivenessTime = time.Now()
104 }
105 }
106
107 // Emit log message only for alive state change
108 if b.alive != alive {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000109 logger.Debugw(ctx, "change-kvstore-alive-status", log.Fields{"alive": alive})
Scott Baker973f8ba2019-11-19 15:00:22 -0800110 b.alive = alive
111 }
112}
113
114// Perform a dummy Key Lookup on kvstore to test Connection Liveness and
115// post on Liveness channel
npujar467fe752020-01-16 20:17:45 +0530116func (b *Backend) PerformLivenessCheck(ctx context.Context) bool {
117 alive := b.Client.IsConnectionUp(ctx)
Rohan Agrawal31f21802020-06-12 05:38:46 +0000118 logger.Debugw(ctx, "kvstore-liveness-check-result", log.Fields{"alive": alive})
Scott Baker973f8ba2019-11-19 15:00:22 -0800119
Rohan Agrawal31f21802020-06-12 05:38:46 +0000120 b.updateLiveness(ctx, alive)
Scott Baker973f8ba2019-11-19 15:00:22 -0800121 return alive
122}
123
124// Enable the liveness monitor channel. This channel will report
125// a "true" or "false" on every kvstore operation which indicates whether
126// or not the connection is still Live. This channel is then picked up
127// by the service (i.e. rw_core / ro_core) to update readiness status
128// and/or take other actions.
Rohan Agrawal31f21802020-06-12 05:38:46 +0000129func (b *Backend) EnableLivenessChannel(ctx context.Context) chan bool {
130 logger.Debug(ctx, "enable-kvstore-liveness-channel")
Scott Baker973f8ba2019-11-19 15:00:22 -0800131
132 if b.liveness == nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000133 logger.Debug(ctx, "create-kvstore-liveness-channel")
Scott Baker973f8ba2019-11-19 15:00:22 -0800134
135 // Channel size of 10 to avoid any possibility of blocking in Load conditions
136 b.liveness = make(chan bool, 10)
137
138 // Post initial alive state
139 b.liveness <- b.alive
140 b.lastLivenessTime = time.Now()
141 }
142
143 return b.liveness
144}
145
146// Extract Alive status of Kvstore based on type of error
Rohan Agrawal31f21802020-06-12 05:38:46 +0000147func (b *Backend) isErrorIndicatingAliveKvstore(ctx context.Context, err error) bool {
Scott Baker973f8ba2019-11-19 15:00:22 -0800148 // Alive unless observed an error indicating so
149 alive := true
150
151 if err != nil {
152
153 // timeout indicates kvstore not reachable/alive
154 if err == context.DeadlineExceeded {
155 alive = false
156 }
157
158 // Need to analyze client-specific errors based on backend type
159 if b.StoreType == "etcd" {
160
161 // For etcd backend, consider not-alive only for errors indicating
162 // timedout request or unavailable/corrupted cluster. For all remaining
163 // error codes listed in https://godoc.org/google.golang.org/grpc/codes#Code,
164 // we would not infer a not-alive backend because such a error may also
165 // occur due to bad client requests or sequence of operations
166 switch status.Code(err) {
167 case codes.DeadlineExceeded:
168 fallthrough
169 case codes.Unavailable:
170 fallthrough
171 case codes.DataLoss:
172 alive = false
173 }
174
175 //} else {
176 // TODO: Implement for consul backend; would it be needed ever?
177 }
178 }
179
180 return alive
181}
182
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500183// List retrieves one or more items that match the specified key
npujar467fe752020-01-16 20:17:45 +0530184func (b *Backend) List(ctx context.Context, key string) (map[string]*kvstore.KVPair, error) {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000185 formattedPath := b.makePath(ctx, key)
186 logger.Debugw(ctx, "listing-key", log.Fields{"key": key, "path": formattedPath})
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500187
npujar467fe752020-01-16 20:17:45 +0530188 pair, err := b.Client.List(ctx, formattedPath)
Scott Baker973f8ba2019-11-19 15:00:22 -0800189
Rohan Agrawal31f21802020-06-12 05:38:46 +0000190 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
Scott Baker973f8ba2019-11-19 15:00:22 -0800191
192 return pair, err
Stephane Barbarie4a2564d2018-07-26 11:02:58 -0400193}
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500194
195// Get retrieves an item that matches the specified key
npujar467fe752020-01-16 20:17:45 +0530196func (b *Backend) Get(ctx context.Context, key string) (*kvstore.KVPair, error) {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000197 formattedPath := b.makePath(ctx, key)
198 logger.Debugw(ctx, "getting-key", log.Fields{"key": key, "path": formattedPath})
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500199
npujar467fe752020-01-16 20:17:45 +0530200 pair, err := b.Client.Get(ctx, formattedPath)
Scott Baker973f8ba2019-11-19 15:00:22 -0800201
Rohan Agrawal31f21802020-06-12 05:38:46 +0000202 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
Scott Baker973f8ba2019-11-19 15:00:22 -0800203
204 return pair, err
Stephane Barbarie4a2564d2018-07-26 11:02:58 -0400205}
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500206
207// Put stores an item value under the specifed key
npujar467fe752020-01-16 20:17:45 +0530208func (b *Backend) Put(ctx context.Context, key string, value interface{}) error {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000209 formattedPath := b.makePath(ctx, key)
210 logger.Debugw(ctx, "putting-key", log.Fields{"key": key, "path": formattedPath})
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500211
npujar467fe752020-01-16 20:17:45 +0530212 err := b.Client.Put(ctx, formattedPath, value)
Scott Baker973f8ba2019-11-19 15:00:22 -0800213
Rohan Agrawal31f21802020-06-12 05:38:46 +0000214 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
Scott Baker973f8ba2019-11-19 15:00:22 -0800215
216 return err
Stephane Barbarie4a2564d2018-07-26 11:02:58 -0400217}
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500218
219// Delete removes an item under the specified key
npujar467fe752020-01-16 20:17:45 +0530220func (b *Backend) Delete(ctx context.Context, key string) error {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000221 formattedPath := b.makePath(ctx, key)
222 logger.Debugw(ctx, "deleting-key", log.Fields{"key": key, "path": formattedPath})
Stephane Barbariedc5022d2018-11-19 15:21:44 -0500223
npujar467fe752020-01-16 20:17:45 +0530224 err := b.Client.Delete(ctx, formattedPath)
Scott Baker973f8ba2019-11-19 15:00:22 -0800225
Rohan Agrawal31f21802020-06-12 05:38:46 +0000226 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
Scott Baker973f8ba2019-11-19 15:00:22 -0800227
228 return err
Stephane Barbarie4a2564d2018-07-26 11:02:58 -0400229}
Stephane Barbariee0a4c792019-01-16 11:26:29 -0500230
231// CreateWatch starts watching events for the specified key
Scott Baker0e78ba22020-02-24 17:58:47 -0800232func (b *Backend) CreateWatch(ctx context.Context, key string, withPrefix bool) chan *kvstore.Event {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000233 formattedPath := b.makePath(ctx, key)
234 logger.Debugw(ctx, "creating-key-watch", log.Fields{"key": key, "path": formattedPath})
Stephane Barbariee0a4c792019-01-16 11:26:29 -0500235
Scott Baker0e78ba22020-02-24 17:58:47 -0800236 return b.Client.Watch(ctx, formattedPath, withPrefix)
Stephane Barbariee0a4c792019-01-16 11:26:29 -0500237}
238
239// DeleteWatch stops watching events for the specified key
Rohan Agrawal31f21802020-06-12 05:38:46 +0000240func (b *Backend) DeleteWatch(ctx context.Context, key string, ch chan *kvstore.Event) {
241 formattedPath := b.makePath(ctx, key)
242 logger.Debugw(ctx, "deleting-key-watch", log.Fields{"key": key, "path": formattedPath})
Stephane Barbariee0a4c792019-01-16 11:26:29 -0500243
Rohan Agrawal31f21802020-06-12 05:38:46 +0000244 b.Client.CloseWatch(ctx, formattedPath, ch)
Stephane Barbariee0a4c792019-01-16 11:26:29 -0500245}