github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/cmd/jujud/agent/engine/flag.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package engine
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/juju/worker.v1"
     9  	tomb "gopkg.in/tomb.v2"
    10  )
    11  
    12  // Flag represents a single boolean used to determine whether a given
    13  // manifold worker should run.
    14  type Flag interface {
    15  
    16  	// Check returns the flag's value. Check calls must *always* return
    17  	// the same value for a given instatiation of the type implementing
    18  	// Flag.
    19  	Check() bool
    20  }
    21  
    22  // FlagOutput will expose, as a Flag, any worker that implements Flag.
    23  func FlagOutput(in worker.Worker, out interface{}) error {
    24  	inFlag, ok := in.(Flag)
    25  	if !ok {
    26  		return errors.Errorf("expected in to implement Flag; got a %T", in)
    27  	}
    28  	outFlag, ok := out.(*Flag)
    29  	if !ok {
    30  		return errors.Errorf("expected out to be a *Flag; got a %T", out)
    31  	}
    32  	*outFlag = inFlag
    33  	return nil
    34  }
    35  
    36  type staticFlagWorker struct {
    37  	tomb  tomb.Tomb
    38  	value bool
    39  }
    40  
    41  // NewStaticFlagWorker returns a new Worker that implements Flag,
    42  // whose Check method always returns the specified value.
    43  func NewStaticFlagWorker(value bool) worker.Worker {
    44  	w := &staticFlagWorker{value: value}
    45  	w.tomb.Go(func() error {
    46  		<-w.tomb.Dying()
    47  		return tomb.ErrDying
    48  	})
    49  	return w
    50  }
    51  
    52  // Check is part of the Flag interface.
    53  func (w *staticFlagWorker) Check() bool {
    54  	return w.value
    55  }
    56  
    57  // Kill is part of the Worker interface.
    58  func (w *staticFlagWorker) Kill() {
    59  	w.tomb.Kill(nil)
    60  }
    61  
    62  // Wait is part of the Worker interface.
    63  func (w *staticFlagWorker) Wait() error {
    64  	return w.tomb.Wait()
    65  }