descriptionsignalcontext
ownerJoe Wreschnig
last changeMon, 15 Jun 2020 21:20:19 +0000 (23:20 +0200)
readme

signalcontext

A signalcontext.Context provides a context.Context which cancels when an operating system signal (e.g. os.Interrupt) is received. This can be useful to bound some long or infinite operation running near the top-level of a program so the rest of the program can proceed with a clean shutdown.

Usage

Using this module correctly requires some knowledge of the standard context package. In its simplest form it can be used exactly like any other context, e.g. to read from a sarama ConsumerGroup until an interrupt is received:

parent := context.Background() // for example
ctx := signalcontext.UntilSignal(parent, os.Interrupt)
var err error
for err == nil {
    select {
    case <-ctx.Done():
        err = ctx.Err()
    default:
        err = consumer.Consume(ctx, topics, hander)
    }
}
ctx.Cancel()
return err

A more advanced use would be to push decisions about acceptable cleanup times out of the process, into an orchestration layer that communicates by sending signals:

parent := context.Background() // for example
srv := &http.Server{…}

// Run an HTTP server until a SIGTERM is received…
srvctx := signalcontext.UntilSignal(parent, syscall.SIGTERM)
go func() {
    handleError(srv.ListenAndServe())
    srvctx.Cancel()
}()
<-srvctx.Done()
// no need to cancel, srvctx must be done by now.

// Then try a clean shutdown, giving up if a second SIGTERM is received.
shutdownctx := signalcontext.UntilSignal(parent, syscall.SIGTERM)
defer shutdownctx.Cancel()
return srv.Shutdown(srvctx)

Licensing

Copyright 2020 Joe Wreschnig

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

shortlog
2020-06-15 Joe WreschnigAdd project documentation and licensing master
2020-06-14 Joe WreschnigReuse the same channel for all precompleted contexts
2020-06-14 Joe WreschnigAdd a benchmark for precompleted context creation
2020-06-14 Joe WreschnigImprove Error.Error() performance
2020-06-14 Joe WreschnigRemove ‘Signal’ from structure names
2020-06-14 Joe WreschnigInitial import
heads
15 months ago master