Skip to content

Commit

Permalink
Handle sigterm [#3398]
Browse files Browse the repository at this point in the history
And remove the service code
  • Loading branch information
firelizzard18 committed Sep 19, 2023
1 parent adb1d2b commit 8d7ec3e
Show file tree
Hide file tree
Showing 10 changed files with 59 additions and 288 deletions.
39 changes: 12 additions & 27 deletions cmd/accumulated/cmd_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ import (
tmconfig "github.com/cometbft/cometbft/config"
service2 "github.com/cometbft/cometbft/libs/service"
"github.com/fatih/color"
"github.com/kardianos/service"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"gitlab.com/accumulatenetwork/accumulate/internal/logging"
"gitlab.com/accumulatenetwork/accumulate/pkg/database/keyvalue/badger"
"gitlab.com/accumulatenetwork/accumulate/test/testing"
"golang.org/x/exp/slog"
)

var cmdRun = &cobra.Command{
Expand Down Expand Up @@ -90,45 +90,35 @@ func initRunFlags(cmd *cobra.Command, forService bool) {
func runNode(cmd *cobra.Command, _ []string) (string, error) {
prog := NewProgram(cmd, singleNodeWorkDir, nil)

svc, err := service.New(prog, serviceConfig)
if err != nil {
return "", err
}

logger, err := svc.Logger(nil)
if err != nil {
return "", err
}

if flagRun.CiStopAfter != 0 {
go watchDog(prog, svc, flagRun.CiStopAfter)
go watchDog(prog, flagRun.CiStopAfter)
}
color.HiGreen("------ starting a new node ------")

err = svc.Run()
err := prog.Run()
if err != nil {
//if it is already stopped, that is ok.
if !errors.Is(err, service2.ErrAlreadyStopped) {
_ = logger.Error(err)
slog.Error("Service failed", err)
return "", err
}
}
return "shutdown complete", nil
}

func watchDog(prog *Program, svc service.Service, duration time.Duration) {
func watchDog(prog *Program, duration time.Duration) {
time.Sleep(duration)

//this will cause tendermint to stop and exit cleanly.
_ = prog.Stop(svc)
_ = prog.Stop()

//the following will stop the Run()
interrupt(syscall.Getpid())
}

type logAnnotator func(io.Writer, string, bool) io.Writer

func newLogWriter(s service.Service) func(string, logAnnotator) (io.Writer, error) {
func newLogWriter() func(string, logAnnotator) (io.Writer, error) {
// Each log file writer must be created once, otherwise different copies
// will step on each other
var logFile *rotateWriter
Expand Down Expand Up @@ -156,17 +146,12 @@ func newLogWriter(s service.Service) func(string, logAnnotator) (io.Writer, erro
return func(format string, annotate logAnnotator) (io.Writer, error) {
var mainWriter io.Writer
var err error
if !service.Interactive() && s != nil {
mainWriter, err = logging.NewServiceLogger(s, format)
check(err)
} else {
mainWriter = os.Stderr
if annotate != nil {
mainWriter = annotate(mainWriter, format, true)
}
mainWriter, err = logging.NewConsoleWriterWith(mainWriter, format)
check(err)
mainWriter = os.Stderr
if annotate != nil {
mainWriter = annotate(mainWriter, format, true)
}
mainWriter, err = logging.NewConsoleWriterWith(mainWriter, format)
check(err)

var writers multiWriter
writers = append(writers, mainWriter)
Expand Down
2 changes: 1 addition & 1 deletion cmd/accumulated/cmd_run_devnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func runDevNet(*cobra.Command, []string) {
didStop := make(chan struct{}, len(vals)*2+len(bsns))
done := new(sync.WaitGroup)

logWriter := newLogWriter(nil)
logWriter := newLogWriter()

var daemons []*accumulated.Daemon
started := new(sync.WaitGroup)
Expand Down
36 changes: 4 additions & 32 deletions cmd/accumulated/cmd_run_dual.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,13 @@ package main

import (
"net/http"
"os"
"os/signal"
"time"

service2 "github.com/cometbft/cometbft/libs/service"
"github.com/kardianos/service"
"github.com/spf13/cobra"
"gitlab.com/accumulatenetwork/accumulate/pkg/database/keyvalue/badger"
"gitlab.com/accumulatenetwork/accumulate/pkg/errors"
"golang.org/x/exp/slog"
)

var cmdRunDual = &cobra.Command{
Expand Down Expand Up @@ -67,41 +65,15 @@ func runDualNode(cmd *cobra.Command, args []string) (string, error) {

flagRun.EnableTimingLogs = flagRunDual.EnableTimingLogs

// TODO: This only works on POSIX platforms. We need to seriously refactor
// how service mode works.
serviceConfig.Option = service.KeyValue{
"RunWait": func() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt)
defer signal.Stop(sigChan)

select {
case <-prog.primary.Done():
case <-prog.secondary.Done():
case <-sigChan:
}
},
}

svc, err := service.New(prog, serviceConfig)
if err != nil {
return "", err
}

logger, err := svc.Logger(nil)
if err != nil {
return "", err
}

if flagRunDual.CiStopAfter != 0 {
go watchDog(prog, svc, flagRunDual.CiStopAfter)
go watchDog(prog, flagRunDual.CiStopAfter)
}

err = svc.Run()
err := prog.Run()
if err != nil {
//if it is already stopped, that is ok.
if !errors.Is(err, service2.ErrAlreadyStopped) {
_ = logger.Error(err)
slog.Error("Service failed", err)
return "", err
}
}
Expand Down
106 changes: 0 additions & 106 deletions cmd/accumulated/cmd_service.go

This file was deleted.

16 changes: 1 addition & 15 deletions cmd/accumulated/main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2022 The Accumulate Authors
// Copyright 2023 The Accumulate Authors
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
Expand Down Expand Up @@ -83,17 +83,3 @@ func warnf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
}
}

func composeArgs(fn cobra.PositionalArgs, fns ...cobra.PositionalArgs) cobra.PositionalArgs {
if len(fns) == 0 {
return fn
}

rest := composeArgs(fns[0], fns[1:]...)
return func(cmd *cobra.Command, args []string) error {
if err := fn(cmd, args); err != nil {
return err
}
return rest(cmd, args)
}
}
44 changes: 34 additions & 10 deletions cmd/accumulated/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
package main

import (
"context"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"syscall"

"github.com/kardianos/service"
"github.com/spf13/cobra"
"gitlab.com/accumulatenetwork/accumulate/internal/node/config"
accumulated "gitlab.com/accumulatenetwork/accumulate/internal/node/daemon"
Expand Down Expand Up @@ -44,17 +46,25 @@ func singleNodeWorkDir(cmd *cobra.Command) (string, error) {
return flagMain.WorkDir, nil
}

if service.Interactive() {
fmt.Fprint(os.Stderr, "Error: at least one of --work-dir or --node is required\n")
printUsageAndExit1(cmd, []string{})
return "", nil // Not reached
} else {
return "", fmt.Errorf("at least one of --work-dir or --node is required")
fmt.Fprint(os.Stderr, "Error: at least one of --work-dir or --node is required\n")
printUsageAndExit1(cmd, []string{})
return "", nil // Not reached
}

func (p *Program) Run() error {
ctx := contextForMainProcess(context.Background())

err := p.Start()
if err != nil {
return err
}

<-ctx.Done()
return p.Stop()
}

func (p *Program) Start(s service.Service) (err error) {
logWriter := newLogWriter(s)
func (p *Program) Start() (err error) {
logWriter := newLogWriter()

primaryDir, err := p.primaryDir(p.cmd)
if err != nil {
Expand Down Expand Up @@ -105,7 +115,7 @@ func (p *Program) Start(s service.Service) (err error) {
return startDual(p.primary, p.secondary)
}

func (p *Program) Stop(service.Service) error {
func (p *Program) Stop() error {
if p.secondary == nil {
return p.primary.Stop()
}
Expand Down Expand Up @@ -158,3 +168,17 @@ func stopDual(primary, secondary *accumulated.Daemon) error {
errg.Go(secondary.Stop)
return errg.Wait()
}

func contextForMainProcess(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

go func() {
<-sigs
signal.Stop(sigs)
cancel()
}()

return ctx
}
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ require (
github.com/go-playground/validator/v10 v10.9.0
github.com/golang/mock v1.6.0 // indirect
github.com/golangci/golangci-lint v1.52.2
github.com/kardianos/service v1.2.0
github.com/pelletier/go-toml v1.9.5
github.com/prometheus/client_golang v1.14.0 // indirect
github.com/prometheus/common v0.42.0 // indirect
Expand Down
3 changes: 0 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -633,8 +633,6 @@ github.com/julz/importas v0.1.0 h1:F78HnrsjY3cR7j0etXy5+TU1Zuy7Xt08X/1aJnH5xXY=
github.com/julz/importas v0.1.0/go.mod h1:oSFU2R4XK/P7kNBrnL/FEQlDGN1/6WoxXEjSSXO0DV0=
github.com/junk1tm/musttag v0.5.0 h1:bV1DTdi38Hi4pG4OVWa7Kap0hi0o7EczuK6wQt9zPOM=
github.com/junk1tm/musttag v0.5.0/go.mod h1:PcR7BA+oREQYvHwgjIDmw3exJeds5JzRcvEJTfjrA0M=
github.com/kardianos/service v1.2.0 h1:bGuZ/epo3vrt8IPC7mnKQolqFeYJb7Cs8Rk4PSOBB/g=
github.com/kardianos/service v1.2.0/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
Expand Down Expand Up @@ -1382,7 +1380,6 @@ golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand Down
Loading

0 comments on commit 8d7ec3e

Please sign in to comment.