github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/worker/apiaddressupdater/apiaddressupdater.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package apiaddressupdater
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/juju/loggo"
    10  
    11  	"github.com/juju/juju/instance"
    12  	"github.com/juju/juju/state/api/watcher"
    13  	"github.com/juju/juju/worker"
    14  )
    15  
    16  var logger = loggo.GetLogger("juju.worker.apiaddressupdater")
    17  
    18  // APIAddressUpdater is responsible for cleaning up the state.
    19  type APIAddressUpdater struct {
    20  	addresser APIAddresser
    21  	setter    APIAddressSetter
    22  }
    23  
    24  // APIAddresser is an interface that is provided to NewAPIAddressUpdater
    25  // which can be used to watch for API address changes.
    26  type APIAddresser interface {
    27  	APIHostPorts() ([][]instance.HostPort, error)
    28  	WatchAPIHostPorts() (watcher.NotifyWatcher, error)
    29  }
    30  
    31  // APIAddressSetter is an interface that is provided to NewAPIAddressUpdater
    32  // whose SetAPIHostPorts method will be invoked whenever address changes occur.
    33  type APIAddressSetter interface {
    34  	SetAPIHostPorts(servers [][]instance.HostPort) error
    35  }
    36  
    37  // NewAPIAddressUpdater returns a worker.Worker that runs state.Cleanup()
    38  // if the CleanupWatcher signals documents marked for deletion.
    39  func NewAPIAddressUpdater(addresser APIAddresser, setter APIAddressSetter) worker.Worker {
    40  	return worker.NewNotifyWorker(&APIAddressUpdater{
    41  		addresser: addresser,
    42  		setter:    setter,
    43  	})
    44  }
    45  
    46  func (c *APIAddressUpdater) SetUp() (watcher.NotifyWatcher, error) {
    47  	return c.addresser.WatchAPIHostPorts()
    48  }
    49  
    50  func (c *APIAddressUpdater) Handle() error {
    51  	addresses, err := c.addresser.APIHostPorts()
    52  	if err != nil {
    53  		return fmt.Errorf("error getting addresses: %v", err)
    54  	}
    55  	if err := c.setter.SetAPIHostPorts(addresses); err != nil {
    56  		return fmt.Errorf("error setting addresses: %v", err)
    57  	}
    58  	logger.Infof("API addresses updated to %q", addresses)
    59  	return nil
    60  }
    61  
    62  func (c *APIAddressUpdater) TearDown() error {
    63  	return nil
    64  }