blob: 462b7433f479ae3a3cb8876433b235701bffe5de [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 */
16package config
17
18import (
19 "context"
20 "fmt"
21 "github.com/opencord/voltha-lib-go/v3/pkg/db"
22 "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
23 "github.com/opencord/voltha-lib-go/v3/pkg/log"
24 "strings"
25)
26
27func init() {
28 _, err := log.AddPackage(log.JSON, log.FatalLevel, nil)
29 if err != nil {
30 log.Errorw("unable-to-register-package-to-the-log-map", log.Fields{"error": err})
31 }
32}
33
34const (
35 defaultkvStoreConfigPath = "config"
36 kvStoreDataPathPrefix = "/service/voltha"
37 kvStorePathSeparator = "/"
38)
39
40// ConfigType represents the type for which config is created inside the kvstore
41// For example, loglevel
42type ConfigType int
43
44const (
45 ConfigTypeLogLevel ConfigType = iota
46 ConfigTypeKafka
47)
48
49func (c ConfigType) String() string {
50 return [...]string{"loglevel", "kafka"}[c]
51}
52
53// ChangeEvent represents the event recieved from watch
54// For example, Put Event
55type ChangeEvent int
56
57const (
58 Put ChangeEvent = iota
59 Delete
60)
61
62// ConfigChangeEvent represents config for the events recieved from watch
63// For example,ChangeType is Put ,ConfigAttribute default
64type ConfigChangeEvent struct {
65 ChangeType ChangeEvent
66 ConfigAttribute string
67}
68
69// ConfigManager is a wrapper over backend to maintain Configuration of voltha components
70// in kvstore based persistent storage
71type ConfigManager struct {
72 backend *db.Backend
73 KvStoreConfigPrefix string
74}
75
76// ComponentConfig represents a category of configuration for a specific VOLTHA component type
77// stored in a persistent storage pointed to by Config Manager
78// For example, one ComponentConfig instance will be created for loglevel config type for rw-core
79// component while another ComponentConfig instance will refer to connection config type for same
80// rw-core component. So, there can be multiple ComponentConfig instance created per component
81// pointing to different category of configuration.
82//
83// Configuration pointed to be by ComponentConfig is stored in kvstore as a list of key/value pairs
84// under the hierarchical tree with following base path
85// <Backend Prefix Path>/<Config Prefix>/<Component Name>/<Config Type>/
86//
87// For example, rw-core ComponentConfig for loglevel config entries will be stored under following path
88// /voltha/service/config/rw-core/loglevel/
89type ComponentConfig struct {
90 cManager *ConfigManager
91 componentLabel string
92 configType ConfigType
93 changeEventChan chan *ConfigChangeEvent
94 kvStoreEventChan chan *kvstore.Event
95}
96
97func NewConfigManager(kvClient kvstore.Client, kvStoreType, kvStoreHost string, kvStorePort, kvStoreTimeout int) *ConfigManager {
98
99 return &ConfigManager{
100 KvStoreConfigPrefix: defaultkvStoreConfigPath,
101 backend: &db.Backend{
102 Client: kvClient,
103 StoreType: kvStoreType,
104 Host: kvStoreHost,
105 Port: kvStorePort,
106 Timeout: kvStoreTimeout,
107 PathPrefix: kvStoreDataPathPrefix,
108 },
109 }
110}
111
112// RetrieveComponentList list the component Names for which loglevel is stored in kvstore
113func (c *ConfigManager) RetrieveComponentList(ctx context.Context, configType ConfigType) ([]string, error) {
114 data, err := c.backend.List(ctx, c.KvStoreConfigPrefix)
115 if err != nil {
116 return nil, err
117 }
118
119 // Looping through the data recieved from the backend for config
120 // Trimming and Splitting the required key and value from data and storing as componentName,PackageName and Level
121 // For Example, recieved key would be <Backend Prefix Path>/<Config Prefix>/<Component Name>/<Config Type>/default and value \"DEBUG\"
122 // Then in default will be stored as PackageName,componentName as <Component Name> and DEBUG will be stored as value in List struct
123 ccPathPrefix := kvStorePathSeparator + configType.String() + kvStorePathSeparator
124 pathPrefix := kvStoreDataPathPrefix + kvStorePathSeparator + c.KvStoreConfigPrefix + kvStorePathSeparator
125 var list []string
126 keys := make(map[string]interface{})
127 for attr := range data {
128 cname := strings.TrimPrefix(attr, pathPrefix)
129 cName := strings.SplitN(cname, ccPathPrefix, 2)
130 if len(cName) != 2 {
131 continue
132 }
133 if _, exist := keys[cName[0]]; !exist {
134 keys[cName[0]] = nil
135 list = append(list, cName[0])
136 }
137 }
138 return list, nil
139}
140
141// Initialize the component config
142func (cm *ConfigManager) InitComponentConfig(componentLabel string, configType ConfigType) *ComponentConfig {
143
144 return &ComponentConfig{
145 componentLabel: componentLabel,
146 configType: configType,
147 cManager: cm,
148 changeEventChan: nil,
149 kvStoreEventChan: nil,
150 }
151
152}
153
154func (c *ComponentConfig) makeConfigPath() string {
155
156 cType := c.configType.String()
157 return c.cManager.KvStoreConfigPrefix + kvStorePathSeparator +
158 c.componentLabel + kvStorePathSeparator + cType
159}
160
161// MonitorForConfigChange watch on the subkeys for the given key
162// Any changes to the subkeys for the given key will return an event channel
163// Then Event channel will be processed and new event channel with required values will be created and return
164// For example, rw-core will be watching on <Backend Prefix Path>/<Config Prefix>/<Component Name>/<Config Type>/
165// will return an event channel for PUT,DELETE eventType.
166// Then values from event channel will be processed and stored in kvStoreEventChan.
167func (c *ComponentConfig) MonitorForConfigChange(ctx context.Context) chan *ConfigChangeEvent {
168 key := c.makeConfigPath()
169
170 log.Debugw("monitoring-for-config-change", log.Fields{"key": key})
171
172 c.changeEventChan = make(chan *ConfigChangeEvent, 1)
173
174 c.kvStoreEventChan = c.cManager.backend.CreateWatch(ctx, key, true)
175
176 go c.processKVStoreWatchEvents()
177
178 return c.changeEventChan
179}
180
181// processKVStoreWatchEvents process event channel recieved from the backend for any ChangeType
182// It checks for the EventType is valid or not.For the valid EventTypes creates ConfigChangeEvent and send it on channel
183func (c *ComponentConfig) processKVStoreWatchEvents() {
184
185 ccKeyPrefix := c.makeConfigPath()
186
187 log.Debugw("processing-kvstore-event-change", log.Fields{"key-prefix": ccKeyPrefix})
188
189 ccPathPrefix := c.cManager.backend.PathPrefix + ccKeyPrefix + kvStorePathSeparator
190
191 for watchResp := range c.kvStoreEventChan {
192
193 if watchResp.EventType == kvstore.CONNECTIONDOWN || watchResp.EventType == kvstore.UNKNOWN {
194 log.Warnw("received-invalid-change-type-in-watch-channel-from-kvstore", log.Fields{"change-type": watchResp.EventType})
195 continue
196 }
197
198 // populating the configAttribute from the received Key
199 // For Example, Key received would be <Backend Prefix Path>/<Config Prefix>/<Component Name>/<Config Type>/default
200 // Storing default in configAttribute variable
201 ky := fmt.Sprintf("%s", watchResp.Key)
202
203 c.changeEventChan <- &ConfigChangeEvent{
204 ChangeType: ChangeEvent(watchResp.EventType),
205 ConfigAttribute: strings.TrimPrefix(ky, ccPathPrefix),
206 }
207 }
208}
209
210func (c *ComponentConfig) RetrieveAll(ctx context.Context) (map[string]string, error) {
211 key := c.makeConfigPath()
212
213 log.Debugw("retreiving-list", log.Fields{"key": key})
214
215 data, err := c.cManager.backend.List(ctx, key)
216 if err != nil {
217 return nil, err
218 }
219
220 // Looping through the data recieved from the backend for the given key
221 // Trimming the required key and value from data and storing as key/value pair
222 // For Example, recieved key would be <Backend Prefix Path>/<Config Prefix>/<Component Name>/<Config Type>/default and value \"DEBUG\"
223 // Then in default will be stored as key and DEBUG will be stored as value in map[string]string
224 res := make(map[string]string)
225 ccPathPrefix := c.cManager.backend.PathPrefix + kvStorePathSeparator + key + kvStorePathSeparator
226 for attr, val := range data {
227 res[strings.TrimPrefix(attr, ccPathPrefix)] = strings.Trim(fmt.Sprintf("%s", val.Value), "\"")
228 }
229
230 return res, nil
231}
232
233func (c *ComponentConfig) Save(ctx context.Context, configKey string, configValue string) error {
234 key := c.makeConfigPath() + "/" + configKey
235
236 log.Debugw("saving-key", log.Fields{"key": key, "value": configValue})
237
238 //save the data for update config
239 if err := c.cManager.backend.Put(ctx, key, configValue); err != nil {
240 return err
241 }
242 return nil
243}
244
245func (c *ComponentConfig) Delete(ctx context.Context, configKey string) error {
246 //construct key using makeConfigPath
247 key := c.makeConfigPath() + "/" + configKey
248
249 log.Debugw("deleting-key", log.Fields{"key": key})
250 //delete the config
251 if err := c.cManager.backend.Delete(ctx, key); err != nil {
252 return err
253 }
254 return nil
255}