Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update bfgd.go #329

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 77 additions & 33 deletions cmd/bfgd/bfgd.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@
"syscall"

"github.com/juju/loggo"

"github.com/hemilabs/heminetwork/api/bfgapi"
"github.com/hemilabs/heminetwork/config"
"github.com/hemilabs/heminetwork/service/bfg"
"github.com/hemilabs/heminetwork/version"

Check failure on line 19 in cmd/bfgd/bfgd.go

View workflow job for this annotation

GitHub Actions / Lint

"github.com/hemilabs/heminetwork/version" imported and not used

Check failure on line 19 in cmd/bfgd/bfgd.go

View workflow job for this annotation

GitHub Actions / Build

"github.com/hemilabs/heminetwork/version" imported and not used

Check failure on line 19 in cmd/bfgd/bfgd.go

View workflow job for this annotation

GitHub Actions / Build

"github.com/hemilabs/heminetwork/version" imported and not used
)

const (
Expand All @@ -28,9 +27,13 @@
var (
log = loggo.GetLogger(daemonName)
welcome string
cfg = bfg.NewDefaultConfig()
cm = initializeConfigMap()

Check failure on line 31 in cmd/bfgd/bfgd.go

View workflow job for this annotation

GitHub Actions / Lint

undefined: initializeConfigMap (typecheck)

Check failure on line 31 in cmd/bfgd/bfgd.go

View workflow job for this annotation

GitHub Actions / Build

undefined: initializeConfigMap

Check failure on line 31 in cmd/bfgd/bfgd.go

View workflow job for this annotation

GitHub Actions / Build

undefined: initializeConfigMap
)

cfg = bfg.NewDefaultConfig()
cm = config.CfgMap{
// initConfigMap initialises the configuration map.
func initConfigMap() config.CfgMap {
return config.CfgMap{
"BFG_EXBTC_ADDRESS": config.Config{
Value: &cfg.EXBTCAddress,
DefaultValue: "localhost:18001",
Expand Down Expand Up @@ -136,10 +139,12 @@
Print: config.PrintSecret,
},
}
)
}

func HandleSignals(ctx context.Context, cancel context.CancelFunc, callback func(os.Signal)) {
// handleSignals gracefully shuts down the application on OS signals.
func handleSignals(ctx context.Context, cancel context.CancelFunc, callback func(os.Signal)) {
signalChan := make(chan os.Signal, 1)
defer close(signalChan)
signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)
defer func() {
signal.Stop(signalChan)
Expand All @@ -148,61 +153,100 @@

select {
case <-ctx.Done():
case s := <-signalChan: // First signal, cancel context.
case s := <-signalChan:
if callback != nil {
callback(s) // Do whatever caller wants first.
cancel()
callback(s)
}
cancel()
}
<-signalChan // Second signal, hard exit.
<-signalChan
log.Errorf("Received second termination signal, forcing exit.")
os.Exit(2)
}

func _main() error {
joshuasing marked this conversation as resolved.
Show resolved Hide resolved
// Parse configuration from environment
if err := config.Parse(cm); err != nil {
return err
// initializeLogger configures logging for the application.
func initializeLogger(logLevel string) error {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this function is necessarily needed. Could you inline the loggo.ConfigureLoggers call instead? 🤔

if err := loggo.ConfigureLoggers(logLevel); err != nil {
return fmt.Errorf("failed to configure logger with level %s: %w", logLevel, err)
}
log.Infof("Logger initialized with level: %s", logLevel)
return nil
}

loggo.ConfigureLoggers(cfg.LogLevel)
log.Infof(welcome)

pc := config.PrintableConfig(cm)
for k := range pc {
log.Infof("%v", pc[k])
}

ctx, cancel := context.WithCancel(context.Background())
go HandleSignals(ctx, cancel, func(s os.Signal) {
log.Infof("bfg service received signal: %s", s)
})

// runServer starts the BFG server with the provided configuration.
func runServer(ctx context.Context) error {
server, err := bfg.NewServer(cfg)
if err != nil {
return fmt.Errorf("create BFG server: %w", err)
}
if err = server.Run(ctx); !errors.Is(err, context.Canceled) {
return fmt.Errorf("bfg server terminated: %w", err)
return fmt.Errorf("server terminated unexpectedly: %w", err)
}

return nil
}

func init() {
version.Component = "bfgd"
welcome = "Hemi Bitcoin Finality Governor " + version.BuildInfo()
Comment on lines -191 to -193
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The init function needs to be kept in order to initialise the welcome variable, and set version.Component = "bfgd".

func _main() error {
// Parse configuration
if err := config.Parse(cm); err != nil {
return fmt.Errorf("failed to parse configuration: %w", err)
}

// Configure loggers
if err := loggo.ConfigureLoggers(cfg.LogLevel); err != nil {
return fmt.Errorf("failed to configure logger with level %s: %w", cfg.LogLevel, err)
}
log.Infof("Logger initialized with level: %s", cfg.LogLevel)

// Print parsed configuration
for key, value := range config.PrintableConfig(cm) {
log.Infof("%s: %v", key, value)
}

// Set up signal handling
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go handleSignals(ctx, cancel, func(s os.Signal) {
log.Infof("Received signal: %s", s)
})

// Initialize and run server
server, err := bfg.NewServer(cfg)
if err != nil {
return fmt.Errorf("failed to create server: %w", err)
}

log.Infof("Starting server...")
if err := server.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
return fmt.Errorf("server terminated unexpectedly: %w", err)
}

log.Infof("Server shut down gracefully.")
return nil
}



func main() {
// Verify command-line arguments
if len(os.Args) != 1 {
fmt.Fprintf(os.Stderr, "%v\n", welcome)
fmt.Fprintf(os.Stderr, "Usage:\n")
fmt.Fprintf(os.Stderr, "\thelp (this help)\n")
fmt.Fprintf(os.Stderr, "Environment:\n")
fmt.Fprintln(os.Stderr, welcome)
fmt.Fprintln(os.Stderr, "Usage:")
fmt.Fprintln(os.Stderr, "\thelp (this help)")
fmt.Fprintln(os.Stderr, "Environment:")
config.Help(os.Stderr, cm)
os.Exit(1)
}

// Print welcome message and configuration
log.Infof(welcome)
pc := config.PrintableConfig(cm)
for k, v := range pc {
Comment on lines +245 to +246
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of this change?

Suggested change
pc := config.PrintableConfig(cm)
for k, v := range pc {
for k, v := range config.PrintableConfig(cm) {

log.Infof("%s: %v", k, v)
}

if err := _main(); err != nil {
log.Errorf("%v", err)
os.Exit(1)
Expand Down
Loading