98 lines
2.6 KiB
Go
98 lines
2.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"git.solsynth.dev/goatworks/turbine/pkg/shared/hash"
|
|
"git.solsynth.dev/goatworks/turbine/pkg/shared/registrar"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/rs/zerolog"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
func init() {
|
|
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
|
}
|
|
|
|
func main() {
|
|
log.Info().Msg("Starting Turbine Ring...")
|
|
viper.SetConfigName("settings")
|
|
viper.AddConfigPath(".")
|
|
viper.AddConfigPath("/etc/turbine/")
|
|
viper.SetConfigType("toml")
|
|
|
|
log.Info().Msg("Reading configuration...")
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
log.Fatal().Err(err).Msg("Failed to read config file...")
|
|
}
|
|
log.Info().Msg("Configuration loaded.")
|
|
// --- Service Registration ---
|
|
etcdEndpoints := viper.GetStringSlice("etcd.endpoints")
|
|
if len(etcdEndpoints) == 0 {
|
|
log.Fatal().Msg("etcd.endpoints not configured")
|
|
}
|
|
|
|
if viper.GetBool("etcd.insecure") {
|
|
for i, ep := range etcdEndpoints {
|
|
if !strings.HasPrefix(ep, "http://") && !strings.HasPrefix(ep, "https://") {
|
|
etcdEndpoints[i] = "http://" + ep
|
|
}
|
|
}
|
|
}
|
|
|
|
serviceReg, err := registrar.NewServiceRegistrar(etcdEndpoints)
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msg("Failed to create service registrar")
|
|
}
|
|
|
|
listenAddr := viper.GetString("listen")
|
|
host := viper.GetString("host")
|
|
if host == "" {
|
|
log.Fatal().Msg("host not configured")
|
|
}
|
|
portStr := strings.TrimPrefix(listenAddr, ":")
|
|
port, err := strconv.Atoi(portStr)
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msg("Invalid listen address")
|
|
}
|
|
|
|
serviceName := "config"
|
|
instanceID := fmt.Sprint(hash.Hash(fmt.Sprintf("%s-%s-%d", serviceName, host, port)))[:8]
|
|
|
|
err = serviceReg.Register(serviceName, "http", instanceID, host, port, 30)
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msg("Failed to register service")
|
|
}
|
|
log.Info().Str("service", serviceName).Str("instanceID", instanceID).Msg("Service registered successfully")
|
|
|
|
// --- Web Server ---
|
|
app := fiber.New(fiber.Config{
|
|
ServerHeader: "Turbine Ring",
|
|
})
|
|
|
|
// This is the main endpoint that serves the configuration as JSON.
|
|
app.Get("/", func(c fiber.Ctx) error {
|
|
log.Info().Msg("Serving shared configuration as JSON")
|
|
|
|
// Use a new Viper instance to read the shared config
|
|
v := viper.New()
|
|
v.SetConfigName("shared_config")
|
|
v.AddConfigPath(".") // Look in the current directory (pkg/config)
|
|
v.SetConfigType("toml")
|
|
|
|
if err := v.ReadInConfig(); err != nil {
|
|
log.Error().Err(err).Msg("Failed to read shared_config.toml")
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
|
"error": "could not load configuration",
|
|
})
|
|
}
|
|
|
|
return c.JSON(v.AllSettings())
|
|
})
|
|
}
|