github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/e2e/servicediscovery/simple_lb_test.go (about)

     1  package servicediscovery
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/hashicorp/nomad/api"
    10  	"github.com/hashicorp/nomad/e2e/e2eutil"
    11  	"github.com/hashicorp/nomad/helper/uuid"
    12  	"github.com/shoenig/test/must"
    13  )
    14  
    15  func testSimpleLoadBalancing(t *testing.T) {
    16  	nomadClient := e2eutil.NomadClient(t)
    17  
    18  	// Generate our unique job ID which will be used for this test.
    19  	jobID := "nsd-simple-lb-replicas-" + uuid.Short()
    20  	jobIDs := []string{jobID}
    21  
    22  	// Defer a cleanup function to remove the job. This will trigger if the
    23  	// test fails, unless the cancel function is called.
    24  	ctx, cancel := context.WithCancel(context.Background())
    25  	defer cancel()
    26  	defer e2eutil.CleanupJobsAndGCWithContext(t, ctx, &jobIDs)
    27  
    28  	// Register the replicas job.
    29  	allocStubs := e2eutil.RegisterAndWaitForAllocs(t, nomadClient, jobSimpleLBReplicas, jobID, "")
    30  	must.Len(t, 3, allocStubs)
    31  
    32  	for _, stub := range allocStubs {
    33  		var tag string
    34  		switch stub.TaskGroup {
    35  		case "db_replica_1":
    36  			tag = "r1"
    37  		case "db_replica_2":
    38  			tag = "r2"
    39  		case "db_replica_3":
    40  			tag = "r3"
    41  		}
    42  		expectService := api.ServiceRegistration{
    43  			ServiceName: "db",
    44  			Namespace:   api.DefaultNamespace,
    45  			Datacenter:  "dc1",
    46  			JobID:       jobID,
    47  			AllocID:     stub.ID,
    48  			Tags:        []string{tag},
    49  		}
    50  		filter := fmt.Sprintf("Tags contains %q", tag)
    51  		requireEventuallyNomadService(t, &expectService, filter)
    52  	}
    53  
    54  	jobID2 := "nsd-simple-lb-clients" + uuid.Short()
    55  	jobIDs = append(jobIDs, jobID2)
    56  
    57  	// Register the clients job.
    58  	allocStubs = e2eutil.RegisterAndWaitForAllocs(t, nomadClient, jobSimpleLBClients, jobID2, "")
    59  	must.Len(t, 2, allocStubs)
    60  
    61  	for _, stub := range allocStubs {
    62  		var expCount int
    63  		switch stub.TaskGroup {
    64  		case "client_1":
    65  			expCount = 1
    66  		case "client_2":
    67  			expCount = 2
    68  		}
    69  		must.NoError(t, e2eutil.WaitForAllocFile(stub.ID, "cat/output.txt", func(content string) bool {
    70  			count := strings.Count(content, "server ")
    71  			return count == expCount
    72  		}, nil))
    73  	}
    74  }