@@ -2,15 +2,19 @@ package cmd
22
33import (
44 "bufio"
5+ "context"
56 "errors"
67 "fmt"
78 "os"
9+ "os/signal"
810 "strings"
11+ "syscall"
912
1013 "github.com/hyperledger-labs/yui-relayer/config"
1114 "github.com/hyperledger-labs/yui-relayer/core"
1215 "github.com/hyperledger-labs/yui-relayer/log"
1316 "github.com/hyperledger-labs/yui-relayer/metrics"
17+ "golang.org/x/sys/unix"
1418
1519 "github.com/cosmos/cosmos-sdk/client/flags"
1620 "github.com/spf13/cobra"
@@ -91,6 +95,7 @@ func Execute(modules ...config.ModuleI) error {
9195 if err := metrics .InitializeMetrics (metrics.ExporterNull {}); err != nil {
9296 return fmt .Errorf ("failed to initialize the metrics: %v" , err )
9397 }
98+ cmd .SetContext (notifyContext (cmd .Context (), syscall .SIGINT , syscall .SIGTERM ))
9499 return nil
95100 }
96101 rootCmd .PersistentPostRunE = func (cmd * cobra.Command , _ []string ) error {
@@ -118,3 +123,24 @@ func noCommand(cmd *cobra.Command, args []string) error {
118123 cmd .Help ()
119124 return errors .New ("specified command does not exist" )
120125}
126+
127+ func notifyContext (ctx context.Context , signals ... os.Signal ) context.Context {
128+ ctx , cancel := context .WithCancel (ctx )
129+
130+ sigChan := make (chan os.Signal , 1 )
131+ signal .Notify (sigChan , signals ... )
132+
133+ go func () {
134+ sig := <- sigChan
135+ var sigName string
136+ if s , ok := sig .(syscall.Signal ); ok {
137+ sigName = unix .SignalName (s )
138+ } else {
139+ sigName = s .String ()
140+ }
141+ log .GetLogger ().Info (fmt .Sprintf ("Received %s. Shutting down..." , sigName ))
142+ cancel ()
143+ }()
144+
145+ return ctx
146+ }
0 commit comments