-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
186 lines (161 loc) · 5.57 KB
/
Copy pathmain.go
File metadata and controls
186 lines (161 loc) · 5.57 KB
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
package main
import (
"allora_offchain_node/lib"
"allora_offchain_node/metrics"
usecase "allora_offchain_node/usecase"
"context"
"encoding/json"
"fmt"
"os"
"os/signal"
"syscall"
"time"
sdktypes "github.com/cosmos/cosmos-sdk/types"
"github.com/joho/godotenv"
"github.com/rs/zerolog/log"
)
func ConvertEntrypointsToInstances(userConfig lib.UserConfig) error {
// / Initialize adapters using the factory function
for i, worker := range userConfig.Worker {
if worker.InferenceEntrypointName != "" {
adapter, err := NewAlloraAdapter(worker.InferenceEntrypointName)
if err != nil {
fmt.Println("Error creating inference adapter:", err)
return err
}
userConfig.Worker[i].InferenceEntrypoint = adapter
}
if worker.ForecastEntrypointName != "" {
adapter, err := NewAlloraAdapter(worker.ForecastEntrypointName)
if err != nil {
fmt.Println("Error creating forecast adapter:", err)
return err
}
userConfig.Worker[i].ForecastEntrypoint = adapter
}
}
for i, reputer := range userConfig.Reputer {
if reputer.GroundTruthEntrypointName != "" {
adapter, err := NewAlloraAdapter(reputer.GroundTruthEntrypointName)
if err != nil {
fmt.Println("Error creating reputer adapter:", err)
return err
}
userConfig.Reputer[i].GroundTruthEntrypoint = adapter
}
}
for i, reputer := range userConfig.Reputer {
if reputer.LossFunctionEntrypointName != "" {
adapter, err := NewAlloraAdapter(reputer.LossFunctionEntrypointName)
if err != nil {
fmt.Println("Error creating reputer adapter:", err)
return err
}
userConfig.Reputer[i].LossFunctionEntrypoint = adapter
}
}
return nil
}
func readConfig() (lib.UserConfig, error) {
finalUserConfig := lib.UserConfig{} //nolint:exhaustruct
alloraJsonConfig := os.Getenv(lib.ALLORA_OFFCHAIN_NODE_CONFIG_JSON)
if alloraJsonConfig != "" {
log.Info().Msg("Config using JSON env var")
if err := json.Unmarshal([]byte(alloraJsonConfig), &finalUserConfig); err != nil {
return finalUserConfig, fmt.Errorf("failed to parse JSON config from env var: %w", err)
}
return finalUserConfig, nil
}
configPath := os.Getenv(lib.ALLORA_OFFCHAIN_NODE_CONFIG_FILE_PATH)
if configPath != "" {
log.Info().Msg("Config using JSON config file")
file, err := os.Open(configPath)
if err != nil {
return finalUserConfig, fmt.Errorf("failed to open JSON config file: %w", err)
}
defer file.Close()
if err := json.NewDecoder(file).Decode(&finalUserConfig); err != nil {
return finalUserConfig, fmt.Errorf("failed to parse JSON config file: %w", err)
}
return finalUserConfig, nil
}
return finalUserConfig, fmt.Errorf("could not find config file. Please create a config.json file and pass as environment variable")
}
func main() {
// Context tree:
// root context (rootCtx)
// ├── essential context (essentialCtx) - for connections, wallet, workers, reputers
// └── non-essential context (nonEssentialCtx) - for metrics, gas price updates
rootCtx, rootCancel := context.WithCancel(context.Background())
defer rootCancel()
// closed when the root context is cancelled in cascade
essentialCtx, essentialCancel := context.WithCancel(rootCtx)
nonEssentialCtx, nonEssentialCancel := context.WithCancel(rootCtx)
// Signal handling
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
log.Info().Msg("Received shutdown signal")
// Cancel non-essential first
nonEssentialCancel()
// Give some time for non-essential services to cleanup
time.Sleep(time.Second)
// Then cancel essential services
essentialCancel()
// Finally cancel root context
rootCancel()
}()
// Initialize logger
initLogger()
if dotErr := godotenv.Load(); dotErr != nil {
log.Info().Msg("Unable to load .env file")
}
// Set and lock sdk config
config := sdktypes.GetConfig()
config.SetBech32PrefixForAccount(lib.ADDRESS_PREFIX, lib.ADDRESS_PREFIX)
config.Seal()
log.Info().Msg("Starting allora offchain node...")
// Metrics
metrics.InitMetrics(metrics.CounterData)
metricsServer := metrics.GetMetrics()
metricsServer.StartMetricsServer(nonEssentialCtx, ":2112")
// Load config
userConfig, err := readConfig()
if err != nil {
log.Error().Err(err).Msg("Failed to read configuration, exiting")
return
}
// Convert entrypoints to instances of adapters
err = ConvertEntrypointsToInstances(userConfig)
if err != nil {
log.Error().Err(err).Msg("Failed to convert Entrypoints to instances of adapters - wrong entrypoint name? Exiting")
return
}
// Check and set defaults for the user config if any values are not set
userConfig.CheckAndSetDefaults()
// Creates the ConnectionManager and initialises the NodeConfigs with essential context
connectionManager, err := lib.NewConnectionManager(essentialCtx, userConfig)
if err != nil {
log.Error().Err(err).Msg("Failed to initialize ConnectionManager, exiting")
return
}
defer connectionManager.Close()
wallet, err := connectionManager.GetWallet()
if err != nil {
log.Error().Err(err).Msg("Failed to get wallet, exiting")
return
}
metricsServer.IncrementMetricsCounter(metrics.ApplicationStartedCount, wallet.Address, 0)
// Initialize spawner with both contexts
spawner, err := usecase.NewUseCaseSuite(essentialCtx, nonEssentialCtx, metricsServer, userConfig, connectionManager)
if err != nil {
log.Error().Err(err).Msg("Failed to initialize use case, exiting")
return
}
log.Info().Msg("Starting spawning processes...")
if err := spawner.Start(); err != nil {
log.Error().Err(err).Msg("Failed to spawn processes, exiting")
}
log.Info().Msg("End of application, closing...")
}