github.com/clly/consul@v1.4.5/agent/consul/issue_test.go (about)

     1  package consul
     2  
     3  import (
     4  	"os"
     5  	"reflect"
     6  	"testing"
     7  
     8  	consulfsm "github.com/hashicorp/consul/agent/consul/fsm"
     9  	"github.com/hashicorp/consul/agent/structs"
    10  	"github.com/hashicorp/consul/api"
    11  	"github.com/hashicorp/raft"
    12  )
    13  
    14  func makeLog(buf []byte) *raft.Log {
    15  	return &raft.Log{
    16  		Index: 1,
    17  		Term:  1,
    18  		Type:  raft.LogCommand,
    19  		Data:  buf,
    20  	}
    21  }
    22  
    23  // Testing for GH-300 and GH-279
    24  func TestHealthCheckRace(t *testing.T) {
    25  	t.Parallel()
    26  	fsm, err := consulfsm.New(nil, os.Stderr)
    27  	if err != nil {
    28  		t.Fatalf("err: %v", err)
    29  	}
    30  	state := fsm.State()
    31  
    32  	req := structs.RegisterRequest{
    33  		Datacenter: "dc1",
    34  		Node:       "foo",
    35  		Address:    "127.0.0.1",
    36  		Service: &structs.NodeService{
    37  			ID:      "db",
    38  			Service: "db",
    39  		},
    40  		Check: &structs.HealthCheck{
    41  			Node:      "foo",
    42  			CheckID:   "db",
    43  			Name:      "db connectivity",
    44  			Status:    api.HealthPassing,
    45  			ServiceID: "db",
    46  		},
    47  	}
    48  	buf, err := structs.Encode(structs.RegisterRequestType, req)
    49  	if err != nil {
    50  		t.Fatalf("err: %v", err)
    51  	}
    52  
    53  	log := makeLog(buf)
    54  	log.Index = 10
    55  	resp := fsm.Apply(log)
    56  	if resp != nil {
    57  		t.Fatalf("resp: %v", resp)
    58  	}
    59  
    60  	// Verify the index
    61  	idx, out1, err := state.CheckServiceNodes(nil, "db")
    62  	if err != nil {
    63  		t.Fatalf("err: %s", err)
    64  	}
    65  	if idx != 10 {
    66  		t.Fatalf("Bad index: %d", idx)
    67  	}
    68  
    69  	// Update the check state
    70  	req.Check.Status = api.HealthCritical
    71  	buf, err = structs.Encode(structs.RegisterRequestType, req)
    72  	if err != nil {
    73  		t.Fatalf("err: %v", err)
    74  	}
    75  
    76  	log = makeLog(buf)
    77  	log.Index = 20
    78  	resp = fsm.Apply(log)
    79  	if resp != nil {
    80  		t.Fatalf("resp: %v", resp)
    81  	}
    82  
    83  	// Verify the index changed
    84  	idx, out2, err := state.CheckServiceNodes(nil, "db")
    85  	if err != nil {
    86  		t.Fatalf("err: %s", err)
    87  	}
    88  	if idx != 20 {
    89  		t.Fatalf("Bad index: %d", idx)
    90  	}
    91  
    92  	if reflect.DeepEqual(out1, out2) {
    93  		t.Fatalf("match: %#v %#v", *out1[0].Checks[0], *out2[0].Checks[0])
    94  	}
    95  }