blob: c63e32c21db3ea9ce2f346435e1e83a1c98fce58 [file] [log] [blame]
Mohamed Abukar2e78e422019-06-02 11:45:52 +03001/*
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
20package xapp
21
22import (
23 "flag"
24 "github.com/fsnotify/fsnotify"
25 "github.com/spf13/viper"
26 "os"
27)
28
29type Configurator struct {
30}
31
32type ConfigChangeCB func(filename string)
33
34var ConfigChangeListeners []ConfigChangeCB
35
36func parseCmd() string {
37 var fileName *string
38 fileName = flag.String("f", os.Getenv("CFG_FILE"), "Specify the configuration file.")
39 flag.Parse()
40
41 return *fileName
42}
43
44func LoadConfig() (l Log) {
45 l = Log{}
46 viper.SetConfigFile(parseCmd())
47
48 if err := viper.ReadInConfig(); err != nil {
49 l.Error("Reading config file failed: %v", err.Error())
50 }
51 l.Info("Using config file: %s", viper.ConfigFileUsed())
52
53 viper.WatchConfig()
54 viper.OnConfigChange(func(e fsnotify.Event) {
55 l.Info("config file %s changed ", e.Name)
56
57 Logger.SetLevel(viper.GetInt("logger.level"))
58 if len(ConfigChangeListeners) > 0 {
59 for _, f := range ConfigChangeListeners {
60 go f(e.Name)
61 }
62 }
63 })
64
65 return
66}
67
68func AddConfigChangeListener(f ConfigChangeCB) {
69 if ConfigChangeListeners == nil {
70 ConfigChangeListeners = make([]ConfigChangeCB, 0)
71 }
72 ConfigChangeListeners = append(ConfigChangeListeners, f)
73}
74
75func (*Configurator) GetString(key string) string {
76 return viper.GetString(key)
77}
78
79func (*Configurator) GetInt(key string) int {
80 return viper.GetInt(key)
81}