Use shared func for registering Sigterm on a context (#799)

This commit is contained in:
6543
2022-02-28 09:27:31 +01:00
committed by GitHub
parent a2315fe931
commit a3ac393264
5 changed files with 50 additions and 73 deletions

View File

@@ -35,6 +35,7 @@ import (
"github.com/woodpecker-ci/woodpecker/agent"
"github.com/woodpecker-ci/woodpecker/pipeline/backend"
"github.com/woodpecker-ci/woodpecker/pipeline/rpc"
"github.com/woodpecker-ci/woodpecker/shared/utils"
)
func loop(c *cli.Context) error {
@@ -119,7 +120,7 @@ func loop(c *cli.Context) error {
context.Background(),
metadata.Pairs("hostname", hostname),
)
ctx = WithContextFunc(ctx, func() {
ctx = utils.WithContextSigtermCallback(ctx, func() {
println("ctrl+c received, terminating process")
sigterm.Set()
})

View File

@@ -1,34 +0,0 @@
// Copyright 2017 Drone.IO Inc.
//
// This file is licensed under the terms of the MIT license.
// For a copy, see https://opensource.org/licenses/MIT.
package main
import (
"context"
"os"
"os/signal"
"syscall"
)
// WithContextFunc returns a copy of parent context that is canceled when
// an os interrupt signal is received. The callback function f is invoked
// before cancellation.
func WithContextFunc(ctx context.Context, f func()) context.Context {
ctx, cancel := context.WithCancel(ctx)
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(c)
select {
case <-ctx.Done():
case <-c:
f()
cancel()
}
}()
return ctx
}