blob: 04fe35de73455af379223bfb1af6d78cfa654ab1 [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -07001/*
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 */
16
sbarbari1e3e29c2019-11-05 10:06:50 -050017package db
Scott Baker2c1c4822019-10-16 11:02:41 -070018
19import (
Girish Kumarca522102019-11-08 11:26:35 +000020 "context"
Scott Baker2c1c4822019-10-16 11:02:41 -070021 "errors"
22 "fmt"
Scott Baker2c1c4822019-10-16 11:02:41 -070023 "strconv"
24 "sync"
Girish Kumarca522102019-11-08 11:26:35 +000025 "time"
serkant.uluderyab38671c2019-11-01 09:35:38 -070026
27 "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
28 "github.com/opencord/voltha-lib-go/v3/pkg/log"
29 "google.golang.org/grpc/codes"
30 "google.golang.org/grpc/status"
Girish Kumarca522102019-11-08 11:26:35 +000031)
32
33const (
34 // Default Minimal Interval for posting alive state of backend kvstore on Liveness Channel
35 DefaultLivenessChannelInterval = time.Second * 30
Scott Baker2c1c4822019-10-16 11:02:41 -070036)
37
Scott Baker2c1c4822019-10-16 11:02:41 -070038// Backend structure holds details for accessing the kv store
39type Backend struct {
40 sync.RWMutex
Girish Kumarca522102019-11-08 11:26:35 +000041 Client kvstore.Client
42 StoreType string
43 Host string
44 Port int
45 Timeout int
46 PathPrefix string
47 alive bool // Is this backend connection alive?
48 liveness chan bool // channel to post alive state
49 LivenessChannelInterval time.Duration // regularly push alive state beyond this interval
50 lastLivenessTime time.Time // Instant of last alive state push
Scott Baker2c1c4822019-10-16 11:02:41 -070051}
52
53// NewBackend creates a new instance of a Backend structure
54func NewBackend(storeType string, host string, port int, timeout int, pathPrefix string) *Backend {
55 var err error
56
57 b := &Backend{
Girish Kumarca522102019-11-08 11:26:35 +000058 StoreType: storeType,
59 Host: host,
60 Port: port,
61 Timeout: timeout,
62 LivenessChannelInterval: DefaultLivenessChannelInterval,
63 PathPrefix: pathPrefix,
64 alive: false, // connection considered down at start
Scott Baker2c1c4822019-10-16 11:02:41 -070065 }
66
67 address := host + ":" + strconv.Itoa(port)
68 if b.Client, err = b.newClient(address, timeout); err != nil {
khenaidoob332f9b2020-01-16 16:25:26 -050069 logger.Errorw("failed-to-create-kv-client",
Scott Baker2c1c4822019-10-16 11:02:41 -070070 log.Fields{
71 "type": storeType, "host": host, "port": port,
72 "timeout": timeout, "prefix": pathPrefix,
73 "error": err.Error(),
74 })
75 }
76
77 return b
78}
79
80func (b *Backend) newClient(address string, timeout int) (kvstore.Client, error) {
81 switch b.StoreType {
82 case "consul":
83 return kvstore.NewConsulClient(address, timeout)
84 case "etcd":
85 return kvstore.NewEtcdClient(address, timeout)
86 }
87 return nil, errors.New("unsupported-kv-store")
88}
89
90func (b *Backend) makePath(key string) string {
91 path := fmt.Sprintf("%s/%s", b.PathPrefix, key)
92 return path
93}
94
Girish Kumarca522102019-11-08 11:26:35 +000095func (b *Backend) updateLiveness(alive bool) {
96 // Periodically push stream of liveness data to the channel,
97 // so that in a live state, the core does not timeout and
98 // send a forced liveness message. Push alive state if the
99 // last push to channel was beyond livenessChannelInterval
100 if b.liveness != nil {
101
102 if b.alive != alive {
khenaidoob332f9b2020-01-16 16:25:26 -0500103 logger.Debug("update-liveness-channel-reason-change")
Girish Kumarca522102019-11-08 11:26:35 +0000104 b.liveness <- alive
105 b.lastLivenessTime = time.Now()
David K. Bainbridge7c75cac2020-02-19 08:53:46 -0800106 } else if time.Since(b.lastLivenessTime) > b.LivenessChannelInterval {
khenaidoob332f9b2020-01-16 16:25:26 -0500107 logger.Debug("update-liveness-channel-reason-interval")
Girish Kumarca522102019-11-08 11:26:35 +0000108 b.liveness <- alive
109 b.lastLivenessTime = time.Now()
110 }
111 }
112
113 // Emit log message only for alive state change
114 if b.alive != alive {
khenaidoob332f9b2020-01-16 16:25:26 -0500115 logger.Debugw("change-kvstore-alive-status", log.Fields{"alive": alive})
Girish Kumarca522102019-11-08 11:26:35 +0000116 b.alive = alive
117 }
118}
119
120// Perform a dummy Key Lookup on kvstore to test Connection Liveness and
121// post on Liveness channel
npujar5bf737f2020-01-16 19:35:25 +0530122func (b *Backend) PerformLivenessCheck(ctx context.Context) bool {
123 alive := b.Client.IsConnectionUp(ctx)
khenaidoob332f9b2020-01-16 16:25:26 -0500124 logger.Debugw("kvstore-liveness-check-result", log.Fields{"alive": alive})
Girish Kumarca522102019-11-08 11:26:35 +0000125
126 b.updateLiveness(alive)
127 return alive
128}
129
130// Enable the liveness monitor channel. This channel will report
131// a "true" or "false" on every kvstore operation which indicates whether
132// or not the connection is still Live. This channel is then picked up
133// by the service (i.e. rw_core / ro_core) to update readiness status
134// and/or take other actions.
135func (b *Backend) EnableLivenessChannel() chan bool {
khenaidoob332f9b2020-01-16 16:25:26 -0500136 logger.Debug("enable-kvstore-liveness-channel")
Girish Kumarca522102019-11-08 11:26:35 +0000137
138 if b.liveness == nil {
khenaidoob332f9b2020-01-16 16:25:26 -0500139 logger.Debug("create-kvstore-liveness-channel")
Girish Kumarca522102019-11-08 11:26:35 +0000140
141 // Channel size of 10 to avoid any possibility of blocking in Load conditions
142 b.liveness = make(chan bool, 10)
143
144 // Post initial alive state
145 b.liveness <- b.alive
146 b.lastLivenessTime = time.Now()
147 }
148
149 return b.liveness
150}
151
152// Extract Alive status of Kvstore based on type of error
153func (b *Backend) isErrorIndicatingAliveKvstore(err error) bool {
154 // Alive unless observed an error indicating so
155 alive := true
156
157 if err != nil {
158
159 // timeout indicates kvstore not reachable/alive
160 if err == context.DeadlineExceeded {
161 alive = false
162 }
163
164 // Need to analyze client-specific errors based on backend type
165 if b.StoreType == "etcd" {
166
167 // For etcd backend, consider not-alive only for errors indicating
168 // timedout request or unavailable/corrupted cluster. For all remaining
169 // error codes listed in https://godoc.org/google.golang.org/grpc/codes#Code,
170 // we would not infer a not-alive backend because such a error may also
171 // occur due to bad client requests or sequence of operations
172 switch status.Code(err) {
173 case codes.DeadlineExceeded:
174 fallthrough
175 case codes.Unavailable:
176 fallthrough
177 case codes.DataLoss:
178 alive = false
179 }
180
181 //} else {
182 // TODO: Implement for consul backend; would it be needed ever?
183 }
184 }
185
186 return alive
187}
188
Scott Baker2c1c4822019-10-16 11:02:41 -0700189// List retrieves one or more items that match the specified key
npujar5bf737f2020-01-16 19:35:25 +0530190func (b *Backend) List(ctx context.Context, key string) (map[string]*kvstore.KVPair, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700191 b.Lock()
192 defer b.Unlock()
193
194 formattedPath := b.makePath(key)
khenaidoob332f9b2020-01-16 16:25:26 -0500195 logger.Debugw("listing-key", log.Fields{"key": key, "path": formattedPath})
Scott Baker2c1c4822019-10-16 11:02:41 -0700196
npujar5bf737f2020-01-16 19:35:25 +0530197 pair, err := b.Client.List(ctx, formattedPath)
Girish Kumarca522102019-11-08 11:26:35 +0000198
199 b.updateLiveness(b.isErrorIndicatingAliveKvstore(err))
200
201 return pair, err
Scott Baker2c1c4822019-10-16 11:02:41 -0700202}
203
204// Get retrieves an item that matches the specified key
npujar5bf737f2020-01-16 19:35:25 +0530205func (b *Backend) Get(ctx context.Context, key string) (*kvstore.KVPair, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700206 b.Lock()
207 defer b.Unlock()
208
209 formattedPath := b.makePath(key)
khenaidoob332f9b2020-01-16 16:25:26 -0500210 logger.Debugw("getting-key", log.Fields{"key": key, "path": formattedPath})
Scott Baker2c1c4822019-10-16 11:02:41 -0700211
npujar5bf737f2020-01-16 19:35:25 +0530212 pair, err := b.Client.Get(ctx, formattedPath)
Girish Kumarca522102019-11-08 11:26:35 +0000213
214 b.updateLiveness(b.isErrorIndicatingAliveKvstore(err))
215
216 return pair, err
Scott Baker2c1c4822019-10-16 11:02:41 -0700217}
218
219// Put stores an item value under the specifed key
npujar5bf737f2020-01-16 19:35:25 +0530220func (b *Backend) Put(ctx context.Context, key string, value interface{}) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700221 b.Lock()
222 defer b.Unlock()
223
224 formattedPath := b.makePath(key)
khenaidoob332f9b2020-01-16 16:25:26 -0500225 logger.Debugw("putting-key", log.Fields{"key": key, "value": string(value.([]byte)), "path": formattedPath})
Scott Baker2c1c4822019-10-16 11:02:41 -0700226
npujar5bf737f2020-01-16 19:35:25 +0530227 err := b.Client.Put(ctx, formattedPath, value)
Girish Kumarca522102019-11-08 11:26:35 +0000228
229 b.updateLiveness(b.isErrorIndicatingAliveKvstore(err))
230
231 return err
Scott Baker2c1c4822019-10-16 11:02:41 -0700232}
233
234// Delete removes an item under the specified key
npujar5bf737f2020-01-16 19:35:25 +0530235func (b *Backend) Delete(ctx context.Context, key string) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700236 b.Lock()
237 defer b.Unlock()
238
239 formattedPath := b.makePath(key)
khenaidoob332f9b2020-01-16 16:25:26 -0500240 logger.Debugw("deleting-key", log.Fields{"key": key, "path": formattedPath})
Scott Baker2c1c4822019-10-16 11:02:41 -0700241
npujar5bf737f2020-01-16 19:35:25 +0530242 err := b.Client.Delete(ctx, formattedPath)
Girish Kumarca522102019-11-08 11:26:35 +0000243
244 b.updateLiveness(b.isErrorIndicatingAliveKvstore(err))
245
246 return err
Scott Baker2c1c4822019-10-16 11:02:41 -0700247}
248
249// CreateWatch starts watching events for the specified key
divyadesai8bf96862020-02-07 12:24:26 +0000250func (b *Backend) CreateWatch(ctx context.Context, key string, withPrefix bool) chan *kvstore.Event {
Scott Baker2c1c4822019-10-16 11:02:41 -0700251 b.Lock()
252 defer b.Unlock()
253
254 formattedPath := b.makePath(key)
khenaidoob332f9b2020-01-16 16:25:26 -0500255 logger.Debugw("creating-key-watch", log.Fields{"key": key, "path": formattedPath})
Scott Baker2c1c4822019-10-16 11:02:41 -0700256
divyadesai8bf96862020-02-07 12:24:26 +0000257 return b.Client.Watch(ctx, formattedPath, withPrefix)
Scott Baker2c1c4822019-10-16 11:02:41 -0700258}
259
260// DeleteWatch stops watching events for the specified key
261func (b *Backend) DeleteWatch(key string, ch chan *kvstore.Event) {
262 b.Lock()
263 defer b.Unlock()
264
265 formattedPath := b.makePath(key)
khenaidoob332f9b2020-01-16 16:25:26 -0500266 logger.Debugw("deleting-key-watch", log.Fields{"key": key, "path": formattedPath})
Scott Baker2c1c4822019-10-16 11:02:41 -0700267
268 b.Client.CloseWatch(formattedPath, ch)
269}