/
manager.go
77 lines (67 loc) · 1.98 KB
/
manager.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
package config
import (
"sync"
"time"
"github.com/alexadastra/ramme/config"
"github.com/pkg/errors"
)
// InitAdvancedConfig inits config
func InitAdvancedConfig() (*MutexConfigManager, *config.FileWatcher, error) {
configData, err := config.LoadFileData(config.File)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to load file")
}
unmarshalledConfig, err := UnmarshalConfig(configData)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to unmarshal unmarshalledConfig")
}
confManager := NewMutexConfigManager(&unmarshalledConfig.Advanced)
// Watch the file for modification and update the unmarshalledConfig manager with the new unmarshalledConfig when it's available
watcher, err := config.WatchFile(config.File, time.Second, func() error {
var configData []byte
configData, err = config.LoadFileData(config.File)
if err != nil {
return errors.Wrap(err, "failed to load file")
}
err = confManager.Set(configData)
if err != nil {
return errors.Wrap(err, "failed to reset unmarshalledConfig")
}
return nil
})
if err != nil {
return nil, nil, err
}
return confManager, watcher, nil
}
// MutexConfigManager manages the configuration instance by preforming locking around access to the Config struct.
type MutexConfigManager struct {
conf *AdvancedConfig
mutex *sync.Mutex
}
// NewMutexConfigManager constructs new MutexConfigManager
func NewMutexConfigManager(conf *AdvancedConfig) *MutexConfigManager {
return &MutexConfigManager{conf, &sync.Mutex{}}
}
// Set sets new config
func (m *MutexConfigManager) Set(confBytes []byte) error {
conf, err := UnmarshalConfig(confBytes)
if err != nil {
return errors.Wrap(err, "failed to unmarshal config")
}
m.mutex.Lock()
m.conf = &conf.Advanced
m.mutex.Unlock()
return nil
}
// Get returns current config
func (m *MutexConfigManager) Get() *AdvancedConfig {
m.mutex.Lock()
temp := m.conf
m.mutex.Unlock()
return temp
}
// Close shuts manager down
func (m *MutexConfigManager) Close() {
//Do Nothing
}