github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/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 "sync" 8 9 "github.com/juju/errors" 10 11 "github.com/juju/juju/instance" 12 "github.com/juju/juju/network" 13 ) 14 15 type apiHostPortsSetter interface { 16 SetAPIHostPorts([][]network.HostPort) error 17 } 18 19 type publisher struct { 20 st apiHostPortsSetter 21 preferIPv6 bool 22 23 mu sync.Mutex 24 lastAPIServers [][]network.HostPort 25 } 26 27 func newPublisher(st apiHostPortsSetter, preferIPv6 bool) *publisher { 28 return &publisher{ 29 st: st, 30 preferIPv6: preferIPv6, 31 } 32 } 33 34 func (pub *publisher) publishAPIServers(apiServers [][]network.HostPort, instanceIds []instance.Id) error { 35 if len(apiServers) == 0 { 36 return errors.Errorf("no api servers specified") 37 } 38 pub.mu.Lock() 39 defer pub.mu.Unlock() 40 41 sortedAPIServers := make([][]network.HostPort, len(apiServers)) 42 for i, hostPorts := range apiServers { 43 sortedAPIServers[i] = append([]network.HostPort{}, hostPorts...) 44 network.SortHostPorts(sortedAPIServers[i], pub.preferIPv6) 45 } 46 if apiServersEqual(sortedAPIServers, pub.lastAPIServers) { 47 logger.Debugf("API host ports have not changed") 48 return nil 49 } 50 51 // TODO(rog) publish instanceIds in environment storage. 52 err := pub.st.SetAPIHostPorts(sortedAPIServers) 53 if err != nil { 54 return err 55 } 56 pub.lastAPIServers = sortedAPIServers 57 return nil 58 } 59 60 func apiServersEqual(a, b [][]network.HostPort) bool { 61 if len(a) != len(b) { 62 return false 63 } 64 for i, hostPortsA := range a { 65 hostPortsB := b[i] 66 if len(hostPortsA) != len(hostPortsB) { 67 return false 68 } 69 for j := range hostPortsA { 70 if hostPortsA[j] != hostPortsB[j] { 71 return false 72 } 73 } 74 } 75 return true 76 }