github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/worker/peergrouper/publish.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package peergrouper
     5  
     6  import (
     7  	"reflect"
     8  	"sort"
     9  	"sync"
    10  
    11  	"github.com/juju/errors"
    12  
    13  	"github.com/juju/juju/core/network"
    14  )
    15  
    16  // CachingAPIHostPortsSetter is an APIHostPortsSetter that caches the
    17  // most recently set values, suppressing further calls to the underlying
    18  // setter if any call's arguments match those of the preceding call.
    19  type CachingAPIHostPortsSetter struct {
    20  	APIHostPortsSetter
    21  
    22  	mu   sync.Mutex
    23  	last []network.SpaceHostPorts
    24  }
    25  
    26  func (s *CachingAPIHostPortsSetter) SetAPIHostPorts(apiServers []network.SpaceHostPorts) error {
    27  	if len(apiServers) == 0 {
    28  		return errors.Errorf("no API servers specified")
    29  	}
    30  
    31  	sorted := make([]network.SpaceHostPorts, len(apiServers))
    32  	for i, hostPorts := range apiServers {
    33  		sorted[i] = append(network.SpaceHostPorts{}, hostPorts...)
    34  		sort.Sort(sorted[i])
    35  	}
    36  
    37  	s.mu.Lock()
    38  	defer s.mu.Unlock()
    39  	if reflect.DeepEqual(sorted, s.last) {
    40  		logger.Debugf("API host ports have not changed")
    41  		return nil
    42  	}
    43  
    44  	if err := s.APIHostPortsSetter.SetAPIHostPorts(sorted); err != nil {
    45  		return errors.Annotate(err, "setting API host ports")
    46  	}
    47  	s.last = sorted
    48  	return nil
    49  }