github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/worker/applicationscaler/worker.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package applicationscaler 5 6 import ( 7 "github.com/juju/errors" 8 "gopkg.in/juju/worker.v1" 9 10 "github.com/juju/juju/core/watcher" 11 ) 12 13 // Facade defines the capabilities required by the worker. 14 type Facade interface { 15 16 // Watch returns a StringsWatcher reporting names of 17 // applications which may have insufficient units. 18 Watch() (watcher.StringsWatcher, error) 19 20 // Rescale scales up any named application observed to be 21 // running too few units. 22 Rescale(applications []string) error 23 } 24 25 // Config defines a worker's dependencies. 26 type Config struct { 27 Facade Facade 28 } 29 30 // Validate returns an error if the config can't be expected 31 // to run a functional worker. 32 func (config Config) Validate() error { 33 if config.Facade == nil { 34 return errors.NotValidf("nil Facade") 35 } 36 return nil 37 } 38 39 // New returns a worker that will attempt to rescale any 40 // applications that might be undersized. 41 func New(config Config) (worker.Worker, error) { 42 if err := config.Validate(); err != nil { 43 return nil, errors.Trace(err) 44 } 45 swConfig := watcher.StringsConfig{ 46 Handler: &handler{config}, 47 } 48 return watcher.NewStringsWorker(swConfig) 49 } 50 51 // handler implements watcher.StringsHandler, backed by the 52 // configured facade. 53 type handler struct { 54 config Config 55 } 56 57 // SetUp is part of the watcher.StringsHandler interface. 58 func (handler *handler) SetUp() (watcher.StringsWatcher, error) { 59 return handler.config.Facade.Watch() 60 } 61 62 // Handle is part of the watcher.StringsHandler interface. 63 func (handler *handler) Handle(_ <-chan struct{}, applications []string) error { 64 return handler.config.Facade.Rescale(applications) 65 } 66 67 // TearDown is part of the watcher.StringsHandler interface. 68 func (handler *handler) TearDown() error { 69 return nil 70 }