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