Skip to content

Commit

Permalink
feat: auto-update databases and auto-reload configuration (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
danroc authored Nov 14, 2024
1 parent 42ec875 commit 9b06cad
Showing 1 changed file with 59 additions and 1 deletion.
60 changes: 59 additions & 1 deletion cmd/geoblock/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main

import (
"os"
"time"

log "github.com/sirupsen/logrus"

Expand All @@ -12,6 +13,11 @@ import (
"github.com/danroc/geoblock/pkg/server"
)

const (
autoUpdateInterval = 24 * time.Hour
autoReloadInterval = 5 * time.Second
)

func getEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
Expand All @@ -31,6 +37,55 @@ func getOptions() *appOptions {
}
}

// autoUpdate updates the databases at regular intervals.
func autoUpdate(resolver *database.Resolver) {
for range time.Tick(autoUpdateInterval) {
if err := resolver.Update(); err != nil {
log.Errorf("Cannot update databases: %v", err)
continue
}
log.Info("Databases updated")
}
}

// hasChanged returns true if the two file infos are different. It only checks
// the size and the modification time.
func hasChanged(a, b os.FileInfo) bool {
return a.Size() != b.Size() || a.ModTime() != b.ModTime()
}

// autoReload watches the configuration file for changes and updates the engine
// when it happens.
func autoReload(engine *rules.Engine, config string) {
prevStat, err := os.Stat(config)
if err != nil {
log.Errorf("Cannot watch configuration file: %v", err)
return
}

for range time.Tick(autoReloadInterval) {
stat, err := os.Stat(config)
if err != nil {
log.Errorf("Cannot watch configuration file: %v", err)
continue
}

if !hasChanged(prevStat, stat) {
continue
}
prevStat = stat

config, err := schema.ReadFile(config)
if err != nil {
log.Errorf("Cannot read configuration file: %v", err)
continue
}

engine.UpdateConfig(&config.AccessControl)
log.Info("Configuration reloaded")
}
}

func main() {
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
Expand All @@ -41,7 +96,7 @@ func main() {
log.Info("Loading configuration file")
config, err := schema.ReadFile(options.configPath)
if err != nil {
log.Fatalf("Failed to read configuration file: %v", err)
log.Fatalf("Cannot read configuration file: %v", err)
}

log.Info("Initializing database resolver")
Expand All @@ -56,6 +111,9 @@ func main() {
server = server.NewServer(address, engine, resolver)
)

go autoUpdate(resolver)
go autoReload(engine, options.configPath)

log.Infof("Starting server at %s", server.Addr)
log.Fatal(server.ListenAndServe())
}

0 comments on commit 9b06cad

Please sign in to comment.