/
price-feeder.go
178 lines (146 loc) · 4.54 KB
/
price-feeder.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
package cmd
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/cicizeo/hilo/price-feeder/config"
"github.com/cicizeo/hilo/price-feeder/oracle"
"github.com/cicizeo/hilo/price-feeder/router"
"golang.org/x/sync/errgroup"
)
const (
logLevelJSON = "json"
logLevelText = "text"
)
var (
logLevel string
logFormat string
)
var rootCmd = &cobra.Command{
Use: "price-feeder [config-file]",
Args: cobra.ExactArgs(1),
Short: "price-feeder is a side-car process for providing Hilo's on-chain oracle with price data",
Long: `A side-car process that Hilo validators must run in order to provide
Hilo's on-chain price oracle with price information. The price-feeder performs
two primary functions. First, it is responsible for obtaining price information
from various reliable data sources, e.g. exchanges, and exposing this data via
an API. Secondly, the price-feeder consumes this data and periodically submits
vote and prevote messages following the oracle voting procedure.`,
RunE: priceFeederCmdHandler,
}
func init() {
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", zerolog.InfoLevel.String(), "logging level")
rootCmd.PersistentFlags().StringVar(&logFormat, "log-format", logLevelJSON, "logging format; must be either json or text")
rootCmd.AddCommand(getVersionCmd())
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func priceFeederCmdHandler(cmd *cobra.Command, args []string) error {
logLvl, err := zerolog.ParseLevel(logLevel)
if err != nil {
return err
}
zerolog.SetGlobalLevel(logLvl)
switch logFormat {
case logLevelJSON:
// JSON is the default logging format
case logLevelText:
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
default:
return fmt.Errorf("invalid logging format: %s", logFormat)
}
cfg, err := config.ParseConfig(args[0])
if err != nil {
return err
}
oracle := oracle.New()
ctx, cancel := context.WithCancel(context.Background())
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return startPriceFeeder(ctx, cfg, oracle)
})
g.Go(func() error {
return startPriceOracle(ctx, oracle)
})
// listen for and trap any OS signal to gracefully shutdown and exit
trapSignal(cancel)
// Block main process until all spawned goroutines have gracefully exited and
// signal has been captured in the main process or if an error occurs.
return g.Wait()
}
// trapSignal will listen for any OS signal and invoke Done on the main
// WaitGroup allowing the main process to gracefully exit.
func trapSignal(cancel context.CancelFunc) {
var sigCh = make(chan os.Signal)
signal.Notify(sigCh, syscall.SIGTERM)
signal.Notify(sigCh, syscall.SIGINT)
go func() {
sig := <-sigCh
log.Info().Str("signal", sig.String()).Msg("caught signal; shutting down...")
cancel()
}()
}
func startPriceFeeder(ctx context.Context, cfg config.Config, oracle *oracle.Oracle) error {
rtr := mux.NewRouter()
rtrWrapper := router.New(cfg, rtr, oracle)
rtrWrapper.RegisterRoutes()
writeTimeout, err := time.ParseDuration(cfg.Server.WriteTimeout)
if err != nil {
return err
}
readTimeout, err := time.ParseDuration(cfg.Server.ReadTimeout)
if err != nil {
return err
}
srvErrCh := make(chan error, 1)
srv := &http.Server{
Handler: rtr,
Addr: cfg.Server.ListenAddr,
WriteTimeout: writeTimeout,
ReadTimeout: readTimeout,
}
go func() {
log.Info().Str("listen_addr", cfg.Server.ListenAddr).Msg("starting price-feeder server...")
srvErrCh <- srv.ListenAndServe()
}()
for {
select {
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
log.Info().Str("listen_addr", cfg.Server.ListenAddr).Msg("shutting down price-feeder server...")
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Error().Err(err).Msg("failed to gracefully shutdown price-feeder server")
return err
}
return nil
case err := <-srvErrCh:
log.Error().Err(err).Msg("failed to start price-feeder server")
return err
}
}
}
func startPriceOracle(ctx context.Context, oracle *oracle.Oracle) error {
go func() {
log.Info().Msg("starting price-feeder oracle...")
oracle.Start(ctx)
}()
<-ctx.Done()
log.Info().Msg("shutting down price-feeder oracle...")
oracle.Stop()
return nil
}