-
Notifications
You must be signed in to change notification settings - Fork 0
/
configFile.go
97 lines (83 loc) · 2.13 KB
/
configFile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/yaml.v2"
"os"
"sync"
"time"
)
type ConfigFile struct {
FilePath string
FileModified time.Time
Config *Config
Mutex sync.Mutex
OnReload func()
}
func (configFile *ConfigFile) Save() error {
configFile.Mutex.Lock()
defer configFile.Mutex.Unlock()
f, err := os.OpenFile(configFile.FilePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) //TODO: get perm from struct
if err != nil {
ErrorLog.Println(configFile.FilePath, err.Error())
return err
}
encoder := yaml.NewEncoder(f)
if err := encoder.Encode(configFile.Config); err != nil {
ErrorLog.Println(configFile.Config, err.Error())
f.Close()
return err
}
f.Close()
configFile.FileModified = time.Now()
return nil
}
func (configFile *ConfigFile) Reload() error {
configFile.Mutex.Lock()
defer configFile.Mutex.Unlock()
f, err := os.Open(configFile.FilePath)
if err != nil {
ErrorLog.Println(configFile.FilePath, err.Error())
return err
}
defer f.Close()
config := Config{}
decoder := yaml.NewDecoder(f)
if err := decoder.Decode(&config); err != nil {
ErrorLog.Println(configFile.FilePath, err.Error())
return err
}
configFile.Config = &config
configFile.FileModified = configFile.GetFileMTime()
if configFile.OnReload != nil {
configFile.OnReload()
}
return nil
}
func (configFile *ConfigFile) GetFileMTime() time.Time {
fileInfo, err := os.Stat(configFile.FilePath)
if err != nil {
return time.Time{}
}
return fileInfo.ModTime()
}
func (configFile *ConfigFile) ReloadRoutine() {
for {
time.Sleep(30 * time.Second)
if configFile.GetFileMTime().After(configFile.FileModified) {
DebugLog.Printf("%s updated. Reloading config file...\n", configFile.FilePath)
if err := configFile.Reload(); err != nil {
PrometheusErrors.With(prometheus.Labels{`action`: `config_reload`, `get`: ``, `repost`: ``}).Inc()
}
}
}
}
func NewConfigFile(filePath string) (*ConfigFile, error) {
configFile := ConfigFile{
FilePath: filePath,
}
if err := configFile.Reload(); err != nil {
return nil, err
}
go configFile.ReloadRoutine()
return &configFile, nil
}