blob: ff0b5b7ef18750e182a07627068bc13b2fe89330 [file] [log] [blame]
divyadesai81bb7ba2020-03-11 11:45:23 +00001/*
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
17package db
18
19import (
20 "context"
21 "errors"
22 "fmt"
Girish Kumarcd402012020-08-18 12:17:38 +000023 "sync"
divyadesai81bb7ba2020-03-11 11:45:23 +000024 "time"
25
Andrea Campanella18448bc2021-07-08 18:47:22 +020026 "github.com/opencord/voltha-lib-go/v5/pkg/db/kvstore"
27 "github.com/opencord/voltha-lib-go/v5/pkg/log"
divyadesai81bb7ba2020-03-11 11:45:23 +000028 "google.golang.org/grpc/codes"
29 "google.golang.org/grpc/status"
30)
31
32const (
33 // Default Minimal Interval for posting alive state of backend kvstore on Liveness Channel
34 DefaultLivenessChannelInterval = time.Second * 30
35)
36
37// Backend structure holds details for accessing the kv store
38type Backend struct {
divyadesai81bb7ba2020-03-11 11:45:23 +000039 Client kvstore.Client
40 StoreType string
Neha Sharma87d43d72020-04-08 14:10:40 +000041 Timeout time.Duration
Neha Sharma318a1292020-05-14 19:53:26 +000042 Address string
divyadesai81bb7ba2020-03-11 11:45:23 +000043 PathPrefix string
Girish Kumarcd402012020-08-18 12:17:38 +000044 alive bool // Is this backend connection alive?
45 livenessMutex sync.Mutex
divyadesai81bb7ba2020-03-11 11:45:23 +000046 liveness chan bool // channel to post alive state
47 LivenessChannelInterval time.Duration // regularly push alive state beyond this interval
48 lastLivenessTime time.Time // Instant of last alive state push
49}
50
51// NewBackend creates a new instance of a Backend structure
Rohan Agrawalc32d9932020-06-15 11:01:47 +000052func NewBackend(ctx context.Context, storeType string, address string, timeout time.Duration, pathPrefix string) *Backend {
divyadesai81bb7ba2020-03-11 11:45:23 +000053 var err error
54
55 b := &Backend{
56 StoreType: storeType,
Neha Sharma318a1292020-05-14 19:53:26 +000057 Address: address,
divyadesai81bb7ba2020-03-11 11:45:23 +000058 Timeout: timeout,
59 LivenessChannelInterval: DefaultLivenessChannelInterval,
60 PathPrefix: pathPrefix,
61 alive: false, // connection considered down at start
62 }
63
Rohan Agrawalc32d9932020-06-15 11:01:47 +000064 if b.Client, err = b.newClient(ctx, address, timeout); err != nil {
65 logger.Errorw(ctx, "failed-to-create-kv-client",
divyadesai81bb7ba2020-03-11 11:45:23 +000066 log.Fields{
Neha Sharma318a1292020-05-14 19:53:26 +000067 "type": storeType, "address": address,
divyadesai81bb7ba2020-03-11 11:45:23 +000068 "timeout": timeout, "prefix": pathPrefix,
69 "error": err.Error(),
70 })
71 }
72
73 return b
74}
75
Rohan Agrawalc32d9932020-06-15 11:01:47 +000076func (b *Backend) newClient(ctx context.Context, address string, timeout time.Duration) (kvstore.Client, error) {
divyadesai81bb7ba2020-03-11 11:45:23 +000077 switch b.StoreType {
divyadesai81bb7ba2020-03-11 11:45:23 +000078 case "etcd":
Rohan Agrawalc32d9932020-06-15 11:01:47 +000079 return kvstore.NewEtcdClient(ctx, address, timeout, log.WarnLevel)
divyadesai81bb7ba2020-03-11 11:45:23 +000080 }
81 return nil, errors.New("unsupported-kv-store")
82}
83
Rohan Agrawalc32d9932020-06-15 11:01:47 +000084func (b *Backend) makePath(ctx context.Context, key string) string {
divyadesai81bb7ba2020-03-11 11:45:23 +000085 path := fmt.Sprintf("%s/%s", b.PathPrefix, key)
86 return path
87}
88
Rohan Agrawalc32d9932020-06-15 11:01:47 +000089func (b *Backend) updateLiveness(ctx context.Context, alive bool) {
divyadesai81bb7ba2020-03-11 11:45:23 +000090 // 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
Girish Kumarcd402012020-08-18 12:17:38 +000094 b.livenessMutex.Lock()
95 defer b.livenessMutex.Unlock()
divyadesai81bb7ba2020-03-11 11:45:23 +000096 if b.liveness != nil {
divyadesai81bb7ba2020-03-11 11:45:23 +000097 if b.alive != alive {
Rohan Agrawalc32d9932020-06-15 11:01:47 +000098 logger.Debug(ctx, "update-liveness-channel-reason-change")
divyadesai81bb7ba2020-03-11 11:45:23 +000099 b.liveness <- alive
100 b.lastLivenessTime = time.Now()
101 } else if time.Since(b.lastLivenessTime) > b.LivenessChannelInterval {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000102 logger.Debug(ctx, "update-liveness-channel-reason-interval")
divyadesai81bb7ba2020-03-11 11:45:23 +0000103 b.liveness <- alive
104 b.lastLivenessTime = time.Now()
105 }
106 }
107
108 // Emit log message only for alive state change
109 if b.alive != alive {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000110 logger.Debugw(ctx, "change-kvstore-alive-status", log.Fields{"alive": alive})
divyadesai81bb7ba2020-03-11 11:45:23 +0000111 b.alive = alive
112 }
113}
114
115// Perform a dummy Key Lookup on kvstore to test Connection Liveness and
116// post on Liveness channel
117func (b *Backend) PerformLivenessCheck(ctx context.Context) bool {
118 alive := b.Client.IsConnectionUp(ctx)
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000119 logger.Debugw(ctx, "kvstore-liveness-check-result", log.Fields{"alive": alive})
divyadesai81bb7ba2020-03-11 11:45:23 +0000120
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000121 b.updateLiveness(ctx, alive)
divyadesai81bb7ba2020-03-11 11:45:23 +0000122 return alive
123}
124
125// Enable the liveness monitor channel. This channel will report
126// a "true" or "false" on every kvstore operation which indicates whether
127// or not the connection is still Live. This channel is then picked up
128// by the service (i.e. rw_core / ro_core) to update readiness status
129// and/or take other actions.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000130func (b *Backend) EnableLivenessChannel(ctx context.Context) chan bool {
131 logger.Debug(ctx, "enable-kvstore-liveness-channel")
Girish Kumarcd402012020-08-18 12:17:38 +0000132 b.livenessMutex.Lock()
133 defer b.livenessMutex.Unlock()
divyadesai81bb7ba2020-03-11 11:45:23 +0000134 if b.liveness == nil {
divyadesai81bb7ba2020-03-11 11:45:23 +0000135 b.liveness = make(chan bool, 10)
divyadesai81bb7ba2020-03-11 11:45:23 +0000136 b.liveness <- b.alive
137 b.lastLivenessTime = time.Now()
138 }
139
140 return b.liveness
141}
142
143// Extract Alive status of Kvstore based on type of error
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000144func (b *Backend) isErrorIndicatingAliveKvstore(ctx context.Context, err error) bool {
divyadesai81bb7ba2020-03-11 11:45:23 +0000145 // Alive unless observed an error indicating so
146 alive := true
147
148 if err != nil {
149
150 // timeout indicates kvstore not reachable/alive
151 if err == context.DeadlineExceeded {
152 alive = false
153 }
154
155 // Need to analyze client-specific errors based on backend type
156 if b.StoreType == "etcd" {
157
158 // For etcd backend, consider not-alive only for errors indicating
159 // timedout request or unavailable/corrupted cluster. For all remaining
160 // error codes listed in https://godoc.org/google.golang.org/grpc/codes#Code,
161 // we would not infer a not-alive backend because such a error may also
162 // occur due to bad client requests or sequence of operations
163 switch status.Code(err) {
164 case codes.DeadlineExceeded:
165 fallthrough
166 case codes.Unavailable:
167 fallthrough
168 case codes.DataLoss:
169 alive = false
170 }
divyadesai81bb7ba2020-03-11 11:45:23 +0000171 }
172 }
173
174 return alive
175}
176
177// List retrieves one or more items that match the specified key
178func (b *Backend) List(ctx context.Context, key string) (map[string]*kvstore.KVPair, error) {
Girish Kumarcd402012020-08-18 12:17:38 +0000179 span, ctx := log.CreateChildSpan(ctx, "etcd-list")
180 defer span.Finish()
181
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000182 formattedPath := b.makePath(ctx, key)
183 logger.Debugw(ctx, "listing-key", log.Fields{"key": key, "path": formattedPath})
divyadesai81bb7ba2020-03-11 11:45:23 +0000184
185 pair, err := b.Client.List(ctx, formattedPath)
186
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000187 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
divyadesai81bb7ba2020-03-11 11:45:23 +0000188
189 return pair, err
190}
191
192// Get retrieves an item that matches the specified key
193func (b *Backend) Get(ctx context.Context, key string) (*kvstore.KVPair, error) {
Girish Kumarcd402012020-08-18 12:17:38 +0000194 span, ctx := log.CreateChildSpan(ctx, "etcd-get")
195 defer span.Finish()
196
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000197 formattedPath := b.makePath(ctx, key)
198 logger.Debugw(ctx, "getting-key", log.Fields{"key": key, "path": formattedPath})
divyadesai81bb7ba2020-03-11 11:45:23 +0000199
200 pair, err := b.Client.Get(ctx, formattedPath)
201
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000202 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
divyadesai81bb7ba2020-03-11 11:45:23 +0000203
204 return pair, err
205}
206
207// Put stores an item value under the specifed key
208func (b *Backend) Put(ctx context.Context, key string, value interface{}) error {
Girish Kumarcd402012020-08-18 12:17:38 +0000209 span, ctx := log.CreateChildSpan(ctx, "etcd-put")
210 defer span.Finish()
211
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000212 formattedPath := b.makePath(ctx, key)
213 logger.Debugw(ctx, "putting-key", log.Fields{"key": key, "path": formattedPath})
divyadesai81bb7ba2020-03-11 11:45:23 +0000214
215 err := b.Client.Put(ctx, formattedPath, value)
216
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000217 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
divyadesai81bb7ba2020-03-11 11:45:23 +0000218
219 return err
220}
221
222// Delete removes an item under the specified key
223func (b *Backend) Delete(ctx context.Context, key string) error {
Girish Kumarcd402012020-08-18 12:17:38 +0000224 span, ctx := log.CreateChildSpan(ctx, "etcd-delete")
225 defer span.Finish()
226
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000227 formattedPath := b.makePath(ctx, key)
228 logger.Debugw(ctx, "deleting-key", log.Fields{"key": key, "path": formattedPath})
divyadesai81bb7ba2020-03-11 11:45:23 +0000229
230 err := b.Client.Delete(ctx, formattedPath)
231
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000232 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
divyadesai81bb7ba2020-03-11 11:45:23 +0000233
234 return err
235}
236
David K. Bainbridge595b6702021-04-09 16:10:58 +0000237// DeleteWithPrefix removes items having prefix key
238func (b *Backend) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
239 span, ctx := log.CreateChildSpan(ctx, "etcd-delete-with-prefix")
240 defer span.Finish()
241
242 formattedPath := b.makePath(ctx, prefixKey)
243 logger.Debugw(ctx, "deleting-prefix-key", log.Fields{"key": prefixKey, "path": formattedPath})
244
245 err := b.Client.DeleteWithPrefix(ctx, formattedPath)
246
247 b.updateLiveness(ctx, b.isErrorIndicatingAliveKvstore(ctx, err))
248
249 return err
250}
251
divyadesai81bb7ba2020-03-11 11:45:23 +0000252// CreateWatch starts watching events for the specified key
253func (b *Backend) CreateWatch(ctx context.Context, key string, withPrefix bool) chan *kvstore.Event {
Girish Kumarcd402012020-08-18 12:17:38 +0000254 span, ctx := log.CreateChildSpan(ctx, "etcd-create-watch")
255 defer span.Finish()
256
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000257 formattedPath := b.makePath(ctx, key)
258 logger.Debugw(ctx, "creating-key-watch", log.Fields{"key": key, "path": formattedPath})
divyadesai81bb7ba2020-03-11 11:45:23 +0000259
260 return b.Client.Watch(ctx, formattedPath, withPrefix)
261}
262
263// DeleteWatch stops watching events for the specified key
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000264func (b *Backend) DeleteWatch(ctx context.Context, key string, ch chan *kvstore.Event) {
Girish Kumarcd402012020-08-18 12:17:38 +0000265 span, ctx := log.CreateChildSpan(ctx, "etcd-delete-watch")
266 defer span.Finish()
267
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000268 formattedPath := b.makePath(ctx, key)
269 logger.Debugw(ctx, "deleting-key-watch", log.Fields{"key": key, "path": formattedPath})
divyadesai81bb7ba2020-03-11 11:45:23 +0000270
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000271 b.Client.CloseWatch(ctx, formattedPath, ch)
divyadesai81bb7ba2020-03-11 11:45:23 +0000272}