Skip to content

Commit

Permalink
refactor: add config struct and use slog
Browse files Browse the repository at this point in the history
- Move node to internal package
- Add a struct that contains all node config
- Add structured logging with slog
- Add CARTESI_LOG_PRETTY
- Remove CARTESI_LOG_TIMESTAMP
- Log Rust service's messages in the correct level
- Print cartesi-rollups-cli to stdout

Co-Author: Victor Yves Crispim <[email protected]>
Co-Author: Francisco Moura <[email protected]>
  • Loading branch information
gligneul committed Mar 13, 2024
1 parent 01cf64d commit b86786e
Show file tree
Hide file tree
Showing 36 changed files with 1,470 additions and 1,499 deletions.
3 changes: 3 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ linters-settings:
lll:
line-length: 100
tab-width: 4
gomnd:
ignored-functions:
- "^make"
14 changes: 10 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,21 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased
## [Unreleased]

### Added

- Added verification to ensure CARTESI_BLOCKCHAIN_ID matches the id returned from the Ethereum node
- Added verification to ensure `CARTESI_BLOCKCHAIN_ID` matches the id returned from the Ethereum node
- Added `CARTESI_AUTH_KIND` environment variable
- Added structured logging with slog. Colored logs can now be enabled with `CARTESI_LOG_PRETTY` environment variable.

## Changed
### Changed

- Changed `CARTESI_BLOCKCHAIN_ID` type from int to uint64

### Removed

- Changed CARTESI_BLOCKCHAIN_ID type from int to uint64
- Removed `CARTESI_LOG_TIMESTAMP` environment variable

## [1.3.0] 2024-02-09

Expand Down
2 changes: 1 addition & 1 deletion build/compose-node.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ services:
- "10000:10000" # Supervisor
environment:
CARTESI_LOG_LEVEL: "info"
CARTESI_LOG_TIMESTAMP: "false"
CARTESI_LOG_PRETTY: "true"
CARTESI_FEATURE_HOST_MODE: "false"
CARTESI_FEATURE_DISABLE_CLAIMER: "false"
CARTESI_HTTP_ADDRESS: "0.0.0.0"
Expand Down
4 changes: 2 additions & 2 deletions cmd/cartesi-rollups-cli/root/deps/deps.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ package deps

import (
"context"
"fmt"
"os/signal"
"syscall"

"github.com/cartesi/rollups-node/internal/config"
"github.com/cartesi/rollups-node/internal/deps"
"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -55,7 +55,7 @@ func run(cmd *cobra.Command, args []string) {
depsContainers, err := deps.Run(ctx, *depsConfig)
cobra.CheckErr(err)

config.InfoLogger.Println("all deps are up")
fmt.Println("all deps are up")

<-ctx.Done()

Expand Down
10 changes: 5 additions & 5 deletions cmd/cartesi-rollups-cli/root/execute/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
package execute

import (
"fmt"
"os"

"github.com/Khan/genqlient/graphql"
"github.com/cartesi/rollups-node/internal/config"
"github.com/cartesi/rollups-node/pkg/addresses"
"github.com/cartesi/rollups-node/pkg/ethutil"
"github.com/cartesi/rollups-node/pkg/readerclient"
Expand Down Expand Up @@ -70,13 +70,13 @@ func run(cmd *cobra.Command, args []string) {
cobra.CheckErr(err)

if resp.Proof == nil {
config.InfoLogger.Printf("The voucher has no associated proof yet.\n")
fmt.Println("The voucher has no associated proof yet")
os.Exit(0)
}

client, err := ethclient.DialContext(ctx, ethEndpoint)
cobra.CheckErr(err)
config.InfoLogger.Printf("connected to %v\n", ethEndpoint)
fmt.Printf("connected to %v\n", ethEndpoint)

signer, err := ethutil.NewMnemonicSigner(ctx, client, mnemonic, account)
cobra.CheckErr(err)
Expand All @@ -91,7 +91,7 @@ func run(cmd *cobra.Command, args []string) {

proof := readerclient.ConvertToContractProof(resp.Proof)

config.InfoLogger.Printf("executing voucher %d from input %d\n",
fmt.Printf("executing voucher %d from input %d\n",
voucherIndex,
inputIndex,
)
Expand All @@ -106,5 +106,5 @@ func run(cmd *cobra.Command, args []string) {
)
cobra.CheckErr(err)

config.InfoLogger.Printf("The voucher was executed! (tx=%v)\n", txHash)
fmt.Printf("The voucher was executed! (tx=%v)\n", txHash)
}
2 changes: 0 additions & 2 deletions cmd/cartesi-rollups-cli/root/savesnapshot/savesnapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ func init() {
}

func run(cmd *cobra.Command, args []string) {

err := machine.Save(sourceDockerImage, destDir, tempContainerName)

cobra.CheckErr(err)
}
9 changes: 5 additions & 4 deletions cmd/cartesi-rollups-cli/root/send/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
package send

import (
"github.com/cartesi/rollups-node/internal/config"
"fmt"

"github.com/cartesi/rollups-node/pkg/addresses"
"github.com/cartesi/rollups-node/pkg/ethutil"
"github.com/ethereum/go-ethereum/common/hexutil"
Expand Down Expand Up @@ -56,7 +57,7 @@ func run(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
client, err := ethclient.DialContext(ctx, ethEndpoint)
cobra.CheckErr(err)
config.InfoLogger.Printf("connected to %v", ethEndpoint)
fmt.Printf("connected to %v\n", ethEndpoint)

signer, err := ethutil.NewMnemonicSigner(ctx, client, mnemonic, account)
cobra.CheckErr(err)
Expand All @@ -69,9 +70,9 @@ func run(cmd *cobra.Command, args []string) {
book = addresses.GetTestBook()
}

config.InfoLogger.Printf("sending input to %x", book.CartesiDApp)
fmt.Printf("sending input to %x\n", book.CartesiDApp)
inputIndex, err := ethutil.AddInput(ctx, client, book, signer, payload)
cobra.CheckErr(err)

config.InfoLogger.Printf("added input with index %v", inputIndex)
fmt.Printf("added input with index %v\n", inputIndex)
}
10 changes: 5 additions & 5 deletions cmd/cartesi-rollups-cli/root/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
package validate

import (
"fmt"
"os"

"github.com/Khan/genqlient/graphql"
"github.com/cartesi/rollups-node/internal/config"
"github.com/cartesi/rollups-node/pkg/addresses"
"github.com/cartesi/rollups-node/pkg/ethutil"
"github.com/cartesi/rollups-node/pkg/readerclient"
Expand Down Expand Up @@ -62,13 +62,13 @@ func run(cmd *cobra.Command, args []string) {
cobra.CheckErr(err)

if resp.Proof == nil {
config.InfoLogger.Printf("The notice has no associated proof yet.\n")
fmt.Println("The notice has no associated proof yet.")
os.Exit(0)
}

client, err := ethclient.DialContext(ctx, ethEndpoint)
cobra.CheckErr(err)
config.InfoLogger.Printf("connected to %v\n", ethEndpoint)
fmt.Printf("connected to %v\n", ethEndpoint)

var book *addresses.Book
if addressBookFile != "" {
Expand All @@ -80,13 +80,13 @@ func run(cmd *cobra.Command, args []string) {

proof := readerclient.ConvertToContractProof(resp.Proof)

config.InfoLogger.Printf("validating notice %d from input %d with address %x\n",
fmt.Printf("validating notice %d from input %d with address %x\n",
noticeIndex,
inputIndex,
book.CartesiDApp,
)
err = ethutil.ValidateNotice(ctx, client, book, resp.Payload, proof)
cobra.CheckErr(err)

config.InfoLogger.Printf("The notice is valid!\n")
fmt.Println("The notice is valid!")
}
68 changes: 0 additions & 68 deletions cmd/cartesi-rollups-node/handlers.go

This file was deleted.

77 changes: 36 additions & 41 deletions cmd/cartesi-rollups-node/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,73 +5,68 @@ package main

import (
"context"
"log/slog"
"os"
"os/signal"
"syscall"
"time"

"github.com/cartesi/rollups-node/internal/config"
"github.com/cartesi/rollups-node/internal/services"
"github.com/cartesi/rollups-node/internal/node"
"github.com/cartesi/rollups-node/internal/node/config"
"github.com/lmittmann/tint"
)

func main() {
startTime := time.Now()
var s []services.Service

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

if err := validateChainId(
ctx,
config.GetCartesiBlockchainId(),
config.GetCartesiBlockchainHttpEndpoint(),
); err != nil {
config.ErrorLogger.Fatal(err)
}

sunodoValidatorEnabled := config.GetCartesiExperimentalSunodoValidatorEnabled()
if !sunodoValidatorEnabled {
// add Redis first
s = append(s, newRedis())
}

// add services without dependencies
s = append(s, newGraphQLServer())
s = append(s, newIndexer())
s = append(s, newStateServer())
config := config.FromEnv()

// start either the server manager or host runner
if config.GetCartesiFeatureHostMode() {
s = append(s, newHostRunner())
} else {
s = append(s, newServerManager())
}
// setup log
handler := createLogHandler(config)
logger := slog.New(handler)
slog.SetDefault(logger)
slog.Info("starting node", "config", config)

// enable claimer if reader mode and sunodo validator mode are disabled
if !config.GetCartesiFeatureDisableClaimer() && !sunodoValidatorEnabled {
s = append(s, newAuthorityClaimer())
// create the node supervisor
supervisor, err := node.Setup(ctx, config)
if err != nil {
slog.Error("node: exited with error", "error", err)
os.Exit(1)
}

// add services with dependencies
s = append(s, newAdvanceRunner()) // Depends on the server-manager/host-runner
s = append(s, newDispatcher()) // Depends on the state server
s = append(s, newInspectServer()) // Depends on the server-manager/host-runner

s = append(s, newHttpService())

ready := make(chan struct{}, 1)
// logs startup time
ready := make(chan struct{}, 1)
go func() {
select {
case <-ready:
duration := time.Since(startTime)
config.InfoLogger.Printf("rollups-node: ready after %s", duration)
slog.Info("node: ready", "after", duration)
case <-ctx.Done():
}
}()

// start supervisor
supervisor := newSupervisorService(s)
if err := supervisor.Start(ctx, ready); err != nil {
config.ErrorLogger.Print(err)
slog.Error("node: exited with error", "error", err)
os.Exit(1)
}
}

func createLogHandler(c config.NodeConfig) slog.Handler {
if c.Log.Pretty {
opts := &tint.Options{
Level: c.Log.Level,
AddSource: c.Log.Level == slog.LevelDebug,
}
return tint.NewHandler(os.Stdout, opts)
} else {
opts := &slog.HandlerOptions{
Level: c.Log.Level,
AddSource: c.Log.Level == slog.LevelDebug,
}
return slog.NewTextHandler(os.Stdout, opts)
}
}
Loading

0 comments on commit b86786e

Please sign in to comment.