-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.go
109 lines (87 loc) · 2.4 KB
/
main.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
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/musix/backhaul/cmd"
"github.com/musix/backhaul/internal/utils"
)
var (
logger = utils.NewLogger("info")
)
// Define the version of the application
const version = "v0.6.3"
func getLastModTime(file string) (time.Time, error) {
absPath, _ := filepath.Abs(file)
fileInfo, err := os.Stat(absPath)
if err != nil {
return time.Time{}, err
}
return fileInfo.ModTime(), nil
}
func main() {
configPath := flag.String("c", "", "path to the configuration file (TOML format)")
showVersion := flag.Bool("v", false, "print the version and exit")
flag.Parse()
// If the version flag is provided, print the version and exit
if *showVersion {
fmt.Println(version)
os.Exit(0)
}
// Check if the configPath is provided
if *configPath == "" {
logger.Fatalf("Usage: %s -c /path/to/config.toml", flag.CommandLine.Name())
}
// Apply temporary TCP optimizations at startup
cmd.ApplyTCPTuning()
// Create a context for graceful shutdown handling
ctx, cancel := context.WithCancel(context.Background())
// Set up signal handling for graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go cmd.Run(*configPath, ctx)
// Get initial modification time of the config file
lastModTime, err := getLastModTime(*configPath)
if err != nil {
logger.Fatalf("Error getting modification time: %v", err)
}
// Polling for file changes
go func() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
modTime, err := getLastModTime(*configPath)
if err != nil {
logger.Errorf("Error checking file modification time: %v", err)
continue
}
// If the modification time has changed, reload the app
if modTime.After(lastModTime) {
logger.Info("Config file changed, reloading application")
// Cancel the previous context to stop the old running instance
cancel()
time.Sleep(2 * time.Second)
// Create a new context for the new instance
newCtx, newCancel := context.WithCancel(context.Background())
go cmd.Run(*configPath, newCtx)
// Update the last modification time and the context
lastModTime = modTime
ctx = newCtx
cancel = newCancel
}
}
}
}()
<-sigChan
cancel()
time.Sleep(1 * time.Second)
}