diff --git a/consul/rtt.go b/consul/rtt.go index b74e65b5bf..596d1d3146 100644 --- a/consul/rtt.go +++ b/consul/rtt.go @@ -223,23 +223,22 @@ func getDatacenterDistance(s serfer, dc string) (float64, error) { return 0.0, err } - // Fetch all the nodes in the DC. + // Fetch all the nodes in the DC and record their distance, if available. nodes := s.GetNodesForDatacenter(dc) - subvec := make([]float64, len(nodes)) - for j, node := range nodes { + subvec := make([]float64, 0, len(nodes)) + for _, node := range nodes { if other, ok := s.GetCachedCoordinate(node); ok { - subvec[j] = computeDistance(coord, other) - } else { - subvec[j] = computeDistance(coord, nil) + subvec = append(subvec, computeDistance(coord, other)) } } // Compute the median by sorting and taking the middle item. - sort.Float64s(subvec) if len(subvec) > 0 { + sort.Float64s(subvec) return subvec[len(subvec)/2], nil } + // Return the default infinity value. return computeDistance(coord, nil), nil } diff --git a/consul/rtt_test.go b/consul/rtt_test.go index f2da14e8de..4a882eaab7 100644 --- a/consul/rtt_test.go +++ b/consul/rtt_test.go @@ -337,12 +337,13 @@ func TestRtt_getDatacenterDistance(t *testing.T) { } // Check the more interesting median case, note that there's a mystery - // node4 in there that should make the distances sort like this: + // node4 in there that should be excluded to make the distances sort + // like this: // - // [0] node3 (0.005), [1] node1 (0.007), [2] node2 (0.008), [3] node4 (+Inf) + // [0] node3 (0.005), [1] node1 (0.007), [2] node2 (0.008) // - // So the median should be at index 4 / 2 = 2 -> 0.008. - if dist, err := getDatacenterDistance(s, "dc1"); err != nil || dist != 0.008 { + // So the median should be at index 3 / 2 = 1 -> 0.007. + if dist, err := getDatacenterDistance(s, "dc1"); err != nil || dist != 0.007 { t.Fatalf("bad: %v err: %v", dist, err) } }