Skip to content

Commit 69782ad

Browse files
committed
Improve shutdown behaviour (fixes #891)
1 parent ee21c56 commit 69782ad

File tree

1 file changed

+20
-28
lines changed

1 file changed

+20
-28
lines changed

cmd/yggdrasil/main.go

+20-28
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"os/signal"
1515
"regexp"
1616
"strings"
17+
"sync"
1718
"syscall"
1819

1920
"golang.org/x/text/encoding/unicode"
@@ -183,8 +184,7 @@ func getArgs() yggArgs {
183184
}
184185

185186
// The main function is responsible for configuring and starting Yggdrasil.
186-
func run(args yggArgs, ctx context.Context, done chan struct{}) {
187-
defer close(done)
187+
func run(args yggArgs, ctx context.Context) {
188188
// Create a new logger that logs output to stdout.
189189
var logger *log.Logger
190190
switch args.logto {
@@ -371,14 +371,11 @@ func run(args yggArgs, ctx context.Context, done chan struct{}) {
371371
logger.Infof("Your public key is %s", hex.EncodeToString(public[:]))
372372
logger.Infof("Your IPv6 address is %s", address.String())
373373
logger.Infof("Your IPv6 subnet is %s", subnet.String())
374-
// Catch interrupts from the operating system to exit gracefully.
374+
375+
// Block until we are told to shut down.
375376
<-ctx.Done()
376-
// Capture the service being stopped on Windows.
377-
minwinsvc.SetOnExit(n.shutdown)
378-
n.shutdown()
379-
}
380377

381-
func (n *node) shutdown() {
378+
// Shut down the node.
382379
_ = n.admin.Stop()
383380
_ = n.multicast.Stop()
384381
_ = n.tun.Stop()
@@ -387,24 +384,19 @@ func (n *node) shutdown() {
387384

388385
func main() {
389386
args := getArgs()
390-
hup := make(chan os.Signal, 1)
391-
//signal.Notify(hup, os.Interrupt, syscall.SIGHUP)
392-
term := make(chan os.Signal, 1)
393-
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
394-
for {
395-
done := make(chan struct{})
396-
ctx, cancel := context.WithCancel(context.Background())
397-
go run(args, ctx, done)
398-
select {
399-
case <-hup:
400-
cancel()
401-
<-done
402-
case <-term:
403-
cancel()
404-
<-done
405-
return
406-
case <-done:
407-
return
408-
}
409-
}
387+
388+
// Catch interrupts from the operating system to exit gracefully.
389+
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
390+
391+
// Capture the service being stopped on Windows.
392+
minwinsvc.SetOnExit(cancel)
393+
394+
// Start the node, block and then wait for it to shut down.
395+
var wg sync.WaitGroup
396+
wg.Add(1)
397+
go func() {
398+
defer wg.Done()
399+
run(args, ctx)
400+
}()
401+
wg.Wait()
410402
}

0 commit comments

Comments
 (0)