-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
307 lines (263 loc) · 8.99 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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package main
import (
"context"
"errors"
"flag"
"fmt"
stdlog "log"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/ethereum/go-ethereum/log"
gethmetrics "github.com/ethereum/go-ethereum/metrics"
"github.com/status-im/status-go/api"
"github.com/status-im/status-go/cmd/statusd/debug"
"github.com/status-im/status-go/logutils"
nodemetrics "github.com/status-im/status-go/metrics/node"
"github.com/status-im/status-go/node"
"github.com/status-im/status-go/params"
"github.com/status-im/status-go/profiling"
"golang.org/x/crypto/ssh/terminal"
)
const (
serverClientName = "Statusd"
)
var (
buildStamp = "N/A" // rely on linker: -ldflags -X main.buildStamp"
)
var (
configFiles configFlags
logLevel = flag.String("log", "", `Log level, one of: "ERROR", "WARN", "INFO", "DEBUG", and "TRACE"`)
logWithoutColors = flag.Bool("log-without-color", false, "Disables log colors")
cliEnabled = flag.Bool("cli", false, "Enable debugging CLI server")
cliPort = flag.String("cli-port", debug.CLIPort, "CLI server's listening port")
pprofEnabled = flag.Bool("pprof", false, "Enable runtime profiling via pprof")
pprofPort = flag.Int("pprof-port", 52525, "Port for runtime profiling via pprof")
version = flag.Bool("version", false, "Print version and dump configuration")
dataDir = flag.String("dir", getDefaultDataDir(), "Directory used by node to store data")
register = flag.Bool("register", false, "Register and make the node discoverable by other nodes")
mailserver = flag.Bool("mailserver", false, "Enable Mail Server with default configuration")
networkID = flag.Int(
"network-id",
params.RopstenNetworkID,
fmt.Sprintf(
"A network ID: %d (Mainnet), %d (Ropsten), %d (Rinkeby)",
params.MainNetworkID, params.RopstenNetworkID, params.RinkebyNetworkID,
),
)
// don't change the name of this flag, https://github.com/ethereum/go-ethereum/blob/master/metrics/metrics.go#L41
metrics = flag.Bool("metrics", false, "Expose ethereum metrics with debug_metrics jsonrpc call")
syncAndExit = flag.Int("sync-and-exit", -1, "Timeout in minutes for blockchain sync and exit, zero means no timeout unless sync is finished")
)
// All general log messages in this package should be routed through this logger.
var logger = log.New("package", "status-go/cmd/statusd")
func init() {
flag.Var(&configFiles, "c", "JSON configuration file(s). Multiple configuration files can be specified, and will be merged in occurrence order")
colors := terminal.IsTerminal(int(os.Stdin.Fd()))
if err := logutils.OverrideRootLog(true, "ERROR", "", colors); err != nil {
stdlog.Fatalf("Error initializing logger: %v", err)
}
flag.Usage = printUsage
flag.Parse()
if flag.NArg() > 0 {
printUsage()
logger.Error("Extra args in command line: %v", flag.Args())
os.Exit(1)
}
}
// nolint:gocyclo
func main() {
opts := []params.Option{params.WithFleet(params.FleetBeta)}
if *mailserver {
opts = append(opts, params.WithMailserver())
}
config, err := params.NewNodeConfigWithDefaultsAndFiles(
*dataDir,
uint64(*networkID),
opts,
configFiles,
)
if err != nil {
printUsage()
if err != nil {
logger.Error(err.Error())
}
os.Exit(1)
}
if *register && *mailserver {
config.RegisterTopics = append(config.RegisterTopics, params.MailServerDiscv5Topic)
} else if *register {
config.RegisterTopics = append(config.RegisterTopics, params.WhisperDiscv5Topic)
}
// set up logging options
setupLogging(config)
// We want statusd to be distinct from StatusIM client.
config.Name = serverClientName
if *version {
printVersion(config, buildStamp)
return
}
backend := api.NewStatusBackend()
err = backend.StartNode(config)
if err != nil {
logger.Error("Node start failed", "error", err)
return
}
// handle interrupt signals
interruptCh := haltOnInterruptSignal(backend.StatusNode())
// Check if debugging CLI connection shall be enabled.
if *cliEnabled {
err := startDebug(backend)
if err != nil {
logger.Error("Starting debugging CLI server failed", "error", err)
return
}
}
// Check if profiling shall be enabled.
if *pprofEnabled {
profiling.NewProfiler(*pprofPort).Go()
}
// Run stats server.
if *metrics {
go startCollectingNodeMetrics(interruptCh, backend.StatusNode())
go gethmetrics.CollectProcessMetrics(3 * time.Second)
}
// Sync blockchain and stop.
if *syncAndExit >= 0 {
exitCode := syncAndStopNode(interruptCh, backend.StatusNode(), *syncAndExit)
// Call was interrupted. Wait for graceful shutdown.
if exitCode == -1 {
if gethNode := backend.StatusNode().GethNode(); gethNode != nil {
gethNode.Wait()
}
return
}
// Otherwise, exit immediately with a returned exit code.
os.Exit(exitCode)
}
gethNode := backend.StatusNode().GethNode()
if gethNode != nil {
// wait till node has been stopped
gethNode.Wait()
}
}
func getDefaultDataDir() string {
if home := os.Getenv("HOME"); home != "" {
return filepath.Join(home, ".statusd")
}
return "./statusd-data"
}
func setupLogging(config *params.NodeConfig) {
if *logLevel != "" {
config.LogLevel = *logLevel
}
colors := !(*logWithoutColors) && terminal.IsTerminal(int(os.Stdin.Fd()))
if err := logutils.OverrideRootLog(
logEnabled(config),
config.LogLevel,
config.LogFile,
colors,
); err != nil {
stdlog.Fatalf("Error initializing logger: %v", err)
}
}
// startDebug starts the debugging API server.
func startDebug(backend *api.StatusBackend) error {
_, err := debug.New(backend, *cliPort)
return err
}
// startCollectingStats collects various stats about the node and other protocols like Whisper.
func startCollectingNodeMetrics(interruptCh <-chan struct{}, statusNode *node.StatusNode) {
logger.Info("Starting collecting node metrics")
gethNode := statusNode.GethNode()
if gethNode == nil {
logger.Error("Failed to run metrics because it could not get the node")
return
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
if err := nodemetrics.SubscribeServerEvents(ctx, gethNode); err != nil {
logger.Error("Failed to subscribe server events", "error", err)
}
}()
<-interruptCh
}
func logEnabled(config *params.NodeConfig) bool {
return config.LogLevel != "" || config.LogFile != ""
}
var (
errStatusServiceRequiresIPC = errors.New("to enable the StatusService on IPC, -ipc flag must be set")
errStatusServiceRequiresHTTP = errors.New("to enable the StatusService on HTTP, -http flag must be set")
errStatusServiceInvalidFlag = errors.New("-status flag valid values are: ipc, http")
)
func configureStatusService(flagValue string, nodeConfig *params.NodeConfig) (*params.NodeConfig, error) {
switch flagValue {
case "ipc":
if !nodeConfig.IPCEnabled {
return nil, errStatusServiceRequiresIPC
}
nodeConfig.StatusServiceEnabled = true
case "http":
if !nodeConfig.HTTPEnabled {
return nil, errStatusServiceRequiresHTTP
}
nodeConfig.StatusServiceEnabled = true
nodeConfig.AddAPIModule("status")
case "":
nodeConfig.StatusServiceEnabled = false
default:
return nil, errStatusServiceInvalidFlag
}
return nodeConfig, nil
}
// printVersion prints verbose output about version and config.
func printVersion(config *params.NodeConfig, buildStamp string) {
fmt.Println(strings.Title(config.Name))
fmt.Println("Version:", config.Version)
if buildStamp != "" {
fmt.Println("Build Stamp:", buildStamp)
}
fmt.Println("Network Id:", config.NetworkID)
fmt.Println("Go Version:", runtime.Version())
fmt.Println("OS:", runtime.GOOS)
fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
fmt.Println("Loaded Config: ", config)
}
func printUsage() {
usage := `
Usage: statusd [options]
Examples:
statusd # run regular Whisper node that joins Status network
statusd -c ./default.json # run node with configuration specified in ./default.json file
statusd -c ./default.json -c ./standalone.json # run node with configuration specified in ./default.json file, after merging ./standalone.json file
statusd -c ./default.json -metrics # run node with configuration specified in ./default.json file, and expose ethereum metrics with debug_metrics jsonrpc call
statusd -c ./default.json -cli # run node with configuration specified in ./default.json file, and enable connection by statusd-cli on default port
Options:
`
fmt.Fprintf(os.Stderr, usage)
flag.PrintDefaults()
}
// haltOnInterruptSignal catches interrupt signal (SIGINT) and
// stops the node. It times out after 5 seconds
// if the node can not be stopped.
func haltOnInterruptSignal(statusNode *node.StatusNode) <-chan struct{} {
interruptCh := make(chan struct{})
go func() {
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt)
defer signal.Stop(signalCh)
<-signalCh
close(interruptCh)
logger.Info("Got interrupt, shutting down...")
if err := statusNode.Stop(); err != nil {
logger.Error("Failed to stop node", "error", err)
os.Exit(1)
}
}()
return interruptCh
}