github.com/zhizhiboom/nomad@v0.8.5-0.20180907175415-f28fd3a1a056/client/fingerprint/consul_test.go (about)

     1  package fingerprint
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/hashicorp/nomad/client/config"
    11  	cstructs "github.com/hashicorp/nomad/client/structs"
    12  	"github.com/hashicorp/nomad/helper/testlog"
    13  	"github.com/hashicorp/nomad/nomad/structs"
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  func TestConsulFingerprint(t *testing.T) {
    18  	fp := NewConsulFingerprint(testlog.Logger(t))
    19  	node := &structs.Node{
    20  		Attributes: make(map[string]string),
    21  	}
    22  
    23  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    24  		w.Header().Set("Content-Type", "application/json")
    25  		fmt.Fprintln(w, mockConsulResponse)
    26  	}))
    27  	defer ts.Close()
    28  
    29  	conf := config.DefaultConfig()
    30  	conf.ConsulConfig.Addr = strings.TrimPrefix(ts.URL, "http://")
    31  
    32  	request := &cstructs.FingerprintRequest{Config: conf, Node: node}
    33  	var response cstructs.FingerprintResponse
    34  	err := fp.Fingerprint(request, &response)
    35  	if err != nil {
    36  		t.Fatalf("Failed to fingerprint: %s", err)
    37  	}
    38  
    39  	if !response.Detected {
    40  		t.Fatalf("expected response to be applicable")
    41  	}
    42  
    43  	assertNodeAttributeContains(t, response.Attributes, "consul.server")
    44  	assertNodeAttributeContains(t, response.Attributes, "consul.version")
    45  	assertNodeAttributeContains(t, response.Attributes, "consul.revision")
    46  	assertNodeAttributeContains(t, response.Attributes, "unique.consul.name")
    47  	assertNodeAttributeContains(t, response.Attributes, "consul.datacenter")
    48  
    49  	if _, ok := response.Links["consul"]; !ok {
    50  		t.Errorf("Expected a link to consul, none found")
    51  	}
    52  }
    53  
    54  // Taken from tryconsul using consul release 0.5.2
    55  const mockConsulResponse = `
    56  {
    57    "Config": {
    58      "Bootstrap": false,
    59      "BootstrapExpect": 3,
    60      "Server": true,
    61      "Datacenter": "vagrant",
    62      "DataDir": "/var/lib/consul",
    63      "DNSRecursor": "",
    64      "DNSRecursors": [],
    65      "DNSConfig": {
    66        "NodeTTL": 0,
    67        "ServiceTTL": null,
    68        "AllowStale": false,
    69        "EnableTruncate": false,
    70        "MaxStale": 5000000000,
    71        "OnlyPassing": false
    72      },
    73      "Domain": "consul.",
    74      "LogLevel": "INFO",
    75      "NodeName": "consul2",
    76      "ClientAddr": "0.0.0.0",
    77      "BindAddr": "0.0.0.0",
    78      "AdvertiseAddr": "172.16.59.133",
    79      "AdvertiseAddrWan": "172.16.59.133",
    80      "Ports": {
    81        "DNS": 8600,
    82        "HTTP": 8500,
    83        "HTTPS": -1,
    84        "RPC": 8400,
    85        "SerfLan": 8301,
    86        "SerfWan": 8302,
    87        "Server": 8300
    88      },
    89      "Addresses": {
    90        "DNS": "",
    91        "HTTP": "",
    92        "HTTPS": "",
    93        "RPC": ""
    94      },
    95      "LeaveOnTerm": false,
    96      "SkipLeaveOnInt": false,
    97      "StatsiteAddr": "",
    98      "StatsitePrefix": "consul",
    99      "StatsdAddr": "",
   100      "Protocol": 2,
   101      "EnableDebug": false,
   102      "VerifyIncoming": false,
   103      "VerifyOutgoing": false,
   104      "VerifyServerHostname": false,
   105      "CAFile": "",
   106      "CertFile": "",
   107      "KeyFile": "",
   108      "ServerName": "",
   109      "StartJoin": [],
   110      "StartJoinWan": [],
   111      "RetryJoin": [],
   112      "RetryMaxAttempts": 0,
   113      "RetryIntervalRaw": "",
   114      "RetryJoinWan": [],
   115      "RetryMaxAttemptsWan": 0,
   116      "RetryIntervalWanRaw": "",
   117      "UiDir": "/opt/consul-ui",
   118      "PidFile": "",
   119      "EnableSyslog": true,
   120      "SyslogFacility": "LOCAL0",
   121      "RejoinAfterLeave": false,
   122      "CheckUpdateInterval": 300000000000,
   123      "ACLDatacenter": "",
   124      "ACLTTL": 30000000000,
   125      "ACLTTLRaw": "",
   126      "ACLDefaultPolicy": "allow",
   127      "ACLDownPolicy": "extend-cache",
   128      "Watches": null,
   129      "DisableRemoteExec": false,
   130      "DisableUpdateCheck": false,
   131      "DisableAnonymousSignature": false,
   132      "HTTPAPIResponseHeaders": null,
   133      "AtlasInfrastructure": "",
   134      "AtlasJoin": false,
   135      "Revision": "9a9cc9341bb487651a0399e3fc5e1e8a42e62dd9+CHANGES",
   136      "Version": "0.5.2",
   137      "VersionPrerelease": "",
   138      "UnixSockets": {
   139        "Usr": "",
   140        "Grp": "",
   141        "Perms": ""
   142      },
   143      "SessionTTLMin": 0,
   144      "SessionTTLMinRaw": ""
   145    },
   146    "Member": {
   147      "Name": "consul2",
   148      "Addr": "172.16.59.133",
   149      "Port": 8301,
   150      "Tags": {
   151        "build": "0.5.2:9a9cc934",
   152        "dc": "vagrant",
   153        "expect": "3",
   154        "port": "8300",
   155        "role": "consul",
   156        "vsn": "2"
   157      },
   158      "Status": 1,
   159      "ProtocolMin": 1,
   160      "ProtocolMax": 2,
   161      "ProtocolCur": 2,
   162      "DelegateMin": 2,
   163      "DelegateMax": 4,
   164      "DelegateCur": 4
   165    }
   166  }
   167  `
   168  
   169  // TestConsulFingerprint_UnexpectedResponse asserts that the Consul
   170  // fingerprinter does not panic when it encounters an unexpected response.
   171  // See https://github.com/hashicorp/nomad/issues/3326
   172  func TestConsulFingerprint_UnexpectedResponse(t *testing.T) {
   173  	assert := assert.New(t)
   174  	fp := NewConsulFingerprint(testlog.Logger(t))
   175  	node := &structs.Node{
   176  		Attributes: make(map[string]string),
   177  	}
   178  
   179  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   180  		w.Header().Set("Content-Type", "application/json")
   181  		fmt.Fprintln(w, "{}")
   182  	}))
   183  	defer ts.Close()
   184  
   185  	conf := config.DefaultConfig()
   186  	conf.ConsulConfig.Addr = strings.TrimPrefix(ts.URL, "http://")
   187  
   188  	request := &cstructs.FingerprintRequest{Config: conf, Node: node}
   189  	var response cstructs.FingerprintResponse
   190  	err := fp.Fingerprint(request, &response)
   191  	assert.Nil(err)
   192  
   193  	if !response.Detected {
   194  		t.Fatalf("expected response to be applicable")
   195  	}
   196  
   197  	attrs := []string{
   198  		"consul.server",
   199  		"consul.version",
   200  		"consul.revision",
   201  		"unique.consul.name",
   202  		"consul.datacenter",
   203  	}
   204  
   205  	for _, attr := range attrs {
   206  		if v, ok := response.Attributes[attr]; ok {
   207  			t.Errorf("unexpected node attribute %q with vlaue %q", attr, v)
   208  		}
   209  	}
   210  
   211  	if v, ok := response.Links["consul"]; ok {
   212  		t.Errorf("Unexpected link to consul: %v", v)
   213  	}
   214  }