-
Notifications
You must be signed in to change notification settings - Fork 13
/
poet.go
164 lines (148 loc) · 4.47 KB
/
poet.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
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
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
_ "net/http/pprof" //#nosec G108 -- DefaultServeMux is not used
"os"
"os/signal"
"path/filepath"
"runtime"
"runtime/pprof"
"time"
"github.com/jessevdk/go-flags"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"github.com/spacemeshos/poet/logging"
"github.com/spacemeshos/poet/migrations"
"github.com/spacemeshos/poet/server"
)
// Poet binary version.
// It should be passed during the build with '-ldflags "-X main.version="'.
var version = "unknown"
// poetMain is the true entry point for poet. This function is required since
// defers created in the top-level scope of a main method aren't executed if
// os.Exit() is called.
func poetMain() (err error) {
// Start with a default Config with sane settings
cfg := server.DefaultConfig()
cfg.Version = func() {
fmt.Println(version)
os.Exit(0)
}
// Pre-parse the command line to check for an alternative Config file
cfg, err = server.ParseFlags(cfg, os.Args[1:])
if err != nil {
return err
}
// Load configuration file overwriting defaults with any specified options
// Parse CLI options and overwrite/add any specified options
cfg, err = server.ReadConfigFile(cfg)
if err != nil {
return err
}
server.SetupConfig(cfg)
// Finally, parse the remaining command line options again to ensure
// they take precedence.
cfg, err = server.ParseFlags(cfg, os.Args[1:])
if err != nil {
return err
}
// Initialize logging
logLevel := zap.InfoLevel
if cfg.DebugLog {
logLevel = zap.DebugLevel
}
logger := logging.New(logLevel, filepath.Join(cfg.LogDir, "poet.log"), cfg.JSONLog)
ctx := logging.NewContext(context.Background(), logger)
defer func() {
logger.Info("shutdown complete")
}()
logger.Info(
"starting up poet",
zap.String("version", version),
zap.String("poet dir", cfg.PoetDir),
zap.String("datadir", cfg.DataDir),
zap.String("dbdir", cfg.DbDir),
zap.Time("genesis", cfg.Genesis.Time()),
zap.Object("round config", cfg.Round),
)
// Migrate data if needed
if err := migrations.Migrate(ctx, cfg); err != nil {
return fmt.Errorf("migrations failed: %w", err)
}
if cfg.MetricsPort != nil {
// Start Prometheus
lis, err := net.Listen("tcp", fmt.Sprintf(":%v", *cfg.MetricsPort))
if err != nil {
return err
}
logger.Info("spawning Prometheus", zap.String("endpoint", fmt.Sprintf("http://%s", lis.Addr().String())))
go func() {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
server := &http.Server{Handler: mux, ReadHeaderTimeout: time.Second * 5}
err := server.Serve(lis)
logger.With().Info("Metrics server stopped", zap.Error(err))
}()
}
// Enable http profiling server if requested.
if cfg.Profile != "" {
logger.Sugar().Info("starting HTTP profiling on port %v", cfg.Profile)
go func() {
listenAddr := net.JoinHostPort("", cfg.Profile)
profileRedirect := http.RedirectHandler("/debug/pprof",
http.StatusSeeOther)
http.Handle("/", profileRedirect)
server := &http.Server{Addr: listenAddr, ReadHeaderTimeout: time.Second * 5}
if err := server.ListenAndServe(); err != nil {
logger.Warn("Failed to start profiling HTTP server", zap.Error(err))
}
}()
} else {
// Disable go default unbounded memory profiler.
runtime.MemProfileRate = 0
}
if cfg.CPUProfile != "" {
f, err := os.Create(cfg.CPUProfile)
if err != nil {
logger.Error("could not create CPU profile", zap.Error(err))
}
defer func() {
err = errors.Join(err, f.Close())
}()
if err := pprof.StartCPUProfile(f); err != nil {
logger.Error("could not start CPU profile", zap.Error(err))
}
defer pprof.StopCPUProfile()
}
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
defer stop()
server, err := server.New(ctx, *cfg)
if err != nil {
return fmt.Errorf("failed to create server: %w", err)
}
if err := server.Start(ctx); err != nil {
errClosing := server.Close()
return fmt.Errorf("failure in server: %w (closing: %w)", err, errClosing)
}
if err := server.Close(); err != nil {
return fmt.Errorf("failed closing server: %w", err)
}
return nil
}
func main() {
// Call the "real" main in a nested manner so the defers will properly
// be executed in the case of a graceful shutdown.
if err := poetMain(); err != nil {
// If it's the flag utility error don't print it,
// because it was already printed.
if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp {
} else {
_, _ = fmt.Fprintln(os.Stderr, err)
}
os.Exit(1)
}
}