/
node_pre.go
369 lines (304 loc) · 12.9 KB
/
node_pre.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package start
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/elysiumstation/fury/libs/subscribers"
"github.com/cenkalti/backoff"
"google.golang.org/grpc"
"gopkg.in/natefinch/lumberjack.v2"
"github.com/elysiumstation/fury/datanode/broker"
"github.com/elysiumstation/fury/datanode/config"
"github.com/elysiumstation/fury/datanode/networkhistory"
"github.com/elysiumstation/fury/datanode/networkhistory/snapshot"
"github.com/elysiumstation/fury/datanode/sqlstore"
"github.com/elysiumstation/fury/libs/pprof"
"github.com/elysiumstation/fury/logging"
"github.com/elysiumstation/fury/paths"
furyprotoapi "github.com/elysiumstation/fury/protos/fury/api/v1"
)
func (l *NodeCommand) persistentPre([]string) (err error) {
// ensure we cancel the context on error
defer func() {
if err != nil {
l.cancel()
}
}()
conf := l.configWatcher.Get()
// reload logger with the setup from configuration
l.Log = logging.NewLoggerFromConfig(conf.Logging).Named(l.Log.GetName())
preLog := l.Log.Named("start.persistentPre")
if conf.Pprof.Enabled {
preLog.Info("fury is starting with pprof profile, this is not a recommended setting for production")
l.pproffhandlr, err = pprof.New(l.Log, conf.Pprof)
if err != nil {
return
}
l.configWatcher.OnConfigUpdate(
func(cfg config.Config) { l.pproffhandlr.ReloadConf(cfg.Pprof) },
)
}
preLog.Info("Starting Fury Datanode",
logging.String("version", l.Version),
logging.String("version-hash", l.VersionHash))
if l.conf.SQLStore.UseEmbedded {
logDir := l.furyPaths.StatePathFor(paths.DataNodeLogsHome)
postgresLogger := &lumberjack.Logger{
Filename: filepath.Join(logDir, "embedded-postgres.log"),
MaxSize: l.conf.SQLStore.LogRotationConfig.MaxSize,
MaxAge: l.conf.SQLStore.LogRotationConfig.MaxAge,
Compress: true,
}
runtimeDir := l.furyPaths.StatePathFor(paths.DataNodeEmbeddedPostgresRuntimeDir)
l.embeddedPostgres, err = sqlstore.StartEmbeddedPostgres(l.Log, l.conf.SQLStore,
runtimeDir, postgresLogger)
if err != nil {
return fmt.Errorf("failed to start embedded postgres: %w", err)
}
go func() {
for range l.ctx.Done() {
l.embeddedPostgres.Stop()
}
}()
}
if l.conf.SQLStore.WipeOnStartup {
if ResetDatabaseAndNetworkHistory(l.ctx, l.Log, l.furyPaths, l.conf.SQLStore.ConnectionConfig); err != nil {
return fmt.Errorf("failed to reset database and network history: %w", err)
}
}
initialisedFromNetworkHistory := false
if l.conf.NetworkHistory.Enabled {
preLog.Info("Initializing Network History")
if l.conf.AutoInitialiseFromNetworkHistory {
if err := networkhistory.KillAllConnectionsToDatabase(l.ctx, l.conf.SQLStore.ConnectionConfig); err != nil {
return fmt.Errorf("failed to kill all connections to database: %w", err)
}
}
err = l.initialiseNetworkHistory(preLog, l.conf.SQLStore.ConnectionConfig)
if err != nil {
l.Log.Error("Failed to initialise network history", logging.Error(err))
return fmt.Errorf("failed to initialise network history:%w", err)
}
if l.conf.AutoInitialiseFromNetworkHistory {
preLog.Info("Auto Initialising Datanode From Network History")
apiPorts := []int{l.conf.API.Port}
apiPorts = append(apiPorts, l.conf.NetworkHistory.Initialise.GrpcAPIPorts...)
if err = networkhistory.InitialiseDatanodeFromNetworkHistory(l.ctx, l.conf.NetworkHistory.Initialise,
preLog, l.conf.SQLStore.ConnectionConfig, l.networkHistoryService, apiPorts,
bool(l.conf.SQLStore.VerboseMigration)); err != nil {
return fmt.Errorf("failed to initialize datanode from network history: %w", err)
}
initialisedFromNetworkHistory = true
preLog.Info("Initialized from network history")
}
}
if !initialisedFromNetworkHistory {
operation := func() (opErr error) {
preLog.Info("Attempting to initialise database...")
opErr = l.initialiseDatabase(preLog)
if opErr != nil {
preLog.Error("Failed to initialise database, retrying...", logging.Error(opErr))
}
preLog.Info("Database initialised")
return opErr
}
retryConfig := l.conf.SQLStore.ConnectionRetryConfig
expBackoff := backoff.NewExponentialBackOff()
expBackoff.InitialInterval = retryConfig.InitialInterval
expBackoff.MaxInterval = retryConfig.MaxInterval
expBackoff.MaxElapsedTime = retryConfig.MaxElapsedTime
err = backoff.Retry(operation, backoff.WithMaxRetries(expBackoff, retryConfig.MaxRetries))
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
}
preLog.Info("Applying Data Retention Policies")
err = sqlstore.ApplyDataRetentionPolicies(l.conf.SQLStore, preLog)
if err != nil {
return fmt.Errorf("failed to apply data retention policies:%w", err)
}
preLog.Info("Enabling SQL stores")
l.transactionalConnectionSource, err = sqlstore.NewTransactionalConnectionSource(preLog, l.conf.SQLStore.ConnectionConfig)
if err != nil {
return fmt.Errorf("failed to create transactional connection source: %w", err)
}
logSqlstore := l.Log.Named("sqlstore")
l.CreateAllStores(l.ctx, logSqlstore, l.transactionalConnectionSource, l.conf.CandlesV2.CandleStore)
logService := l.Log.Named("service")
logService.SetLevel(l.conf.Service.Level.Get())
if err := l.SetupServices(l.ctx, logService, l.conf.CandlesV2); err != nil {
return err
}
err = networkhistory.VerifyChainID(l.conf.ChainID, l.chainService)
if err != nil {
return fmt.Errorf("failed to verify chain id:%w", err)
}
l.SetupSQLSubscribers()
return nil
}
func (l *NodeCommand) initialiseDatabase(preLog *logging.Logger) error {
var err error
conf := l.conf.SQLStore.ConnectionConfig
conf.MaxConnPoolSize = 1
pool, err := sqlstore.CreateConnectionPool(conf)
if err != nil {
return fmt.Errorf("failed to create connection pool: %w", err)
}
defer pool.Close()
hasFurySchema, err := sqlstore.HasFurySchema(l.ctx, pool)
if err != nil {
return fmt.Errorf("failed to check if database has schema: %w", err)
}
// If it's an empty database, recreate it with correct locale settings
if !hasFurySchema {
err = sqlstore.RecreateFuryDatabase(l.ctx, preLog, l.conf.SQLStore.ConnectionConfig)
if err != nil {
return fmt.Errorf("failed to recreate fury schema: %w", err)
}
}
err = sqlstore.MigrateToLatestSchema(preLog, l.conf.SQLStore)
if err != nil {
return fmt.Errorf("failed to migrate to latest schema:%w", err)
}
return nil
}
// we've already set everything up WRT arguments etc... just bootstrap the node.
func (l *NodeCommand) preRun([]string) (err error) {
// ensure that context is cancelled if we return an error here
defer func() {
if err != nil {
l.cancel()
}
}()
preLog := l.Log.Named("start.preRun")
brokerLog := l.Log.Named("broker")
eventSourceLog := brokerLog.Named("eventsource")
eventReceiverSender, err := broker.NewEventReceiverSender(l.conf.Broker, eventSourceLog, l.conf.ChainID)
if err != nil {
preLog.Error("unable to initialise event source", logging.Error(err))
return err
}
var rawEventSource broker.RawEventReceiver = eventReceiverSender
if l.conf.Broker.UseBufferedEventSource {
bufferFilePath, err := l.furyPaths.CreateStatePathFor(paths.DataNodeEventBufferHome)
if err != nil {
preLog.Error("failed to create path for buffered event source", logging.Error(err))
return err
}
archiveFilesPath, err := l.furyPaths.CreateStatePathFor(paths.DataNodeArchivedEventBufferHome)
if err != nil {
l.Log.Error("failed to create archive path for buffered event source", logging.Error(err))
return err
}
rawEventSource, err = broker.NewBufferedEventSource(l.ctx, l.Log, l.conf.Broker.BufferedEventSourceConfig, eventReceiverSender,
bufferFilePath, archiveFilesPath)
if err != nil {
preLog.Error("unable to initialise file buffered event source", logging.Error(err))
return err
}
}
var eventSource broker.EventReceiver
eventSource = broker.NewDeserializer(rawEventSource)
eventSource = broker.NewFanOutEventSource(eventSource, l.conf.SQLStore.FanOutBufferSize, 2)
var onBlockCommittedHandler func(ctx context.Context, chainId string, lastCommittedBlockHeight int64, snapshotTaken bool)
var protocolUpgradeHandler broker.ProtocolUpgradeHandler
if l.conf.NetworkHistory.Enabled {
blockCommitHandler := networkhistory.NewBlockCommitHandler(l.Log, l.conf.NetworkHistory, l.snapshotService.SnapshotData,
bool(l.conf.Broker.UseEventFile), l.conf.Broker.FileEventSourceConfig.TimeBetweenBlocks.Duration,
5*time.Second, 6)
onBlockCommittedHandler = blockCommitHandler.OnBlockCommitted
protocolUpgradeHandler = networkhistory.NewProtocolUpgradeHandler(l.Log, l.protocolUpgradeService, eventReceiverSender,
l.networkHistoryService.CreateAndPublishSegment)
} else {
onBlockCommittedHandler = func(ctx context.Context, chainId string, lastCommittedBlockHeight int64, snapshotTaken bool) {}
protocolUpgradeHandler = networkhistory.NewProtocolUpgradeHandler(l.Log, l.protocolUpgradeService, eventReceiverSender,
func(ctx context.Context, chainID string, toHeight int64) error { return nil })
}
l.sqlBroker = broker.NewSQLStoreBroker(l.Log, l.conf.Broker, l.conf.ChainID, eventSource,
l.transactionalConnectionSource,
l.blockStore,
onBlockCommittedHandler,
protocolUpgradeHandler,
l.GetSQLSubscribers(),
)
l.broker, err = broker.New(l.ctx, brokerLog, l.conf.Broker, l.conf.ChainID, eventSource)
if err != nil {
preLog.Error("unable to initialise broker", logging.Error(err))
return err
}
// Event service as used by old and new world
l.eventService = subscribers.NewService(preLog, l.broker, l.conf.Broker.EventBusClientBufferSize)
nodeAddr := fmt.Sprintf("%v:%v", l.conf.API.CoreNodeIP, l.conf.API.CoreNodeGRPCPort)
conn, err := grpc.Dial(nodeAddr, grpc.WithInsecure())
if err != nil {
return err
}
l.furyCoreServiceClient = furyprotoapi.NewCoreServiceClient(conn)
return nil
}
func (l *NodeCommand) initialiseNetworkHistory(preLog *logging.Logger, connConfig sqlstore.ConnectionConfig) error {
// Want to pre-allocate some connections to ensure a connection is always available,
// 3 is chosen to allow for the fact that pool size can temporarily drop below the min pool size.
connConfig.MaxConnPoolSize = 3
connConfig.MinConnPoolSize = 3
networkHistoryPool, err := sqlstore.CreateConnectionPool(connConfig)
if err != nil {
return fmt.Errorf("failed to create network history connection pool: %w", err)
}
preNetworkHistoryLog := preLog.Named("networkHistory")
networkHistoryLog := l.Log.Named("networkHistory")
networkHistoryLog.SetLevel(l.conf.NetworkHistory.Level.Get())
snapshotServiceLog := networkHistoryLog.Named("snapshot")
networkHistoryServiceLog := networkHistoryLog.Named("service")
l.snapshotService, err = snapshot.NewSnapshotService(snapshotServiceLog, l.conf.NetworkHistory.Snapshot,
networkHistoryPool,
l.furyPaths.StatePathFor(paths.DataNodeNetworkHistorySnapshotCopyTo), func(version int64) error {
if err = sqlstore.MigrateUpToSchemaVersion(preNetworkHistoryLog, l.conf.SQLStore, version, sqlstore.EmbedMigrations); err != nil {
return fmt.Errorf("failed to migrate up to schema version %d: %w", version, err)
}
return nil
},
func(version int64) error {
if err = sqlstore.MigrateDownToSchemaVersion(preNetworkHistoryLog, l.conf.SQLStore, version, sqlstore.EmbedMigrations); err != nil {
return fmt.Errorf("failed to migrate down to schema version %d: %w", version, err)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to create snapshot service:%w", err)
}
l.networkHistoryService, err = networkhistory.New(l.ctx, networkHistoryServiceLog, l.conf.NetworkHistory,
l.furyPaths.StatePathFor(paths.DataNodeNetworkHistoryHome),
networkHistoryPool,
l.conf.ChainID, l.snapshotService, l.conf.API.Port, l.furyPaths.StatePathFor(paths.DataNodeNetworkHistorySnapshotCopyFrom),
l.furyPaths.StatePathFor(paths.DataNodeNetworkHistorySnapshotCopyTo), l.conf.MaxMemoryPercent)
if err != nil {
return fmt.Errorf("failed to create networkHistory service:%w", err)
}
return nil
}
func ResetDatabaseAndNetworkHistory(ctx context.Context, log *logging.Logger, furyPaths paths.Paths, connConfig sqlstore.ConnectionConfig) error {
err := os.RemoveAll(furyPaths.StatePathFor(paths.DataNodeNetworkHistoryHome))
if err != nil {
return fmt.Errorf("failed to remove network history dir: %w", err)
}
log.Info("Wiped all network history")
if err := sqlstore.RecreateFuryDatabase(ctx, log, connConfig); err != nil {
return fmt.Errorf("failed to wipe database:%w", err)
}
log.Info("Wiped all existing data from the database")
return nil
}