github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/e2e/e2eutil/consul.go (about) 1 package e2eutil 2 3 import ( 4 "fmt" 5 "time" 6 7 capi "github.com/hashicorp/consul/api" 8 "github.com/hashicorp/nomad/testutil" 9 "github.com/kr/pretty" 10 "github.com/stretchr/testify/require" 11 ) 12 13 // RequireConsulStatus asserts the aggregate health of the service converges to the expected status. 14 func RequireConsulStatus(require *require.Assertions, client *capi.Client, serviceName, expectedStatus string) { 15 testutil.WaitForResultRetries(30, func() (bool, error) { 16 defer time.Sleep(time.Second) // needs a long time for killing tasks/clients 17 18 _, status := serviceStatus(require, client, serviceName) 19 return status == expectedStatus, fmt.Errorf("service %v: expected %v but found %v", serviceName, expectedStatus, status) 20 }, func(err error) { 21 require.NoError(err, "timedout waiting for consul status") 22 }) 23 } 24 25 // serviceStatus gets the aggregate health of the service and returns the []ServiceEntry for further checking. 26 func serviceStatus(require *require.Assertions, client *capi.Client, serviceName string) ([]*capi.ServiceEntry, string) { 27 services, _, err := client.Health().Service(serviceName, "", false, nil) 28 require.NoError(err, "expected no error for %q, got %v", serviceName, err) 29 if len(services) > 0 { 30 return services, services[0].Checks.AggregatedStatus() 31 } 32 return nil, "(unknown status)" 33 } 34 35 // RequireConsulDeregistered asserts that the service eventually is de-registered from Consul. 36 func RequireConsulDeregistered(require *require.Assertions, client *capi.Client, service string) { 37 testutil.WaitForResultRetries(5, func() (bool, error) { 38 defer time.Sleep(time.Second) 39 40 services, _, err := client.Health().Service(service, "", false, nil) 41 require.NoError(err) 42 if len(services) != 0 { 43 return false, fmt.Errorf("service %v: expected empty services but found %v %v", service, len(services), pretty.Sprint(services)) 44 } 45 return true, nil 46 }, func(err error) { 47 require.NoError(err) 48 }) 49 } 50 51 // RequireConsulRegistered assert that the service is registered in Consul. 52 func RequireConsulRegistered(require *require.Assertions, client *capi.Client, service string, count int) { 53 testutil.WaitForResultRetries(5, func() (bool, error) { 54 defer time.Sleep(time.Second) 55 56 services, _, err := client.Catalog().Service(service, "", nil) 57 require.NoError(err) 58 if len(services) != count { 59 return false, fmt.Errorf("service %v: expected %v services but found %v %v", service, count, len(services), pretty.Sprint(services)) 60 } 61 return true, nil 62 }, func(err error) { 63 require.NoError(err) 64 }) 65 }