github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/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  	"github.com/hashicorp/nomad/helper/testlog"
    12  	"github.com/hashicorp/nomad/nomad/structs"
    13  	"github.com/stretchr/testify/assert"
    14  )
    15  
    16  func TestConsulFingerprint(t *testing.T) {
    17  	fp := NewConsulFingerprint(testlog.HCLogger(t))
    18  	node := &structs.Node{
    19  		Attributes: make(map[string]string),
    20  	}
    21  
    22  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    23  		w.Header().Set("Content-Type", "application/json")
    24  		fmt.Fprintln(w, mockConsulResponse)
    25  	}))
    26  	defer ts.Close()
    27  
    28  	conf := config.DefaultConfig()
    29  	conf.ConsulConfig.Addr = strings.TrimPrefix(ts.URL, "http://")
    30  
    31  	request := &FingerprintRequest{Config: conf, Node: node}
    32  	var response FingerprintResponse
    33  	err := fp.Fingerprint(request, &response)
    34  	if err != nil {
    35  		t.Fatalf("Failed to fingerprint: %s", err)
    36  	}
    37  
    38  	if !response.Detected {
    39  		t.Fatalf("expected response to be applicable")
    40  	}
    41  
    42  	assertNodeAttributeContains(t, response.Attributes, "consul.server")
    43  	assertNodeAttributeContains(t, response.Attributes, "consul.version")
    44  	assertNodeAttributeContains(t, response.Attributes, "consul.revision")
    45  	assertNodeAttributeContains(t, response.Attributes, "unique.consul.name")
    46  	assertNodeAttributeContains(t, response.Attributes, "consul.datacenter")
    47  	assertNodeAttributeContains(t, response.Attributes, "consul.segment")
    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        "segment": "mysegment",
   157        "vsn": "2"
   158      },
   159      "Status": 1,
   160      "ProtocolMin": 1,
   161      "ProtocolMax": 2,
   162      "ProtocolCur": 2,
   163      "DelegateMin": 2,
   164      "DelegateMax": 4,
   165      "DelegateCur": 4
   166    }
   167  }
   168  `
   169  
   170  // TestConsulFingerprint_UnexpectedResponse asserts that the Consul
   171  // fingerprinter does not panic when it encounters an unexpected response.
   172  // See https://github.com/hashicorp/nomad/issues/3326
   173  func TestConsulFingerprint_UnexpectedResponse(t *testing.T) {
   174  	assert := assert.New(t)
   175  	fp := NewConsulFingerprint(testlog.HCLogger(t))
   176  	node := &structs.Node{
   177  		Attributes: make(map[string]string),
   178  	}
   179  
   180  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   181  		w.Header().Set("Content-Type", "application/json")
   182  		fmt.Fprintln(w, "{}")
   183  	}))
   184  	defer ts.Close()
   185  
   186  	conf := config.DefaultConfig()
   187  	conf.ConsulConfig.Addr = strings.TrimPrefix(ts.URL, "http://")
   188  
   189  	request := &FingerprintRequest{Config: conf, Node: node}
   190  	var response FingerprintResponse
   191  	err := fp.Fingerprint(request, &response)
   192  	assert.Nil(err)
   193  
   194  	if !response.Detected {
   195  		t.Fatalf("expected response to be applicable")
   196  	}
   197  
   198  	attrs := []string{
   199  		"consul.server",
   200  		"consul.version",
   201  		"consul.revision",
   202  		"unique.consul.name",
   203  		"consul.datacenter",
   204  		"consul.segment",
   205  	}
   206  
   207  	for _, attr := range attrs {
   208  		if v, ok := response.Attributes[attr]; ok {
   209  			t.Errorf("unexpected node attribute %q with vlaue %q", attr, v)
   210  		}
   211  	}
   212  
   213  	if v, ok := response.Links["consul"]; ok {
   214  		t.Errorf("Unexpected link to consul: %v", v)
   215  	}
   216  }