-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
271 lines (242 loc) · 8.83 KB
/
Copy pathmain.go
File metadata and controls
271 lines (242 loc) · 8.83 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package main
import (
"context"
"flag"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"dumpstore/internal/ansible"
"dumpstore/internal/api"
"dumpstore/internal/auth"
"dumpstore/internal/autosnap"
"dumpstore/internal/broker"
"dumpstore/internal/jobs"
"dumpstore/internal/logging"
otelx "dumpstore/internal/otel"
"dumpstore/internal/platform"
"dumpstore/internal/replication"
"dumpstore/internal/schema"
"dumpstore/internal/scheduler"
)
// version is overridden at build time via:
//
// go build -ldflags "-X main.version=v1.2.3"
var version = "dev"
func main() {
var (
addr = flag.String("addr", ":8080", "Listen address (used when --tls is not set)")
baseDir = flag.String("dir", "", "Base directory (contains playbooks/ and static/); defaults to executable location")
debug = flag.Bool("debug", false, "Enable debug log level")
showVersion = flag.Bool("version", false, "Print version and exit")
configPath = flag.String("config", platform.ConfigDir(runtime.GOOS)+"/dumpstore.conf", "Config file path")
setPassword = flag.Bool("set-password", false, "Set admin password and exit")
logStdout = flag.Bool("log-stdout", true, "Write logs to stdout (journald/logfile); disable when shipping logs via OTLP only")
tlsFlag = flag.Bool("tls", false, "Enable HTTPS (requires tls_cert_path and tls_key_path in config)")
tlsPort = flag.String("tls-port", "443", "HTTPS listen port")
httpPort = flag.String("http-port", "80", "HTTP listen port for redirect to HTTPS (used when --tls is set)")
)
flag.Parse()
if *showVersion {
fmt.Println(version)
os.Exit(0)
}
if *setPassword {
if err := auth.SetPassword(*configPath); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
os.Exit(0)
}
level := slog.LevelInfo
if *debug {
level = slog.LevelDebug
}
// Single-producer logging: slog feeds the OTEL log pipeline, whose journald
// exporter reproduces the classic format (syslog <N> priority prefixes under
// systemd, see internal/logging). When OTEL_EXPORTER_OTLP_* is set, the same
// records are additionally exported over OTLP, and trace/metric providers
// are installed (no-op otherwise). -log-stdout=false drops the local branch
// for OTLP-only setups.
var logOut io.Writer = os.Stdout
if !*logStdout {
if !otelx.Enabled() {
// Explicit choice is respected, but a server with no log sink at
// all is almost certainly a misconfiguration — say so while we
// still can.
fmt.Fprintln(os.Stderr, "warning: -log-stdout=false with no OTLP endpoint configured — all logs will be discarded")
}
logOut = nil
}
otelProviders, err := otelx.Init(context.Background(), version, logOut)
if err != nil {
slog.SetDefault(slog.New(logging.NewJournalHandler(os.Stdout, &slog.HandlerOptions{Level: level})))
slog.Error("otel init failed — continuing with journald-only logging", "err", err)
} else {
slog.SetDefault(slog.New(logging.NewAppHandler(otelProviders.Logs, level)))
defer otelProviders.Shutdown(context.Background()) //nolint:errcheck
}
if *baseDir == "" {
exe, err := os.Executable()
if err != nil {
slog.Error("cannot resolve executable path", "err", err)
os.Exit(1)
}
*baseDir = filepath.Dir(exe)
}
if err := checkDeps(*baseDir); err != nil {
slog.Error("dependency check failed", "err", err)
os.Exit(1)
}
if err := schema.WriteVarsFile(filepath.Join(*baseDir, "playbooks")); err != nil {
slog.Error("failed to write Ansible vars file", "err", err)
os.Exit(1)
}
cfg, err := auth.LoadConfig(*configPath)
if err != nil {
slog.Error("failed to load config", "err", err)
os.Exit(1)
}
if cfg.ACMEEnabled {
if _, err := exec.LookPath("lego"); err != nil {
slog.Warn("lego not found in PATH — ACME cert issuance/renewal will fail")
}
}
if cfg.PasswordHash == "" {
slog.Warn("no password configured — binding to loopback only; run with --set-password to configure authentication")
*addr = "127.0.0.1:8080"
}
store := auth.NewSessionStore(cfg.SessionTTL.Duration)
rl := auth.NewRateLimiter()
runner := ansible.NewRunner(*baseDir)
b := broker.New()
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
broker.StartPoller(ctx, b)
jobMgr, err := jobs.NewManager(platform.StateDir(runtime.GOOS), func(j jobs.Job) {
b.PublishNoCache("jobs.update", j)
})
if err != nil {
slog.Error("failed to initialise job manager", "err", err)
os.Exit(1)
}
sched := scheduler.New()
replStore, err := replication.NewStore(platform.StateDir(runtime.GOOS))
if err != nil {
slog.Error("failed to initialise replication store", "err", err)
os.Exit(1)
}
replRunner := replication.NewRunner(replStore, sched, jobMgr, b)
if err := replRunner.LoadAndRegisterAll(); err != nil {
slog.Error("failed to register replication tasks", "err", err)
os.Exit(1)
}
autosnapRunner := autosnap.New(sched, b)
// Only register tasks if the OS daemon isn't already managing snapshots.
// Takeover (POST /api/auto-snapshot/takeover) disables the daemon and
// calls Register at runtime; release reverses that.
if status := autosnap.DetectStatus(); !status.OSDaemonActive {
if err := autosnapRunner.Register(); err != nil {
slog.Error("failed to register autosnap tasks", "err", err)
} else {
slog.Info("autosnap: scheduler registered — dumpstore is managing com.sun:auto-snapshot:* execution",
"buckets", "frequent,hourly,daily,weekly,monthly")
}
} else {
slog.Warn("autosnap: OS daemon active — dumpstore scheduler not registered until takeover",
"daemon", status.OSDaemon)
}
sched.Start(ctx)
defer sched.Stop()
apiHandler := api.NewHandler(runner, version, b, jobMgr, replRunner, autosnapRunner, cfg, store, *configPath)
apiHandler.SetOtelInfo(otelx.Status())
mux := http.NewServeMux()
auth.RegisterRoutes(mux, cfg, store, rl)
apiHandler.RegisterRoutes(mux)
staticDir := filepath.Join(*baseDir, "static")
mux.Handle("/", http.FileServer(http.Dir(staticDir)))
authMW := auth.NewMiddleware(cfg, store)
handler := logging.RequestLogger(authMW.Wrap(mux))
if otelx.Enabled() {
// Outermost so RequestLogger's context carries the span. Static assets
// and the hours-long SSE stream are not worth a span each.
handler = otelhttp.NewHandler(handler, "dumpstore",
otelhttp.WithFilter(func(r *http.Request) bool {
if r.URL.Path == "/api/events" {
return false
}
return strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/auth/")
}),
)
}
if *tlsFlag && cfg.TLSCertPath != "" && cfg.TLSKeyPath != "" {
httpsAddr := ":" + *tlsPort
srv := &http.Server{Addr: httpsAddr, Handler: handler}
// HTTP redirect server: plain HTTP → HTTPS.
redirectAddr := ":" + *httpPort
redirectSrv := &http.Server{
Addr: redirectAddr,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
target := "https://" + r.Host + r.URL.RequestURI()
http.Redirect(w, r, target, http.StatusMovedPermanently)
}),
}
go func() {
<-ctx.Done()
slog.Info("dumpstore shutting down")
srv.Shutdown(context.Background()) //nolint:errcheck
redirectSrv.Shutdown(context.Background()) //nolint:errcheck
}()
go func() {
if err := redirectSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("redirect server stopped", "err", err)
}
}()
slog.Info("dumpstore starting (TLS)", "https_addr", httpsAddr, "redirect_addr", redirectAddr, "base", *baseDir)
if err := srv.ListenAndServeTLS(cfg.TLSCertPath, cfg.TLSKeyPath); err != nil && err != http.ErrServerClosed {
slog.Error("server stopped", "err", err)
os.Exit(1)
}
} else {
srv := &http.Server{Addr: *addr, Handler: handler}
go func() {
<-ctx.Done()
slog.Info("dumpstore shutting down")
if err := srv.Shutdown(context.Background()); err != nil {
slog.Error("server shutdown error", "err", err)
}
}()
slog.Info("dumpstore starting", "addr", *addr, "base", *baseDir)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("server stopped", "err", err)
os.Exit(1)
}
}
}
func checkDeps(baseDir string) error {
for _, bin := range []string{"zfs", "zpool"} {
if _, err := exec.LookPath(bin); err != nil {
return fmt.Errorf("%s not found in PATH (is ZFS installed?): %w", bin, err)
}
}
if _, err := exec.LookPath("ansible-playbook"); err != nil {
return fmt.Errorf("ansible-playbook not found in PATH: %w", err)
}
pbDir := filepath.Join(baseDir, "playbooks")
if _, err := os.Stat(pbDir); err != nil {
return fmt.Errorf("playbooks directory not found at %s: %w", pbDir, err)
}
staticDir := filepath.Join(baseDir, "static")
if _, err := os.Stat(staticDir); err != nil {
return fmt.Errorf("static directory not found at %s: %w", staticDir, err)
}
return nil
}