forked from ChainSafe/chainbridge-utils
/
core.go
72 lines (61 loc) · 1.47 KB
/
core.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
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: LGPL-3.0-only
package core
import (
"fmt"
"os"
"os/signal"
"syscall"
"github.com/ChainSafe/log15"
)
type Core struct {
Registry []Chain
route *Router
log log15.Logger
sysErr <-chan error
}
func NewCore(sysErr <-chan error) *Core {
return &Core{
Registry: make([]Chain, 0),
route: NewRouter(log15.New("system", "router")),
log: log15.New("system", "core"),
sysErr: sysErr,
}
}
// AddChain registers the chain in the Registry and calls Chain.SetRouter()
func (c *Core) AddChain(chain Chain) {
c.Registry = append(c.Registry, chain)
chain.SetRouter(c.route)
}
// Start will call all registered chains' Start methods and block forever (or until signal is received)
func (c *Core) Start() {
for _, chain := range c.Registry {
err := chain.Start()
if err != nil {
c.log.Error(
"failed to start chain",
"chain", chain.Id(),
"err", err,
)
return
}
c.log.Info(fmt.Sprintf("Started %s chain", chain.Name()))
}
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigc)
// Block here and wait for a signal
select {
case err := <-c.sysErr:
c.log.Error("FATAL ERROR. Shutting down.", "err", err)
case <-sigc:
c.log.Warn("Interrupt received, shutting down now.")
}
// Signal chains to shutdown
for _, chain := range c.Registry {
chain.Stop()
}
}
func (c *Core) Errors() <-chan error {
return c.sysErr
}