tracker/pkg/stopper/stopper.go

99 lines
2.3 KiB
Go
Raw Normal View History

// Package stopper implements a pattern for shutting down a group of processes.
2016-08-04 21:54:24 +02:00
package stopper
import (
"sync"
)
2016-08-05 07:47:04 +02:00
// AlreadyStopped is a closed error channel to be used by Funcs when
2016-08-04 21:54:24 +02:00
// an element was already stopped.
var AlreadyStopped <-chan error
2016-08-05 07:47:04 +02:00
// AlreadyStoppedFunc is a Func that returns AlreadyStopped.
2016-08-04 21:54:24 +02:00
var AlreadyStoppedFunc = func() <-chan error { return AlreadyStopped }
func init() {
closeMe := make(chan error)
close(closeMe)
AlreadyStopped = closeMe
}
// Stopper is an interface that allows a clean shutdown.
type Stopper interface {
// Stop returns a channel that indicates whether the stop was
// successful.
// The channel can either return one error or be closed. Closing the
// channel signals a clean shutdown.
// The Stop function should return immediately and perform the actual
2016-09-06 06:44:13 +02:00
// shutdown in a separate goroutine.
2016-08-04 21:54:24 +02:00
Stop() <-chan error
}
// StopGroup is a group that can be stopped.
type StopGroup struct {
2016-09-06 06:44:33 +02:00
stoppables []Func
sync.Mutex
2016-08-04 21:54:24 +02:00
}
// Func is a function that can be used to provide a clean shutdown.
type Func func() <-chan error
// NewStopGroup creates a new StopGroup.
func NewStopGroup() *StopGroup {
return &StopGroup{
2016-08-05 07:47:04 +02:00
stoppables: make([]Func, 0),
2016-08-04 21:54:24 +02:00
}
}
// Add adds a Stopper to the StopGroup.
// On the next call to Stop(), the Stopper will be stopped.
func (cg *StopGroup) Add(toAdd Stopper) {
2016-09-06 06:44:33 +02:00
cg.Lock()
defer cg.Unlock()
2016-08-04 21:54:24 +02:00
cg.stoppables = append(cg.stoppables, toAdd.Stop)
}
2016-08-05 07:47:04 +02:00
// AddFunc adds a Func to the StopGroup.
// On the next call to Stop(), the Func will be called.
func (cg *StopGroup) AddFunc(toAddFunc Func) {
2016-09-06 06:44:33 +02:00
cg.Lock()
defer cg.Unlock()
2016-08-04 21:54:24 +02:00
cg.stoppables = append(cg.stoppables, toAddFunc)
}
// Stop stops all members of the StopGroup.
// Stopping will be done in a concurrent fashion.
// The slice of errors returned contains all errors returned by stopping the
// members.
func (cg *StopGroup) Stop() []error {
2016-09-06 06:44:33 +02:00
cg.Lock()
defer cg.Unlock()
2016-08-04 21:54:24 +02:00
var errors []error
whenDone := make(chan struct{})
waitChannels := make([]<-chan error, 0, len(cg.stoppables))
for _, toStop := range cg.stoppables {
waitFor := toStop()
if waitFor == nil {
panic("received a nil chan from Stop")
}
waitChannels = append(waitChannels, waitFor)
}
go func() {
for _, waitForMe := range waitChannels {
err := <-waitForMe
if err != nil {
errors = append(errors, err)
}
}
close(whenDone)
}()
<-whenDone
return errors
}