github.com/Aestek/consul@v1.2.4-0.20190309222502-b2c31e33971a/agent/consul/server_test.go (about)

     1  package consul
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net"
     7  	"os"
     8  	"strings"
     9  	"sync/atomic"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/hashicorp/consul/agent/connect"
    14  	"github.com/hashicorp/consul/agent/metadata"
    15  	"github.com/hashicorp/consul/agent/structs"
    16  	"github.com/hashicorp/consul/agent/token"
    17  	"github.com/hashicorp/consul/lib/freeport"
    18  	"github.com/hashicorp/consul/testrpc"
    19  	"github.com/hashicorp/consul/testutil"
    20  	"github.com/hashicorp/consul/testutil/retry"
    21  	"github.com/hashicorp/consul/tlsutil"
    22  	"github.com/hashicorp/consul/types"
    23  	"github.com/hashicorp/go-uuid"
    24  
    25  	"github.com/stretchr/testify/require"
    26  )
    27  
    28  func configureTLS(config *Config) {
    29  	config.CAFile = "../../test/ca/root.cer"
    30  	config.CertFile = "../../test/key/ourdomain.cer"
    31  	config.KeyFile = "../../test/key/ourdomain.key"
    32  }
    33  
    34  var id int64
    35  
    36  func uniqueNodeName(name string) string {
    37  	return fmt.Sprintf("%s-node-%d", name, atomic.AddInt64(&id, 1))
    38  }
    39  
    40  func testServerConfig(t *testing.T) (string, *Config) {
    41  	dir := testutil.TempDir(t, "consul")
    42  	config := DefaultConfig()
    43  
    44  	ports := freeport.Get(3)
    45  	config.NodeName = uniqueNodeName(t.Name())
    46  	config.Bootstrap = true
    47  	config.Datacenter = "dc1"
    48  	config.DataDir = dir
    49  	config.LogOutput = testutil.TestWriter(t)
    50  
    51  	// bind the rpc server to a random port. config.RPCAdvertise will be
    52  	// set to the listen address unless it was set in the configuration.
    53  	// In that case get the address from srv.Listener.Addr().
    54  	config.RPCAddr = &net.TCPAddr{IP: []byte{127, 0, 0, 1}, Port: ports[0]}
    55  
    56  	nodeID, err := uuid.GenerateUUID()
    57  	if err != nil {
    58  		t.Fatal(err)
    59  	}
    60  	config.NodeID = types.NodeID(nodeID)
    61  
    62  	// set the memberlist bind port to 0 to bind to a random port.
    63  	// memberlist will update the value of BindPort after bind
    64  	// to the actual value.
    65  	config.SerfLANConfig.MemberlistConfig.BindAddr = "127.0.0.1"
    66  	config.SerfLANConfig.MemberlistConfig.BindPort = ports[1]
    67  	config.SerfLANConfig.MemberlistConfig.AdvertisePort = ports[1]
    68  	config.SerfLANConfig.MemberlistConfig.SuspicionMult = 2
    69  	config.SerfLANConfig.MemberlistConfig.ProbeTimeout = 50 * time.Millisecond
    70  	config.SerfLANConfig.MemberlistConfig.ProbeInterval = 100 * time.Millisecond
    71  	config.SerfLANConfig.MemberlistConfig.GossipInterval = 100 * time.Millisecond
    72  
    73  	config.SerfWANConfig.MemberlistConfig.BindAddr = "127.0.0.1"
    74  	config.SerfWANConfig.MemberlistConfig.BindPort = ports[2]
    75  	config.SerfWANConfig.MemberlistConfig.AdvertisePort = ports[2]
    76  	config.SerfWANConfig.MemberlistConfig.SuspicionMult = 2
    77  	config.SerfWANConfig.MemberlistConfig.ProbeTimeout = 50 * time.Millisecond
    78  	config.SerfWANConfig.MemberlistConfig.ProbeInterval = 100 * time.Millisecond
    79  	config.SerfWANConfig.MemberlistConfig.GossipInterval = 100 * time.Millisecond
    80  
    81  	config.RaftConfig.LeaderLeaseTimeout = 100 * time.Millisecond
    82  	config.RaftConfig.HeartbeatTimeout = 200 * time.Millisecond
    83  	config.RaftConfig.ElectionTimeout = 200 * time.Millisecond
    84  
    85  	config.ReconcileInterval = 300 * time.Millisecond
    86  
    87  	config.AutopilotConfig.ServerStabilizationTime = 100 * time.Millisecond
    88  	config.ServerHealthInterval = 50 * time.Millisecond
    89  	config.AutopilotInterval = 100 * time.Millisecond
    90  
    91  	config.Build = "1.4.0"
    92  
    93  	config.CoordinateUpdatePeriod = 100 * time.Millisecond
    94  	config.LeaveDrainTime = 1 * time.Millisecond
    95  
    96  	// TODO (slackpad) - We should be able to run all tests w/o this, but it
    97  	// looks like several depend on it.
    98  	config.RPCHoldTimeout = 5 * time.Second
    99  
   100  	config.ConnectEnabled = true
   101  	config.CAConfig = &structs.CAConfiguration{
   102  		ClusterID: connect.TestClusterID,
   103  		Provider:  structs.ConsulCAProvider,
   104  		Config: map[string]interface{}{
   105  			"PrivateKey":     "",
   106  			"RootCert":       "",
   107  			"RotationPeriod": "2160h",
   108  			"LeafCertTTL":    "72h",
   109  		},
   110  	}
   111  
   112  	return dir, config
   113  }
   114  
   115  func testServer(t *testing.T) (string, *Server) {
   116  	return testServerWithConfig(t, func(c *Config) {
   117  		c.Datacenter = "dc1"
   118  		c.Bootstrap = true
   119  	})
   120  }
   121  
   122  func testServerDC(t *testing.T, dc string) (string, *Server) {
   123  	return testServerWithConfig(t, func(c *Config) {
   124  		c.Datacenter = dc
   125  		c.Bootstrap = true
   126  	})
   127  }
   128  
   129  func testServerDCBootstrap(t *testing.T, dc string, bootstrap bool) (string, *Server) {
   130  	return testServerWithConfig(t, func(c *Config) {
   131  		c.Datacenter = dc
   132  		c.Bootstrap = bootstrap
   133  	})
   134  }
   135  
   136  func testServerDCExpect(t *testing.T, dc string, expect int) (string, *Server) {
   137  	return testServerWithConfig(t, func(c *Config) {
   138  		c.Datacenter = dc
   139  		c.Bootstrap = false
   140  		c.BootstrapExpect = expect
   141  	})
   142  }
   143  
   144  func testServerDCExpectNonVoter(t *testing.T, dc string, expect int) (string, *Server) {
   145  	return testServerWithConfig(t, func(c *Config) {
   146  		c.Datacenter = dc
   147  		c.Bootstrap = false
   148  		c.BootstrapExpect = expect
   149  		c.NonVoter = true
   150  	})
   151  }
   152  
   153  func testServerWithConfig(t *testing.T, cb func(*Config)) (string, *Server) {
   154  	dir, config := testServerConfig(t)
   155  	if cb != nil {
   156  		cb(config)
   157  	}
   158  	srv, err := newServer(config)
   159  	if err != nil {
   160  		t.Fatalf("err: %v", err)
   161  	}
   162  	return dir, srv
   163  }
   164  
   165  func newServer(c *Config) (*Server, error) {
   166  	// chain server up notification
   167  	oldNotify := c.NotifyListen
   168  	up := make(chan struct{})
   169  	c.NotifyListen = func() {
   170  		close(up)
   171  		if oldNotify != nil {
   172  			oldNotify()
   173  		}
   174  	}
   175  
   176  	// start server
   177  	w := c.LogOutput
   178  	if w == nil {
   179  		w = os.Stderr
   180  	}
   181  	logger := log.New(w, c.NodeName+" - ", log.LstdFlags|log.Lmicroseconds)
   182  	srv, err := NewServerLogger(c, logger, new(token.Store), tlsutil.NewConfigurator(c.ToTLSUtilConfig()))
   183  	if err != nil {
   184  		return nil, err
   185  	}
   186  
   187  	// wait until after listen
   188  	<-up
   189  
   190  	// get the real address
   191  	//
   192  	// the server already sets the RPCAdvertise address
   193  	// if it wasn't configured since it needs it for
   194  	// some initialization
   195  	//
   196  	// todo(fs): setting RPCAddr should probably be guarded
   197  	// todo(fs): but for now it is a shortcut to avoid fixing
   198  	// todo(fs): tests which depend on that value. They should
   199  	// todo(fs): just get the listener address instead.
   200  	c.RPCAddr = srv.Listener.Addr().(*net.TCPAddr)
   201  	return srv, nil
   202  }
   203  
   204  func TestServer_StartStop(t *testing.T) {
   205  	t.Parallel()
   206  	// Start up a server and then stop it.
   207  	dir1, s1 := testServer(t)
   208  	defer os.RemoveAll(dir1)
   209  	if err := s1.Shutdown(); err != nil {
   210  		t.Fatalf("err: %v", err)
   211  	}
   212  
   213  	// Shut down again, which should be idempotent.
   214  	if err := s1.Shutdown(); err != nil {
   215  		t.Fatalf("err: %v", err)
   216  	}
   217  }
   218  
   219  func TestServer_JoinLAN(t *testing.T) {
   220  	t.Parallel()
   221  	dir1, s1 := testServer(t)
   222  	defer os.RemoveAll(dir1)
   223  	defer s1.Shutdown()
   224  
   225  	dir2, s2 := testServer(t)
   226  	defer os.RemoveAll(dir2)
   227  	defer s2.Shutdown()
   228  
   229  	// Try to join
   230  	joinLAN(t, s2, s1)
   231  	retry.Run(t, func(r *retry.R) {
   232  		if got, want := len(s1.LANMembers()), 2; got != want {
   233  			r.Fatalf("got %d s1 LAN members want %d", got, want)
   234  		}
   235  		if got, want := len(s2.LANMembers()), 2; got != want {
   236  			r.Fatalf("got %d s2 LAN members want %d", got, want)
   237  		}
   238  	})
   239  }
   240  
   241  func TestServer_LANReap(t *testing.T) {
   242  	t.Parallel()
   243  
   244  	configureServer := func(c *Config) {
   245  		c.SerfFloodInterval = 100 * time.Millisecond
   246  		c.SerfLANConfig.ReconnectTimeout = 250 * time.Millisecond
   247  		c.SerfLANConfig.TombstoneTimeout = 250 * time.Millisecond
   248  		c.SerfLANConfig.ReapInterval = 300 * time.Millisecond
   249  	}
   250  
   251  	dir1, s1 := testServerWithConfig(t, func(c *Config) {
   252  		c.Datacenter = "dc1"
   253  		c.Bootstrap = true
   254  		configureServer(c)
   255  	})
   256  	defer os.RemoveAll(dir1)
   257  	defer s1.Shutdown()
   258  
   259  	dir2, s2 := testServerWithConfig(t, func(c *Config) {
   260  		c.Datacenter = "dc1"
   261  		c.Bootstrap = false
   262  		configureServer(c)
   263  	})
   264  	defer os.RemoveAll(dir2)
   265  
   266  	dir3, s3 := testServerWithConfig(t, func(c *Config) {
   267  		c.Datacenter = "dc1"
   268  		c.Bootstrap = false
   269  		configureServer(c)
   270  	})
   271  	defer os.RemoveAll(dir3)
   272  	defer s3.Shutdown()
   273  
   274  	// Try to join
   275  	joinLAN(t, s2, s1)
   276  	joinLAN(t, s3, s1)
   277  
   278  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   279  	testrpc.WaitForLeader(t, s2.RPC, "dc1")
   280  	testrpc.WaitForLeader(t, s3.RPC, "dc1")
   281  
   282  	retry.Run(t, func(r *retry.R) {
   283  		require.Len(r, s1.LANMembers(), 3)
   284  		require.Len(r, s2.LANMembers(), 3)
   285  		require.Len(r, s3.LANMembers(), 3)
   286  	})
   287  
   288  	// Check the router has both
   289  	retry.Run(t, func(r *retry.R) {
   290  		require.Len(r, s1.serverLookup.Servers(), 3)
   291  		require.Len(r, s2.serverLookup.Servers(), 3)
   292  		require.Len(r, s3.serverLookup.Servers(), 3)
   293  	})
   294  
   295  	// shutdown the second dc
   296  	s2.Shutdown()
   297  
   298  	retry.Run(t, func(r *retry.R) {
   299  		require.Len(r, s1.LANMembers(), 2)
   300  		servers := s1.serverLookup.Servers()
   301  		require.Len(r, servers, 2)
   302  		// require.Equal(r, s1.config.NodeName, servers[0].Name)
   303  	})
   304  }
   305  
   306  func TestServer_JoinWAN(t *testing.T) {
   307  	t.Parallel()
   308  	dir1, s1 := testServer(t)
   309  	defer os.RemoveAll(dir1)
   310  	defer s1.Shutdown()
   311  
   312  	dir2, s2 := testServerDC(t, "dc2")
   313  	defer os.RemoveAll(dir2)
   314  	defer s2.Shutdown()
   315  
   316  	// Try to join
   317  	joinWAN(t, s2, s1)
   318  	retry.Run(t, func(r *retry.R) {
   319  		if got, want := len(s1.WANMembers()), 2; got != want {
   320  			r.Fatalf("got %d s1 WAN members want %d", got, want)
   321  		}
   322  		if got, want := len(s2.WANMembers()), 2; got != want {
   323  			r.Fatalf("got %d s2 WAN members want %d", got, want)
   324  		}
   325  	})
   326  
   327  	// Check the router has both
   328  	retry.Run(t, func(r *retry.R) {
   329  		if got, want := len(s1.router.GetDatacenters()), 2; got != want {
   330  			r.Fatalf("got %d routes want %d", got, want)
   331  		}
   332  		if got, want := len(s2.router.GetDatacenters()), 2; got != want {
   333  			r.Fatalf("got %d datacenters want %d", got, want)
   334  		}
   335  	})
   336  }
   337  
   338  func TestServer_WANReap(t *testing.T) {
   339  	t.Parallel()
   340  	dir1, s1 := testServerWithConfig(t, func(c *Config) {
   341  		c.Datacenter = "dc1"
   342  		c.Bootstrap = true
   343  		c.SerfFloodInterval = 100 * time.Millisecond
   344  		c.SerfWANConfig.ReconnectTimeout = 250 * time.Millisecond
   345  		c.SerfWANConfig.TombstoneTimeout = 250 * time.Millisecond
   346  		c.SerfWANConfig.ReapInterval = 500 * time.Millisecond
   347  	})
   348  	defer os.RemoveAll(dir1)
   349  	defer s1.Shutdown()
   350  
   351  	dir2, s2 := testServerDC(t, "dc2")
   352  	defer os.RemoveAll(dir2)
   353  
   354  	// Try to join
   355  	joinWAN(t, s2, s1)
   356  	retry.Run(t, func(r *retry.R) {
   357  		require.Len(r, s1.WANMembers(), 2)
   358  		require.Len(r, s2.WANMembers(), 2)
   359  	})
   360  
   361  	// Check the router has both
   362  	retry.Run(t, func(r *retry.R) {
   363  		require.Len(r, s1.router.GetDatacenters(), 2)
   364  		require.Len(r, s2.router.GetDatacenters(), 2)
   365  	})
   366  
   367  	// shutdown the second dc
   368  	s2.Shutdown()
   369  
   370  	retry.Run(t, func(r *retry.R) {
   371  		require.Len(r, s1.WANMembers(), 1)
   372  		datacenters := s1.router.GetDatacenters()
   373  		require.Len(r, datacenters, 1)
   374  		require.Equal(r, "dc1", datacenters[0])
   375  	})
   376  
   377  }
   378  
   379  func TestServer_JoinWAN_Flood(t *testing.T) {
   380  	t.Parallel()
   381  	// Set up two servers in a WAN.
   382  	dir1, s1 := testServerDCBootstrap(t, "dc1", true)
   383  	defer os.RemoveAll(dir1)
   384  	defer s1.Shutdown()
   385  
   386  	dir2, s2 := testServerDCBootstrap(t, "dc2", true)
   387  	defer os.RemoveAll(dir2)
   388  	defer s2.Shutdown()
   389  
   390  	joinWAN(t, s2, s1)
   391  
   392  	for _, s := range []*Server{s1, s2} {
   393  		retry.Run(t, func(r *retry.R) {
   394  			if got, want := len(s.WANMembers()), 2; got != want {
   395  				r.Fatalf("got %d WAN members want %d", got, want)
   396  			}
   397  		})
   398  	}
   399  
   400  	dir3, s3 := testServerDCBootstrap(t, "dc1", false)
   401  	defer os.RemoveAll(dir3)
   402  	defer s3.Shutdown()
   403  
   404  	// Do just a LAN join for the new server and make sure it
   405  	// shows up in the WAN.
   406  	joinLAN(t, s3, s1)
   407  
   408  	for _, s := range []*Server{s1, s2, s3} {
   409  		retry.Run(t, func(r *retry.R) {
   410  			if got, want := len(s.WANMembers()), 3; got != want {
   411  				r.Fatalf("got %d WAN members for %s want %d", got, s.config.NodeName, want)
   412  			}
   413  		})
   414  	}
   415  }
   416  
   417  func TestServer_JoinSeparateLanAndWanAddresses(t *testing.T) {
   418  	t.Parallel()
   419  	dir1, s1 := testServerWithConfig(t, func(c *Config) {
   420  		c.NodeName = t.Name() + "-s1"
   421  		c.Datacenter = "dc1"
   422  		c.Bootstrap = true
   423  		c.SerfFloodInterval = 100 * time.Millisecond
   424  	})
   425  	defer os.RemoveAll(dir1)
   426  	defer s1.Shutdown()
   427  
   428  	s2Name := t.Name() + "-s2"
   429  	dir2, s2 := testServerWithConfig(t, func(c *Config) {
   430  		c.NodeName = s2Name
   431  		c.Datacenter = "dc2"
   432  		c.Bootstrap = false
   433  		// This wan address will be expected to be seen on s1
   434  		c.SerfWANConfig.MemberlistConfig.AdvertiseAddr = "127.0.0.2"
   435  		// This lan address will be expected to be seen on s3
   436  		c.SerfLANConfig.MemberlistConfig.AdvertiseAddr = "127.0.0.3"
   437  		c.SerfFloodInterval = 100 * time.Millisecond
   438  	})
   439  
   440  	defer os.RemoveAll(dir2)
   441  	defer s2.Shutdown()
   442  
   443  	dir3, s3 := testServerWithConfig(t, func(c *Config) {
   444  		c.NodeName = t.Name() + "-s3"
   445  		c.Datacenter = "dc2"
   446  		c.Bootstrap = true
   447  		c.SerfFloodInterval = 100 * time.Millisecond
   448  	})
   449  	defer os.RemoveAll(dir3)
   450  	defer s3.Shutdown()
   451  
   452  	// Join s2 to s1 on wan
   453  	joinWAN(t, s2, s1)
   454  
   455  	// Join s3 to s2 on lan
   456  	joinLAN(t, s3, s2)
   457  
   458  	// We rely on flood joining to fill across the LAN, so we expect s3 to
   459  	// show up on the WAN as well, even though it's not explicitly joined.
   460  	retry.Run(t, func(r *retry.R) {
   461  		if got, want := len(s1.WANMembers()), 3; got != want {
   462  			r.Fatalf("got %d s1 WAN members want %d", got, want)
   463  		}
   464  		if got, want := len(s2.WANMembers()), 3; got != want {
   465  			r.Fatalf("got %d s2 WAN members want %d", got, want)
   466  		}
   467  		if got, want := len(s2.LANMembers()), 2; got != want {
   468  			r.Fatalf("got %d s2 LAN members want %d", got, want)
   469  		}
   470  		if got, want := len(s3.LANMembers()), 2; got != want {
   471  			r.Fatalf("got %d s3 LAN members want %d", got, want)
   472  		}
   473  	})
   474  
   475  	// Check the router has both
   476  	retry.Run(t, func(r *retry.R) {
   477  		if len(s1.router.GetDatacenters()) != 2 {
   478  			r.Fatalf("remote consul missing")
   479  		}
   480  		if len(s2.router.GetDatacenters()) != 2 {
   481  			r.Fatalf("remote consul missing")
   482  		}
   483  		if len(s2.serverLookup.Servers()) != 2 {
   484  			r.Fatalf("local consul fellow s3 for s2 missing")
   485  		}
   486  	})
   487  
   488  	// Get and check the wan address of s2 from s1
   489  	var s2WanAddr string
   490  	for _, member := range s1.WANMembers() {
   491  		if member.Name == s2Name+".dc2" {
   492  			s2WanAddr = member.Addr.String()
   493  		}
   494  	}
   495  	if s2WanAddr != "127.0.0.2" {
   496  		t.Fatalf("s1 sees s2 on a wrong address: %s, expecting: %s", s2WanAddr, "127.0.0.2")
   497  	}
   498  
   499  	// Get and check the lan address of s2 from s3
   500  	var s2LanAddr string
   501  	for _, lanmember := range s3.LANMembers() {
   502  		if lanmember.Name == s2Name {
   503  			s2LanAddr = lanmember.Addr.String()
   504  		}
   505  	}
   506  	if s2LanAddr != "127.0.0.3" {
   507  		t.Fatalf("s3 sees s2 on a wrong address: %s, expecting: %s", s2LanAddr, "127.0.0.3")
   508  	}
   509  }
   510  
   511  func TestServer_LeaveLeader(t *testing.T) {
   512  	t.Parallel()
   513  	dir1, s1 := testServer(t)
   514  	defer os.RemoveAll(dir1)
   515  	defer s1.Shutdown()
   516  
   517  	dir2, s2 := testServerDCBootstrap(t, "dc1", false)
   518  	defer os.RemoveAll(dir2)
   519  	defer s2.Shutdown()
   520  
   521  	dir3, s3 := testServerDCBootstrap(t, "dc1", false)
   522  	defer os.RemoveAll(dir3)
   523  	defer s3.Shutdown()
   524  
   525  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   526  	joinLAN(t, s2, s1)
   527  	joinLAN(t, s3, s1)
   528  	retry.Run(t, func(r *retry.R) {
   529  		r.Check(wantPeers(s1, 3))
   530  		r.Check(wantPeers(s2, 3))
   531  		r.Check(wantPeers(s3, 3))
   532  	})
   533  	// Issue a leave to the leader
   534  	var leader *Server
   535  	switch {
   536  	case s1.IsLeader():
   537  		leader = s1
   538  	case s2.IsLeader():
   539  		leader = s2
   540  	case s3.IsLeader():
   541  		leader = s3
   542  	default:
   543  		t.Fatal("no leader")
   544  	}
   545  	if err := leader.Leave(); err != nil {
   546  		t.Fatal("leave failed: ", err)
   547  	}
   548  
   549  	// Should lose a peer
   550  	retry.Run(t, func(r *retry.R) {
   551  		r.Check(wantPeers(s1, 2))
   552  		r.Check(wantPeers(s2, 2))
   553  		r.Check(wantPeers(s3, 2))
   554  	})
   555  }
   556  
   557  func TestServer_Leave(t *testing.T) {
   558  	t.Parallel()
   559  	dir1, s1 := testServer(t)
   560  	defer os.RemoveAll(dir1)
   561  	defer s1.Shutdown()
   562  
   563  	// Second server not in bootstrap mode
   564  	dir2, s2 := testServerDCBootstrap(t, "dc1", false)
   565  	defer os.RemoveAll(dir2)
   566  	defer s2.Shutdown()
   567  
   568  	// Try to join
   569  	joinLAN(t, s2, s1)
   570  
   571  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   572  	testrpc.WaitForLeader(t, s2.RPC, "dc1")
   573  
   574  	// Issue a leave to the non-leader
   575  	var nonleader *Server
   576  	switch {
   577  	case s1.IsLeader():
   578  		nonleader = s2
   579  	case s2.IsLeader():
   580  		nonleader = s1
   581  	default:
   582  		t.Fatal("no leader")
   583  	}
   584  	if err := nonleader.Leave(); err != nil {
   585  		t.Fatal("leave failed: ", err)
   586  	}
   587  
   588  	// Should lose a peer
   589  	retry.Run(t, func(r *retry.R) {
   590  		r.Check(wantPeers(s1, 1))
   591  		r.Check(wantPeers(s2, 1))
   592  	})
   593  }
   594  
   595  func TestServer_RPC(t *testing.T) {
   596  	t.Parallel()
   597  	dir1, s1 := testServer(t)
   598  	defer os.RemoveAll(dir1)
   599  	defer s1.Shutdown()
   600  
   601  	var out struct{}
   602  	if err := s1.RPC("Status.Ping", struct{}{}, &out); err != nil {
   603  		t.Fatalf("err: %v", err)
   604  	}
   605  }
   606  
   607  func TestServer_JoinLAN_TLS(t *testing.T) {
   608  	t.Parallel()
   609  	dir1, conf1 := testServerConfig(t)
   610  	conf1.VerifyIncoming = true
   611  	conf1.VerifyOutgoing = true
   612  	configureTLS(conf1)
   613  	s1, err := newServer(conf1)
   614  	if err != nil {
   615  		t.Fatalf("err: %v", err)
   616  	}
   617  	defer os.RemoveAll(dir1)
   618  	defer s1.Shutdown()
   619  	testrpc.WaitForTestAgent(t, s1.RPC, "dc1")
   620  
   621  	dir2, conf2 := testServerConfig(t)
   622  	conf2.Bootstrap = false
   623  	conf2.VerifyIncoming = true
   624  	conf2.VerifyOutgoing = true
   625  	configureTLS(conf2)
   626  	s2, err := newServer(conf2)
   627  	if err != nil {
   628  		t.Fatalf("err: %v", err)
   629  	}
   630  	defer os.RemoveAll(dir2)
   631  	defer s2.Shutdown()
   632  
   633  	// Try to join
   634  	joinLAN(t, s2, s1)
   635  	testrpc.WaitForTestAgent(t, s2.RPC, "dc1")
   636  
   637  	// Verify Raft has established a peer
   638  	retry.Run(t, func(r *retry.R) {
   639  		r.Check(wantRaft([]*Server{s1, s2}))
   640  	})
   641  }
   642  
   643  func TestServer_Expect(t *testing.T) {
   644  	t.Parallel()
   645  	// All test servers should be in expect=3 mode, except for the 3rd one,
   646  	// but one with expect=0 can cause a bootstrap to occur from the other
   647  	// servers as currently implemented.
   648  	dir1, s1 := testServerDCExpect(t, "dc1", 3)
   649  	defer os.RemoveAll(dir1)
   650  	defer s1.Shutdown()
   651  
   652  	dir2, s2 := testServerDCExpect(t, "dc1", 3)
   653  	defer os.RemoveAll(dir2)
   654  	defer s2.Shutdown()
   655  
   656  	dir3, s3 := testServerDCExpect(t, "dc1", 0)
   657  	defer os.RemoveAll(dir3)
   658  	defer s3.Shutdown()
   659  
   660  	dir4, s4 := testServerDCExpect(t, "dc1", 3)
   661  	defer os.RemoveAll(dir4)
   662  	defer s4.Shutdown()
   663  
   664  	// Join the first two servers.
   665  	joinLAN(t, s2, s1)
   666  
   667  	// Should have no peers yet since the bootstrap didn't occur.
   668  	retry.Run(t, func(r *retry.R) {
   669  		r.Check(wantPeers(s1, 0))
   670  		r.Check(wantPeers(s2, 0))
   671  	})
   672  
   673  	// Join the third node.
   674  	joinLAN(t, s3, s1)
   675  
   676  	// Now we have three servers so we should bootstrap.
   677  	retry.Run(t, func(r *retry.R) {
   678  		r.Check(wantPeers(s1, 3))
   679  		r.Check(wantPeers(s2, 3))
   680  		r.Check(wantPeers(s3, 3))
   681  	})
   682  
   683  	// Make sure a leader is elected, grab the current term and then add in
   684  	// the fourth server.
   685  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   686  	termBefore := s1.raft.Stats()["last_log_term"]
   687  	joinLAN(t, s4, s1)
   688  
   689  	// Wait for the new server to see itself added to the cluster.
   690  	retry.Run(t, func(r *retry.R) {
   691  		r.Check(wantRaft([]*Server{s1, s2, s3, s4}))
   692  	})
   693  
   694  	// Make sure there's still a leader and that the term didn't change,
   695  	// so we know an election didn't occur.
   696  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   697  	termAfter := s1.raft.Stats()["last_log_term"]
   698  	if termAfter != termBefore {
   699  		t.Fatalf("looks like an election took place")
   700  	}
   701  }
   702  
   703  func TestServer_Expect_NonVoters(t *testing.T) {
   704  	t.Parallel()
   705  	dir1, s1 := testServerDCExpectNonVoter(t, "dc1", 3)
   706  	defer os.RemoveAll(dir1)
   707  	defer s1.Shutdown()
   708  
   709  	dir2, s2 := testServerDCExpectNonVoter(t, "dc1", 3)
   710  	defer os.RemoveAll(dir2)
   711  	defer s2.Shutdown()
   712  
   713  	dir3, s3 := testServerDCExpect(t, "dc1", 3)
   714  	defer os.RemoveAll(dir3)
   715  	defer s3.Shutdown()
   716  
   717  	dir4, s4 := testServerDCExpect(t, "dc1", 3)
   718  	defer os.RemoveAll(dir4)
   719  	defer s4.Shutdown()
   720  
   721  	dir5, s5 := testServerDCExpect(t, "dc1", 3)
   722  	defer os.RemoveAll(dir5)
   723  	defer s5.Shutdown()
   724  
   725  	// Join the first three servers.
   726  	joinLAN(t, s2, s1)
   727  	joinLAN(t, s3, s1)
   728  
   729  	// Should have no peers yet since the bootstrap didn't occur.
   730  	retry.Run(t, func(r *retry.R) {
   731  		r.Check(wantPeers(s1, 0))
   732  		r.Check(wantPeers(s2, 0))
   733  		r.Check(wantPeers(s3, 0))
   734  	})
   735  
   736  	// Join the fourth node.
   737  	joinLAN(t, s4, s1)
   738  	joinLAN(t, s5, s1)
   739  
   740  	// Now we have three servers so we should bootstrap.
   741  	retry.Run(t, func(r *retry.R) {
   742  		r.Check(wantPeers(s1, 3))
   743  		r.Check(wantPeers(s2, 3))
   744  		r.Check(wantPeers(s3, 3))
   745  		r.Check(wantPeers(s4, 3))
   746  	})
   747  
   748  	// Make sure a leader is elected
   749  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   750  	retry.Run(t, func(r *retry.R) {
   751  		r.Check(wantRaft([]*Server{s1, s2, s3, s4, s5}))
   752  	})
   753  }
   754  
   755  func TestServer_BadExpect(t *testing.T) {
   756  	t.Parallel()
   757  	// this one is in expect=3 mode
   758  	dir1, s1 := testServerDCExpect(t, "dc1", 3)
   759  	defer os.RemoveAll(dir1)
   760  	defer s1.Shutdown()
   761  
   762  	// this one is in expect=2 mode
   763  	dir2, s2 := testServerDCExpect(t, "dc1", 2)
   764  	defer os.RemoveAll(dir2)
   765  	defer s2.Shutdown()
   766  
   767  	// and this one is in expect=3 mode
   768  	dir3, s3 := testServerDCExpect(t, "dc1", 3)
   769  	defer os.RemoveAll(dir3)
   770  	defer s3.Shutdown()
   771  
   772  	// Try to join
   773  	joinLAN(t, s2, s1)
   774  
   775  	// should have no peers yet
   776  	retry.Run(t, func(r *retry.R) {
   777  		r.Check(wantPeers(s1, 0))
   778  		r.Check(wantPeers(s2, 0))
   779  	})
   780  
   781  	// join the third node
   782  	joinLAN(t, s3, s1)
   783  
   784  	// should still have no peers (because s2 is in expect=2 mode)
   785  	retry.Run(t, func(r *retry.R) {
   786  		r.Check(wantPeers(s1, 0))
   787  		r.Check(wantPeers(s2, 0))
   788  		r.Check(wantPeers(s3, 0))
   789  	})
   790  }
   791  
   792  type fakeGlobalResp struct{}
   793  
   794  func (r *fakeGlobalResp) Add(interface{}) {
   795  	return
   796  }
   797  
   798  func (r *fakeGlobalResp) New() interface{} {
   799  	return struct{}{}
   800  }
   801  
   802  func TestServer_globalRPCErrors(t *testing.T) {
   803  	t.Parallel()
   804  	dir1, s1 := testServerDC(t, "dc1")
   805  	defer os.RemoveAll(dir1)
   806  	defer s1.Shutdown()
   807  	retry.Run(t, func(r *retry.R) {
   808  		if len(s1.router.GetDatacenters()) != 1 {
   809  			r.Fatal(nil)
   810  		}
   811  	})
   812  
   813  	// Check that an error from a remote DC is returned
   814  	err := s1.globalRPC("Bad.Method", nil, &fakeGlobalResp{})
   815  	if err == nil {
   816  		t.Fatalf("should have errored")
   817  	}
   818  	if !strings.Contains(err.Error(), "Bad.Method") {
   819  		t.Fatalf("unexpected error: %s", err)
   820  	}
   821  }
   822  
   823  func TestServer_Encrypted(t *testing.T) {
   824  	t.Parallel()
   825  	dir1, s1 := testServer(t)
   826  	defer os.RemoveAll(dir1)
   827  	defer s1.Shutdown()
   828  
   829  	key := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
   830  	dir2, s2 := testServerWithConfig(t, func(c *Config) {
   831  		c.SerfLANConfig.MemberlistConfig.SecretKey = key
   832  		c.SerfWANConfig.MemberlistConfig.SecretKey = key
   833  	})
   834  	defer os.RemoveAll(dir2)
   835  	defer s2.Shutdown()
   836  
   837  	if s1.Encrypted() {
   838  		t.Fatalf("should not be encrypted")
   839  	}
   840  	if !s2.Encrypted() {
   841  		t.Fatalf("should be encrypted")
   842  	}
   843  }
   844  
   845  func testVerifyRPC(s1, s2 *Server, t *testing.T) (bool, error) {
   846  	joinLAN(t, s1, s2)
   847  	retry.Run(t, func(r *retry.R) {
   848  		r.Check(wantRaft([]*Server{s1, s2}))
   849  	})
   850  
   851  	// Have s2 make an RPC call to s1
   852  	var leader *metadata.Server
   853  	for _, server := range s2.serverLookup.Servers() {
   854  		if server.Name == s1.config.NodeName {
   855  			leader = server
   856  		}
   857  	}
   858  	if leader == nil {
   859  		t.Fatal("no leader")
   860  	}
   861  	return s2.connPool.Ping(leader.Datacenter, leader.Addr, leader.Version, leader.UseTLS)
   862  }
   863  
   864  func TestServer_TLSToNoTLS(t *testing.T) {
   865  	t.Parallel()
   866  	// Set up a server with no TLS configured
   867  	dir1, s1 := testServer(t)
   868  	defer os.RemoveAll(dir1)
   869  	defer s1.Shutdown()
   870  
   871  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   872  
   873  	// Add a second server with TLS configured
   874  	dir2, s2 := testServerWithConfig(t, func(c *Config) {
   875  		c.Bootstrap = false
   876  		c.CAFile = "../../test/client_certs/rootca.crt"
   877  		c.CertFile = "../../test/client_certs/server.crt"
   878  		c.KeyFile = "../../test/client_certs/server.key"
   879  	})
   880  	defer os.RemoveAll(dir2)
   881  	defer s2.Shutdown()
   882  
   883  	success, err := testVerifyRPC(s1, s2, t)
   884  	if err != nil {
   885  		t.Fatal(err)
   886  	}
   887  	if !success {
   888  		t.Fatalf("bad: %v", success)
   889  	}
   890  }
   891  
   892  func TestServer_TLSForceOutgoingToNoTLS(t *testing.T) {
   893  	t.Parallel()
   894  	// Set up a server with no TLS configured
   895  	dir1, s1 := testServer(t)
   896  	defer os.RemoveAll(dir1)
   897  	defer s1.Shutdown()
   898  
   899  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   900  
   901  	// Add a second server with TLS and VerifyOutgoing set
   902  	dir2, s2 := testServerWithConfig(t, func(c *Config) {
   903  		c.Bootstrap = false
   904  		c.CAFile = "../../test/client_certs/rootca.crt"
   905  		c.CertFile = "../../test/client_certs/server.crt"
   906  		c.KeyFile = "../../test/client_certs/server.key"
   907  		c.VerifyOutgoing = true
   908  	})
   909  	defer os.RemoveAll(dir2)
   910  	defer s2.Shutdown()
   911  
   912  	_, err := testVerifyRPC(s1, s2, t)
   913  	if err == nil || !strings.Contains(err.Error(), "remote error: tls") {
   914  		t.Fatalf("should fail")
   915  	}
   916  }
   917  
   918  func TestServer_TLSToFullVerify(t *testing.T) {
   919  	t.Parallel()
   920  	// Set up a server with TLS and VerifyIncoming set
   921  	dir1, s1 := testServerWithConfig(t, func(c *Config) {
   922  		c.CAFile = "../../test/client_certs/rootca.crt"
   923  		c.CertFile = "../../test/client_certs/server.crt"
   924  		c.KeyFile = "../../test/client_certs/server.key"
   925  		c.VerifyIncoming = true
   926  		c.VerifyOutgoing = true
   927  	})
   928  	defer os.RemoveAll(dir1)
   929  	defer s1.Shutdown()
   930  
   931  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   932  
   933  	// Add a second server with TLS configured
   934  	dir2, s2 := testServerWithConfig(t, func(c *Config) {
   935  		c.Bootstrap = false
   936  		c.CAFile = "../../test/client_certs/rootca.crt"
   937  		c.CertFile = "../../test/client_certs/server.crt"
   938  		c.KeyFile = "../../test/client_certs/server.key"
   939  	})
   940  	defer os.RemoveAll(dir2)
   941  	defer s2.Shutdown()
   942  
   943  	success, err := testVerifyRPC(s1, s2, t)
   944  	if err != nil {
   945  		t.Fatal(err)
   946  	}
   947  	if !success {
   948  		t.Fatalf("bad: %v", success)
   949  	}
   950  }
   951  
   952  func TestServer_RevokeLeadershipIdempotent(t *testing.T) {
   953  	t.Parallel()
   954  	dir1, s1 := testServer(t)
   955  	defer os.RemoveAll(dir1)
   956  	defer s1.Shutdown()
   957  
   958  	testrpc.WaitForLeader(t, s1.RPC, "dc1")
   959  
   960  	err := s1.revokeLeadership()
   961  	if err != nil {
   962  		t.Fatal(err)
   963  	}
   964  	err = s1.revokeLeadership()
   965  	if err != nil {
   966  		t.Fatal(err)
   967  	}
   968  }