|
| 1 | +package terminator |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "math/rand" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "os/signal" |
| 9 | + "sync" |
| 10 | + "syscall" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +type Options struct { |
| 15 | + // Server is the HTTP server that will be started and eventually |
| 16 | + // gracefully shut down |
| 17 | + Server *http.Server |
| 18 | + |
| 19 | + // ShutdownAfter indicates how long we should keep the HTTP |
| 20 | + // server alive before starting to shutdown |
| 21 | + ShutdownAfter time.Duration |
| 22 | + |
| 23 | + // Jitter represents a random offset in either direction of |
| 24 | + // ShutdownAfter that we'll add to ShutdownAfter. This ensures |
| 25 | + // that not all servers go down at once, thus avoiding outages. |
| 26 | + Jitter time.Duration |
| 27 | + |
| 28 | + // GracefulShutdownPeriod represents the maximum amount of time |
| 29 | + // we allow in-flight requests to finish before we force shutdown |
| 30 | + GracefulShutdownPeriod time.Duration |
| 31 | +} |
| 32 | + |
| 33 | +// ServeAndShutdownAfter starts the given HTTP server, waits for the given shutdownAfter duration, |
| 34 | +// then gracefully shuts the server down and returns to the caller. The maximum amount of time |
| 35 | +// in-progress requests are given is represented by gracefulShutdownTimeout. |
| 36 | +func ServeAndShutdownAfter(opts *Options) error { |
| 37 | + sig := make(chan os.Signal, 1) |
| 38 | + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) |
| 39 | + |
| 40 | + wg := sync.WaitGroup{} |
| 41 | + wg.Add(1) |
| 42 | + |
| 43 | + go func() { |
| 44 | + defer wg.Done() |
| 45 | + |
| 46 | + // add a random jitter in the range of (-n, n) seconds to the max shutdown |
| 47 | + // time to ensure not all servers in a deployment go down at the same time |
| 48 | + rng := rand.New(rand.NewSource(time.Now().UnixNano())) |
| 49 | + jitterSecs := int(opts.Jitter.Seconds()) |
| 50 | + offset := rng.Intn(2*jitterSecs) - jitterSecs |
| 51 | + offsetSecs := time.Second * time.Duration(offset) |
| 52 | + waitFor := opts.ShutdownAfter + offsetSecs |
| 53 | + |
| 54 | + // wait for a SIGINT to arrive or for the wait duration to elapse |
| 55 | + select { |
| 56 | + case <-sig: |
| 57 | + case <-time.After(waitFor): |
| 58 | + } |
| 59 | + |
| 60 | + ctx, cancel := context.WithTimeout(context.Background(), opts.GracefulShutdownPeriod) |
| 61 | + defer cancel() |
| 62 | + |
| 63 | + // gracefully shut down the server |
| 64 | + opts.Server.SetKeepAlivesEnabled(false) |
| 65 | + opts.Server.Shutdown(ctx) |
| 66 | + }() |
| 67 | + |
| 68 | + err := opts.Server.ListenAndServe() |
| 69 | + if err != nil && err != http.ErrServerClosed { |
| 70 | + return err |
| 71 | + } |
| 72 | + |
| 73 | + wg.Wait() |
| 74 | + return nil |
| 75 | +} |
0 commit comments