Prepare for SdlInstance usage removal in xapp-frame
[ric-plt/xapp-frame.git] / pkg / xapp / config.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package xapp
21
22 import (
23         "flag"
24         "fmt"
25         "github.com/fsnotify/fsnotify"
26         "github.com/spf13/viper"
27         "os"
28         "path/filepath"
29 )
30
31 //-----------------------------------------------------------------------------
32 //
33 //-----------------------------------------------------------------------------
34
35 type mtype struct {
36         Name string
37         Id   int
38 }
39
40 type Configurator struct {
41 }
42
43 type ConfigChangeCB func(filename string)
44
45 type SDLNotificationCB func(string, ...string)
46
47 var ConfigChangeListeners []ConfigChangeCB
48
49 func parseCmd() string {
50         var fileName *string
51         fileName = flag.String("f", os.Getenv("CFG_FILE"), "Specify the configuration file.")
52         flag.Parse()
53
54         return *fileName
55 }
56
57 func LoadConfig() (l *Log) {
58         l = NewLogger(filepath.Base(os.Args[0]))
59         viper.SetConfigFile(parseCmd())
60
61         if err := viper.ReadInConfig(); err != nil {
62                 l.Error("Reading config file failed: %v", err.Error())
63         }
64         l.Info("Using config file: %s", viper.ConfigFileUsed())
65
66         updateMTypes := func() {
67                 var mtypes []mtype
68                 viper.UnmarshalKey("messaging.mtypes", &mtypes)
69
70                 if len(mtypes) > 0 {
71                         l.Info("Config mtypes before RICMessageTypes:%d RicMessageTypeToName:%d", len(RICMessageTypes), len(RicMessageTypeToName))
72                         for _, v := range mtypes {
73                                 nadd := false
74                                 iadd := false
75                                 if _, ok := RICMessageTypes[v.Name]; ok == false {
76                                         nadd = true
77                                 }
78                                 if _, ok := RicMessageTypeToName[int(v.Id)]; ok == false {
79                                         iadd = true
80                                 }
81                                 if iadd != nadd {
82                                         l.Error("Config mtypes rmr.mtypes entry skipped due conflict with existing values %s(%t) %d(%t) ", v.Name, nadd, v.Id, iadd)
83                                 } else if iadd {
84                                         l.Info("Config mtypes rmr.mtypes entry added %s(%t) %d(%t) ", v.Name, nadd, v.Id, iadd)
85                                         RICMessageTypes[v.Name] = int(v.Id)
86                                         RicMessageTypeToName[int(v.Id)] = v.Name
87                                 } else {
88                                         l.Info("Config mtypes rmr.mtypes entry skipped %s(%t) %d(%t) ", v.Name, nadd, v.Id, iadd)
89                                 }
90                         }
91                         l.Info("Config mtypes after RICMessageTypes:%d RicMessageTypeToName:%d", len(RICMessageTypes), len(RicMessageTypeToName))
92                 }
93         }
94
95         updateMTypes()
96
97         viper.WatchConfig()
98         viper.OnConfigChange(func(e fsnotify.Event) {
99                 l.Info("config file %s changed ", e.Name)
100
101                 updateMTypes()
102                 if viper.IsSet("controls.logger.level") {
103                         Logger.SetLevel(viper.GetInt("controls.logger.level"))
104                 } else {
105                         Logger.SetLevel(viper.GetInt("logger.level"))
106                 }
107
108                 if len(ConfigChangeListeners) > 0 {
109                         for _, f := range ConfigChangeListeners {
110                                 go f(e.Name)
111                         }
112                 }
113         })
114
115         return
116 }
117
118 func AddConfigChangeListener(f ConfigChangeCB) {
119         if ConfigChangeListeners == nil {
120                 ConfigChangeListeners = make([]ConfigChangeCB, 0)
121         }
122         ConfigChangeListeners = append(ConfigChangeListeners, f)
123 }
124
125 func PublishConfigChange(appName, eventJson string) error {
126         channel := fmt.Sprintf("CM_UPDATE:%s", appName)
127         if err := SdlStorage.StoreAndPublish(getCmSdlNs(), channel, eventJson, appName, eventJson); err != nil {
128                 Logger.Error("Sdl.Store failed: %v", err)
129                 return err
130         }
131         return nil
132 }
133
134 func ReadConfig(appName string) (map[string]interface{}, error) {
135         return SdlStorage.Read(getCmSdlNs(), appName)
136 }
137
138 func GetPortData(pname string) (d PortData) {
139         var getPolicies = func(policies []interface{}) (plist []int) {
140                 for _, p := range policies {
141                         plist = append(plist, int(p.(float64)))
142                 }
143                 return plist
144         }
145
146         if viper.IsSet("messaging") == false {
147                 if pname == "http" {
148                         d.Port = 8080
149                 }
150                 if pname == "rmrdata" {
151                         d.Port = 4560
152                 }
153                 return
154         }
155
156         for _, v := range viper.GetStringMap("messaging")["ports"].([]interface{}) {
157                 if n, ok := v.(map[string]interface{})["name"].(string); ok && n == pname {
158                         d.Name = n
159                         if p, _ := v.(map[string]interface{})["port"].(float64); ok {
160                                 d.Port = int(p)
161                         }
162                         if m, _ := v.(map[string]interface{})["maxSize"].(float64); ok {
163                                 d.MaxSize = int(m)
164                         }
165                         if m, _ := v.(map[string]interface{})["threadType"].(float64); ok {
166                                 d.ThreadType = int(m)
167                         }
168                         if m, _ := v.(map[string]interface{})["lowLatency"].(bool); ok {
169                                 d.LowLatency = bool(m)
170                         }
171                         if m, _ := v.(map[string]interface{})["fastAck"].(bool); ok {
172                                 d.FastAck = bool(m)
173                         }
174                         if m, _ := v.(map[string]interface{})["maxRetryOnFailure"].(float64); ok {
175                                 d.MaxRetryOnFailure = int(m)
176                         }
177                         if policies, ok := v.(map[string]interface{})["policies"]; ok {
178                                 d.Policies = getPolicies(policies.([]interface{}))
179                         }
180                 }
181         }
182         return
183 }
184
185 func getCmSdlNs() string {
186         return fmt.Sprintf("cm/%s", viper.GetString("name"))
187 }
188
189 func (*Configurator) SetSDLNotificationCB(appName string, sdlNotificationCb SDLNotificationCB) error {
190         return SdlStorage.Subscribe(getCmSdlNs(), sdlNotificationCb, fmt.Sprintf("CM_UPDATE:%s", appName))
191 }
192
193 func (*Configurator) GetString(key string) string {
194         return viper.GetString(key)
195 }
196
197 func (*Configurator) GetInt(key string) int {
198         return viper.GetInt(key)
199 }
200
201 func (*Configurator) GetUint32(key string) uint32 {
202         return viper.GetUint32(key)
203 }
204
205 func (*Configurator) GetBool(key string) bool {
206         return viper.GetBool(key)
207 }
208
209 func (*Configurator) Get(key string) interface{} {
210         return viper.Get(key)
211 }
212
213 func (*Configurator) GetStringSlice(key string) []string {
214         return viper.GetStringSlice(key)
215 }
216
217 func (*Configurator) GetStringMap(key string) map[string]interface{} {
218         return viper.GetStringMap(key)
219 }
220
221 func (*Configurator) IsSet(key string) bool {
222         return viper.IsSet(key)
223 }