-
Notifications
You must be signed in to change notification settings - Fork 71
/
main.go
230 lines (189 loc) · 6.66 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
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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/ardanlabs/blockchain/app/services/node/handlers"
"github.com/ardanlabs/blockchain/foundation/logger"
"github.com/ardanlabs/blockchain/foundation/node"
"github.com/ardanlabs/conf/v2"
"go.uber.org/zap"
)
// build is the git version of this program. It is set using build flags in the makefile.
var build = "develop"
func main() {
// Construct the application logger.
log, err := logger.New("BAR-LED")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer log.Sync()
// Perform the startup and shutdown sequence.
if err := run(log); err != nil {
log.Errorw("startup", "ERROR", err)
log.Sync()
os.Exit(1)
}
}
func run(log *zap.SugaredLogger) error {
// =========================================================================
// Configuration
cfg := struct {
conf.Version
Web struct {
ReadTimeout time.Duration `conf:"default:5s"`
WriteTimeout time.Duration `conf:"default:10s"`
IdleTimeout time.Duration `conf:"default:120s"`
ShutdownTimeout time.Duration `conf:"default:20s"`
DebugHost string `conf:"default:0.0.0.0:7080"`
PublicHost string `conf:"default:0.0.0.0:8080"`
PrivateHost string `conf:"default:0.0.0.0:9080"`
}
Node struct {
DBPath string `conf:"default:zblock/blocks.db"`
KnownPeers []string `conf:"default:0.0.0.0:9080;0.0.0.0:9180"`
}
}{
Version: conf.Version{
Build: build,
Desc: "copyright information here",
},
}
const prefix = "BARLED"
help, err := conf.Parse(prefix, &cfg)
if err != nil {
if errors.Is(err, conf.ErrHelpWanted) {
fmt.Println(help)
return nil
}
return fmt.Errorf("parsing config: %w", err)
}
// =========================================================================
// App Starting
log.Infow("starting service", "version", build)
defer log.Infow("shutdown complete")
out, err := conf.String(&cfg)
if err != nil {
return fmt.Errorf("generating config for output: %w", err)
}
log.Infow("startup", "config", out)
// =========================================================================
// Node Support
node, err := node.New(node.Config{
DBPath: cfg.Node.DBPath,
IPPort: cfg.Web.PrivateHost,
KnownPeers: cfg.Node.KnownPeers,
EvHandler: func(v string, args ...interface{}) {
s := fmt.Sprintf(v, args...)
log.Infow(s, "traceid", "11111111-1111-1111-1111-111111111111")
},
})
if err != nil {
return err
}
defer node.Shutdown()
// =========================================================================
// Start Debug Service
log.Infow("startup", "status", "debug v1 router started", "host", cfg.Web.DebugHost)
// The Debug function returns a mux to listen and serve on for all the debug
// related endpoints. This includes the standard library endpoints.
// Construct the mux for the debug calls.
debugMux := handlers.DebugMux(build, log)
// Start the service listening for debug requests.
// Not concerned with shutting this down with load shedding.
go func() {
if err := http.ListenAndServe(cfg.Web.DebugHost, debugMux); err != nil {
log.Errorw("shutdown", "status", "debug v1 router closed", "host", cfg.Web.DebugHost, "ERROR", err)
}
}()
// =========================================================================
// Service Start/Stop Support
// Make a channel to listen for an interrupt or terminate signal from the OS.
// Use a buffered channel because the signal package requires it.
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
// Make a channel to listen for errors coming from the listener. Use a
// buffered channel so the goroutine can exit if we don't collect this error.
serverErrors := make(chan error, 1)
// =========================================================================
// Start Public Service
log.Infow("startup", "status", "initializing V1 public API support")
// Construct the mux for the public API calls.
publicMux := handlers.PublicMux(handlers.MuxConfig{
Shutdown: shutdown,
Log: log,
Node: node,
})
// Construct a server to service the requests against the mux.
public := http.Server{
Addr: cfg.Web.PublicHost,
Handler: publicMux,
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
IdleTimeout: cfg.Web.IdleTimeout,
ErrorLog: zap.NewStdLog(log.Desugar()),
}
// Start the service listening for api requests.
go func() {
log.Infow("startup", "status", "public api router started", "host", public.Addr)
serverErrors <- public.ListenAndServe()
}()
// =========================================================================
// Start Private Service
log.Infow("startup", "status", "initializing V1 private API support")
// Construct the mux for the private API calls.
privateMux := handlers.PrivateMux(handlers.MuxConfig{
Shutdown: shutdown,
Log: log,
Node: node,
})
// Construct a server to service the requests against the mux.
private := http.Server{
Addr: cfg.Web.PrivateHost,
Handler: privateMux,
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
IdleTimeout: cfg.Web.IdleTimeout,
ErrorLog: zap.NewStdLog(log.Desugar()),
}
// Start the service listening for api requests.
go func() {
log.Infow("startup", "status", "private api router started", "host", private.Addr)
serverErrors <- private.ListenAndServe()
}()
// =========================================================================
// Shutdown
// Blocking main and waiting for shutdown.
select {
case err := <-serverErrors:
return fmt.Errorf("server error: %w", err)
case sig := <-shutdown:
log.Infow("shutdown", "status", "shutdown started", "signal", sig)
defer log.Infow("shutdown", "status", "shutdown complete", "signal", sig)
// Give outstanding requests a deadline for completion.
ctx, cancelPub := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
defer cancelPub()
// Asking listener to shut down and shed load.
log.Infow("shutdown", "status", "shutdown private API started")
if err := private.Shutdown(ctx); err != nil {
public.Close()
return fmt.Errorf("could not stop private service gracefully: %w", err)
}
// Give outstanding requests a deadline for completion.
ctx, cancelPri := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
defer cancelPri()
// Asking listener to shut down and shed load.
log.Infow("shutdown", "status", "shutdown public API started")
if err := public.Shutdown(ctx); err != nil {
public.Close()
return fmt.Errorf("could not stop public service gracefully: %w", err)
}
}
return nil
}