diff --git a/cmd/cartesi-rollups-advancer/root/root.go b/cmd/cartesi-rollups-advancer/root/root.go index 56051f5af..123f64f2d 100644 --- a/cmd/cartesi-rollups-advancer/root/root.go +++ b/cmd/cartesi-rollups-advancer/root/root.go @@ -17,13 +17,13 @@ var ( createInfo = advancer.CreateInfo{ CreateInfo: service.CreateInfo{ Name: "advancer", - ProcOwner: true, EnableSignalHandling: true, TelemetryCreate: true, - TelemetryAddress: ":10001", + TelemetryAddress: ":10002", Impl: &advancerService, }, MaxStartupTime: 10 * time.Second, + InspectAddress: ":10012", } ) @@ -36,6 +36,9 @@ var Cmd = &cobra.Command{ func init() { createInfo.LoadEnv() + Cmd.Flags().StringVar(&createInfo.TelemetryAddress, + "telemetry-address", createInfo.TelemetryAddress, + "telemetry address") Cmd.Flags().Var(&createInfo.LogLevel, "log-level", "log level: debug, info, warn or error") @@ -45,10 +48,13 @@ func init() { Cmd.Flags().DurationVar(&createInfo.MaxStartupTime, "max-startup-time", createInfo.MaxStartupTime, "maximum startup time in seconds") + Cmd.Flags().StringVar(&createInfo.InspectAddress, + "inspect-address", createInfo.InspectAddress, + "inspect address") } func run(cmd *cobra.Command, args []string) { cobra.CheckErr(advancer.Create(&createInfo, &advancerService)) - advancerService.CreateDefaultHandlers("/" + advancerService.Name) + advancerService.CreateDefaultHandlers("") cobra.CheckErr(advancerService.Serve()) } diff --git a/cmd/cartesi-rollups-claimer/root/root.go b/cmd/cartesi-rollups-claimer/root/root.go index 0d38f0987..ba7f002b3 100644 --- a/cmd/cartesi-rollups-claimer/root/root.go +++ b/cmd/cartesi-rollups-claimer/root/root.go @@ -19,10 +19,9 @@ var ( createInfo = claimer.CreateInfo{ CreateInfo: service.CreateInfo{ Name: "claimer", - ProcOwner: true, EnableSignalHandling: true, TelemetryCreate: true, - TelemetryAddress: ":10003", + TelemetryAddress: ":10004", Impl: &claimerService, }, EnableSubmission: true, @@ -42,18 +41,18 @@ func init() { Cmd.Flags().StringVar(&createInfo.TelemetryAddress, "telemetry-address", createInfo.TelemetryAddress, "health check and metrics address and port") - Cmd.Flags().StringVar(&createInfo.BlockchainHttpEndpoint.Value, - "blockchain-http-endpoint", createInfo.BlockchainHttpEndpoint.Value, - "blockchain http endpoint") - Cmd.Flags().DurationVar(&createInfo.PollInterval, - "poll-interval", createInfo.PollInterval, - "poll interval") Cmd.Flags().Var(&createInfo.LogLevel, "log-level", "log level: debug, info, warn or error") Cmd.Flags().BoolVar(&createInfo.LogPretty, "log-color", createInfo.LogPretty, "tint the logs (colored output)") + Cmd.Flags().StringVar(&createInfo.BlockchainHttpEndpoint.Value, + "blockchain-http-endpoint", createInfo.BlockchainHttpEndpoint.Value, + "blockchain http endpoint") + Cmd.Flags().DurationVar(&createInfo.PollInterval, + "poll-interval", createInfo.PollInterval, + "poll interval") Cmd.Flags().DurationVar(&createInfo.MaxStartupTime, "max-startup-time", createInfo.MaxStartupTime, "maximum startup time in seconds") @@ -64,6 +63,6 @@ func init() { func run(cmd *cobra.Command, args []string) { cobra.CheckErr(claimer.Create(&createInfo, &claimerService)) - claimerService.CreateDefaultHandlers("/" + claimerService.Name) + claimerService.CreateDefaultHandlers("") cobra.CheckErr(claimerService.Serve()) } diff --git a/cmd/cartesi-rollups-evm-reader/root/root.go b/cmd/cartesi-rollups-evm-reader/root/root.go index d4b1a63ae..2d4a6f3bc 100644 --- a/cmd/cartesi-rollups-evm-reader/root/root.go +++ b/cmd/cartesi-rollups-evm-reader/root/root.go @@ -23,10 +23,9 @@ var ( createInfo = evmreader.CreateInfo{ CreateInfo: service.CreateInfo{ Name: "evm-reader", - ProcOwner: true, EnableSignalHandling: true, TelemetryCreate: true, - TelemetryAddress: ":10000", + TelemetryAddress: ":10001", Impl: &readerService, }, EvmReaderPersistentConfig: model.EvmReaderPersistentConfig{ @@ -47,45 +46,40 @@ var Cmd = &cobra.Command{ func init() { createInfo.LoadEnv() - + Cmd.Flags().StringVar(&createInfo.TelemetryAddress, + "telemetry-address", createInfo.TelemetryAddress, + "telemetry address") + Cmd.Flags().Var(&createInfo.LogLevel, + "log-level", + "log level: debug, info, warn or error") + Cmd.Flags().BoolVar(&createInfo.LogPretty, + "log-color", createInfo.LogPretty, + "tint the logs (colored output)") Cmd.Flags().StringVarP(&DefaultBlockString, "default-block", "d", DefaultBlockString, `Default block to be used when fetching new blocks. One of 'latest', 'safe', 'pending', 'finalized'`) - Cmd.Flags().StringVarP(&createInfo.PostgresEndpoint.Value, "postgres-endpoint", "p", createInfo.PostgresEndpoint.Value, "Postgres endpoint") - Cmd.Flags().StringVarP(&createInfo.BlockchainHttpEndpoint.Value, "blockchain-http-endpoint", "b", createInfo.BlockchainHttpEndpoint.Value, "Blockchain HTTP Endpoint") - Cmd.Flags().StringVarP(&createInfo.BlockchainWsEndpoint.Value, "blockchain-ws-endpoint", "w", createInfo.BlockchainWsEndpoint.Value, "Blockchain WS Endpoint") - Cmd.Flags().Var(&inputBoxAddress, "inputbox-address", "Input Box contract address") - Cmd.Flags().Uint64VarP(&createInfo.InputBoxDeploymentBlock, - "inputbox-block-number", - "n", - 0, + "inputbox-block-number", "n", 0, "Input Box deployment block number") - Cmd.Flags().Var(&createInfo.LogLevel, - "log-level", - "log level: debug, info, warn or error") - Cmd.Flags().BoolVar(&createInfo.LogPretty, - "log-color", createInfo.LogPretty, - "tint the logs (colored output)") Cmd.Flags().DurationVar(&createInfo.MaxStartupTime, "max-startup-time", createInfo.MaxStartupTime, "maximum startup time in seconds") @@ -102,6 +96,6 @@ func run(cmd *cobra.Command, args []string) { } cobra.CheckErr(evmreader.Create(&createInfo, &readerService)) - readerService.CreateDefaultHandlers("/" + readerService.Name) + readerService.CreateDefaultHandlers("") cobra.CheckErr(readerService.Serve()) } diff --git a/cmd/cartesi-rollups-node/root/root.go b/cmd/cartesi-rollups-node/root/root.go index fb8e5feff..519146809 100644 --- a/cmd/cartesi-rollups-node/root/root.go +++ b/cmd/cartesi-rollups-node/root/root.go @@ -19,10 +19,9 @@ var ( createInfo = node.CreateInfo{ CreateInfo: service.CreateInfo{ Name: "cartesi-rollups-node", - ProcOwner: true, EnableSignalHandling: true, TelemetryCreate: true, - TelemetryAddress: ":10001", + TelemetryAddress: ":10000", Impl: &nodeService, }, MaxStartupTime: 10 * time.Second, @@ -38,15 +37,18 @@ var Cmd = &cobra.Command{ func init() { createInfo.LoadEnv() - Cmd.Flags().BoolVar(&createInfo.EnableClaimSubmission, - "claim-submission", createInfo.EnableClaimSubmission, - "enable or disable claim submission (reader mode)") + Cmd.Flags().StringVar(&createInfo.TelemetryAddress, + "telemetry-address", createInfo.TelemetryAddress, + "telemetry address") Cmd.Flags().Var(&createInfo.LogLevel, "log-level", "log level: debug, info, warn or error") Cmd.Flags().BoolVar(&createInfo.LogPretty, "log-color", createInfo.LogPretty, "tint the logs (colored output)") + Cmd.Flags().BoolVar(&createInfo.EnableClaimSubmission, + "claim-submission", createInfo.EnableClaimSubmission, + "enable or disable claim submission (reader mode)") Cmd.Flags().DurationVar(&createInfo.MaxStartupTime, "max-startup-time", createInfo.MaxStartupTime, "maximum startup time in seconds") diff --git a/cmd/cartesi-rollups-validator/root/root.go b/cmd/cartesi-rollups-validator/root/root.go index 68b5b117b..18c656d24 100644 --- a/cmd/cartesi-rollups-validator/root/root.go +++ b/cmd/cartesi-rollups-validator/root/root.go @@ -17,10 +17,9 @@ var ( createInfo = validator.CreateInfo{ CreateInfo: service.CreateInfo{ Name: "validator", - ProcOwner: true, EnableSignalHandling: true, TelemetryCreate: true, - TelemetryAddress: ":10002", + TelemetryAddress: ":10003", Impl: &validatorService, }, } @@ -54,6 +53,6 @@ func init() { func run(cmd *cobra.Command, args []string) { cobra.CheckErr(validator.Create(&createInfo, &validatorService)) - validatorService.CreateDefaultHandlers("/" + validatorService.Name) + validatorService.CreateDefaultHandlers("") cobra.CheckErr(validatorService.Serve()) } diff --git a/internal/advancer/advancer.go b/internal/advancer/advancer.go index 5b28b965a..8d296cba4 100644 --- a/internal/advancer/advancer.go +++ b/internal/advancer/advancer.go @@ -46,9 +46,11 @@ type IAdvancerMachines interface { type Service struct { service.Service - repository IAdvancerRepository - machines IAdvancerMachines - inspector inspect.Inspector + repository IAdvancerRepository + machines IAdvancerMachines + inspector inspect.Inspector + HTTPServer *http.Server + HTTPServerFunc func() error } type CreateInfo struct { @@ -57,23 +59,22 @@ type CreateInfo struct { PostgresEndpoint config.Redacted[string] PostgresSslMode bool Repository *repository.Database - HttpAddress string - HttpPort int MachineServerVerbosity config.Redacted[cartesimachine.ServerVerbosity] Machines *machines.Machines MaxStartupTime time.Duration + InspectAddress string + InspectServeMux *http.ServeMux } func (c *CreateInfo) LoadEnv() { c.PostgresEndpoint.Value = config.GetPostgresEndpoint() c.PollInterval = config.GetAdvancerPollingInterval() - c.HttpAddress = config.GetHttpAddress() - c.HttpPort = config.GetHttpPort() c.MachineServerVerbosity.Value = cartesimachine.ServerVerbosity(config.GetMachineServerVerbosity()) c.LogLevel = service.LogLevel(config.GetLogLevel()) c.LogPretty = config.GetLogPrettyEnabled() c.MaxStartupTime = config.GetMaxStartupTime() + c.InspectAddress = config.GetInspectAddress() } func Create(c *CreateInfo, s *Service) error { @@ -110,19 +111,17 @@ func Create(c *CreateInfo, s *Service) error { logger = logger.With("service", "inspect") s.inspector = inspect.Inspector{ IInspectMachines: c.Machines, - Logger: logger, - } - if s.Service.ServeMux == nil { - if c.CreateInfo.ServeMux == nil { - c.ServeMux = http.NewServeMux() - } - s.ServeMux = c.ServeMux + Logger: logger, + ServeMux: http.NewServeMux(), } - s.ServeMux.Handle("/inspect/{dapp}", + s.inspector.ServeMux.Handle("/inspect/{dapp}", services.CorsMiddleware(http.Handler(&s.inspector))) - s.ServeMux.Handle("/inspect/{dapp}/{payload}", + s.inspector.ServeMux.Handle("/inspect/{dapp}/{payload}", services.CorsMiddleware(http.Handler(&s.inspector))) + s.HTTPServer, s.HTTPServerFunc = s.inspector.CreateInspectServer( + c.InspectAddress, 3, 5*time.Second, s.inspector.ServeMux) + go s.HTTPServerFunc() } return nil }) diff --git a/internal/claimer/claimer.go b/internal/claimer/claimer.go index cfe3d6bf4..bb17115fb 100644 --- a/internal/claimer/claimer.go +++ b/internal/claimer/claimer.go @@ -94,8 +94,9 @@ func (c *CreateInfo) LoadEnv() { c.BlockchainHttpEndpoint.Value = config.GetBlockchainHttpEndpoint() c.PostgresEndpoint.Value = config.GetPostgresEndpoint() c.PollInterval = config.GetClaimerPollingInterval() - c.LogLevel = service.LogLevel(config.GetLogLevel()) c.MaxStartupTime = config.GetMaxStartupTime() + c.LogLevel = service.LogLevel(config.GetLogLevel()) + c.LogPretty = config.GetLogPrettyEnabled() } func Create(c *CreateInfo, s *Service) error { diff --git a/internal/config/generate/Config.toml b/internal/config/generate/Config.toml index 718f7e4bc..f17639a17 100644 --- a/internal/config/generate/Config.toml +++ b/internal/config/generate/Config.toml @@ -209,18 +209,11 @@ for more information.""" # HTTP # -[http.CARTESI_HTTP_ADDRESS] -default = "127.0.0.1" +[http.CARTESI_INSPECT_ADDRESS] +default = ":10012" go-type = "string" description = """ -HTTP address for the node.""" - -[http.CARTESI_HTTP_PORT] -default = "10000" -go-type = "int" -description = """ -HTTP port for the node. -The node will also use the 20 ports after this one for internal services.""" +HTTP address for inspect.""" # # Temporary diff --git a/internal/config/generated.go b/internal/config/generated.go index a798fc6b2..7ece2a595 100644 --- a/internal/config/generated.go +++ b/internal/config/generated.go @@ -336,26 +336,14 @@ func GetFeatureMachineHashCheckEnabled() bool { return val } -func GetHttpAddress() string { - s, ok := os.LookupEnv("CARTESI_HTTP_ADDRESS") +func GetInspectAddress() string { + s, ok := os.LookupEnv("CARTESI_INSPECT_ADDRESS") if !ok { - s = "127.0.0.1" + s = ":10012" } val, err := toString(s) if err != nil { - panic(fmt.Sprintf("failed to parse CARTESI_HTTP_ADDRESS: %v", err)) - } - return val -} - -func GetHttpPort() int { - s, ok := os.LookupEnv("CARTESI_HTTP_PORT") - if !ok { - s = "10000" - } - val, err := toInt(s) - if err != nil { - panic(fmt.Sprintf("failed to parse CARTESI_HTTP_PORT: %v", err)) + panic(fmt.Sprintf("failed to parse CARTESI_INSPECT_ADDRESS: %v", err)) } return val } diff --git a/internal/evmreader/retrypolicy_application_delegator.go b/internal/evmreader/retrypolicy_application_delegator.go index deff15551..0f4509f89 100644 --- a/internal/evmreader/retrypolicy_application_delegator.go +++ b/internal/evmreader/retrypolicy_application_delegator.go @@ -24,13 +24,13 @@ func NewApplicationWithRetryPolicy( delegate ApplicationContract, maxRetries uint64, delayBetweenCalls time.Duration, - logger *slog.Logger, + logger *slog.Logger, ) *ApplicationRetryPolicyDelegator { return &ApplicationRetryPolicyDelegator{ delegate: delegate, maxRetries: maxRetries, delayBetweenCalls: delayBetweenCalls, - logger: logger, + logger: logger, } } diff --git a/internal/evmreader/retrypolicy_consensus_delegator.go b/internal/evmreader/retrypolicy_consensus_delegator.go index 0ca10fae7..662efd250 100644 --- a/internal/evmreader/retrypolicy_consensus_delegator.go +++ b/internal/evmreader/retrypolicy_consensus_delegator.go @@ -28,13 +28,13 @@ func NewConsensusWithRetryPolicy( delegate ConsensusContract, maxRetries uint64, delayBetweenCalls time.Duration, - logger *slog.Logger, + logger *slog.Logger, ) *ConsensusRetryPolicyDelegator { return &ConsensusRetryPolicyDelegator{ delegate: delegate, maxRetries: maxRetries, delayBetweenCalls: delayBetweenCalls, - logger: logger, + logger: logger, } } diff --git a/internal/evmreader/retrypolicy_ethclient_delegator.go b/internal/evmreader/retrypolicy_ethclient_delegator.go index a81e5d6cc..663f7aed4 100644 --- a/internal/evmreader/retrypolicy_ethclient_delegator.go +++ b/internal/evmreader/retrypolicy_ethclient_delegator.go @@ -33,7 +33,7 @@ func NewEhtClientWithRetryPolicy( delegate: delegate, maxRetries: maxRetries, delayBetweenCalls: delayBetweenCalls, - logger: logger, + logger: logger, } } diff --git a/internal/evmreader/retrypolicy_ethwsclient_delegator.go b/internal/evmreader/retrypolicy_ethwsclient_delegator.go index 6df5b1694..dbda4224b 100644 --- a/internal/evmreader/retrypolicy_ethwsclient_delegator.go +++ b/internal/evmreader/retrypolicy_ethwsclient_delegator.go @@ -30,7 +30,7 @@ func NewEthWsClientWithRetryPolicy( delegate: delegate, maxRetries: maxRetries, delayBetweenCalls: delayBetweenCalls, - logger: logger, + logger: logger, } } diff --git a/internal/evmreader/retrypolicy_inputsource_delegator.go b/internal/evmreader/retrypolicy_inputsource_delegator.go index 4d042fad2..e05a45ce8 100644 --- a/internal/evmreader/retrypolicy_inputsource_delegator.go +++ b/internal/evmreader/retrypolicy_inputsource_delegator.go @@ -25,7 +25,7 @@ func NewInputSourceWithRetryPolicy( delegate InputSource, maxRetries uint64, delay time.Duration, - logger *slog.Logger, + logger *slog.Logger, ) *InputSourceWithRetryPolicyDelegator { return &InputSourceWithRetryPolicyDelegator{ delegate: delegate, diff --git a/internal/inspect/inspect.go b/internal/inspect/inspect.go index 1fd6d3048..f9f85b6fa 100644 --- a/internal/inspect/inspect.go +++ b/internal/inspect/inspect.go @@ -12,6 +12,7 @@ import ( "log/slog" "net/http" "net/url" + "time" "github.com/cartesi/rollups-node/internal/advancer/machines" . "github.com/cartesi/rollups-node/internal/model" @@ -27,7 +28,8 @@ var ( type Inspector struct { IInspectMachines - Logger *slog.Logger + Logger *slog.Logger + ServeMux *http.ServeMux } type ReportResponse struct { @@ -41,6 +43,37 @@ type InspectResponse struct { ProcessedInputs uint64 `json:"processed_input_count"` } +func (s *Inspector) CreateInspectServer( + addr string, + maxRetries int, + retryInterval time.Duration, + mux *http.ServeMux, +) (*http.Server, func() error) { + server := &http.Server{ + Addr: addr, + Handler: mux, + ErrorLog: slog.NewLogLogger(s.Logger.Handler(), slog.LevelError), + } + return server, func() error { + s.Logger.Info("Create Inspect Server", "addr", addr) + var err error = nil + for retry := 0; retry < maxRetries+1; retry++ { + switch err = server.ListenAndServe(); err { + case http.ErrServerClosed: + return nil + default: + s.Logger.Error("http", + "error", err, + "try", retry+1, + "maxRetries", maxRetries, + "error", err) + } + time.Sleep(retryInterval) + } + return err + } +} + func (inspect *Inspector) ServeHTTP(w http.ResponseWriter, r *http.Request) { var ( dapp Address diff --git a/internal/inspect/inspect_test.go b/internal/inspect/inspect_test.go index 3c8bc64b6..7e05c3180 100644 --- a/internal/inspect/inspect_test.go +++ b/internal/inspect/inspect_test.go @@ -4,13 +4,13 @@ package inspect import ( - "log/slog" "bytes" "context" crand "crypto/rand" "encoding/json" "fmt" "io" + "log/slog" "net/http" "net/url" "strings" @@ -151,7 +151,7 @@ func (s *InspectSuite) setup() (*Inspector, Address, Hash) { machines.Map[app] = &MockMachine{} inspect := &Inspector{ IInspectMachines: machines, - Logger: service.NewLogger(slog.LevelDebug, true), + Logger: service.NewLogger(slog.LevelDebug, true), } payload := randomHash() return inspect, app, payload diff --git a/internal/node/node.go b/internal/node/node.go index c9208c150..79633f0ed 100644 --- a/internal/node/node.go +++ b/internal/node/node.go @@ -27,7 +27,6 @@ type CreateInfo struct { BlockchainHttpEndpoint config.Redacted[string] BlockchainID uint64 - HTTPEndpoint config.Redacted[string] PostgresEndpoint config.Redacted[string] EnableClaimSubmission bool MaxStartupTime time.Duration @@ -49,10 +48,6 @@ func (c *CreateInfo) LoadEnv() { c.MaxStartupTime = config.GetMaxStartupTime() c.LogLevel = service.LogLevel(config.GetLogLevel()) c.LogPretty = config.GetLogPrettyEnabled() - - httpAddress := config.GetHttpAddress() - httpPort := config.GetHttpPort() - c.HTTPEndpoint.Value = fmt.Sprintf("%v:%v", httpAddress, httpPort) } func Create(c *CreateInfo, s *Service) error { @@ -103,7 +98,7 @@ func createServices(c *CreateInfo, s *Service) error { numChildren++ go func() { - ch <- newEVMReader(c, s.Logger, s.Repository) + ch <- newEVMReader(c, s.Logger, s.Repository, s.ServeMux) }() numChildren++ @@ -113,12 +108,12 @@ func createServices(c *CreateInfo, s *Service) error { numChildren++ go func() { - ch <- newValidator(c, s.Logger, s.Repository) + ch <- newValidator(c, s.Logger, s.Repository, s.ServeMux) }() numChildren++ go func() { - ch <- newClaimer(c, s.Logger, s.Repository) + ch <- newClaimer(c, s.Logger, s.Repository, s.ServeMux) }() for range numChildren { @@ -173,13 +168,19 @@ func newEVMReader( nc *CreateInfo, logger *slog.Logger, database *repository.Database, + serveMux *http.ServeMux, ) service.IService { - s := evmreader.Service{} + s := evmreader.Service{ + Service: service.Service{ + ServeMux: serveMux, + }, + } c := evmreader.CreateInfo{ CreateInfo: service.CreateInfo{ - Name: "evm-reader", - Impl: &s, - ProcOwner: true, // TODO: Remove this after updating supervisor + Name: "evm-reader", + Impl: &s, + ServeMux: serveMux, + EnableSignalHandling: true, }, EvmReaderPersistentConfig: model.EvmReaderPersistentConfig{ DefaultBlock: model.DefaultBlockStatusSafe, @@ -196,6 +197,7 @@ func newEVMReader( "error", err) panic(err) } + s.CreateDefaultHandlers("/" + s.Name) return &s } @@ -205,13 +207,17 @@ func newAdvancer( database *repository.Database, serveMux *http.ServeMux, ) service.IService { - s := advancer.Service{} + s := advancer.Service{ + Service: service.Service{ + ServeMux: serveMux, + }, + } c := advancer.CreateInfo{ CreateInfo: service.CreateInfo{ - Name: "advancer", - Impl: &s, - ProcOwner: true, - ServeMux: serveMux, + Name: "advancer", + Impl: &s, + ServeMux: serveMux, + EnableSignalHandling: true, }, Repository: database, } @@ -225,6 +231,7 @@ func newAdvancer( "error", err) panic(err) } + s.CreateDefaultHandlers("/" + s.Name) return &s } @@ -232,13 +239,19 @@ func newValidator( nc *CreateInfo, logger *slog.Logger, database *repository.Database, + serveMux *http.ServeMux, ) service.IService { - s := validator.Service{} + s := validator.Service{ + Service: service.Service{ + ServeMux: serveMux, + }, + } c := validator.CreateInfo{ CreateInfo: service.CreateInfo{ - Name: "validator", - Impl: &s, - ProcOwner: true, + Name: "validator", + Impl: &s, + ServeMux: serveMux, + EnableSignalHandling: true, }, Repository: database, } @@ -252,6 +265,7 @@ func newValidator( "error", err) panic(err) } + s.CreateDefaultHandlers("/" + s.Name) return &s } @@ -259,13 +273,18 @@ func newClaimer( nc *CreateInfo, logger *slog.Logger, database *repository.Database, + serveMux *http.ServeMux, ) service.IService { - s := claimer.Service{} + s := claimer.Service{ + Service: service.Service{ + ServeMux: serveMux, + }, + } c := claimer.CreateInfo{ CreateInfo: service.CreateInfo{ - Name: "claimer", - Impl: &s, - ProcOwner: true, + Name: "claimer", + Impl: &s, + EnableSignalHandling: true, }, Repository: database, } @@ -280,5 +299,6 @@ func newClaimer( "error", err) panic(err) } + s.CreateDefaultHandlers("/" + s.Name) return &s } diff --git a/internal/repository/base.go b/internal/repository/base.go index d047441de..1c2b957e7 100644 --- a/internal/repository/base.go +++ b/internal/repository/base.go @@ -18,7 +18,7 @@ import ( ) type Database struct { - db *pgxpool.Pool + db *pgxpool.Pool Logger *slog.Logger } @@ -80,7 +80,7 @@ func Connect( } pgInstance = &Database{ - db: dbpool, + db: dbpool, Logger: logger, } }) diff --git a/pkg/rollupsmachine/machine.go b/pkg/rollupsmachine/machine.go index 7b0561ced..d0c535e8f 100644 --- a/pkg/rollupsmachine/machine.go +++ b/pkg/rollupsmachine/machine.go @@ -69,7 +69,7 @@ type rollupsMachine struct { inner cartesimachine.CartesiMachine inc, max Cycle - logger *slog.Logger + logger *slog.Logger } // New checks if the provided cartesimachine.CartesiMachine is in a valid state to receive @@ -81,9 +81,9 @@ func New(ctx context.Context, logger *slog.Logger, ) (RollupsMachine, error) { machine := &rollupsMachine{ - inner: inner, - inc: inc, - max: max, + inner: inner, + inc: inc, + max: max, logger: logger, } @@ -111,9 +111,9 @@ func (machine *rollupsMachine) Fork(ctx context.Context) (RollupsMachine, error) return nil, err } return &rollupsMachine{ - inner: inner, - inc: machine.inc, - max: machine.max, + inner: inner, + inc: machine.inc, + max: machine.max, logger: machine.logger, }, nil } diff --git a/pkg/rollupsmachine/machine_test.go b/pkg/rollupsmachine/machine_test.go index 4004721eb..a9f7ca47e 100644 --- a/pkg/rollupsmachine/machine_test.go +++ b/pkg/rollupsmachine/machine_test.go @@ -58,7 +58,7 @@ type NewSuite struct { acceptSnapshot *snapshot.Snapshot rejectSnapshot *snapshot.Snapshot - logger *slog.Logger + logger *slog.Logger } func (s *NewSuite) SetupSuite() { @@ -203,7 +203,7 @@ type AdvanceSuite struct { snapshotEcho *snapshot.Snapshot snapshotReject *snapshot.Snapshot address string - logger *slog.Logger + logger *slog.Logger } func (s *AdvanceSuite) SetupSuite() { @@ -366,7 +366,7 @@ type InspectSuite struct { suite.Suite snapshotEcho *snapshot.Snapshot address string - logger *slog.Logger + logger *slog.Logger } func (s *InspectSuite) SetupSuite() { @@ -451,9 +451,9 @@ type UnitSuite struct{ suite.Suite } func (_ *UnitSuite) newMachines() (*CartesiMachineMock, *rollupsMachine) { mock := new(CartesiMachineMock) machine := &rollupsMachine{ - inner: mock, - inc: defaultInc, - max: defaultMax, + inner: mock, + inc: defaultInc, + max: defaultMax, logger: service.NewLogger(slog.LevelDebug, true), } return mock, machine diff --git a/pkg/service/service.go b/pkg/service/service.go index d6108f81c..f10f094f4 100644 --- a/pkg/service/service.go +++ b/pkg/service/service.go @@ -95,7 +95,6 @@ type CreateInfo struct { Impl ServiceImpl LogLevel LogLevel LogPretty bool - ProcOwner bool ServeMux *http.ServeMux Context context.Context PollInterval time.Duration @@ -106,19 +105,19 @@ type CreateInfo struct { // Service stores runtime information. type Service struct { - Running atomic.Bool - Name string - Impl ServiceImpl - Logger *slog.Logger - Ticker *time.Ticker - PollInterval time.Duration - Context context.Context - Cancel context.CancelFunc - Sighup chan os.Signal // SIGHUP to reload - Sigint chan os.Signal // SIGINT to exit gracefully - ServeMux *http.ServeMux - HTTPServer *http.Server - HTTPServerFunc func() error + Running atomic.Bool + Name string + Impl ServiceImpl + Logger *slog.Logger + Ticker *time.Ticker + PollInterval time.Duration + Context context.Context + Cancel context.CancelFunc + Sighup chan os.Signal // SIGHUP to reload + Sigint chan os.Signal // SIGINT to exit gracefully + ServeMux *http.ServeMux + Telemetry *http.Server + TelemetryFunc func() error } // Create a service by: @@ -151,36 +150,29 @@ func Create(c *CreateInfo, s *Service) error { s.Context, s.Cancel = context.WithCancel(c.Context) } - if c.ProcOwner { - // ticker - if s.Ticker == nil { - if c.PollInterval == 0 { - c.PollInterval = 60 * time.Second - } - s.PollInterval = c.PollInterval - s.Ticker = time.NewTicker(s.PollInterval) + // ticker + if s.Ticker == nil { + if c.PollInterval == 0 { + c.PollInterval = 60 * time.Second } + s.PollInterval = c.PollInterval + s.Ticker = time.NewTicker(s.PollInterval) + } - // signal handling - if s.Sighup == nil { - s.Sighup = make(chan os.Signal, 1) - signal.Notify(s.Sighup, syscall.SIGHUP) - } - if s.Sigint == nil { - s.Sigint = make(chan os.Signal, 1) - signal.Notify(s.Sigint, syscall.SIGINT) - } + // signal handling + if s.Sighup == nil { + s.Sighup = make(chan os.Signal, 1) + signal.Notify(s.Sighup, syscall.SIGHUP) + } + if s.Sigint == nil { + s.Sigint = make(chan os.Signal, 1) + signal.Notify(s.Sigint, syscall.SIGINT) } // telemetry if c.TelemetryCreate { if s.ServeMux == nil { if c.ServeMux == nil { - if !c.ProcOwner { - s.Logger.Warn("Create:Created a new ServeMux", - "ProcOwner", c.ProcOwner, - "LogLevel", c.LogLevel) - } c.ServeMux = http.NewServeMux() } s.ServeMux = c.ServeMux @@ -188,21 +180,12 @@ func Create(c *CreateInfo, s *Service) error { if c.TelemetryAddress == "" { c.TelemetryAddress = ":8080" } - s.HTTPServer, s.HTTPServerFunc = s.CreateDefaultTelemetry( + s.Telemetry, s.TelemetryFunc = s.CreateDefaultTelemetry( c.TelemetryAddress, 3, 5*time.Second, s.ServeMux) - go s.HTTPServerFunc() + go s.TelemetryFunc() } - // ProcOwner will be ready on the call to Serve - if c.ProcOwner { - s.Logger.Info("Create", - "LogLevel", c.LogLevel, - "pid", os.Getpid()) - } else { - s.Running.Store(true) - s.Logger.Info("Create", - "LogLevel", c.LogLevel) - } + s.Logger.Info("Create", "LogLevel", c.LogLevel, "pid", os.Getpid()) return nil } @@ -249,8 +232,8 @@ func (s *Service) Tick() []error { func (s *Service) Stop(force bool) []error { start := time.Now() errs := s.Impl.Stop(force) - if s.HTTPServer != nil { - s.HTTPServer.Shutdown(s.Context) + if s.Telemetry != nil { + s.Telemetry.Shutdown(s.Context) } elapsed := time.Since(start) @@ -319,7 +302,7 @@ func WithTimeout(limit time.Duration, fn func() error) error { case err := <-ch: return err case <-deadline: - return fmt.Errorf("Time limit exceded") + return fmt.Errorf("Time limit exceeded") } } @@ -341,7 +324,7 @@ func (s *Service) CreateDefaultTelemetry( ErrorLog: slog.NewLogLogger(s.Logger.Handler(), slog.LevelError), } return server, func() error { - s.Logger.Info("Telemetry", "service", s.Name, "addr", addr) + s.Logger.Info("Telemetry", "addr", addr) var err error = nil for retry := 0; retry < maxRetries+1; retry++ { switch err = server.ListenAndServe(); err {