github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/api/applicationscaler/api.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  	"github.com/juju/loggo"
     9  	"gopkg.in/juju/names.v2"
    10  
    11  	"github.com/juju/juju/api/base"
    12  	"github.com/juju/juju/apiserver/params"
    13  	"github.com/juju/juju/watcher"
    14  )
    15  
    16  var logger = loggo.GetLogger("juju.api.applicationscaler")
    17  
    18  // NewWatcherFunc exists to let us test Watch properly.
    19  type NewWatcherFunc func(base.APICaller, params.StringsWatchResult) watcher.StringsWatcher
    20  
    21  // API makes calls to the ApplicationScaler facade.
    22  type API struct {
    23  	caller     base.FacadeCaller
    24  	newWatcher NewWatcherFunc
    25  }
    26  
    27  // NewAPI returns a new API using the supplied caller.
    28  func NewAPI(caller base.APICaller, newWatcher NewWatcherFunc) *API {
    29  	return &API{
    30  		caller:     base.NewFacadeCaller(caller, "ApplicationScaler"),
    31  		newWatcher: newWatcher,
    32  	}
    33  }
    34  
    35  // Watch returns a StringsWatcher that delivers the names of services
    36  // that may need to be rescaled.
    37  func (api *API) Watch() (watcher.StringsWatcher, error) {
    38  	var result params.StringsWatchResult
    39  	err := api.caller.FacadeCall("Watch", nil, &result)
    40  	if err != nil {
    41  		return nil, errors.Trace(err)
    42  	}
    43  	if result.Error != nil {
    44  		return nil, errors.Trace(result.Error)
    45  	}
    46  	w := api.newWatcher(api.caller.RawAPICaller(), result)
    47  	return w, nil
    48  }
    49  
    50  // Rescale requests that all supplied service names be rescaled to
    51  // their minimum configured sizes. It returns the first error it
    52  // encounters.
    53  func (api *API) Rescale(services []string) error {
    54  	args := params.Entities{
    55  		Entities: make([]params.Entity, len(services)),
    56  	}
    57  	for i, service := range services {
    58  		if !names.IsValidApplication(service) {
    59  			return errors.NotValidf("application name %q", service)
    60  		}
    61  		tag := names.NewApplicationTag(service)
    62  		args.Entities[i].Tag = tag.String()
    63  	}
    64  	var results params.ErrorResults
    65  	err := api.caller.FacadeCall("Rescale", args, &results)
    66  	if err != nil {
    67  		return errors.Trace(err)
    68  	}
    69  	for _, result := range results.Results {
    70  		if result.Error != nil {
    71  			if err == nil {
    72  				err = result.Error
    73  			} else {
    74  				logger.Errorf("additional rescale error: %v", err)
    75  			}
    76  		}
    77  	}
    78  	return errors.Trace(err)
    79  }