Skip to content
This repository has been archived by the owner on Mar 31, 2023. It is now read-only.

Sleep before context cancellation #37

Merged
merged 7 commits into from
Jan 20, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ Commands using this framework implement these external specifications:

This is used internally for graceful restart.

* `CANCELLATION_DELAY_SECONDS`

After `SIGINT` or `SIGTERM` received, the signal handler waits for the seconds before cancelling the context.
The default value is 5 sec.

Usage
-----

Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ require (
github.com/spf13/viper v1.3.2
golang.org/x/net v0.0.0-20190921015927-1a5e07d1ff72
)

go 1.13
23 changes: 23 additions & 0 deletions signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ import (
"errors"
"os"
"os/signal"
"strconv"
"time"

"github.com/cybozu-go/log"
)

var (
errSignaled = errors.New("signaled")

cancellationDelaySecondsEnv = "CANCELLATION_DELAY_SECONDS"

defaultCancellationDelaySeconds = 5
)

// IsSignaled returns true if err returned by Wait indicates that
Expand All @@ -28,6 +34,23 @@ func handleSignal(env *Environment) {
log.Warn("well: got signal", map[string]interface{}{
"signal": s.String(),
})
delayStr := os.Getenv(cancellationDelaySecondsEnv)
delay, err := strconv.Atoi(delayStr)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be done only when if len(delayStr) > 0.

if err != nil {
log.Warn("well: set default cancellation delay seconds", map[string]interface{}{
"env": delayStr,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should err be added?

    log.FnError: err

"delay": defaultCancellationDelaySeconds,
})
delay = defaultCancellationDelaySeconds
}
if delay < 0 {
log.Warn("well: round up negative cancellation delay seconds to 0s", map[string]interface{}{
"env": delayStr,
"delay": 0,
})
delay = 0
}
time.Sleep(time.Duration(delay) * time.Second)
env.Cancel(errSignaled)
}()
}