-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
113 lines (99 loc) · 2.68 KB
/
config.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package config
import (
"encoding/gob"
"encoding/json"
"errors"
"io/ioutil"
"os"
)
const (
DEFAULT_STATS_PORT = ":9090"
)
var (
DEFAULT_LUA_PATH = os.Getenv("GOPATH") + "/src/github.com/barracudanetworks/GoWorker/lua"
WRONG_CONFIG_TYPE = errors.New("config: wrong config type")
LUA_PATH = DEFAULT_LUA_PATH
)
func init() {
gob.Register(AppConfig{})
gob.Register(Config{})
}
// Configer has the ability to return a config struct and a method to apply that configuartion
type Configer interface {
ConfigStruct() interface{}
Init(i interface{}) error
}
type ConfigBlock []map[string]json.RawMessage
type ConfigPair struct {
Type string
Config Config
}
// AppConfig contains all of the information needed to configure the app
type AppConfig struct {
ProviderConfigs []ConfigPair
WorkerConfigs []ConfigPair
FailureHanldlerConfigs []ConfigPair
ManagerToManager string `json:"manager_to_manager_port"`
StatsPort string `json:"stats_port"`
LuaPath string `json:"lua_path"`
RawProviders ConfigBlock `json:"providers"`
RawWorkers ConfigBlock `json:"workers"`
RawFailureHandler ConfigBlock `json:"failure_handler"`
}
// defaultAppConfig returns a app config with defaults params
func DefaultAppConfig() *AppConfig {
return &AppConfig{
ProviderConfigs: []ConfigPair{},
WorkerConfigs: []ConfigPair{},
LuaPath: DEFAULT_LUA_PATH,
StatsPort: DEFAULT_STATS_PORT,
}
}
// LoadAppConfigFromFile loads configuration needed for the initilization of the manager
func LoadAppConfigFromFile(fileName string) (*AppConfig, error) {
b, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
a := DefaultAppConfig()
err = json.Unmarshal(b, a)
// cast the raw configs
a.ProviderConfigs = castConfigs(a.RawProviders)
a.WorkerConfigs = castConfigs(a.RawWorkers)
a.FailureHanldlerConfigs = castConfigs(a.RawFailureHandler)
LUA_PATH = a.LuaPath
return a, err
}
// Holds generic config information
type Config json.RawMessage
// Apply decode the config into the given interface and call it's init function
func (c Config) Apply(conf Configer) error {
i := conf.ConfigStruct()
err := json.Unmarshal([]byte(c), i)
if err != nil {
return err
}
return conf.Init(i)
}
// Encode endcode the given interface onto a Config struct
func (c Config) Encode(i interface{}) error {
b, err := json.Marshal(i)
if err != nil {
return err
}
c = Config(b)
return nil
}
func castConfigs(c ConfigBlock) []ConfigPair {
n := make([]ConfigPair, len(c))
for i := range n {
for k, v := range c[i] {
n[i] = ConfigPair{
Type: k,
Config: Config(v),
}
break
}
}
return n
}