forked from ignite/cli
/
serve.go
531 lines (442 loc) · 13.9 KB
/
serve.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package chain
import (
"context"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/otiai10/copy"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/notional-labs/tinyport/tinyport/chainconfig"
chaincmdrunner "github.com/notional-labs/tinyport/tinyport/pkg/chaincmd/runner"
"github.com/notional-labs/tinyport/tinyport/pkg/cosmosfaucet"
"github.com/notional-labs/tinyport/tinyport/pkg/dirchange"
"github.com/notional-labs/tinyport/tinyport/pkg/localfs"
"github.com/notional-labs/tinyport/tinyport/pkg/xexec"
"github.com/notional-labs/tinyport/tinyport/pkg/xfilepath"
"github.com/notional-labs/tinyport/tinyport/pkg/xhttp"
"github.com/notional-labs/tinyport/tinyport/pkg/xurl"
)
const (
// exportedGenesis is the name of the exported genesis file for a chain
exportedGenesis = "exported_genesis.json"
// sourceChecksum is the file containing the checksum to detect source modification
sourceChecksum = "source_checksum.txt"
// binaryChecksum is the file containing the checksum to detect binary modification
binaryChecksum = "binary_checksum.txt"
// configChecksum is the file containing the checksum to detect config modification
configChecksum = "config_checksum.txt"
)
var (
// ignoredExts holds a list of ignored files from watching.
ignoredExts = []string{"pb.go", "pb.gw.go"}
// starportSavePath is the place where chain exported genesis are saved
starportSavePath = xfilepath.Join(
chainconfig.ConfigDirPath,
xfilepath.Path("local-chains"),
)
)
type serveOptions struct {
forceReset bool
resetOnce bool
}
func newServeOption() serveOptions {
return serveOptions{
forceReset: false,
resetOnce: false,
}
}
// ServeOption provides options for the serve command
type ServeOption func(*serveOptions)
// ServeForceReset allows to force reset of the state when the chain is served and on every source change
func ServeForceReset() ServeOption {
return func(c *serveOptions) {
c.forceReset = true
}
}
// ServeResetOnce allows to reset of the state when the chain is served once
func ServeResetOnce() ServeOption {
return func(c *serveOptions) {
c.resetOnce = true
}
}
// Serve serves an app.
func (c *Chain) Serve(ctx context.Context, options ...ServeOption) error {
serveOptions := newServeOption()
// apply the options
for _, apply := range options {
apply(&serveOptions)
}
// initial checks and setup.
if err := c.setup(); err != nil {
return err
}
// make sure that config.yml exists
if c.options.ConfigFile != "" {
if _, err := os.Stat(c.options.ConfigFile); err != nil {
return err
}
} else if _, err := chainconfig.LocateDefault(c.app.Path); err != nil {
return err
}
// start serving components.
g, ctx := errgroup.WithContext(ctx)
// blockchain node routine
g.Go(func() error {
c.refreshServe()
for {
if ctx.Err() != nil {
return ctx.Err()
}
select {
case <-ctx.Done():
return ctx.Err()
case <-c.serveRefresher:
commands, err := c.Commands(ctx)
if err != nil {
return err
}
var (
serveCtx context.Context
buildErr *CannotBuildAppError
startErr *CannotStartAppError
)
serveCtx, c.serveCancel = context.WithCancel(ctx)
// determine if the chain should reset the state
shouldReset := serveOptions.forceReset || serveOptions.resetOnce
// serve the app.
err = c.serve(serveCtx, shouldReset)
serveOptions.resetOnce = false
switch {
case err == nil:
case errors.Is(err, context.Canceled):
// If the app has been served, we save the genesis state
if c.served {
c.served = false
fmt.Fprintln(c.stdLog().out, "💿 Saving genesis state...")
// If serve has been stopped, save the genesis state
if err := c.saveChainState(context.TODO(), commands); err != nil {
fmt.Fprint(c.stdLog().err, err.Error())
return err
}
genesisPath, err := c.exportedGenesisPath()
if err != nil {
fmt.Fprintln(c.stdLog().err, err.Error())
return err
}
fmt.Fprintf(c.stdLog().out, "💿 Genesis state saved in %s\n", genesisPath)
}
case errors.As(err, &buildErr):
fmt.Fprintf(c.stdLog().err, "%s\n", errorColor(err.Error()))
var validationErr *chainconfig.ValidationError
if errors.As(err, &validationErr) {
fmt.Fprintln(c.stdLog().out, "see: https://github.com/notional-labs/tinyport#configure")
}
fmt.Fprintf(c.stdLog().out, "%s\n", infoColor("Waiting for a fix before retrying..."))
case errors.As(err, &startErr):
// Parse returned error logs
parsedErr := startErr.ParseStartError()
// If empty, we cannot recognized the error
// Therefore, the error may be caused by a new logic that is not compatible with the old app state
// We suggest the user to eventually reset the app state
if parsedErr == "" {
fmt.Fprintf(c.stdLog().out, "%s %s\n", infoColor(`Blockchain failed to start.
If the new code is no longer compatible with the saved state, you can reset the database by launching:`), "tinyport chain serve --reset-once")
return fmt.Errorf("cannot run %s", startErr.AppName)
}
// return the clear parsed error
return errors.New(parsedErr)
default:
return err
}
}
}
})
// routine to watch back-end
g.Go(func() error {
return c.watchAppBackend(ctx)
})
return g.Wait()
}
func (c *Chain) setup() error {
fmt.Fprintf(c.stdLog().out, "Cosmos SDK's version is: %s\n\n", infoColor(c.Version))
return c.checkSystem()
}
// checkSystem checks if developer's work environment comply must to have
// dependencies and pre-conditions.
func (c *Chain) checkSystem() error {
// check if Go has installed.
if !xexec.IsCommandAvailable("go") {
return errors.New("Please, check that Go language is installed correctly in $PATH. See https://golang.org/doc/install")
}
return nil
}
func (c *Chain) refreshServe() {
if c.serveCancel != nil {
c.serveCancel()
}
c.serveRefresher <- struct{}{}
}
func (c *Chain) watchAppBackend(ctx context.Context) error {
watchPaths := appBackendSourceWatchPaths
if c.ConfigPath() != "" {
watchPaths = append(watchPaths, c.ConfigPath())
}
return localfs.Watch(
ctx,
watchPaths,
localfs.WatcherWorkdir(c.app.Path),
localfs.WatcherOnChange(c.refreshServe),
localfs.WatcherIgnoreHidden(),
localfs.WatcherIgnoreExt(ignoredExts...),
)
}
// serve performs the operations to serve the blockchain: build, init and start
// if the chain is already initialized and the file didn't changed, the app is directly started
// if the files changed, the state is imported
func (c *Chain) serve(ctx context.Context, forceReset bool) error {
conf, err := c.Config()
if err != nil {
return &CannotBuildAppError{err}
}
commands, err := c.Commands(ctx)
if err != nil {
return err
}
saveDir, err := c.chainSavePath()
if err != nil {
return err
}
// isInit determines if the app is initialized
var isInit bool
// determine if the app must reset the state
// if the state must be reset, then we consider the chain as being not initialized
isInit, err = c.IsInitialized()
if err != nil {
return err
}
if isInit {
configModified := false
if c.ConfigPath() != "" {
configModified, err = dirchange.HasDirChecksumChanged(c.app.Path, []string{c.ConfigPath()}, saveDir, configChecksum)
if err != nil {
return err
}
}
if forceReset || configModified {
// if forceReset is set, we consider the app as being not initialized
fmt.Fprintln(c.stdLog().out, "🔄 Resetting the app state...")
isInit = false
}
}
// check if source has been modified since last serve
// if the state must not be reset but the source has changed, we rebuild the chain and import the exported state
sourceModified, err := dirchange.HasDirChecksumChanged(c.app.Path, appBackendSourceWatchPaths, saveDir, sourceChecksum)
if err != nil {
return err
}
// we also consider the binary in the checksum to ensure the binary has not been changed by a third party
var binaryModified bool
binaryName, err := c.Binary()
if err != nil {
return err
}
binaryPath, err := exec.LookPath(binaryName)
if err != nil {
if !errors.Is(err, exec.ErrNotFound) {
return err
}
binaryModified = true
} else {
binaryModified, err = dirchange.HasDirChecksumChanged("", []string{binaryPath}, saveDir, binaryChecksum)
if err != nil {
return err
}
}
appModified := sourceModified || binaryModified
// check if exported genesis exists
exportGenesisExists := true
exportedGenesisPath, err := c.exportedGenesisPath()
if err != nil {
return err
}
if _, err := os.Stat(exportedGenesisPath); os.IsNotExist(err) {
exportGenesisExists = false
} else if err != nil {
return err
}
// build phase
if !isInit || appModified {
// build the blockchain app
if err := c.build(ctx, ""); err != nil {
return err
}
}
// init phase
// nolint:gocritic
if !isInit || (appModified && !exportGenesisExists) {
fmt.Fprintln(c.stdLog().out, "💿 Initializing the app...")
if err := c.Init(ctx, true); err != nil {
return err
}
} else if appModified {
// if the chain is already initialized but the source has been modified
// we reset the chain database and import the genesis state
fmt.Fprintln(c.stdLog().out, "💿 Existent genesis detected, restoring the database...")
if err := commands.UnsafeReset(ctx); err != nil {
return err
}
if err := c.importChainState(); err != nil {
return err
}
} else {
fmt.Fprintln(c.stdLog().out, "▶️ Restarting existing app...")
}
// save checksums
if c.ConfigPath() != "" {
if err := dirchange.SaveDirChecksum(c.app.Path, []string{c.ConfigPath()}, saveDir, configChecksum); err != nil {
return err
}
}
if err := dirchange.SaveDirChecksum(c.app.Path, appBackendSourceWatchPaths, saveDir, sourceChecksum); err != nil {
return err
}
binaryPath, err = exec.LookPath(binaryName)
if err != nil {
return err
}
if err := dirchange.SaveDirChecksum("", []string{binaryPath}, saveDir, binaryChecksum); err != nil {
return err
}
// start the blockchain
return c.start(ctx, conf)
}
func (c *Chain) start(ctx context.Context, config chainconfig.Config) error {
commands, err := c.Commands(ctx)
if err != nil {
return err
}
g, ctx := errgroup.WithContext(ctx)
// start the blockchain.
g.Go(func() error { return c.plugin.Start(ctx, commands, config) })
// start the faucet if enabled.
faucet, err := c.Faucet(ctx)
isFaucetEnabled := err != ErrFaucetIsNotEnabled
if isFaucetEnabled {
if err == ErrFaucetAccountDoesNotExist {
return &CannotBuildAppError{errors.Wrap(err, "faucet account doesn't exist")}
}
if err != nil {
return err
}
g.Go(func() (err error) {
if err := c.runFaucetServer(ctx, faucet); err != nil {
return &CannotBuildAppError{err}
}
return nil
})
}
// set the app as being served
c.served = true
// print the server addresses.
fmt.Fprintf(c.stdLog().out, "🌍 Tendermint node: %s\n", xurl.HTTP(config.Host.RPC))
fmt.Fprintf(c.stdLog().out, "🌍 Blockchain API: %s\n", xurl.HTTP(config.Host.API))
if isFaucetEnabled {
fmt.Fprintf(c.stdLog().out, "🌍 Token faucet: %s\n", xurl.HTTP(chainconfig.FaucetHost(config)))
}
return g.Wait()
}
func (c *Chain) runFaucetServer(ctx context.Context, faucet cosmosfaucet.Faucet) error {
config, err := c.Config()
if err != nil {
return err
}
return xhttp.Serve(ctx, &http.Server{
Addr: chainconfig.FaucetHost(config),
Handler: faucet,
})
}
// saveChainState runs the export command of the chain and store the exported genesis in the chain saved config
func (c *Chain) saveChainState(ctx context.Context, commands chaincmdrunner.Runner) error {
genesisPath, err := c.exportedGenesisPath()
if err != nil {
return err
}
return commands.Export(ctx, genesisPath)
}
// importChainState imports the saved genesis in chain config to use it as the genesis
func (c *Chain) importChainState() error {
exportGenesisPath, err := c.exportedGenesisPath()
if err != nil {
return err
}
genesisPath, err := c.GenesisPath()
if err != nil {
return err
}
return copy.Copy(exportGenesisPath, genesisPath)
}
// chainSavePath returns the path where the chain state is saved
// create the path if it doesn't exist
func (c *Chain) chainSavePath() (string, error) {
savePath, err := starportSavePath()
if err != nil {
return "", err
}
chainID, err := c.ID()
if err != nil {
return "", err
}
chainSavePath := filepath.Join(savePath, chainID)
// ensure the path exists
if err := os.MkdirAll(savePath, 0700); err != nil && !os.IsExist(err) {
return "", err
}
return chainSavePath, nil
}
// exportedGenesisPath returns the path of the exported genesis file
func (c *Chain) exportedGenesisPath() (string, error) {
savePath, err := c.chainSavePath()
if err != nil {
return "", err
}
return filepath.Join(savePath, exportedGenesis), nil
}
type CannotBuildAppError struct {
Err error
}
func (e *CannotBuildAppError) Error() string {
return fmt.Sprintf("cannot build app:\n\n\t%s", e.Err)
}
func (e *CannotBuildAppError) Unwrap() error {
return e.Err
}
type CannotStartAppError struct {
AppName string
Err error
}
func (e *CannotStartAppError) Error() string {
return fmt.Sprintf("cannot run %sd start:\n%s", e.AppName, errors.Unwrap(e.Err))
}
func (e *CannotStartAppError) Unwrap() error {
return e.Err
}
// ParseStartError parses the error into a clear error string
// The error logs from Cosmos SDK application are too extensive to be directly printed
// If the error is not recognized, returns an empty string
func (e *CannotStartAppError) ParseStartError() string {
errorLogs := errors.Unwrap(e.Err).Error()
switch {
case strings.Contains(errorLogs, "bind: address already in use"):
r := regexp.MustCompile(`listen .* bind: address already in use`)
return r.FindString(errorLogs)
case strings.Contains(errorLogs, "validator set is nil in genesis"):
return "Error: error during handshake: error on replay: validator set is nil in genesis and still empty after InitChain"
default:
return ""
}
}