| 1 |
// Copyright 2019-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"cmp" |
| 18 |
"fmt" |
| 19 |
"math/rand" |
| 20 |
"net/url" |
| 21 |
"os" |
| 22 |
"reflect" |
| 23 |
"strings" |
| 24 |
"testing" |
| 25 |
"time" |
| 26 |
|
| 27 |
"github.com/nats-io/nats-server/v2/internal/antithesis" |
| 28 |
) |
| 29 |
|
| 30 |
// DefaultTestOptions are default options for the unit tests. |
| 31 |
var DefaultTestOptions = Options{ |
| 32 |
Host: "127.0.0.1", |
| 33 |
Port: 4222, |
| 34 |
NoLog: true, |
| 35 |
NoSigs: true, |
| 36 |
MaxControlLine: 4096, |
| 37 |
DisableShortFirstPing: true, |
| 38 |
NoJetStreamStrict: false, |
| 39 |
} |
| 40 |
|
| 41 |
func testDefaultClusterOptionsForLeafNodes() *Options { |
| 42 |
o := DefaultTestOptions |
| 43 |
o.Port = -1 |
| 44 |
o.Cluster.Host = o.Host |
| 45 |
o.Cluster.Port = -1 |
| 46 |
o.Gateway.Host = o.Host |
| 47 |
o.Gateway.Port = -1 |
| 48 |
o.LeafNode.Host = o.Host |
| 49 |
o.LeafNode.Port = -1 |
| 50 |
return &o |
| 51 |
} |
| 52 |
|
| 53 |
func RunRandClientPortServer(t *testing.T) *Server { |
| 54 |
opts := DefaultTestOptions |
| 55 |
opts.Port = -1 |
| 56 |
opts.StoreDir = t.TempDir() |
| 57 |
return RunServer(&opts) |
| 58 |
} |
| 59 |
|
| 60 |
func require_True(t testing.TB, b bool) { |
| 61 |
t.Helper() |
| 62 |
if !b { |
| 63 |
antithesis.AssertUnreachable(t, "Failed require_True check", nil) |
| 64 |
t.Fatalf("require true, but got false") |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
func require_False(t testing.TB, b bool) { |
| 69 |
t.Helper() |
| 70 |
if b { |
| 71 |
antithesis.AssertUnreachable(t, "Failed require_False check", nil) |
| 72 |
t.Fatalf("require false, but got true") |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
func require_NoError(t testing.TB, err error) { |
| 77 |
t.Helper() |
| 78 |
if err != nil { |
| 79 |
antithesis.AssertUnreachable(t, "Failed require_NoError check", map[string]any{ |
| 80 |
"error": err.Error(), |
| 81 |
}) |
| 82 |
t.Fatalf("require no error, but got: %v", err) |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
// Must be used in a defer call. |
| 87 |
func require_NoPanic(t testing.TB) { |
| 88 |
t.Helper() |
| 89 |
if err := recover(); err != nil { |
| 90 |
t.Fatal(err) |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
func require_NotNil[T any](t testing.TB, vs ...T) { |
| 95 |
t.Helper() |
| 96 |
for _, v := range vs { |
| 97 |
r := reflect.ValueOf(v) |
| 98 |
switch k := r.Kind(); k { |
| 99 |
case reflect.Pointer, reflect.Interface, reflect.Slice, |
| 100 |
reflect.Map, reflect.Chan, reflect.Func: |
| 101 |
if r.IsNil() { |
| 102 |
antithesis.AssertUnreachable(t, "Failed require_NotNil check", nil) |
| 103 |
t.Fatalf("require not nil, but got nil") |
| 104 |
} |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
func require_Contains(t *testing.T, s string, subStrs ...string) { |
| 110 |
t.Helper() |
| 111 |
for _, subStr := range subStrs { |
| 112 |
if !strings.Contains(s, subStr) { |
| 113 |
antithesis.AssertUnreachable(t, "Failed require_Contains check", map[string]any{ |
| 114 |
"string": s, |
| 115 |
"sub_strings": subStr, |
| 116 |
}) |
| 117 |
t.Fatalf("require %q to be contained in %q", subStr, s) |
| 118 |
} |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
func require_Error(t testing.TB, err error, expected ...error) { |
| 123 |
t.Helper() |
| 124 |
if err == nil { |
| 125 |
antithesis.AssertUnreachable(t, "Failed require_Error check (nil error)", nil) |
| 126 |
t.Fatalf("require error, but got none") |
| 127 |
} |
| 128 |
if len(expected) == 0 { |
| 129 |
return |
| 130 |
} |
| 131 |
// Try to strip nats prefix from Go library if present. |
| 132 |
const natsErrPre = "nats: " |
| 133 |
eStr := err.Error() |
| 134 |
if strings.HasPrefix(eStr, natsErrPre) { |
| 135 |
eStr = strings.Replace(eStr, natsErrPre, _EMPTY_, 1) |
| 136 |
} |
| 137 |
|
| 138 |
for _, e := range expected { |
| 139 |
if err == e || strings.Contains(eStr, e.Error()) || strings.Contains(e.Error(), eStr) { |
| 140 |
return |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
antithesis.AssertUnreachable(t, "Failed require_Error check (unexpected error)", map[string]any{ |
| 145 |
"error": err.Error(), |
| 146 |
}) |
| 147 |
t.Fatalf("Expected one of %v, got '%v'", expected, err) |
| 148 |
} |
| 149 |
|
| 150 |
func require_Equal[T comparable](t testing.TB, a, b T) { |
| 151 |
t.Helper() |
| 152 |
if a != b { |
| 153 |
antithesis.AssertUnreachable(t, "Failed require_Equal check", nil) |
| 154 |
t.Fatalf("require %T equal, but got: %v != %v", a, a, b) |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
func require_NotEqual[T comparable](t testing.TB, a, b T) { |
| 159 |
t.Helper() |
| 160 |
if a == b { |
| 161 |
antithesis.AssertUnreachable(t, "Failed require_NotEqual check", nil) |
| 162 |
t.Fatalf("require %T not equal, but got: %v == %v", a, a, b) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
func require_Len(t testing.TB, a, b int) { |
| 167 |
t.Helper() |
| 168 |
if a != b { |
| 169 |
antithesis.AssertUnreachable(t, "Failed require_Len check", nil) |
| 170 |
t.Fatalf("require len, but got: %v != %v", a, b) |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
func require_LessThan[T cmp.Ordered](t *testing.T, a, b T) { |
| 175 |
t.Helper() |
| 176 |
if a >= b { |
| 177 |
antithesis.AssertUnreachable(t, "Failed require_LessThan check", nil) |
| 178 |
t.Fatalf("require %v to be less than %v", a, b) |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
func require_ChanRead[T any](t *testing.T, ch chan T, timeout time.Duration) T { |
| 183 |
t.Helper() |
| 184 |
select { |
| 185 |
case v := <-ch: |
| 186 |
return v |
| 187 |
case <-time.After(timeout): |
| 188 |
antithesis.AssertUnreachable(t, "Failed require_ChanRead check", nil) |
| 189 |
t.Fatalf("require read from channel within %v but didn't get anything", timeout) |
| 190 |
} |
| 191 |
panic("this shouldn't be possible") |
| 192 |
} |
| 193 |
|
| 194 |
func require_NoChanRead[T any](t *testing.T, ch chan T, timeout time.Duration) { |
| 195 |
t.Helper() |
| 196 |
select { |
| 197 |
case <-ch: |
| 198 |
antithesis.AssertUnreachable(t, "Failed require_NoChanRead check", nil) |
| 199 |
t.Fatalf("require no read from channel within %v but got something", timeout) |
| 200 |
case <-time.After(timeout): |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
func checkNatsError(t *testing.T, e *ApiError, id ErrorIdentifier) { |
| 205 |
t.Helper() |
| 206 |
ae, ok := ApiErrors[id] |
| 207 |
if !ok { |
| 208 |
t.Fatalf("Unknown error ID identifier: %d", id) |
| 209 |
} |
| 210 |
|
| 211 |
if e.ErrCode != ae.ErrCode { |
| 212 |
t.Fatalf("Did not get NATS Error %d: %+v", e.ErrCode, e) |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
// Creates a full cluster with numServers and given name and makes sure its well formed. |
| 217 |
// Will have Gateways and Leaf Node connections active. |
| 218 |
func createClusterWithName(t *testing.T, clusterName string, numServers int, connectTo ...*cluster) *cluster { |
| 219 |
t.Helper() |
| 220 |
return createClusterEx(t, false, 5*time.Millisecond, true, clusterName, numServers, connectTo...) |
| 221 |
} |
| 222 |
|
| 223 |
// Creates a cluster and optionally additional accounts and users. |
| 224 |
// Will have Gateways and Leaf Node connections active. |
| 225 |
func createClusterEx(t *testing.T, doAccounts bool, gwSolicit time.Duration, waitOnGWs bool, clusterName string, numServers int, connectTo ...*cluster) *cluster { |
| 226 |
t.Helper() |
| 227 |
|
| 228 |
if clusterName == "" || numServers < 1 { |
| 229 |
t.Fatalf("Bad params") |
| 230 |
} |
| 231 |
|
| 232 |
// Setup some accounts and users. |
| 233 |
// $SYS is always the system account. And we have default FOO and BAR accounts, as well |
| 234 |
// as DLC and NGS which do a service import. |
| 235 |
createAccountsAndUsers := func() ([]*Account, []*User) { |
| 236 |
if !doAccounts { |
| 237 |
return []*Account{NewAccount("$SYS")}, nil |
| 238 |
} |
| 239 |
|
| 240 |
sys := NewAccount("$SYS") |
| 241 |
ngs := NewAccount("NGS") |
| 242 |
dlc := NewAccount("DLC") |
| 243 |
foo := NewAccount("FOO") |
| 244 |
bar := NewAccount("BAR") |
| 245 |
|
| 246 |
accounts := []*Account{sys, foo, bar, ngs, dlc} |
| 247 |
|
| 248 |
ngs.AddServiceExport("ngs.usage.*", nil) |
| 249 |
dlc.AddServiceImport(ngs, "ngs.usage", "ngs.usage.dlc") |
| 250 |
|
| 251 |
// Setup users |
| 252 |
users := []*User{ |
| 253 |
{Username: "dlc", Password: "pass", Permissions: nil, Account: dlc}, |
| 254 |
{Username: "ngs", Password: "pass", Permissions: nil, Account: ngs}, |
| 255 |
{Username: "foo", Password: "pass", Permissions: nil, Account: foo}, |
| 256 |
{Username: "bar", Password: "pass", Permissions: nil, Account: bar}, |
| 257 |
{Username: "sys", Password: "pass", Permissions: nil, Account: sys}, |
| 258 |
} |
| 259 |
return accounts, users |
| 260 |
} |
| 261 |
|
| 262 |
bindGlobal := func(s *Server) { |
| 263 |
ngs, err := s.LookupAccount("NGS") |
| 264 |
if err != nil { |
| 265 |
return |
| 266 |
} |
| 267 |
// Bind global to service import |
| 268 |
gacc, _ := s.LookupAccount("$G") |
| 269 |
gacc.AddServiceImport(ngs, "ngs.usage", "ngs.usage.$G") |
| 270 |
} |
| 271 |
|
| 272 |
// If we are going to connect to another cluster set that up now for options. |
| 273 |
var gws []*RemoteGatewayOpts |
| 274 |
for _, c := range connectTo { |
| 275 |
// Gateways autodiscover here too, so just need one address from the set. |
| 276 |
gwAddr := fmt.Sprintf("nats-gw://%s:%d", c.opts[0].Gateway.Host, c.opts[0].Gateway.Port) |
| 277 |
gwurl, _ := url.Parse(gwAddr) |
| 278 |
gws = append(gws, &RemoteGatewayOpts{Name: c.name, URLs: []*url.URL{gwurl}}) |
| 279 |
} |
| 280 |
|
| 281 |
// Make the GWs form faster for the tests. |
| 282 |
SetGatewaysSolicitDelay(gwSolicit) |
| 283 |
defer ResetGatewaysSolicitDelay() |
| 284 |
|
| 285 |
// Create seed first. |
| 286 |
o := testDefaultClusterOptionsForLeafNodes() |
| 287 |
o.Gateway.Name = clusterName |
| 288 |
o.Gateway.Gateways = gws |
| 289 |
// All of these need system accounts. |
| 290 |
o.Accounts, o.Users = createAccountsAndUsers() |
| 291 |
o.SystemAccount = "$SYS" |
| 292 |
o.ServerName = fmt.Sprintf("%s1", clusterName) |
| 293 |
// Run the server |
| 294 |
s := RunServer(o) |
| 295 |
bindGlobal(s) |
| 296 |
|
| 297 |
c := &cluster{servers: make([]*Server, 0, numServers), opts: make([]*Options, 0, numServers), name: clusterName} |
| 298 |
c.servers = append(c.servers, s) |
| 299 |
c.opts = append(c.opts, o) |
| 300 |
|
| 301 |
// For connecting to seed server above. |
| 302 |
routeAddr := fmt.Sprintf("nats-route://%s:%d", o.Cluster.Host, o.Cluster.Port) |
| 303 |
rurl, _ := url.Parse(routeAddr) |
| 304 |
routes := []*url.URL{rurl} |
| 305 |
|
| 306 |
for i := 1; i < numServers; i++ { |
| 307 |
o := testDefaultClusterOptionsForLeafNodes() |
| 308 |
o.Gateway.Name = clusterName |
| 309 |
o.Gateway.Gateways = gws |
| 310 |
o.Routes = routes |
| 311 |
// All of these need system accounts. |
| 312 |
o.Accounts, o.Users = createAccountsAndUsers() |
| 313 |
o.SystemAccount = "$SYS" |
| 314 |
o.ServerName = fmt.Sprintf("%s%d", clusterName, i+1) |
| 315 |
s := RunServer(o) |
| 316 |
bindGlobal(s) |
| 317 |
|
| 318 |
c.servers = append(c.servers, s) |
| 319 |
c.opts = append(c.opts, o) |
| 320 |
} |
| 321 |
checkClusterFormed(t, c.servers...) |
| 322 |
|
| 323 |
if waitOnGWs { |
| 324 |
// Wait on gateway connections if we were asked to connect to other gateways. |
| 325 |
if numGWs := len(connectTo); numGWs > 0 { |
| 326 |
for _, s := range c.servers { |
| 327 |
waitForOutboundGateways(t, s, numGWs, 2*time.Second) |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
c.t = t |
| 332 |
return c |
| 333 |
} |
| 334 |
|
| 335 |
func (c *cluster) shutdown() { |
| 336 |
if c == nil { |
| 337 |
return |
| 338 |
} |
| 339 |
// Stop any proxies. |
| 340 |
for _, np := range c.nproxies { |
| 341 |
np.stop() |
| 342 |
} |
| 343 |
// Shutdown and cleanup servers. |
| 344 |
for i, s := range c.servers { |
| 345 |
sd := s.StoreDir() |
| 346 |
s.Shutdown() |
| 347 |
s.WaitForShutdown() |
| 348 |
if cf := c.opts[i].ConfigFile; cf != _EMPTY_ { |
| 349 |
os.Remove(cf) |
| 350 |
} |
| 351 |
if sd != _EMPTY_ { |
| 352 |
sd = strings.TrimSuffix(sd, JetStreamStoreDir) |
| 353 |
os.RemoveAll(sd) |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
func shutdownCluster(c *cluster) { |
| 359 |
c.shutdown() |
| 360 |
} |
| 361 |
|
| 362 |
func (c *cluster) randomServer() *Server { |
| 363 |
return c.randomServerFromCluster(c.name) |
| 364 |
} |
| 365 |
|
| 366 |
func (c *cluster) randomServerFromCluster(cname string) *Server { |
| 367 |
// Since these can be randomly shutdown in certain tests make sure they are running first. |
| 368 |
// Copy our servers list and shuffle then walk looking for first running server. |
| 369 |
cs := append(c.servers[:0:0], c.servers...) |
| 370 |
rand.Shuffle(len(cs), func(i, j int) { cs[i], cs[j] = cs[j], cs[i] }) |
| 371 |
|
| 372 |
for _, s := range cs { |
| 373 |
if s.Running() && s.ClusterName() == cname { |
| 374 |
return s |
| 375 |
} |
| 376 |
} |
| 377 |
return nil |
| 378 |
} |
| 379 |
|
| 380 |
func runSolicitLeafServer(lso *Options) (*Server, *Options) { |
| 381 |
return runSolicitLeafServerToURL(fmt.Sprintf("nats-leaf://%s:%d", lso.LeafNode.Host, lso.LeafNode.Port)) |
| 382 |
} |
| 383 |
|
| 384 |
func runSolicitLeafServerToURL(surl string) (*Server, *Options) { |
| 385 |
o := DefaultTestOptions |
| 386 |
o.Port = -1 |
| 387 |
o.NoSystemAccount = true |
| 388 |
rurl, _ := url.Parse(surl) |
| 389 |
o.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{rurl}}} |
| 390 |
o.LeafNode.ReconnectInterval = 100 * time.Millisecond |
| 391 |
return RunServer(&o), &o |
| 392 |
} |
| 393 |
|
| 394 |
func skipIfBuildkite(t *testing.T) { |
| 395 |
if os.Getenv("BUILDKITE") == "true" { |
| 396 |
t.Skip("skipping test on Buildkite CI") |
| 397 |
} |
| 398 |
} |