1package nomad
2
3import (
4	"context"
5	"testing"
6	"time"
7
8	"github.com/hashicorp/nomad/testutil"
9)
10
11func TestStatsFetcher(t *testing.T) {
12	t.Parallel()
13
14	conf := func(c *Config) {
15		c.Region = "region-a"
16		c.BootstrapExpect = 3
17	}
18
19	s1, cleanupS1 := TestServer(t, conf)
20	defer cleanupS1()
21
22	s2, cleanupS2 := TestServer(t, conf)
23	defer cleanupS2()
24
25	s3, cleanupS3 := TestServer(t, conf)
26	defer cleanupS3()
27
28	TestJoin(t, s1, s2, s3)
29	testutil.WaitForLeader(t, s1.RPC)
30
31	members := s1.serf.Members()
32	if len(members) != 3 {
33		t.Fatalf("bad len: %d", len(members))
34	}
35
36	var servers []*serverParts
37	for _, member := range members {
38		ok, server := isNomadServer(member)
39		if !ok {
40			t.Fatalf("bad: %#v", member)
41		}
42		servers = append(servers, server)
43	}
44
45	// Do a normal fetch and make sure we get three responses.
46	func() {
47		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
48		defer cancel()
49		stats := s1.statsFetcher.Fetch(ctx, s1.Members())
50		if len(stats) != 3 {
51			t.Fatalf("bad: %#v", stats)
52		}
53		for id, stat := range stats {
54			switch id {
55			case s1.config.NodeID, s2.config.NodeID, s3.config.NodeID:
56				// OK
57			default:
58				t.Fatalf("bad: %s", id)
59			}
60
61			if stat == nil || stat.LastTerm == 0 {
62				t.Fatalf("bad: %#v", stat)
63			}
64		}
65	}()
66
67	// Fake an in-flight request to server 3 and make sure we don't fetch
68	// from it.
69	func() {
70		s1.statsFetcher.inflight[string(s3.config.NodeID)] = struct{}{}
71		defer delete(s1.statsFetcher.inflight, string(s3.config.NodeID))
72
73		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
74		defer cancel()
75		stats := s1.statsFetcher.Fetch(ctx, s1.Members())
76		if len(stats) != 2 {
77			t.Fatalf("bad: %#v", stats)
78		}
79		for id, stat := range stats {
80			switch id {
81			case s1.config.NodeID, s2.config.NodeID:
82				// OK
83			case s3.config.NodeID:
84				t.Fatalf("bad")
85			default:
86				t.Fatalf("bad: %s", id)
87			}
88
89			if stat == nil || stat.LastTerm == 0 {
90				t.Fatalf("bad: %#v", stat)
91			}
92		}
93	}()
94}
95