github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/state/apiserver/common/environmachineswatcher.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package common
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/juju/juju/state"
    10  	"github.com/juju/juju/state/api/params"
    11  	"github.com/juju/juju/state/watcher"
    12  )
    13  
    14  // EnvironMachinesWatcher implements a common WatchEnvironMachines
    15  // method for use by various facades.
    16  type EnvironMachinesWatcher struct {
    17  	st          state.EnvironMachinesWatcher
    18  	resources   *Resources
    19  	getCanWatch GetAuthFunc
    20  }
    21  
    22  // NewEnvironMachinesWatcher returns a new EnvironMachinesWatcher. The
    23  // GetAuthFunc will be used on each invocation of WatchUnits to
    24  // determine current permissions.
    25  func NewEnvironMachinesWatcher(st state.EnvironMachinesWatcher, resources *Resources, getCanWatch GetAuthFunc) *EnvironMachinesWatcher {
    26  	return &EnvironMachinesWatcher{
    27  		st:          st,
    28  		resources:   resources,
    29  		getCanWatch: getCanWatch,
    30  	}
    31  }
    32  
    33  // WatchEnvironMachines returns a StringsWatcher that notifies of
    34  // changes to the life cycles of the top level machines in the current
    35  // environment.
    36  func (e *EnvironMachinesWatcher) WatchEnvironMachines() (params.StringsWatchResult, error) {
    37  	result := params.StringsWatchResult{}
    38  	canWatch, err := e.getCanWatch()
    39  	if err != nil {
    40  		return params.StringsWatchResult{}, err
    41  	}
    42  	if !canWatch("") {
    43  		return result, ErrPerm
    44  	}
    45  	watch := e.st.WatchEnvironMachines()
    46  	// Consume the initial event and forward it to the result.
    47  	if changes, ok := <-watch.Changes(); ok {
    48  		result.StringsWatcherId = e.resources.Register(watch)
    49  		result.Changes = changes
    50  	} else {
    51  		err := watcher.MustErr(watch)
    52  		return result, fmt.Errorf("cannot obtain initial environment machines: %v", err)
    53  	}
    54  	return result, nil
    55  }