/
JSONConfig.go
74 lines (65 loc) · 2 KB
/
JSONConfig.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
package config
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"github.com/AbhiswasPatil/olscheduler/proxy"
)
// JSONConfig holds the data configured via a JSON file. This shall be used
// to parse the JSON file and create a proper Config struct that dictates the
// scheduler's behavior.
type JSONConfig struct {
Host string `json:"host"`
Port int `json:"port"`
Balancer string `json:"balancer"`
LoadThreshold int `json:"load-threshold"`
Registry string `json:"registry"`
Workers []string `json:"workers"`
}
type Handle struct {
Handle string `json:handle`
Pkgs []string `json:pkgs`
}
func (c JSONConfig) ToConfig() Config {
return Config{
Host: c.Host,
Port: c.Port,
Balancer: createBalancerFromConfig(c),
Registry: createRegistryFromFile(c.Registry),
ReverseProxy: proxy.NewHTTPReverseProxy(),
}
}
func LoadConfigFromFile(configFilepath string) JSONConfig {
var config JSONConfig
file, rfErr := ioutil.ReadFile(configFilepath)
if rfErr != nil {
log.Fatalf("Cannot read config file (%s)", configFilepath)
}
decoder := json.NewDecoder(bytes.NewReader(file))
jsonErr := decoder.Decode(&config) // Parse json config file
if jsonErr != nil {
log.Fatalf("Config file Ill-formed (%s)", configFilepath)
}
if len(config.Workers)%2 != 0 {
log.Fatalf("Config file Ill-formed (%s), every worker must have a weight", configFilepath)
}
return config
}
func createRegistryFromFile(registryFilePath string) map[string][]string {
var handles []Handle
file, rfErr := ioutil.ReadFile(registryFilePath)
if rfErr != nil {
log.Fatalf("Cannot read registry file (%s)", registryFilePath)
}
decoder := json.NewDecoder(bytes.NewReader(file))
jsonErr := decoder.Decode(&handles) // Parse json registry file
if jsonErr != nil {
log.Fatalf("Registry file Ill-formed (%s)", registryFilePath)
}
registry := make(map[string][]string)
for _, handle := range handles {
registry[handle.Handle] = handle.Pkgs
}
return registry
}