2015-03-03 02:18:38 +00:00
|
|
|
package testutil
|
|
|
|
|
2015-03-11 04:38:31 +00:00
|
|
|
// TestServer is a test helper. It uses a fork/exec model to create
|
|
|
|
// a test Consul server instance in the background and initialize it
|
|
|
|
// with some data and/or services. The test server can then be used
|
|
|
|
// to run a unit test, and offers an easy API to tear itself down
|
|
|
|
// when the test has completed. The only prerequisite is to have a consul
|
|
|
|
// binary available on the $PATH.
|
|
|
|
//
|
|
|
|
// This package does not use Consul's official API client. This is
|
|
|
|
// because we use TestServer to test the API client, which would
|
|
|
|
// otherwise cause an import cycle.
|
|
|
|
|
2015-03-03 02:18:38 +00:00
|
|
|
import (
|
2015-03-11 01:08:14 +00:00
|
|
|
"bytes"
|
2015-03-11 23:10:07 +00:00
|
|
|
"encoding/base64"
|
2015-03-03 02:18:38 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2015-03-11 01:08:14 +00:00
|
|
|
"io"
|
2015-03-03 02:18:38 +00:00
|
|
|
"io/ioutil"
|
2015-03-20 00:44:04 +00:00
|
|
|
"net"
|
2015-03-03 02:18:38 +00:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2017-01-27 00:55:49 +00:00
|
|
|
"strconv"
|
2015-03-20 00:44:04 +00:00
|
|
|
"strings"
|
2015-10-22 14:47:50 +00:00
|
|
|
|
2016-04-23 23:01:59 +00:00
|
|
|
"github.com/hashicorp/consul/consul/structs"
|
2015-10-22 18:14:22 +00:00
|
|
|
"github.com/hashicorp/go-cleanhttp"
|
2015-03-03 02:18:38 +00:00
|
|
|
)
|
|
|
|
|
2016-08-25 00:33:53 +00:00
|
|
|
// TestPerformanceConfig configures the performance parameters.
|
|
|
|
type TestPerformanceConfig struct {
|
|
|
|
RaftMultiplier uint `json:"raft_multiplier,omitempty"`
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// TestPortConfig configures the various ports used for services
|
|
|
|
// provided by the Consul server.
|
2015-03-03 02:18:38 +00:00
|
|
|
type TestPortConfig struct {
|
|
|
|
DNS int `json:"dns,omitempty"`
|
|
|
|
HTTP int `json:"http,omitempty"`
|
|
|
|
RPC int `json:"rpc,omitempty"`
|
|
|
|
SerfLan int `json:"serf_lan,omitempty"`
|
|
|
|
SerfWan int `json:"serf_wan,omitempty"`
|
|
|
|
Server int `json:"server,omitempty"`
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// TestAddressConfig contains the bind addresses for various
|
|
|
|
// components of the Consul server.
|
2015-03-03 02:18:38 +00:00
|
|
|
type TestAddressConfig struct {
|
|
|
|
HTTP string `json:"http,omitempty"`
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// TestServerConfig is the main server configuration struct.
|
2015-03-03 02:18:38 +00:00
|
|
|
type TestServerConfig struct {
|
2016-08-25 00:33:53 +00:00
|
|
|
NodeName string `json:"node_name"`
|
2017-01-18 01:17:20 +00:00
|
|
|
NodeMeta map[string]string `json:"node_meta,omitempty"`
|
2016-08-25 00:33:53 +00:00
|
|
|
Performance *TestPerformanceConfig `json:"performance,omitempty"`
|
|
|
|
Bootstrap bool `json:"bootstrap,omitempty"`
|
|
|
|
Server bool `json:"server,omitempty"`
|
|
|
|
DataDir string `json:"data_dir,omitempty"`
|
|
|
|
Datacenter string `json:"datacenter,omitempty"`
|
|
|
|
DisableCheckpoint bool `json:"disable_update_check"`
|
|
|
|
LogLevel string `json:"log_level,omitempty"`
|
|
|
|
Bind string `json:"bind_addr,omitempty"`
|
|
|
|
Addresses *TestAddressConfig `json:"addresses,omitempty"`
|
|
|
|
Ports *TestPortConfig `json:"ports,omitempty"`
|
|
|
|
ACLMasterToken string `json:"acl_master_token,omitempty"`
|
|
|
|
ACLDatacenter string `json:"acl_datacenter,omitempty"`
|
|
|
|
ACLDefaultPolicy string `json:"acl_default_policy,omitempty"`
|
2016-11-15 02:54:37 +00:00
|
|
|
Encrypt string `json:"encrypt,omitempty"`
|
2016-08-25 00:33:53 +00:00
|
|
|
Stdout, Stderr io.Writer `json:"-"`
|
2016-11-30 18:29:42 +00:00
|
|
|
Args []string `json:"-"`
|
2015-03-03 02:18:38 +00:00
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// ServerConfigCallback is a function interface which can be
|
|
|
|
// passed to NewTestServerConfig to modify the server config.
|
2015-03-03 02:18:38 +00:00
|
|
|
type ServerConfigCallback func(c *TestServerConfig)
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// defaultServerConfig returns a new TestServerConfig struct
|
|
|
|
// with all of the listen ports incremented by one.
|
2015-03-03 02:18:38 +00:00
|
|
|
func defaultServerConfig() *TestServerConfig {
|
|
|
|
return &TestServerConfig{
|
Use a random port instead of idx in testutil
The testutil server uses an atomic incrementer to generate unique port
numbers. This works great until tests are run in parallel, _across
packages_. Because each package starts at the same "offset" idx, they
collide.
One way to overcome this is to run each packages' test in isolation, but
that makes the test suite much longer as it does not maximize
parallelization. Alternatively, instead of having "predictable" ports,
we can let the OS choose a random open port automatically.
This still has a (albeit smaller) race condition in that the OS could
return an open port twice, before the server has a chance to actually
start and occupy said port. In practice, I have not been able to hit
this race condition, so it either doesn't happen or it happens far less
frequently that the existing implementation.
I'm not sure how I feel about the panic, but this is just test code, so
I'm including to say it's okay?
2016-12-01 15:24:26 +00:00
|
|
|
NodeName: fmt.Sprintf("node%d", randomPort()),
|
2015-03-24 02:27:59 +00:00
|
|
|
DisableCheckpoint: true,
|
2016-08-25 00:33:53 +00:00
|
|
|
Performance: &TestPerformanceConfig{
|
|
|
|
RaftMultiplier: 1,
|
|
|
|
},
|
|
|
|
Bootstrap: true,
|
|
|
|
Server: true,
|
|
|
|
LogLevel: "debug",
|
|
|
|
Bind: "127.0.0.1",
|
|
|
|
Addresses: &TestAddressConfig{},
|
2015-03-03 02:18:38 +00:00
|
|
|
Ports: &TestPortConfig{
|
Use a random port instead of idx in testutil
The testutil server uses an atomic incrementer to generate unique port
numbers. This works great until tests are run in parallel, _across
packages_. Because each package starts at the same "offset" idx, they
collide.
One way to overcome this is to run each packages' test in isolation, but
that makes the test suite much longer as it does not maximize
parallelization. Alternatively, instead of having "predictable" ports,
we can let the OS choose a random open port automatically.
This still has a (albeit smaller) race condition in that the OS could
return an open port twice, before the server has a chance to actually
start and occupy said port. In practice, I have not been able to hit
this race condition, so it either doesn't happen or it happens far less
frequently that the existing implementation.
I'm not sure how I feel about the panic, but this is just test code, so
I'm including to say it's okay?
2016-12-01 15:24:26 +00:00
|
|
|
DNS: randomPort(),
|
|
|
|
HTTP: randomPort(),
|
|
|
|
RPC: randomPort(),
|
|
|
|
SerfLan: randomPort(),
|
|
|
|
SerfWan: randomPort(),
|
|
|
|
Server: randomPort(),
|
2015-03-03 02:18:38 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Use a random port instead of idx in testutil
The testutil server uses an atomic incrementer to generate unique port
numbers. This works great until tests are run in parallel, _across
packages_. Because each package starts at the same "offset" idx, they
collide.
One way to overcome this is to run each packages' test in isolation, but
that makes the test suite much longer as it does not maximize
parallelization. Alternatively, instead of having "predictable" ports,
we can let the OS choose a random open port automatically.
This still has a (albeit smaller) race condition in that the OS could
return an open port twice, before the server has a chance to actually
start and occupy said port. In practice, I have not been able to hit
this race condition, so it either doesn't happen or it happens far less
frequently that the existing implementation.
I'm not sure how I feel about the panic, but this is just test code, so
I'm including to say it's okay?
2016-12-01 15:24:26 +00:00
|
|
|
// randomPort asks the kernel for a random port to use.
|
|
|
|
func randomPort() int {
|
|
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
defer l.Close()
|
|
|
|
return l.Addr().(*net.TCPAddr).Port
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// TestService is used to serialize a service definition.
|
2015-03-11 01:47:45 +00:00
|
|
|
type TestService struct {
|
|
|
|
ID string `json:",omitempty"`
|
|
|
|
Name string `json:",omitempty"`
|
|
|
|
Tags []string `json:",omitempty"`
|
|
|
|
Address string `json:",omitempty"`
|
|
|
|
Port int `json:",omitempty"`
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// TestCheck is used to serialize a check definition.
|
2015-03-11 01:47:45 +00:00
|
|
|
type TestCheck struct {
|
|
|
|
ID string `json:",omitempty"`
|
|
|
|
Name string `json:",omitempty"`
|
|
|
|
ServiceID string `json:",omitempty"`
|
|
|
|
TTL string `json:",omitempty"`
|
|
|
|
}
|
|
|
|
|
2016-03-18 11:27:59 +00:00
|
|
|
// TestingT is an interface wrapper around TestingT
|
|
|
|
type TestingT interface {
|
|
|
|
Logf(format string, args ...interface{})
|
|
|
|
Errorf(format string, args ...interface{})
|
|
|
|
Fatalf(format string, args ...interface{})
|
|
|
|
Fatal(args ...interface{})
|
|
|
|
Skip(args ...interface{})
|
|
|
|
}
|
|
|
|
|
2015-03-11 23:10:07 +00:00
|
|
|
// TestKVResponse is what we use to decode KV data.
|
|
|
|
type TestKVResponse struct {
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// TestServer is the main server wrapper struct.
|
2015-03-03 02:18:38 +00:00
|
|
|
type TestServer struct {
|
2016-04-15 12:35:45 +00:00
|
|
|
cmd *exec.Cmd
|
2015-03-11 18:08:08 +00:00
|
|
|
Config *TestServerConfig
|
2016-03-18 11:27:59 +00:00
|
|
|
t TestingT
|
2015-03-11 18:08:08 +00:00
|
|
|
|
2015-03-11 16:47:47 +00:00
|
|
|
HTTPAddr string
|
2015-03-11 18:08:08 +00:00
|
|
|
LANAddr string
|
|
|
|
WANAddr string
|
2015-03-20 00:44:04 +00:00
|
|
|
|
|
|
|
HttpClient *http.Client
|
2015-03-03 02:18:38 +00:00
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// NewTestServer is an easy helper method to create a new Consul
|
|
|
|
// test server with the most basic configuration.
|
2016-03-18 11:27:59 +00:00
|
|
|
func NewTestServer(t TestingT) *TestServer {
|
2015-03-03 02:18:38 +00:00
|
|
|
return NewTestServerConfig(t, nil)
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// NewTestServerConfig creates a new TestServer, and makes a call to
|
|
|
|
// an optional callback function to modify the configuration.
|
2016-03-18 11:27:59 +00:00
|
|
|
func NewTestServerConfig(t TestingT, cb ServerConfigCallback) *TestServer {
|
2015-03-03 02:18:38 +00:00
|
|
|
if path, err := exec.LookPath("consul"); err != nil || path == "" {
|
2017-01-18 00:20:29 +00:00
|
|
|
t.Fatal("consul not found on $PATH - download and install " +
|
|
|
|
"consul or skip this test")
|
2015-03-03 02:18:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
dataDir, err := ioutil.TempDir("", "consul")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
2015-05-09 01:11:17 +00:00
|
|
|
configFile, err := ioutil.TempFile(dataDir, "config")
|
2015-03-03 02:18:38 +00:00
|
|
|
if err != nil {
|
2015-03-24 02:27:59 +00:00
|
|
|
defer os.RemoveAll(dataDir)
|
2015-03-03 02:18:38 +00:00
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
consulConfig := defaultServerConfig()
|
|
|
|
consulConfig.DataDir = dataDir
|
|
|
|
|
|
|
|
if cb != nil {
|
|
|
|
cb(consulConfig)
|
|
|
|
}
|
|
|
|
|
|
|
|
configContent, err := json.Marshal(consulConfig)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := configFile.Write(configContent); err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
configFile.Close()
|
|
|
|
|
2015-06-08 14:16:11 +00:00
|
|
|
stdout := io.Writer(os.Stdout)
|
|
|
|
if consulConfig.Stdout != nil {
|
|
|
|
stdout = consulConfig.Stdout
|
|
|
|
}
|
|
|
|
|
|
|
|
stderr := io.Writer(os.Stderr)
|
|
|
|
if consulConfig.Stderr != nil {
|
|
|
|
stderr = consulConfig.Stderr
|
|
|
|
}
|
|
|
|
|
2015-03-03 02:18:38 +00:00
|
|
|
// Start the server
|
2016-11-30 18:29:42 +00:00
|
|
|
args := []string{"agent", "-config-file", configFile.Name()}
|
|
|
|
args = append(args, consulConfig.Args...)
|
|
|
|
cmd := exec.Command("consul", args...)
|
2015-06-08 14:16:11 +00:00
|
|
|
cmd.Stdout = stdout
|
|
|
|
cmd.Stderr = stderr
|
2015-03-03 02:18:38 +00:00
|
|
|
if err := cmd.Start(); err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
2015-03-20 00:44:04 +00:00
|
|
|
var httpAddr string
|
|
|
|
var client *http.Client
|
|
|
|
if strings.HasPrefix(consulConfig.Addresses.HTTP, "unix://") {
|
|
|
|
httpAddr = consulConfig.Addresses.HTTP
|
2015-10-22 14:47:50 +00:00
|
|
|
trans := cleanhttp.DefaultTransport()
|
|
|
|
trans.Dial = func(_, _ string) (net.Conn, error) {
|
|
|
|
return net.Dial("unix", httpAddr[7:])
|
|
|
|
}
|
2015-03-20 00:44:04 +00:00
|
|
|
client = &http.Client{
|
2015-10-22 14:47:50 +00:00
|
|
|
Transport: trans,
|
2015-03-20 00:44:04 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
httpAddr = fmt.Sprintf("127.0.0.1:%d", consulConfig.Ports.HTTP)
|
2015-10-22 14:47:50 +00:00
|
|
|
client = cleanhttp.DefaultClient()
|
2015-03-20 00:44:04 +00:00
|
|
|
}
|
|
|
|
|
2015-03-03 02:18:38 +00:00
|
|
|
server := &TestServer{
|
2015-03-11 18:08:08 +00:00
|
|
|
Config: consulConfig,
|
2016-04-15 12:35:45 +00:00
|
|
|
cmd: cmd,
|
2015-03-11 18:08:08 +00:00
|
|
|
t: t,
|
|
|
|
|
2015-03-20 00:44:04 +00:00
|
|
|
HTTPAddr: httpAddr,
|
2015-03-11 18:08:08 +00:00
|
|
|
LANAddr: fmt.Sprintf("127.0.0.1:%d", consulConfig.Ports.SerfLan),
|
|
|
|
WANAddr: fmt.Sprintf("127.0.0.1:%d", consulConfig.Ports.SerfWan),
|
2015-03-20 00:44:04 +00:00
|
|
|
|
|
|
|
HttpClient: client,
|
2015-03-03 02:18:38 +00:00
|
|
|
}
|
|
|
|
|
2015-03-03 03:20:13 +00:00
|
|
|
// Wait for the server to be ready
|
2015-05-09 01:16:35 +00:00
|
|
|
if consulConfig.Bootstrap {
|
2015-05-09 01:11:17 +00:00
|
|
|
server.waitForLeader()
|
2015-05-09 01:16:35 +00:00
|
|
|
} else {
|
|
|
|
server.waitForAPI()
|
2015-05-09 01:11:17 +00:00
|
|
|
}
|
2015-03-03 03:20:13 +00:00
|
|
|
|
2015-03-03 02:18:38 +00:00
|
|
|
return server
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// Stop stops the test Consul server, and removes the Consul data
|
|
|
|
// directory once we are done.
|
2015-03-03 02:18:38 +00:00
|
|
|
func (s *TestServer) Stop() {
|
2015-03-03 03:20:13 +00:00
|
|
|
defer os.RemoveAll(s.Config.DataDir)
|
2015-03-03 02:18:38 +00:00
|
|
|
|
2016-04-15 12:35:45 +00:00
|
|
|
if err := s.cmd.Process.Kill(); err != nil {
|
2015-04-23 03:35:27 +00:00
|
|
|
s.t.Errorf("err: %s", err)
|
2015-03-03 02:18:38 +00:00
|
|
|
}
|
2016-04-15 12:35:45 +00:00
|
|
|
|
|
|
|
// wait for the process to exit to be sure that the data dir can be
|
|
|
|
// deleted on all platforms.
|
|
|
|
s.cmd.Wait()
|
2015-03-03 02:18:38 +00:00
|
|
|
}
|
|
|
|
|
2015-05-09 01:11:17 +00:00
|
|
|
// waitForAPI waits for only the agent HTTP endpoint to start
|
|
|
|
// responding. This is an indication that the agent has started,
|
|
|
|
// but will likely return before a leader is elected.
|
|
|
|
func (s *TestServer) waitForAPI() {
|
|
|
|
WaitForResult(func() (bool, error) {
|
|
|
|
resp, err := s.HttpClient.Get(s.url("/v1/agent/self"))
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if err := s.requireOK(resp); err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return true, nil
|
|
|
|
}, func(err error) {
|
|
|
|
defer s.Stop()
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// waitForLeader waits for the Consul server's HTTP API to become
|
|
|
|
// available, and then waits for a known leader and an index of
|
|
|
|
// 1 or more to be observed to confirm leader election is done.
|
2017-01-27 00:55:49 +00:00
|
|
|
// It then waits to ensure the anti-entropy sync has completed.
|
2015-03-21 13:45:26 +00:00
|
|
|
func (s *TestServer) waitForLeader() {
|
2017-01-27 00:55:49 +00:00
|
|
|
var index int64
|
2015-03-03 02:18:38 +00:00
|
|
|
WaitForResult(func() (bool, error) {
|
2017-01-27 00:55:49 +00:00
|
|
|
// Query the API and check the status code.
|
|
|
|
url := s.url(fmt.Sprintf("/v1/catalog/nodes?index=%d&wait=10s", index))
|
|
|
|
resp, err := s.HttpClient.Get(url)
|
2015-03-24 02:27:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if err := s.requireOK(resp); err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
2015-03-03 02:18:38 +00:00
|
|
|
|
2017-01-27 00:55:49 +00:00
|
|
|
// Ensure we have a leader and a node registration.
|
2015-03-03 02:18:38 +00:00
|
|
|
if leader := resp.Header.Get("X-Consul-KnownLeader"); leader != "true" {
|
|
|
|
return false, fmt.Errorf("Consul leader status: %#v", leader)
|
|
|
|
}
|
2017-01-27 00:55:49 +00:00
|
|
|
index, err = strconv.ParseInt(resp.Header.Get("X-Consul-Index"), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return false, fmt.Errorf("Consul index was bad: %v", err)
|
|
|
|
}
|
|
|
|
if index == 0 {
|
2015-03-03 02:18:38 +00:00
|
|
|
return false, fmt.Errorf("Consul index is 0")
|
|
|
|
}
|
2017-01-26 05:13:03 +00:00
|
|
|
|
2017-01-27 00:55:49 +00:00
|
|
|
// Watch for the anti-entropy sync to finish.
|
2017-01-26 05:13:03 +00:00
|
|
|
var parsed []map[string]interface{}
|
|
|
|
dec := json.NewDecoder(resp.Body)
|
|
|
|
if err := dec.Decode(&parsed); err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if len(parsed) < 1 {
|
|
|
|
return false, fmt.Errorf("No nodes")
|
|
|
|
}
|
|
|
|
taggedAddresses, ok := parsed[0]["TaggedAddresses"].(map[string]interface{})
|
|
|
|
if !ok {
|
|
|
|
return false, fmt.Errorf("Missing tagged addresses")
|
|
|
|
}
|
|
|
|
if _, ok := taggedAddresses["lan"]; !ok {
|
|
|
|
return false, fmt.Errorf("No lan tagged addresses")
|
|
|
|
}
|
2015-03-03 02:18:38 +00:00
|
|
|
return true, nil
|
|
|
|
}, func(err error) {
|
2015-03-24 02:27:59 +00:00
|
|
|
defer s.Stop()
|
2015-03-21 13:45:26 +00:00
|
|
|
s.t.Fatalf("err: %s", err)
|
2015-03-03 02:18:38 +00:00
|
|
|
})
|
|
|
|
}
|
2015-03-11 01:08:14 +00:00
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// url is a helper function which takes a relative URL and
|
|
|
|
// makes it into a proper URL against the local Consul server.
|
2015-03-11 01:08:14 +00:00
|
|
|
func (s *TestServer) url(path string) string {
|
|
|
|
return fmt.Sprintf("http://127.0.0.1:%d%s", s.Config.Ports.HTTP, path)
|
|
|
|
}
|
|
|
|
|
2015-03-24 05:47:34 +00:00
|
|
|
// requireOK checks the HTTP response code and ensures it is acceptable.
|
2015-03-24 02:27:59 +00:00
|
|
|
func (s *TestServer) requireOK(resp *http.Response) error {
|
2015-03-21 13:45:26 +00:00
|
|
|
if resp.StatusCode != 200 {
|
2015-03-24 05:47:34 +00:00
|
|
|
return fmt.Errorf("Bad status code: %d", resp.StatusCode)
|
2015-03-11 01:08:14 +00:00
|
|
|
}
|
2015-03-24 02:27:59 +00:00
|
|
|
return nil
|
2015-03-11 01:08:14 +00:00
|
|
|
}
|
|
|
|
|
2015-03-21 13:45:26 +00:00
|
|
|
// put performs a new HTTP PUT request.
|
|
|
|
func (s *TestServer) put(path string, body io.Reader) *http.Response {
|
|
|
|
req, err := http.NewRequest("PUT", s.url(path), body)
|
2015-03-11 18:08:08 +00:00
|
|
|
if err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
2015-03-20 00:44:04 +00:00
|
|
|
resp, err := s.HttpClient.Do(req)
|
2015-03-11 01:08:14 +00:00
|
|
|
if err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
2015-03-24 02:27:59 +00:00
|
|
|
if err := s.requireOK(resp); err != nil {
|
2015-03-24 05:47:34 +00:00
|
|
|
defer resp.Body.Close()
|
|
|
|
s.t.Fatal(err)
|
2015-03-24 02:27:59 +00:00
|
|
|
}
|
2015-03-21 13:45:26 +00:00
|
|
|
return resp
|
|
|
|
}
|
2015-03-11 01:08:14 +00:00
|
|
|
|
2015-03-21 13:45:26 +00:00
|
|
|
// get performs a new HTTP GET request.
|
|
|
|
func (s *TestServer) get(path string) *http.Response {
|
|
|
|
resp, err := s.HttpClient.Get(s.url(path))
|
2015-03-11 01:47:45 +00:00
|
|
|
if err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
2015-03-24 02:27:59 +00:00
|
|
|
if err := s.requireOK(resp); err != nil {
|
2015-03-24 05:47:34 +00:00
|
|
|
defer resp.Body.Close()
|
|
|
|
s.t.Fatal(err)
|
2015-03-24 02:27:59 +00:00
|
|
|
}
|
2015-03-21 13:45:26 +00:00
|
|
|
return resp
|
2015-03-11 01:47:45 +00:00
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// encodePayload returns a new io.Reader wrapping the encoded contents
|
|
|
|
// of the payload, suitable for passing directly to a new request.
|
2015-03-11 01:47:45 +00:00
|
|
|
func (s *TestServer) encodePayload(payload interface{}) io.Reader {
|
|
|
|
var encoded bytes.Buffer
|
|
|
|
enc := json.NewEncoder(&encoded)
|
|
|
|
if err := enc.Encode(payload); err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
2015-03-11 01:08:14 +00:00
|
|
|
}
|
2015-03-11 01:47:45 +00:00
|
|
|
return &encoded
|
2015-03-11 01:08:14 +00:00
|
|
|
}
|
|
|
|
|
2015-03-11 18:08:08 +00:00
|
|
|
// JoinLAN is used to join nodes within the same datacenter.
|
|
|
|
func (s *TestServer) JoinLAN(addr string) {
|
2015-03-21 13:45:26 +00:00
|
|
|
resp := s.get("/v1/agent/join/" + addr)
|
|
|
|
resp.Body.Close()
|
2015-03-11 18:08:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// JoinWAN is used to join remote datacenters together.
|
|
|
|
func (s *TestServer) JoinWAN(addr string) {
|
2015-03-21 13:45:26 +00:00
|
|
|
resp := s.get("/v1/agent/join/" + addr + "?wan=1")
|
|
|
|
resp.Body.Close()
|
2015-03-11 18:08:08 +00:00
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// SetKV sets an individual key in the K/V store.
|
2015-03-11 04:38:31 +00:00
|
|
|
func (s *TestServer) SetKV(key string, val []byte) {
|
2015-03-21 13:45:26 +00:00
|
|
|
resp := s.put("/v1/kv/"+key, bytes.NewBuffer(val))
|
|
|
|
resp.Body.Close()
|
2015-03-11 01:08:14 +00:00
|
|
|
}
|
|
|
|
|
2015-03-11 23:10:07 +00:00
|
|
|
// GetKV retrieves a single key and returns its value
|
|
|
|
func (s *TestServer) GetKV(key string) []byte {
|
2015-03-21 13:45:26 +00:00
|
|
|
resp := s.get("/v1/kv/" + key)
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
2015-03-24 05:47:34 +00:00
|
|
|
raw, err := ioutil.ReadAll(resp.Body)
|
2015-03-21 13:45:26 +00:00
|
|
|
if err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
2015-03-11 23:10:07 +00:00
|
|
|
|
|
|
|
var result []*TestKVResponse
|
2015-03-24 05:47:34 +00:00
|
|
|
if err := json.Unmarshal(raw, &result); err != nil {
|
2015-03-11 23:10:07 +00:00
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
2015-03-24 05:47:34 +00:00
|
|
|
if len(result) < 1 {
|
|
|
|
s.t.Fatalf("key does not exist: %s", key)
|
|
|
|
}
|
2015-03-11 23:10:07 +00:00
|
|
|
|
|
|
|
v, err := base64.StdEncoding.DecodeString(result[0].Value)
|
|
|
|
if err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
2016-03-18 15:12:56 +00:00
|
|
|
return v
|
2015-03-11 23:10:07 +00:00
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// PopulateKV fills the Consul KV with data from a generic map.
|
2015-03-11 04:38:31 +00:00
|
|
|
func (s *TestServer) PopulateKV(data map[string][]byte) {
|
|
|
|
for k, v := range data {
|
|
|
|
s.SetKV(k, v)
|
|
|
|
}
|
2015-03-11 01:08:14 +00:00
|
|
|
}
|
2015-03-11 01:47:45 +00:00
|
|
|
|
2015-03-24 05:47:34 +00:00
|
|
|
// ListKV returns a list of keys present in the KV store. This will list all
|
|
|
|
// keys under the given prefix recursively and return them as a slice.
|
|
|
|
func (s *TestServer) ListKV(prefix string) []string {
|
|
|
|
resp := s.get("/v1/kv/" + prefix + "?keys")
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
raw, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var result []string
|
|
|
|
if err := json.Unmarshal(raw, &result); err != nil {
|
|
|
|
s.t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// AddService adds a new service to the Consul instance. It also
|
|
|
|
// automatically adds a health check with the given status, which
|
|
|
|
// can be one of "passing", "warning", or "critical".
|
2015-03-11 01:47:45 +00:00
|
|
|
func (s *TestServer) AddService(name, status string, tags []string) {
|
|
|
|
svc := &TestService{
|
|
|
|
Name: name,
|
|
|
|
Tags: tags,
|
|
|
|
}
|
|
|
|
payload := s.encodePayload(svc)
|
|
|
|
s.put("/v1/agent/service/register", payload)
|
|
|
|
|
2015-03-11 04:38:31 +00:00
|
|
|
chkName := "service:" + name
|
2015-03-11 01:47:45 +00:00
|
|
|
chk := &TestCheck{
|
2015-03-11 04:38:31 +00:00
|
|
|
Name: chkName,
|
2015-03-11 01:47:45 +00:00
|
|
|
ServiceID: name,
|
|
|
|
TTL: "10m",
|
|
|
|
}
|
|
|
|
payload = s.encodePayload(chk)
|
|
|
|
s.put("/v1/agent/check/register", payload)
|
|
|
|
|
2015-03-11 04:38:31 +00:00
|
|
|
switch status {
|
2016-04-23 23:01:59 +00:00
|
|
|
case structs.HealthPassing:
|
2015-03-11 04:38:31 +00:00
|
|
|
s.put("/v1/agent/check/pass/"+chkName, nil)
|
2016-04-23 23:01:59 +00:00
|
|
|
case structs.HealthWarning:
|
2015-03-11 04:38:31 +00:00
|
|
|
s.put("/v1/agent/check/warn/"+chkName, nil)
|
2016-04-23 23:01:59 +00:00
|
|
|
case structs.HealthCritical:
|
2015-03-11 04:38:31 +00:00
|
|
|
s.put("/v1/agent/check/fail/"+chkName, nil)
|
|
|
|
default:
|
|
|
|
s.t.Fatalf("Unrecognized status: %s", status)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-11 04:53:51 +00:00
|
|
|
// AddCheck adds a check to the Consul instance. If the serviceID is
|
|
|
|
// left empty (""), then the check will be associated with the node.
|
|
|
|
// The check status may be "passing", "warning", or "critical".
|
2015-03-11 04:38:31 +00:00
|
|
|
func (s *TestServer) AddCheck(name, serviceID, status string) {
|
|
|
|
chk := &TestCheck{
|
|
|
|
ID: name,
|
|
|
|
Name: name,
|
|
|
|
TTL: "10m",
|
|
|
|
}
|
|
|
|
if serviceID != "" {
|
|
|
|
chk.ServiceID = serviceID
|
|
|
|
}
|
|
|
|
|
|
|
|
payload := s.encodePayload(chk)
|
|
|
|
s.put("/v1/agent/check/register", payload)
|
|
|
|
|
2015-03-11 01:47:45 +00:00
|
|
|
switch status {
|
2016-04-23 23:01:59 +00:00
|
|
|
case structs.HealthPassing:
|
2015-03-11 01:47:45 +00:00
|
|
|
s.put("/v1/agent/check/pass/"+name, nil)
|
2016-04-23 23:01:59 +00:00
|
|
|
case structs.HealthWarning:
|
2015-03-11 01:47:45 +00:00
|
|
|
s.put("/v1/agent/check/warn/"+name, nil)
|
2016-04-23 23:01:59 +00:00
|
|
|
case structs.HealthCritical:
|
2015-03-11 01:47:45 +00:00
|
|
|
s.put("/v1/agent/check/fail/"+name, nil)
|
2015-03-11 04:38:31 +00:00
|
|
|
default:
|
|
|
|
s.t.Fatalf("Unrecognized status: %s", status)
|
2015-03-11 01:47:45 +00:00
|
|
|
}
|
|
|
|
}
|