-
Notifications
You must be signed in to change notification settings - Fork 6
/
config.go
96 lines (89 loc) · 2.29 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
package main
import (
"fmt"
"io/ioutil"
"log"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type UserInfo struct {
Name string
Key string
ID string
Prefix []string
}
func readconfig() {
viper.SetConfigName("nomadctld")
viper.AddConfigPath("/etc/nomadctld")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Println("Config file changed:", e.Name)
})
}
func checkKey(key string, user string) *UserInfo {
ui := &UserInfo{}
key = strings.TrimSpace(key)
prefixes := []string{}
uprefixes := []string{}
for userID, cfg := range viper.GetStringMap("users") {
ccfg := cfg.(map[string]interface{})
ukey := ccfg["key"].(string)
if ukey == key && userID == user {
ui.ID = userID
ui.Key = key
ui.Name = ccfg["name"].(string)
for _, ia := range ccfg["prefix"].([]interface{}) {
uprefixes = append(uprefixes, ia.(string))
}
}
}
if len(uprefixes) == 0 {
return ui
}
for _, uprefix := range uprefixes {
for prefix, cfg := range viper.GetStringMap("prefix") {
if prefix == uprefix {
// fmt.Printf("uprefix prefix cfg %#v %#v %#v", uprefix, prefix, cfg)
found := cfg.(map[string]interface{})["prefix"].([]interface{})
for _, s := range found {
prefixes = append(prefixes, s.(string))
}
}
}
}
ui.Prefix = prefixes
return ui
}
func getNomadConfig() map[string]*NomadConfig {
res := make(map[string]*NomadConfig)
for id, cfg := range viper.GetStringMap("nomad") {
nc := &NomadConfig{Name: id}
res[id] = nc
nc.URL = cfg.(map[string]interface{})["url"].(string)
nc.Token = getToken(cfg.(map[string]interface{})["token"].(string))
if prefixes, ok := cfg.(map[string]interface{})["prefix"].([]interface{}); ok {
for _, prefix := range prefixes {
nc.Prefix = append(nc.Prefix, prefix.(string))
}
}
if aliases, ok := cfg.(map[string]interface{})["alias"].([]interface{}); ok {
for _, alias := range aliases {
nc.Alias = append(nc.Alias, alias.(string))
}
}
}
return res
}
func getToken(file string) string {
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatalf("no token found: %v", err)
}
return strings.TrimSuffix(string(data), "\n")
}