2023-11-05 20:23:31 +01:00
|
|
|
package config
|
|
|
|
|
2024-01-13 23:26:04 +01:00
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"slices"
|
2024-01-14 01:02:30 +01:00
|
|
|
|
|
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
|
2024-01-13 23:26:04 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
envConfigPath = "CONFIG_PATH"
|
|
|
|
)
|
|
|
|
|
|
|
|
// getConfigPath gets the spaceapid configuration from the respective environment variables
|
|
|
|
func getConfigPath() string {
|
|
|
|
// JSON template path
|
|
|
|
configPath, ok := os.LookupEnv(envConfigPath)
|
|
|
|
if !ok || configPath == "" {
|
|
|
|
log.Fatalln("Could not retrieve", envConfigPath, "env variable or variable is empty")
|
|
|
|
}
|
|
|
|
// Save as absolute path
|
|
|
|
absConfigPath, err := filepath.Abs(configPath)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln("Failed converting", configPath, "to absolute path:", err)
|
|
|
|
}
|
|
|
|
return absConfigPath
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParseConfiguration returns the config from file
|
|
|
|
func ParseConfiguration() (conf SpaceapidConfig) {
|
|
|
|
log.Println("Parsing configuration file")
|
|
|
|
// Read file
|
|
|
|
file, err := os.ReadFile(getConfigPath())
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln("Failed reading file:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse JSON
|
|
|
|
dec := json.NewDecoder(bytes.NewReader(file))
|
|
|
|
dec.DisallowUnknownFields()
|
|
|
|
err = dec.Decode(&conf)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln("Could not parse spaceapid config file:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if compatible with v14
|
|
|
|
if !slices.Contains(conf.Response.APICompatibility, "14") {
|
|
|
|
log.Fatalln("Provided file doesn't specify compatibility with API version 14")
|
|
|
|
}
|
|
|
|
|
2024-01-14 01:02:30 +01:00
|
|
|
// Initialise fields for environment sensors
|
|
|
|
conf.Response.Sensors = make(map[string][]types.EnvironmentSensor)
|
|
|
|
for key, sensorConfigs := range conf.Dynamic.Sensors {
|
|
|
|
conf.Response.Sensors[key] = make([]types.EnvironmentSensor, len(sensorConfigs))
|
|
|
|
for i, sensorConfig := range sensorConfigs {
|
|
|
|
conf.Response.Sensors[key][i] = sensorConfig.SensorData
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-13 23:26:04 +01:00
|
|
|
return
|
2023-11-05 20:23:31 +01:00
|
|
|
}
|