github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/state/watcher/helpers.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package watcher
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"launchpad.net/tomb"
     9  )
    10  
    11  // Stopper is implemented by all watchers.
    12  type Stopper interface {
    13  	Stop() error
    14  }
    15  
    16  // Errer is implemented by all watchers.
    17  type Errer interface {
    18  	Err() error
    19  }
    20  
    21  // Stop stops the watcher. If an error is returned by the
    22  // watcher, t is killed with the error.
    23  func Stop(w Stopper, t *tomb.Tomb) {
    24  	if err := w.Stop(); err != nil {
    25  		if err != tomb.ErrStillAlive && err != tomb.ErrDying {
    26  			// tomb.Kill() checks for the two errors above
    27  			// by value, so we shouldn't wrap them, but we
    28  			// wrap any other error.
    29  			err = errors.Trace(err)
    30  		}
    31  		t.Kill(err)
    32  	}
    33  }
    34  
    35  // EnsureErr returns the error with which w died. Calling it will also
    36  // return an error if w is still running or was stopped cleanly.
    37  func EnsureErr(w Errer) error {
    38  	err := w.Err()
    39  	if err == nil {
    40  		return errors.Errorf("expected an error from %#v, got nil", w)
    41  	} else if err == tomb.ErrStillAlive {
    42  		return errors.Annotatef(err, "expected %#v to be stopped", w)
    43  	}
    44  	return errors.Trace(err)
    45  }