|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "io/ioutil" |
| 6 | + "os" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +type Configuration struct { |
| 12 | + stopRunning chan bool |
| 13 | +} |
| 14 | + |
| 15 | +var confFilePath string |
| 16 | +var confFile *os.File |
| 17 | +var running = make(chan bool) |
| 18 | +var confFileModdTime time.Time |
| 19 | +var confFileSize int64 |
| 20 | + |
| 21 | +type ConfObject struct { |
| 22 | + Configurations Collector |
| 23 | +} |
| 24 | + |
| 25 | +type Collector struct { |
| 26 | + IP string `json:"collector.ip"` |
| 27 | + Udpport string `json:"collector.udp.port"` |
| 28 | + Tcpport string `json:"collector.tcp.port"` |
| 29 | + Instances []DBInstance `json:"db.instances"` |
| 30 | +} |
| 31 | + |
| 32 | +type DBInstance struct { |
| 33 | + IP string `json:"db.ip"` |
| 34 | + Port string `json:"db.port"` |
| 35 | + User string `json:"db.user"` |
| 36 | + Password string `json:"db.password"` |
| 37 | + Slowquery string `json:"db.slowquery"` |
| 38 | +} |
| 39 | + |
| 40 | +func (conf *Configuration) load() { |
| 41 | + var confobj ConfObject |
| 42 | + fileInfo, e := confFile.Stat() |
| 43 | + if e != nil { |
| 44 | + //todo: error handling |
| 45 | + } |
| 46 | + |
| 47 | + if confFileModdTime != fileInfo.ModTime() || confFileSize != fileInfo.Size() { |
| 48 | + file, err := ioutil.ReadFile(confFilePath) |
| 49 | + if err != nil { |
| 50 | + //todo : |
| 51 | + } |
| 52 | + json.Unmarshal(file, &confobj) |
| 53 | + confFileSize = fileInfo.Size() |
| 54 | + confFileModdTime = fileInfo.ModTime() |
| 55 | + } |
| 56 | + |
| 57 | +} |
| 58 | + |
| 59 | +func (conf *Configuration) init() bool { |
| 60 | + f, err := os.Open(confFilePath) |
| 61 | + if err != nil { |
| 62 | + return false |
| 63 | + } else { |
| 64 | + confFile = f |
| 65 | + } |
| 66 | + return true |
| 67 | +} |
| 68 | + |
| 69 | +func (conf *Configuration) Start() { |
| 70 | + go conf.run() |
| 71 | +} |
| 72 | + |
| 73 | +func (conf *Configuration) Stop() { |
| 74 | + conf.stopRunning <- true |
| 75 | +} |
| 76 | + |
| 77 | +func (conf *Configuration) run() { |
| 78 | + for { |
| 79 | + conf.load() |
| 80 | + time.Sleep(1 * time.Second) |
| 81 | + select { |
| 82 | + case <-conf.stopRunning: |
| 83 | + break |
| 84 | + default: |
| 85 | + continue |
| 86 | + } |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +var configure *Configuration |
| 91 | +var once sync.Once |
| 92 | + |
| 93 | +// GetInstance returns configuraton singleton instance |
| 94 | +func GetInstance() *Configuration { |
| 95 | + once.Do(func() { |
| 96 | + configure = &Configuration{} |
| 97 | + if configure.init() { |
| 98 | + configure.Start() |
| 99 | + } |
| 100 | + }) |
| 101 | + return configure |
| 102 | +} |
0 commit comments