-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathsdns.go
More file actions
207 lines (166 loc) · 4.46 KB
/
sdns.go
File metadata and controls
207 lines (166 loc) · 4.46 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package main
//go:generate go run gen.go
import (
"context"
"fmt"
"os"
"os/signal"
"runtime/debug"
"syscall"
"time"
"github.com/semihalev/sdns/api"
"github.com/semihalev/sdns/config"
"github.com/semihalev/sdns/middleware"
"github.com/semihalev/sdns/server"
"github.com/semihalev/zlog/v2"
"github.com/spf13/cobra"
)
const version = "1.6.1"
var (
cfgPath string
testConfig bool
cfg *config.Config
rootCmd = &cobra.Command{
Use: "sdns",
Short: "A high-performance DNS resolver with DNSSEC support",
Long: `SDNS is a high-performance, recursive DNS resolver server with DNSSEC support,
focused on preserving privacy. For more information, visit https://sdns.dev`,
RunE: runServer,
}
versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version information",
Run: printVersion,
}
)
func init() {
rootCmd.PersistentFlags().StringVarP(&cfgPath, "config", "c", "sdns.conf", "Location of the config file. If it doesn't exist, a new one will be generated.")
rootCmd.PersistentFlags().BoolVarP(&testConfig, "test", "t", false, "Test configuration file and exit. Returns exit code 0 if valid, 1 if invalid.")
rootCmd.AddCommand(versionCmd)
}
func setup() error {
var err error
if cfg, err = config.Load(cfgPath, version); err != nil {
return fmt.Errorf("config loading failed: %w", err)
}
if cfg.LogLevel == "" {
cfg.LogLevel = "info"
}
// Create structured logger with zero allocations
logger := zlog.NewStructured()
// Set log level based on config
var lvl zlog.Level
switch cfg.LogLevel {
case "debug":
lvl = zlog.LevelDebug
case "info":
lvl = zlog.LevelInfo
case "warn":
lvl = zlog.LevelWarn
case "error":
lvl = zlog.LevelError
default:
return fmt.Errorf("log verbosity level unknown: %s", cfg.LogLevel)
}
logger.SetLevel(lvl)
logger.SetWriter(zlog.StdoutTerminal())
// Set as default logger for global log calls
zlog.SetDefault(logger)
middleware.Setup(cfg)
return nil
}
func runServer(cmd *cobra.Command, args []string) error {
// Handle config test mode
if testConfig {
return validateConfiguration()
}
zlog.Info("Starting sdns...", "version", version)
if err := setup(); err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
srv := server.New(cfg)
srv.Run(ctx)
api := api.New(cfg)
api.Run(ctx)
// Set up SIGHUP handler for certificate reload
sigHup := make(chan os.Signal, 1)
signal.Notify(sigHup, syscall.SIGHUP)
defer signal.Stop(sigHup)
go func() {
for {
select {
case <-sigHup:
zlog.Info("Received SIGHUP, reloading TLS certificate")
if err := srv.ReloadCertificate(); err != nil {
zlog.Error("Failed to reload certificate", "error", err.Error())
}
case <-ctx.Done():
return
}
}
}()
<-ctx.Done()
zlog.Info("Stopping sdns...")
// Clean up server resources
srv.Stop()
// Graceful shutdown with timeout
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
shutdownDone := make(chan struct{})
go func() {
for !srv.Stopped() {
time.Sleep(100 * time.Millisecond)
}
close(shutdownDone)
}()
select {
case <-shutdownDone:
zlog.Info("Server stopped gracefully")
case <-shutdownCtx.Done():
zlog.Warn("Server shutdown timeout exceeded")
}
return nil
}
func validateConfiguration() error {
var err error
if cfg, err = config.Load(cfgPath, version); err != nil {
fmt.Fprintf(os.Stderr, "Configuration test failed: %v\n", err)
return err
}
// Validate log level
switch cfg.LogLevel {
case "", "debug", "info", "warn", "error":
// Valid log levels
default:
err := fmt.Errorf("log verbosity level unknown: %s", cfg.LogLevel)
fmt.Fprintf(os.Stderr, "Configuration test failed: %v\n", err)
return err
}
fmt.Printf("Configuration file %s test successful\n", cfgPath)
return nil
}
func printVersion(cmd *cobra.Command, args []string) {
buildInfo, _ := debug.ReadBuildInfo()
settings := make(map[string]string)
for _, s := range buildInfo.Settings {
settings[s.Key] = s.Value
}
revision := settings["vcs.revision"]
if len(revision) > 7 {
revision = revision[:7]
}
fmt.Printf("sdns v%s\n", version)
if revision != "" {
fmt.Printf("git revision: %s\n", revision)
}
fmt.Printf("go version: %s\n", buildInfo.GoVersion)
fmt.Printf("platform: %s/%s\n", settings["GOOS"], settings["GOARCH"])
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}