github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/apiserver/common/modelmachineswatcher.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/apiserver/params"
    10  	"github.com/juju/juju/state"
    11  	"github.com/juju/juju/state/watcher"
    12  )
    13  
    14  // ModelMachinesWatcher implements a common WatchModelMachines
    15  // method for use by various facades.
    16  type ModelMachinesWatcher struct {
    17  	st         state.ModelMachinesWatcher
    18  	resources  *Resources
    19  	authorizer Authorizer
    20  }
    21  
    22  // NewModelMachinesWatcher returns a new ModelMachinesWatcher. The
    23  // GetAuthFunc will be used on each invocation of WatchUnits to
    24  // determine current permissions.
    25  func NewModelMachinesWatcher(st state.ModelMachinesWatcher, resources *Resources, authorizer Authorizer) *ModelMachinesWatcher {
    26  	return &ModelMachinesWatcher{
    27  		st:         st,
    28  		resources:  resources,
    29  		authorizer: authorizer,
    30  	}
    31  }
    32  
    33  // WatchModelMachines returns a StringsWatcher that notifies of
    34  // changes to the life cycles of the top level machines in the current
    35  // model.
    36  func (e *ModelMachinesWatcher) WatchModelMachines() (params.StringsWatchResult, error) {
    37  	result := params.StringsWatchResult{}
    38  	if !e.authorizer.AuthModelManager() {
    39  		return result, ErrPerm
    40  	}
    41  	watch := e.st.WatchModelMachines()
    42  	// Consume the initial event and forward it to the result.
    43  	if changes, ok := <-watch.Changes(); ok {
    44  		result.StringsWatcherId = e.resources.Register(watch)
    45  		result.Changes = changes
    46  	} else {
    47  		err := watcher.EnsureErr(watch)
    48  		return result, fmt.Errorf("cannot obtain initial model machines: %v", err)
    49  	}
    50  	return result, nil
    51  }