Skip to content

Commit

Permalink
add an ability to use configuration directory with multiple yml files p…
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaly-m committed Jun 21, 2017
1 parent aa8c078 commit 09e7bff
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
19 changes: 19 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,25 @@ func LoadFile(filename string) (*Config, error) {
return cfg, nil
}

func LoadFiles(dirname string) (*Config, error) {
fileInfos, err := ioutil.ReadDir(dirname)
if err != nil {
return nil, err
}
cfg := &Config{}
for _, fileInfo := range fileInfos {
content, err := ioutil.ReadFile(dirname + "/" + fileInfo.Name())
if err != nil {
return nil, err
}
err = yaml.Unmarshal(content, cfg)
if err != nil {
return nil, err
}
}
return cfg, nil
}

var (
DefaultModule = Module{
Version: 2,
Expand Down
28 changes: 23 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ var (
"config.file", "snmp.yml",
"Path to configuration file.",
)
configDirectory = flag.String(
"config.directory", "",
"Path to directory with configuration files. It will be preferred if specified.",
)
listenAddress = flag.String(
"web.listen-address", ":9116",
"Address to listen on for web interface and telemetry.",
Expand Down Expand Up @@ -50,14 +54,20 @@ func init() {
}

func handler(w http.ResponseWriter, r *http.Request) {
cfg, err := config.LoadFile(*configFile)
var cfg *config.Config
var err error
// Prefer config directory in case it is specified
if *configDirectory != "" {
cfg, err = config.LoadFiles(*configDirectory)
} else {
cfg, err = config.LoadFile(*configFile)
}
if err != nil {
msg := fmt.Sprintf("Error parsing config file: %s", err)
http.Error(w, msg, 400)
log.Errorf(msg)
return
}

target := r.URL.Query().Get("target")
if target == "" {
http.Error(w, "'target' parameter must be specified", 400)
Expand Down Expand Up @@ -100,12 +110,20 @@ func main() {
log.Infoln("Build context", version.BuildContext())

// Bail early if the config is bad.
c, err := config.LoadFile(*configFile)
var cfg *config.Config
var err error
if *configDirectory != "" {
log.Infoln("Read configurations from", *configDirectory)
cfg, err = config.LoadFiles(*configDirectory)
} else {
log.Infoln("Read configuration from", *configFile)
cfg, err = config.LoadFile(*configFile)
}
if err != nil {
log.Fatalf("Error parsing config file: %s", err)
log.Fatalf("Error parsing configuration: %s", err)
}
// Initilise metrics.
for module, _ := range *c {
for module, _ := range *cfg {
snmpDuration.WithLabelValues(module)
}

Expand Down

0 comments on commit 09e7bff

Please sign in to comment.