forked from RedBird96/b7s
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
340 lines (281 loc) · 8.6 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
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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"path/filepath"
"github.com/cockroachdb/pebble"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
"github.com/ziflex/lecho/v3"
"github.com/allora-network/b7s/api"
"github.com/allora-network/b7s/config"
"github.com/allora-network/b7s/executor"
"github.com/allora-network/b7s/executor/limits"
"github.com/allora-network/b7s/fstore"
"github.com/allora-network/b7s/host"
"github.com/allora-network/b7s/models/blockless"
"github.com/allora-network/b7s/node"
"github.com/allora-network/b7s/peerstore"
"github.com/allora-network/b7s/store"
)
const (
success = 0
failure = 1
)
func main() {
os.Exit(run())
}
func run() int {
// Signal catching for clean shutdown.
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
// Initialize logging.
log := zerolog.New(os.Stdout).With().Timestamp().Logger().Level(zerolog.DebugLevel)
// Parse CLI flags and validate that the configuration is valid.
cfg := parseFlags()
// Set log level.
level, err := zerolog.ParseLevel(cfg.Log.Level)
if err != nil {
log.Error().Err(err).Str("level", cfg.Log.Level).Msg("could not parse log level")
return failure
}
log = log.Level(level)
// Determine node role.
role, err := parseNodeRole(cfg.Role)
if err != nil {
log.Error().Err(err).Str("role", cfg.Role).Msg("invalid node role specified")
return failure
}
// If we have a key, use path that corresponds to that key e.g. `.b7s_<peer-id>`.
nodeDir := ""
if cfg.Host.PrivateKey != "" {
id, err := peerIDFromKey(cfg.Host.PrivateKey)
if err != nil {
log.Error().Err(err).Str("key", cfg.Host.PrivateKey).Msg("could not read private key")
return failure
}
nodeDir = generateNodeDirName(id)
} else {
nodeDir, err = os.MkdirTemp("", ".b7s_*")
if err != nil {
log.Error().Err(err).Msg("could not create node directory")
return failure
}
}
// Set relevant working paths for workspace, peerDB and functionDB.
// If paths were set using the CLI flags, use those. Else, use generated path, e.g. .b7s_<peer-id>/<default-option-for-directory>.
updateDirPaths(nodeDir, cfg)
log.Info().
Str("workspace", cfg.Workspace).
Str("peer_db", cfg.PeerDatabasePath).
Str("function_db", cfg.FunctionDatabasePath).
Msg("filepaths used by the node")
// Convert workspace path to an absolute one.
workspace, err := filepath.Abs(cfg.Workspace)
if err != nil {
log.Error().Err(err).Str("path", cfg.Workspace).Msg("could not determine absolute path for workspace")
return failure
}
cfg.Workspace = workspace
// Open the pebble peer database.
pdb, err := pebble.Open(cfg.PeerDatabasePath, &pebble.Options{Logger: &pebbleNoopLogger{}})
if err != nil {
log.Error().Err(err).Str("db", cfg.PeerDatabasePath).Msg("could not open pebble peer database")
return failure
}
defer pdb.Close()
// Create a new store.
pstore := store.New(pdb)
peerstore := peerstore.New(pstore)
// Get the list of dial back peers.
peers, err := peerstore.Peers()
if err != nil {
log.Error().Err(err).Msg("could not get list of dial-back peers")
return failure
}
// Get the list of boot nodes addresses.
bootNodeAddrs, err := getBootNodeAddresses(cfg.BootNodes)
if err != nil {
log.Error().Err(err).Msg("could not get boot node addresses")
return failure
}
// Create libp2p host.
host, err := host.New(log, cfg.Host.Address, cfg.Host.Port,
host.WithPrivateKey(cfg.Host.PrivateKey),
host.WithBootNodes(bootNodeAddrs),
host.WithDialBackPeers(peers),
host.WithDialBackAddress(cfg.Host.DialBackAddress),
host.WithDialBackPort(cfg.Host.DialBackPort),
host.WithDialBackWebsocketPort(cfg.Host.DialBackWebsocketPort),
host.WithWebsocket(cfg.Host.Websocket),
host.WithWebsocketPort(cfg.Host.WebsocketPort),
)
if err != nil {
log.Error().Err(err).Str("key", cfg.Host.PrivateKey).Msg("could not create host")
return failure
}
defer host.Close()
log.Info().
Str("id", host.ID().String()).
Strs("addresses", host.Addresses()).
Int("boot_nodes", len(bootNodeAddrs)).
Int("dial_back_peers", len(peers)).
Msg("created host")
// Set node options.
opts := []node.Option{
node.WithRole(role),
node.WithConcurrency(cfg.Concurrency),
node.WithAttributeLoading(cfg.LoadAttributes),
}
// If this is a worker node, initialize an executor.
if role == blockless.WorkerNode {
// Executor options.
execOptions := []executor.Option{
executor.WithWorkDir(cfg.Workspace),
executor.WithRuntimeDir(cfg.RuntimePath),
executor.WithExecutableName(cfg.RuntimeCLI),
}
if needLimiter(cfg) {
limiter, err := limits.New(limits.WithCPUPercentage(cfg.CPUPercentage), limits.WithMemoryKB(cfg.MemoryMaxKB))
if err != nil {
log.Error().Err(err).Msg("could not create resource limiter")
return failure
}
defer func() {
err = limiter.Shutdown()
if err != nil {
log.Error().Err(err).Msg("could not shutdown resource limiter")
}
}()
execOptions = append(execOptions, executor.WithLimiter(limiter))
}
// Create an executor.
executor, err := executor.New(log, execOptions...)
if err != nil {
log.Error().
Err(err).
Str("workspace", cfg.Workspace).
Str("runtime_path", cfg.RuntimePath).
Str("runtime_cli", cfg.RuntimeCLI).
Msg("could not create an executor")
return failure
}
opts = append(opts, node.WithExecutor(executor))
opts = append(opts, node.WithWorkspace(cfg.Workspace))
}
// Open the pebble function database.
fdb, err := pebble.Open(cfg.FunctionDatabasePath, &pebble.Options{Logger: &pebbleNoopLogger{}})
if err != nil {
log.Error().Err(err).Str("db", cfg.FunctionDatabasePath).Msg("could not open pebble function database")
return failure
}
defer fdb.Close()
functionStore := store.New(fdb)
// Create function store.
fstore := fstore.New(log, functionStore, cfg.Workspace)
// If we have topics specified, use those.
if len(cfg.Topics) > 0 {
opts = append(opts, node.WithTopics(cfg.Topics))
}
// Create the main context.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Instantiate node.
node, err := node.New(log, host, peerstore, fstore, opts...)
if err != nil {
log.Error().Err(err).Msg("could not create node")
return failure
}
done := make(chan struct{})
failed := make(chan struct{})
// Start node main loop in a separate goroutine.
go func() {
log.Info().
Str("role", role.String()).
Msg("Blockless Node starting")
err := node.Run(ctx)
if err != nil {
log.Error().Err(err).Msg("Blockless Node failed")
close(failed)
} else {
close(done)
}
log.Info().Msg("Blockless Node stopped")
}()
// If we're a head node - start the REST API.
if role == blockless.HeadNode {
if cfg.API == "" {
log.Error().Err(err).Msg("REST API address is required")
return failure
}
// Create echo server and iniialize logging.
server := echo.New()
server.HideBanner = true
server.HidePort = true
elog := lecho.From(log)
server.Logger = elog
server.Use(lecho.Middleware(lecho.Config{Logger: elog}))
// Create an API handler.
api := api.New(log, node)
// Set endpoint handlers.
server.GET("/api/v1/health", api.Health)
server.POST("/api/v1/functions/execute", api.Execute)
server.POST("/api/v1/functions/install", api.Install)
server.POST("/api/v1/functions/requests/result", api.ExecutionResult)
// Start API in a separate goroutine.
go func() {
log.Info().Str("port", cfg.API).Msg("Node API starting")
err := server.Start(cfg.API)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Warn().Err(err).Msg("Node API failed")
close(failed)
} else {
close(done)
}
log.Info().Msg("Node API stopped")
}()
}
select {
case <-sig:
log.Info().Msg("Blockless Node stopping")
case <-done:
log.Info().Msg("Blockless Node done")
case <-failed:
log.Info().Msg("Blockless Node aborted")
return failure
}
// If we receive a second interrupt signal, exit immediately.
go func() {
<-sig
log.Warn().Msg("forcing exit")
os.Exit(1)
}()
return success
}
func needLimiter(cfg *config.Config) bool {
return cfg.CPUPercentage != 1.0 || cfg.MemoryMaxKB > 0
}
func updateDirPaths(root string, cfg *config.Config) {
workspace := cfg.Workspace
if workspace == "" {
workspace = filepath.Join(root, defaultWorkspaceDir)
}
cfg.Workspace = workspace
peerDB := cfg.PeerDatabasePath
if peerDB == "" {
peerDB = filepath.Join(root, defaultPeerDB)
}
cfg.PeerDatabasePath = peerDB
functionDB := cfg.FunctionDatabasePath
if functionDB == "" {
functionDB = filepath.Join(root, defaultFunctionDB)
}
cfg.FunctionDatabasePath = functionDB
}
func generateNodeDirName(id string) string {
return fmt.Sprintf(".b7s_%s", id)
}