1package api
2
3import (
4	"strings"
5	"testing"
6	"time"
7
8	"github.com/hashicorp/consul/sdk/testutil/retry"
9	"github.com/hashicorp/serf/coordinate"
10	"github.com/stretchr/testify/require"
11)
12
13func TestAPI_CoordinateDatacenters(t *testing.T) {
14	t.Parallel()
15	c, s := makeClient(t)
16	defer s.Stop()
17
18	coord := c.Coordinate()
19	retry.Run(t, func(r *retry.R) {
20		datacenters, err := coord.Datacenters()
21		if err != nil {
22			r.Fatal(err)
23		}
24
25		if len(datacenters) == 0 {
26			r.Fatalf("Bad: %v", datacenters)
27		}
28	})
29}
30
31func TestAPI_CoordinateNodes(t *testing.T) {
32	t.Parallel()
33	c, s := makeClient(t)
34	defer s.Stop()
35
36	coord := c.Coordinate()
37	retry.Run(t, func(r *retry.R) {
38		_, _, err := coord.Nodes(nil)
39		if err != nil {
40			r.Fatal(err)
41		}
42
43		// There's not a good way to populate coordinates without
44		// waiting for them to calculate and update, so the best
45		// we can do is call the endpoint and make sure we don't
46		// get an error.
47	})
48}
49
50func TestAPI_CoordinateNode(t *testing.T) {
51	t.Parallel()
52	c, s := makeClient(t)
53	defer s.Stop()
54
55	coord := c.Coordinate()
56	retry.Run(t, func(r *retry.R) {
57		_, _, err := coord.Node(s.Config.NodeName, nil)
58		if err != nil && !strings.Contains(err.Error(), "Unexpected response code: 404") {
59			r.Fatal(err)
60		}
61
62		// There's not a good way to populate coordinates without
63		// waiting for them to calculate and update, so the best
64		// we can do is call the endpoint and make sure we don't
65		// get an error.
66	})
67}
68
69func TestAPI_CoordinateUpdate(t *testing.T) {
70	t.Parallel()
71	c, s := makeClient(t)
72	defer s.Stop()
73
74	s.WaitForSerfCheck(t)
75	node := "foo"
76	_, err := c.Catalog().Register(&CatalogRegistration{
77		Node:    node,
78		Address: "1.1.1.1",
79	}, nil)
80	if err != nil {
81		t.Fatal(err)
82	}
83
84	coord := c.Coordinate()
85	newCoord := coordinate.NewCoordinate(coordinate.DefaultConfig())
86	newCoord.Height = 0.5
87	entry := &CoordinateEntry{
88		Node:  node,
89		Coord: newCoord,
90	}
91	_, err = coord.Update(entry, nil)
92	if err != nil {
93		t.Fatal(err)
94	}
95
96	retryer := &retry.Timer{Timeout: 5 * time.Second, Wait: 1 * time.Second}
97	retry.RunWith(retryer, t, func(r *retry.R) {
98		coords, _, err := coord.Node(node, nil)
99		if err != nil {
100			r.Fatal(err)
101		}
102		if len(coords) != 1 {
103			r.Fatalf("bad: %v", coords)
104		}
105		require.Equal(r, entry, coords[0])
106	})
107}
108