| 1 |
// Copyright 2012-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 |
"bufio" |
| 18 |
"bytes" |
| 19 |
"context" |
| 20 |
"crypto/tls" |
| 21 |
"encoding/json" |
| 22 |
"errors" |
| 23 |
"flag" |
| 24 |
"fmt" |
| 25 |
"io" |
| 26 |
"net" |
| 27 |
"net/url" |
| 28 |
"os" |
| 29 |
"reflect" |
| 30 |
"runtime" |
| 31 |
"slices" |
| 32 |
"strings" |
| 33 |
"sync" |
| 34 |
"sync/atomic" |
| 35 |
"testing" |
| 36 |
"time" |
| 37 |
|
| 38 |
"github.com/nats-io/nats.go" |
| 39 |
|
| 40 |
"github.com/nats-io/nats-server/v2/internal/antithesis" |
| 41 |
srvlog "github.com/nats-io/nats-server/v2/logger" |
| 42 |
) |
| 43 |
|
| 44 |
func checkForErr(totalWait, sleepDur time.Duration, f func() error) error { |
| 45 |
timeout := time.Now().Add(totalWait) |
| 46 |
var err error |
| 47 |
for time.Now().Before(timeout) { |
| 48 |
err = f() |
| 49 |
if err == nil { |
| 50 |
return nil |
| 51 |
} |
| 52 |
time.Sleep(sleepDur) |
| 53 |
} |
| 54 |
return err |
| 55 |
} |
| 56 |
|
| 57 |
func checkFor(t testing.TB, totalWait, sleepDur time.Duration, f func() error) { |
| 58 |
t.Helper() |
| 59 |
err := checkForErr(totalWait, sleepDur, f) |
| 60 |
if err != nil { |
| 61 |
antithesis.AssertUnreachable(t, "Timeout in checkFor", nil) |
| 62 |
t.Fatal(err.Error()) |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
func DefaultOptions() *Options { |
| 67 |
return &Options{ |
| 68 |
Host: "127.0.0.1", |
| 69 |
Port: -1, |
| 70 |
HTTPPort: -1, |
| 71 |
Cluster: ClusterOpts{Port: -1, Name: "abc"}, |
| 72 |
NoLog: true, |
| 73 |
NoSigs: true, |
| 74 |
Debug: true, |
| 75 |
Trace: true, |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
// New Go Routine based server |
| 80 |
func RunServer(opts *Options) *Server { |
| 81 |
if opts == nil { |
| 82 |
opts = DefaultOptions() |
| 83 |
} |
| 84 |
s, err := NewServer(opts) |
| 85 |
if err != nil || s == nil { |
| 86 |
panic(fmt.Sprintf("No NATS Server object returned: %v", err)) |
| 87 |
} |
| 88 |
|
| 89 |
if !opts.NoLog { |
| 90 |
s.ConfigureLogger() |
| 91 |
} |
| 92 |
|
| 93 |
if ll := os.Getenv("NATS_LOGGING"); ll != "" { |
| 94 |
log := srvlog.NewTestLogger(fmt.Sprintf("[%s] | ", s), true) |
| 95 |
debug := ll == "debug" || ll == "trace" |
| 96 |
trace := ll == "trace" |
| 97 |
s.SetLoggerV2(log, debug, trace, false) |
| 98 |
} |
| 99 |
|
| 100 |
// Run server in Go routine. |
| 101 |
s.Start() |
| 102 |
|
| 103 |
// Wait for accept loop(s) to be started |
| 104 |
if err := s.readyForConnections(10 * time.Second); err != nil { |
| 105 |
panic(err) |
| 106 |
} |
| 107 |
return s |
| 108 |
} |
| 109 |
|
| 110 |
// LoadConfig loads a configuration from a filename |
| 111 |
func LoadConfig(configFile string) (opts *Options) { |
| 112 |
opts, err := ProcessConfigFile(configFile) |
| 113 |
if err != nil { |
| 114 |
panic(fmt.Sprintf("Error processing configuration file: %v", err)) |
| 115 |
} |
| 116 |
opts.NoSigs, opts.NoLog = true, opts.LogFile == _EMPTY_ |
| 117 |
return |
| 118 |
} |
| 119 |
|
| 120 |
// RunServerWithConfig starts a new Go routine based server with a configuration file. |
| 121 |
func RunServerWithConfig(configFile string) (srv *Server, opts *Options) { |
| 122 |
opts = LoadConfig(configFile) |
| 123 |
srv = RunServer(opts) |
| 124 |
return |
| 125 |
} |
| 126 |
|
| 127 |
func TestSemanticVersion(t *testing.T) { |
| 128 |
if !semVerRe.MatchString(VERSION) { |
| 129 |
t.Fatalf("Version (%s) is not a valid SemVer string", VERSION) |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
func TestVersionMatchesTag(t *testing.T) { |
| 134 |
tag := os.Getenv("TRAVIS_TAG") |
| 135 |
// Travis started to return '' when no tag is set. Support both now. |
| 136 |
if tag == "" || tag == "''" { |
| 137 |
t.SkipNow() |
| 138 |
} |
| 139 |
// We expect a tag of the form vX.Y.Z. If that's not the case, |
| 140 |
// we need someone to have a look. So fail if first letter is not |
| 141 |
// a `v` |
| 142 |
if tag[0] != 'v' { |
| 143 |
t.Fatalf("Expect tag to start with `v`, tag is: %s", tag) |
| 144 |
} |
| 145 |
// Strip the `v` from the tag for the version comparison. |
| 146 |
if VERSION != tag[1:] { |
| 147 |
t.Fatalf("Version (%s) does not match tag (%s)", VERSION, tag[1:]) |
| 148 |
} |
| 149 |
// Check that the version dynamically set via ldflags matches the version |
| 150 |
// from the server previous to releasing. |
| 151 |
if serverVersion == _EMPTY_ { |
| 152 |
t.Fatal("Version missing in ldflags") |
| 153 |
} |
| 154 |
// Unlike VERSION constant, serverVersion is prefixed with a 'v' |
| 155 |
// since it should be the same as the git tag. |
| 156 |
expected := "v" + VERSION |
| 157 |
if serverVersion != _EMPTY_ && expected != serverVersion { |
| 158 |
t.Fatalf("Version (%s) does not match ldflags version (%s)", expected, serverVersion) |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
func TestStartProfiler(t *testing.T) { |
| 163 |
s := New(DefaultOptions()) |
| 164 |
s.StartProfiler() |
| 165 |
s.mu.Lock() |
| 166 |
s.profiler.Close() |
| 167 |
s.mu.Unlock() |
| 168 |
} |
| 169 |
|
| 170 |
func TestStartupAndShutdown(t *testing.T) { |
| 171 |
opts := DefaultOptions() |
| 172 |
opts.NoSystemAccount = true |
| 173 |
|
| 174 |
s := RunServer(opts) |
| 175 |
defer s.Shutdown() |
| 176 |
|
| 177 |
if !s.isRunning() { |
| 178 |
t.Fatal("Could not run server") |
| 179 |
} |
| 180 |
|
| 181 |
// Debug stuff. |
| 182 |
numRoutes := s.NumRoutes() |
| 183 |
if numRoutes != 0 { |
| 184 |
t.Fatalf("Expected numRoutes to be 0 vs %d\n", numRoutes) |
| 185 |
} |
| 186 |
|
| 187 |
numRemotes := s.NumRemotes() |
| 188 |
if numRemotes != 0 { |
| 189 |
t.Fatalf("Expected numRemotes to be 0 vs %d\n", numRemotes) |
| 190 |
} |
| 191 |
|
| 192 |
numClients := s.NumClients() |
| 193 |
if numClients != 0 && numClients != 1 { |
| 194 |
t.Fatalf("Expected numClients to be 1 or 0 vs %d\n", numClients) |
| 195 |
} |
| 196 |
|
| 197 |
numSubscriptions := s.NumSubscriptions() |
| 198 |
if numSubscriptions != 0 { |
| 199 |
t.Fatalf("Expected numSubscriptions to be 0 vs %d\n", numSubscriptions) |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
func TestConcurrentShutdown(t *testing.T) { |
| 204 |
opts := DefaultOptions() |
| 205 |
opts.DisableShortFirstPing = true |
| 206 |
opts.Accounts = []*Account{NewAccount("$SYS")} |
| 207 |
opts.SystemAccount = "$SYS" |
| 208 |
|
| 209 |
s := RunServer(opts) |
| 210 |
if !s.EventsEnabled() { |
| 211 |
t.Fatal("Expected events to be enabled") |
| 212 |
} |
| 213 |
|
| 214 |
const callers = 32 |
| 215 |
start := make(chan struct{}) |
| 216 |
var wg sync.WaitGroup |
| 217 |
wg.Add(callers) |
| 218 |
for i := 0; i < callers; i++ { |
| 219 |
go func() { |
| 220 |
defer wg.Done() |
| 221 |
<-start |
| 222 |
s.Shutdown() |
| 223 |
}() |
| 224 |
} |
| 225 |
close(start) |
| 226 |
|
| 227 |
done := make(chan struct{}) |
| 228 |
go func() { |
| 229 |
wg.Wait() |
| 230 |
close(done) |
| 231 |
}() |
| 232 |
|
| 233 |
select { |
| 234 |
case <-done: |
| 235 |
case <-time.After(5 * time.Second): |
| 236 |
t.Fatal("Timed out waiting for concurrent shutdown calls") |
| 237 |
} |
| 238 |
s.WaitForShutdown() |
| 239 |
} |
| 240 |
|
| 241 |
func TestTLSVersions(t *testing.T) { |
| 242 |
for _, test := range []struct { |
| 243 |
name string |
| 244 |
value uint16 |
| 245 |
expected string |
| 246 |
}{ |
| 247 |
{"1.0", tls.VersionTLS10, "1.0"}, |
| 248 |
{"1.1", tls.VersionTLS11, "1.1"}, |
| 249 |
{"1.2", tls.VersionTLS12, "1.2"}, |
| 250 |
{"1.3", tls.VersionTLS13, "1.3"}, |
| 251 |
{"unknown", 0x999, "Unknown [0x999]"}, |
| 252 |
} { |
| 253 |
t.Run(test.name, func(t *testing.T) { |
| 254 |
if v := tlsVersion(test.value); v != test.expected { |
| 255 |
t.Fatalf("Expected value 0x%x to be %q, got %q", test.value, test.expected, v) |
| 256 |
} |
| 257 |
}) |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
func TestTLSMinVersionConfig(t *testing.T) { |
| 262 |
tmpl := ` |
| 263 |
listen: "127.0.0.1:-1" |
| 264 |
tls { |
| 265 |
cert_file: "../test/configs/certs/server-cert.pem" |
| 266 |
key_file: "../test/configs/certs/server-key.pem" |
| 267 |
timeout: 1 |
| 268 |
min_version: %s |
| 269 |
} |
| 270 |
` |
| 271 |
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, `"1.3"`))) |
| 272 |
s, o := RunServerWithConfig(conf) |
| 273 |
defer s.Shutdown() |
| 274 |
|
| 275 |
connect := func(t *testing.T, tlsConf *tls.Config, expectedErr error) { |
| 276 |
t.Helper() |
| 277 |
opts := []nats.Option{} |
| 278 |
if tlsConf != nil { |
| 279 |
opts = append(opts, nats.Secure(tlsConf)) |
| 280 |
} |
| 281 |
opts = append(opts, nats.RootCAs("../test/configs/certs/ca.pem")) |
| 282 |
nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", o.Port), opts...) |
| 283 |
if err == nil { |
| 284 |
defer nc.Close() |
| 285 |
} |
| 286 |
if expectedErr == nil { |
| 287 |
if err != nil { |
| 288 |
t.Fatalf("Unexpected error: %v", err) |
| 289 |
} |
| 290 |
} else if err == nil || err.Error() != expectedErr.Error() { |
| 291 |
nc.Close() |
| 292 |
t.Fatalf("Expected error %v, got: %v", expectedErr, err) |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
// Cannot connect with client requiring a lower minimum TLS Version. |
| 297 |
connect(t, &tls.Config{ |
| 298 |
MaxVersion: tls.VersionTLS12, |
| 299 |
}, errors.New(`nats: tls error: remote error: tls: protocol version not supported`)) |
| 300 |
|
| 301 |
// Should connect since matching minimum TLS version. |
| 302 |
connect(t, &tls.Config{ |
| 303 |
MinVersion: tls.VersionTLS13, |
| 304 |
}, nil) |
| 305 |
|
| 306 |
// Reloading with invalid values should fail. |
| 307 |
if err := os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, `"1.0"`)), 0666); err != nil { |
| 308 |
t.Fatalf("Error creating config file: %v", err) |
| 309 |
} |
| 310 |
if err := s.Reload(); err == nil { |
| 311 |
t.Fatalf("Expected reload to fail: %v", err) |
| 312 |
} |
| 313 |
|
| 314 |
// Reloading with original values and no changes should be ok. |
| 315 |
if err := os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, `"1.3"`)), 0666); err != nil { |
| 316 |
t.Fatalf("Error creating config file: %v", err) |
| 317 |
} |
| 318 |
if err := s.Reload(); err != nil { |
| 319 |
t.Fatalf("Unexpected error reloading TLS version: %v", err) |
| 320 |
} |
| 321 |
|
| 322 |
// Reloading with a new minimum lower version. |
| 323 |
if err := os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, `"1.2"`)), 0666); err != nil { |
| 324 |
t.Fatalf("Error creating config file: %v", err) |
| 325 |
} |
| 326 |
if err := s.Reload(); err != nil { |
| 327 |
t.Fatalf("Unexpected error reloading: %v", err) |
| 328 |
} |
| 329 |
|
| 330 |
// Should connect since now matching minimum TLS version. |
| 331 |
connect(t, &tls.Config{ |
| 332 |
MaxVersion: tls.VersionTLS12, |
| 333 |
}, nil) |
| 334 |
connect(t, &tls.Config{ |
| 335 |
MinVersion: tls.VersionTLS13, |
| 336 |
}, nil) |
| 337 |
|
| 338 |
// Setting unsupported TLS versions |
| 339 |
if err := os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, `"1.4"`)), 0666); err != nil { |
| 340 |
t.Fatalf("Error creating config file: %v", err) |
| 341 |
} |
| 342 |
if err := s.Reload(); err == nil || !strings.Contains(err.Error(), `unknown version: 1.4`) { |
| 343 |
t.Fatalf("Unexpected error reloading: %v", err) |
| 344 |
} |
| 345 |
|
| 346 |
tc := &TLSConfigOpts{ |
| 347 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 348 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 349 |
CaFile: "../test/configs/certs/ca.pem", |
| 350 |
Timeout: 4.0, |
| 351 |
MinVersion: tls.VersionTLS11, |
| 352 |
} |
| 353 |
_, err := GenTLSConfig(tc) |
| 354 |
if err == nil || err.Error() != `unsupported minimum TLS version: TLS 1.1` { |
| 355 |
t.Fatalf("Expected error generating TLS config: %v", err) |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
func TestTLSCipher(t *testing.T) { |
| 360 |
require_Equal(t, tls.CipherSuiteName(0x0005), "TLS_RSA_WITH_RC4_128_SHA") |
| 361 |
require_Equal(t, tls.CipherSuiteName(0x000a), "TLS_RSA_WITH_3DES_EDE_CBC_SHA") |
| 362 |
require_Equal(t, tls.CipherSuiteName(0x002f), "TLS_RSA_WITH_AES_128_CBC_SHA") |
| 363 |
require_Equal(t, tls.CipherSuiteName(0x0035), "TLS_RSA_WITH_AES_256_CBC_SHA") |
| 364 |
require_Equal(t, tls.CipherSuiteName(0xc007), "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA") |
| 365 |
require_Equal(t, tls.CipherSuiteName(0xc009), "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA") |
| 366 |
require_Equal(t, tls.CipherSuiteName(0xc00a), "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA") |
| 367 |
require_Equal(t, tls.CipherSuiteName(0xc011), "TLS_ECDHE_RSA_WITH_RC4_128_SHA") |
| 368 |
require_Equal(t, tls.CipherSuiteName(0xc012), "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA") |
| 369 |
require_Equal(t, tls.CipherSuiteName(0xc013), "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA") |
| 370 |
require_Equal(t, tls.CipherSuiteName(0xc014), "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA") |
| 371 |
require_Equal(t, tls.CipherSuiteName(0xc02f), "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256") |
| 372 |
require_Equal(t, tls.CipherSuiteName(0xc02b), "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") |
| 373 |
require_Equal(t, tls.CipherSuiteName(0xc030), "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384") |
| 374 |
require_Equal(t, tls.CipherSuiteName(0xc02c), "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384") |
| 375 |
require_Equal(t, tls.CipherSuiteName(0x1301), "TLS_AES_128_GCM_SHA256") |
| 376 |
require_Equal(t, tls.CipherSuiteName(0x1302), "TLS_AES_256_GCM_SHA384") |
| 377 |
require_Equal(t, tls.CipherSuiteName(0x1303), "TLS_CHACHA20_POLY1305_SHA256") |
| 378 |
require_Equal(t, tls.CipherSuiteName(0x9999), "0x9999") |
| 379 |
} |
| 380 |
|
| 381 |
func TestGetConnectURLs(t *testing.T) { |
| 382 |
opts := DefaultOptions() |
| 383 |
opts.Port = 4222 |
| 384 |
|
| 385 |
var globalIP net.IP |
| 386 |
|
| 387 |
checkGlobalConnectURLs := func() { |
| 388 |
s := New(opts) |
| 389 |
defer s.Shutdown() |
| 390 |
|
| 391 |
s.mu.Lock() |
| 392 |
urls := s.getClientConnectURLs() |
| 393 |
s.mu.Unlock() |
| 394 |
if len(urls) == 0 { |
| 395 |
t.Fatalf("Expected to get a list of urls, got none for listen addr: %v", opts.Host) |
| 396 |
} |
| 397 |
for _, u := range urls { |
| 398 |
tcpaddr, err := net.ResolveTCPAddr("tcp", u) |
| 399 |
if err != nil { |
| 400 |
t.Fatalf("Error resolving: %v", err) |
| 401 |
} |
| 402 |
ip := tcpaddr.IP |
| 403 |
if !ip.IsGlobalUnicast() { |
| 404 |
t.Fatalf("IP %v is not global", ip.String()) |
| 405 |
} |
| 406 |
if ip.IsUnspecified() { |
| 407 |
t.Fatalf("IP %v is unspecified", ip.String()) |
| 408 |
} |
| 409 |
addr := strings.TrimSuffix(u, ":4222") |
| 410 |
if addr == opts.Host { |
| 411 |
t.Fatalf("Returned url is not right: %v", u) |
| 412 |
} |
| 413 |
if globalIP == nil { |
| 414 |
globalIP = ip |
| 415 |
} |
| 416 |
} |
| 417 |
} |
| 418 |
|
| 419 |
listenAddrs := []string{"0.0.0.0", "::"} |
| 420 |
for _, listenAddr := range listenAddrs { |
| 421 |
opts.Host = listenAddr |
| 422 |
checkGlobalConnectURLs() |
| 423 |
} |
| 424 |
|
| 425 |
checkConnectURLsHasOnlyOne := func() { |
| 426 |
s := New(opts) |
| 427 |
defer s.Shutdown() |
| 428 |
|
| 429 |
s.mu.Lock() |
| 430 |
urls := s.getClientConnectURLs() |
| 431 |
s.mu.Unlock() |
| 432 |
if len(urls) != 1 { |
| 433 |
t.Fatalf("Expected one URL, got %v", urls) |
| 434 |
} |
| 435 |
tcpaddr, err := net.ResolveTCPAddr("tcp", urls[0]) |
| 436 |
if err != nil { |
| 437 |
t.Fatalf("Error resolving: %v", err) |
| 438 |
} |
| 439 |
ip := tcpaddr.IP |
| 440 |
if ip.String() != opts.Host { |
| 441 |
t.Fatalf("Expected connect URL to be %v, got %v", opts.Host, ip.String()) |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
singleConnectReturned := []string{"127.0.0.1", "::1"} |
| 446 |
if globalIP != nil { |
| 447 |
singleConnectReturned = append(singleConnectReturned, globalIP.String()) |
| 448 |
} |
| 449 |
for _, listenAddr := range singleConnectReturned { |
| 450 |
opts.Host = listenAddr |
| 451 |
checkConnectURLsHasOnlyOne() |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
func TestInfoServerNameDefaultsToPK(t *testing.T) { |
| 456 |
opts := DefaultOptions() |
| 457 |
opts.Port = 4222 |
| 458 |
opts.ClientAdvertise = "nats.example.com" |
| 459 |
s := New(opts) |
| 460 |
defer s.Shutdown() |
| 461 |
|
| 462 |
if s.info.Name != s.info.ID { |
| 463 |
t.Fatalf("server info hostname is incorrect, got: '%v' expected: '%v'", s.info.Name, s.info.ID) |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
func TestInfoServerNameIsSettable(t *testing.T) { |
| 468 |
opts := DefaultOptions() |
| 469 |
opts.Port = 4222 |
| 470 |
opts.ClientAdvertise = "nats.example.com" |
| 471 |
opts.ServerName = "test_server_name" |
| 472 |
s := New(opts) |
| 473 |
defer s.Shutdown() |
| 474 |
|
| 475 |
if s.info.Name != "test_server_name" { |
| 476 |
t.Fatalf("server info hostname is incorrect, got: '%v' expected: 'test_server_name'", s.info.Name) |
| 477 |
} |
| 478 |
} |
| 479 |
|
| 480 |
func TestClientAdvertiseConnectURL(t *testing.T) { |
| 481 |
opts := DefaultOptions() |
| 482 |
opts.Port = 4222 |
| 483 |
opts.ClientAdvertise = "nats.example.com" |
| 484 |
s := New(opts) |
| 485 |
defer s.Shutdown() |
| 486 |
|
| 487 |
s.mu.Lock() |
| 488 |
urls := s.getClientConnectURLs() |
| 489 |
s.mu.Unlock() |
| 490 |
if len(urls) != 1 { |
| 491 |
t.Fatalf("Expected to get one url, got none: %v with ClientAdvertise %v", |
| 492 |
opts.Host, opts.ClientAdvertise) |
| 493 |
} |
| 494 |
if urls[0] != "nats.example.com:4222" { |
| 495 |
t.Fatalf("Expected to get '%s', got: '%v'", "nats.example.com:4222", urls[0]) |
| 496 |
} |
| 497 |
s.Shutdown() |
| 498 |
|
| 499 |
opts.ClientAdvertise = "nats.example.com:7777" |
| 500 |
s = New(opts) |
| 501 |
s.mu.Lock() |
| 502 |
urls = s.getClientConnectURLs() |
| 503 |
s.mu.Unlock() |
| 504 |
if len(urls) != 1 { |
| 505 |
t.Fatalf("Expected to get one url, got none: %v with ClientAdvertise %v", |
| 506 |
opts.Host, opts.ClientAdvertise) |
| 507 |
} |
| 508 |
if urls[0] != "nats.example.com:7777" { |
| 509 |
t.Fatalf("Expected 'nats.example.com:7777', got: '%v'", urls[0]) |
| 510 |
} |
| 511 |
if s.info.Host != "nats.example.com" { |
| 512 |
t.Fatalf("Expected host to be set to nats.example.com") |
| 513 |
} |
| 514 |
if s.info.Port != 7777 { |
| 515 |
t.Fatalf("Expected port to be set to 7777") |
| 516 |
} |
| 517 |
s.Shutdown() |
| 518 |
|
| 519 |
opts = DefaultOptions() |
| 520 |
opts.Port = 0 |
| 521 |
opts.ClientAdvertise = "nats.example.com:7777" |
| 522 |
s = New(opts) |
| 523 |
if s.info.Host != "nats.example.com" && s.info.Port != 7777 { |
| 524 |
t.Fatalf("Expected Client Advertise Host:Port to be nats.example.com:7777, got: %s:%d", |
| 525 |
s.info.Host, s.info.Port) |
| 526 |
} |
| 527 |
s.Shutdown() |
| 528 |
} |
| 529 |
|
| 530 |
func TestClientAdvertiseInCluster(t *testing.T) { |
| 531 |
optsA := DefaultOptions() |
| 532 |
optsA.ClientAdvertise = "srvA:4222" |
| 533 |
srvA := RunServer(optsA) |
| 534 |
defer srvA.Shutdown() |
| 535 |
|
| 536 |
nc := natsConnect(t, srvA.ClientURL()) |
| 537 |
defer nc.Close() |
| 538 |
|
| 539 |
optsB := DefaultOptions() |
| 540 |
optsB.ClientAdvertise = "srvBC:4222" |
| 541 |
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", optsA.Cluster.Port)) |
| 542 |
srvB := RunServer(optsB) |
| 543 |
defer srvB.Shutdown() |
| 544 |
|
| 545 |
checkClusterFormed(t, srvA, srvB) |
| 546 |
|
| 547 |
checkURLs := func(expected string) { |
| 548 |
t.Helper() |
| 549 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 550 |
srvs := nc.DiscoveredServers() |
| 551 |
for _, u := range srvs { |
| 552 |
if u == expected { |
| 553 |
return nil |
| 554 |
} |
| 555 |
} |
| 556 |
return fmt.Errorf("Url %q not found in %q", expected, srvs) |
| 557 |
}) |
| 558 |
} |
| 559 |
checkURLs("nats://srvBC:4222") |
| 560 |
|
| 561 |
optsC := DefaultOptions() |
| 562 |
optsC.ClientAdvertise = "srvBC:4222" |
| 563 |
optsC.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", optsA.Cluster.Port)) |
| 564 |
srvC := RunServer(optsC) |
| 565 |
defer srvC.Shutdown() |
| 566 |
|
| 567 |
checkClusterFormed(t, srvA, srvB, srvC) |
| 568 |
checkURLs("nats://srvBC:4222") |
| 569 |
|
| 570 |
srvB.Shutdown() |
| 571 |
checkNumRoutes(t, srvA, DEFAULT_ROUTE_POOL_SIZE+1) |
| 572 |
checkURLs("nats://srvBC:4222") |
| 573 |
} |
| 574 |
|
| 575 |
func TestClientAdvertiseErrorOnStartup(t *testing.T) { |
| 576 |
opts := DefaultOptions() |
| 577 |
// Set invalid address |
| 578 |
opts.ClientAdvertise = "addr:::123" |
| 579 |
testFatalErrorOnStart(t, opts, "ClientAdvertise") |
| 580 |
} |
| 581 |
|
| 582 |
func TestNoDeadlockOnStartFailure(t *testing.T) { |
| 583 |
opts := DefaultOptions() |
| 584 |
opts.Host = "x.x.x.x" // bad host |
| 585 |
opts.Port = 4222 |
| 586 |
opts.HTTPHost = opts.Host |
| 587 |
opts.Cluster.Host = "127.0.0.1" |
| 588 |
opts.Cluster.Port = -1 |
| 589 |
opts.ProfPort = -1 |
| 590 |
s := New(opts) |
| 591 |
|
| 592 |
// This should return since it should fail to start a listener |
| 593 |
// on x.x.x.x:4222 |
| 594 |
ch := make(chan struct{}) |
| 595 |
go func() { |
| 596 |
s.Start() |
| 597 |
close(ch) |
| 598 |
}() |
| 599 |
select { |
| 600 |
case <-ch: |
| 601 |
case <-time.After(time.Second): |
| 602 |
t.Fatalf("Start() should have returned due to failure to start listener") |
| 603 |
} |
| 604 |
|
| 605 |
// We should be able to shutdown |
| 606 |
s.Shutdown() |
| 607 |
} |
| 608 |
|
| 609 |
func TestMaxConnections(t *testing.T) { |
| 610 |
opts := DefaultOptions() |
| 611 |
opts.MaxConn = 1 |
| 612 |
s := RunServer(opts) |
| 613 |
defer s.Shutdown() |
| 614 |
|
| 615 |
addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) |
| 616 |
nc, err := nats.Connect(addr) |
| 617 |
if err != nil { |
| 618 |
t.Fatalf("Error creating client: %v\n", err) |
| 619 |
} |
| 620 |
defer nc.Close() |
| 621 |
|
| 622 |
nc2, err := nats.Connect(addr) |
| 623 |
if err == nil { |
| 624 |
nc2.Close() |
| 625 |
t.Fatal("Expected connection to fail") |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
func TestMaxConnectionsPreventsAll(t *testing.T) { |
| 630 |
opts := DefaultOptions() |
| 631 |
opts.MaxConn = -1 |
| 632 |
s := RunServer(opts) |
| 633 |
defer s.Shutdown() |
| 634 |
|
| 635 |
addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) |
| 636 |
_, err := nats.Connect(addr) |
| 637 |
require_Error(t, err) |
| 638 |
} |
| 639 |
|
| 640 |
func TestMaxSubscriptions(t *testing.T) { |
| 641 |
opts := DefaultOptions() |
| 642 |
opts.MaxSubs = 10 |
| 643 |
s := RunServer(opts) |
| 644 |
defer s.Shutdown() |
| 645 |
|
| 646 |
addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) |
| 647 |
nc, err := nats.Connect(addr) |
| 648 |
if err != nil { |
| 649 |
t.Fatalf("Error creating client: %v\n", err) |
| 650 |
} |
| 651 |
defer nc.Close() |
| 652 |
|
| 653 |
for i := 0; i < 10; i++ { |
| 654 |
_, err := nc.Subscribe(fmt.Sprintf("foo.%d", i), func(*nats.Msg) {}) |
| 655 |
if err != nil { |
| 656 |
t.Fatalf("Error subscribing: %v\n", err) |
| 657 |
} |
| 658 |
} |
| 659 |
// This should cause the error. |
| 660 |
nc.Subscribe("foo.22", func(*nats.Msg) {}) |
| 661 |
nc.Flush() |
| 662 |
if err := nc.LastError(); err == nil { |
| 663 |
t.Fatal("Expected an error but got none\n") |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
func TestProcessCommandLineArgs(t *testing.T) { |
| 668 |
var host string |
| 669 |
var port int |
| 670 |
cmd := flag.NewFlagSet("nats-server", flag.ExitOnError) |
| 671 |
cmd.StringVar(&host, "a", "0.0.0.0", "Host.") |
| 672 |
cmd.IntVar(&port, "p", 4222, "Port.") |
| 673 |
|
| 674 |
cmd.Parse([]string{"-a", "127.0.0.1", "-p", "9090"}) |
| 675 |
showVersion, showHelp, err := ProcessCommandLineArgs(cmd) |
| 676 |
if err != nil { |
| 677 |
t.Errorf("Expected no errors, got: %s", err) |
| 678 |
} |
| 679 |
if showVersion || showHelp { |
| 680 |
t.Errorf("Expected not having to handle subcommands") |
| 681 |
} |
| 682 |
|
| 683 |
cmd.Parse([]string{"version"}) |
| 684 |
showVersion, showHelp, err = ProcessCommandLineArgs(cmd) |
| 685 |
if err != nil { |
| 686 |
t.Errorf("Expected no errors, got: %s", err) |
| 687 |
} |
| 688 |
if !showVersion { |
| 689 |
t.Errorf("Expected having to handle version command") |
| 690 |
} |
| 691 |
if showHelp { |
| 692 |
t.Errorf("Expected not having to handle help command") |
| 693 |
} |
| 694 |
|
| 695 |
cmd.Parse([]string{"help"}) |
| 696 |
showVersion, showHelp, err = ProcessCommandLineArgs(cmd) |
| 697 |
if err != nil { |
| 698 |
t.Errorf("Expected no errors, got: %s", err) |
| 699 |
} |
| 700 |
if showVersion { |
| 701 |
t.Errorf("Expected not having to handle version command") |
| 702 |
} |
| 703 |
if !showHelp { |
| 704 |
t.Errorf("Expected having to handle help command") |
| 705 |
} |
| 706 |
|
| 707 |
cmd.Parse([]string{"foo", "-p", "9090"}) |
| 708 |
_, _, err = ProcessCommandLineArgs(cmd) |
| 709 |
if err == nil { |
| 710 |
t.Errorf("Expected an error handling the command arguments") |
| 711 |
} |
| 712 |
} |
| 713 |
|
| 714 |
func TestRandomPorts(t *testing.T) { |
| 715 |
opts := DefaultOptions() |
| 716 |
opts.HTTPPort = -1 |
| 717 |
opts.Port = -1 |
| 718 |
s := RunServer(opts) |
| 719 |
|
| 720 |
defer s.Shutdown() |
| 721 |
|
| 722 |
if s.Addr() == nil || s.Addr().(*net.TCPAddr).Port <= 0 { |
| 723 |
t.Fatal("Should have dynamically assigned server port.") |
| 724 |
} |
| 725 |
|
| 726 |
if s.Addr() == nil || s.Addr().(*net.TCPAddr).Port == 4222 { |
| 727 |
t.Fatal("Should not have dynamically assigned default port: 4222.") |
| 728 |
} |
| 729 |
|
| 730 |
if s.MonitorAddr() == nil || s.MonitorAddr().Port <= 0 { |
| 731 |
t.Fatal("Should have dynamically assigned monitoring port.") |
| 732 |
} |
| 733 |
|
| 734 |
} |
| 735 |
|
| 736 |
func TestNilMonitoringPort(t *testing.T) { |
| 737 |
opts := DefaultOptions() |
| 738 |
opts.HTTPPort = 0 |
| 739 |
opts.HTTPSPort = 0 |
| 740 |
s := RunServer(opts) |
| 741 |
|
| 742 |
defer s.Shutdown() |
| 743 |
|
| 744 |
if s.MonitorAddr() != nil { |
| 745 |
t.Fatal("HttpAddr should be nil.") |
| 746 |
} |
| 747 |
} |
| 748 |
|
| 749 |
type DummyAuth struct { |
| 750 |
t *testing.T |
| 751 |
needNonce bool |
| 752 |
deadline time.Time |
| 753 |
register bool |
| 754 |
} |
| 755 |
|
| 756 |
func (d *DummyAuth) Check(c ClientAuthentication) bool { |
| 757 |
if d.needNonce && len(c.GetNonce()) == 0 { |
| 758 |
d.t.Fatalf("Expected a nonce but received none") |
| 759 |
} else if !d.needNonce && len(c.GetNonce()) > 0 { |
| 760 |
d.t.Fatalf("Received a nonce when none was expected") |
| 761 |
} |
| 762 |
|
| 763 |
if c.GetOpts().Username != "valid" { |
| 764 |
return false |
| 765 |
} |
| 766 |
|
| 767 |
if !d.register { |
| 768 |
return true |
| 769 |
} |
| 770 |
|
| 771 |
u := &User{ |
| 772 |
Username: c.GetOpts().Username, |
| 773 |
ConnectionDeadline: d.deadline, |
| 774 |
} |
| 775 |
c.RegisterUser(u) |
| 776 |
|
| 777 |
return true |
| 778 |
} |
| 779 |
|
| 780 |
func TestCustomClientAuthentication(t *testing.T) { |
| 781 |
testAuth := func(t *testing.T, nonce bool) { |
| 782 |
clientAuth := &DummyAuth{t: t, needNonce: nonce} |
| 783 |
|
| 784 |
opts := DefaultOptions() |
| 785 |
opts.CustomClientAuthentication = clientAuth |
| 786 |
opts.AlwaysEnableNonce = nonce |
| 787 |
|
| 788 |
s := RunServer(opts) |
| 789 |
defer s.Shutdown() |
| 790 |
|
| 791 |
addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) |
| 792 |
|
| 793 |
nc, err := nats.Connect(addr, nats.UserInfo("valid", "")) |
| 794 |
if err != nil { |
| 795 |
t.Fatalf("Expected client to connect, got: %s", err) |
| 796 |
} |
| 797 |
nc.Close() |
| 798 |
if _, err := nats.Connect(addr, nats.UserInfo("invalid", "")); err == nil { |
| 799 |
t.Fatal("Expected client to fail to connect") |
| 800 |
} |
| 801 |
} |
| 802 |
|
| 803 |
t.Run("with nonce", func(t *testing.T) { testAuth(t, true) }) |
| 804 |
t.Run("without nonce", func(t *testing.T) { testAuth(t, false) }) |
| 805 |
} |
| 806 |
|
| 807 |
func TestCustomRouterAuthentication(t *testing.T) { |
| 808 |
opts := DefaultOptions() |
| 809 |
opts.CustomRouterAuthentication = &DummyAuth{} |
| 810 |
opts.Cluster.Host = "127.0.0.1" |
| 811 |
s := RunServer(opts) |
| 812 |
defer s.Shutdown() |
| 813 |
clusterPort := s.ClusterAddr().Port |
| 814 |
|
| 815 |
opts2 := DefaultOptions() |
| 816 |
opts2.Cluster.Host = "127.0.0.1" |
| 817 |
opts2.Routes = RoutesFromStr(fmt.Sprintf("nats://[email protected]:%d", clusterPort)) |
| 818 |
s2 := RunServer(opts2) |
| 819 |
defer s2.Shutdown() |
| 820 |
|
| 821 |
// s2 will attempt to connect to s, which should reject. |
| 822 |
// Keep in mind that s2 will try again... |
| 823 |
time.Sleep(50 * time.Millisecond) |
| 824 |
checkNumRoutes(t, s2, 0) |
| 825 |
|
| 826 |
opts3 := DefaultOptions() |
| 827 |
opts3.Cluster.Host = "127.0.0.1" |
| 828 |
opts3.Routes = RoutesFromStr(fmt.Sprintf("nats://[email protected]:%d", clusterPort)) |
| 829 |
s3 := RunServer(opts3) |
| 830 |
defer s3.Shutdown() |
| 831 |
checkClusterFormed(t, s, s3) |
| 832 |
// Default pool size + 1 for system account |
| 833 |
checkNumRoutes(t, s3, DEFAULT_ROUTE_POOL_SIZE+1) |
| 834 |
} |
| 835 |
|
| 836 |
func TestMonitoringNoTimeout(t *testing.T) { |
| 837 |
s := runMonitorServer() |
| 838 |
defer s.Shutdown() |
| 839 |
|
| 840 |
s.mu.Lock() |
| 841 |
srv := s.monitoringServer |
| 842 |
s.mu.Unlock() |
| 843 |
|
| 844 |
if srv == nil { |
| 845 |
t.Fatalf("Monitoring server not set") |
| 846 |
} |
| 847 |
if srv.ReadTimeout != 0 { |
| 848 |
t.Fatalf("ReadTimeout should not be set, was set to %v", srv.ReadTimeout) |
| 849 |
} |
| 850 |
if srv.WriteTimeout != 0 { |
| 851 |
t.Fatalf("WriteTimeout should not be set, was set to %v", srv.WriteTimeout) |
| 852 |
} |
| 853 |
} |
| 854 |
|
| 855 |
func TestProfilingNoTimeout(t *testing.T) { |
| 856 |
opts := DefaultOptions() |
| 857 |
opts.ProfPort = -1 |
| 858 |
s := RunServer(opts) |
| 859 |
defer s.Shutdown() |
| 860 |
|
| 861 |
paddr := s.ProfilerAddr() |
| 862 |
if paddr == nil { |
| 863 |
t.Fatalf("Profiler not started") |
| 864 |
} |
| 865 |
pport := paddr.Port |
| 866 |
if pport <= 0 { |
| 867 |
t.Fatalf("Expected profiler port to be set, got %v", pport) |
| 868 |
} |
| 869 |
s.mu.Lock() |
| 870 |
srv := s.profilingServer |
| 871 |
s.mu.Unlock() |
| 872 |
|
| 873 |
if srv == nil { |
| 874 |
t.Fatalf("Profiling server not set") |
| 875 |
} |
| 876 |
if srv.ReadTimeout != time.Second*5 { |
| 877 |
t.Fatalf("ReadTimeout should not be set, was set to %v", srv.ReadTimeout) |
| 878 |
} |
| 879 |
if srv.WriteTimeout != 0 { |
| 880 |
t.Fatalf("WriteTimeout should not be set, was set to %v", srv.WriteTimeout) |
| 881 |
} |
| 882 |
} |
| 883 |
|
| 884 |
func TestLameDuckOptionsValidation(t *testing.T) { |
| 885 |
o := DefaultOptions() |
| 886 |
o.LameDuckDuration = 5 * time.Second |
| 887 |
o.LameDuckGracePeriod = 10 * time.Second |
| 888 |
s, err := NewServer(o) |
| 889 |
if s != nil { |
| 890 |
s.Shutdown() |
| 891 |
} |
| 892 |
if err == nil || !strings.Contains(err.Error(), "should be strictly lower") { |
| 893 |
t.Fatalf("Expected error saying that ldm grace period should be lower than ldm duration, got %v", err) |
| 894 |
} |
| 895 |
} |
| 896 |
|
| 897 |
func testSetLDMGracePeriod(o *Options, val time.Duration) { |
| 898 |
// For tests, we set the grace period as a negative value |
| 899 |
// so we can have a grace period bigger than the total duration. |
| 900 |
// When validating options, we would not be able to run the |
| 901 |
// server without this trick. |
| 902 |
o.LameDuckGracePeriod = val * -1 |
| 903 |
} |
| 904 |
|
| 905 |
func TestLameDuckMode(t *testing.T) { |
| 906 |
optsA := DefaultOptions() |
| 907 |
testSetLDMGracePeriod(optsA, time.Nanosecond) |
| 908 |
optsA.Cluster.Host = "127.0.0.1" |
| 909 |
srvA := RunServer(optsA) |
| 910 |
defer srvA.Shutdown() |
| 911 |
|
| 912 |
// Check that if there is no client, server is shutdown |
| 913 |
srvA.lameDuckMode() |
| 914 |
if !srvA.isShuttingDown() { |
| 915 |
t.Fatalf("Server should have shutdown") |
| 916 |
} |
| 917 |
|
| 918 |
optsA.LameDuckDuration = 10 * time.Nanosecond |
| 919 |
srvA = RunServer(optsA) |
| 920 |
defer srvA.Shutdown() |
| 921 |
|
| 922 |
optsB := DefaultOptions() |
| 923 |
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 924 |
srvB := RunServer(optsB) |
| 925 |
defer srvB.Shutdown() |
| 926 |
|
| 927 |
checkClusterFormed(t, srvA, srvB) |
| 928 |
|
| 929 |
total := 50 |
| 930 |
connectClients := func() []*nats.Conn { |
| 931 |
ncs := make([]*nats.Conn, 0, total) |
| 932 |
for i := 0; i < total; i++ { |
| 933 |
nc, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port), |
| 934 |
nats.ReconnectWait(50*time.Millisecond)) |
| 935 |
if err != nil { |
| 936 |
t.Fatalf("Error on connect: %v", err) |
| 937 |
} |
| 938 |
ncs = append(ncs, nc) |
| 939 |
} |
| 940 |
return ncs |
| 941 |
} |
| 942 |
stopClientsAndSrvB := func(ncs []*nats.Conn) { |
| 943 |
for _, nc := range ncs { |
| 944 |
nc.Close() |
| 945 |
} |
| 946 |
srvB.Shutdown() |
| 947 |
} |
| 948 |
|
| 949 |
ncs := connectClients() |
| 950 |
|
| 951 |
checkClientsCount(t, srvA, total) |
| 952 |
checkClientsCount(t, srvB, 0) |
| 953 |
|
| 954 |
start := time.Now() |
| 955 |
srvA.lameDuckMode() |
| 956 |
// Make sure that nothing bad happens if called twice |
| 957 |
srvA.lameDuckMode() |
| 958 |
// Wait that shutdown completes |
| 959 |
elapsed := time.Since(start) |
| 960 |
// It should have taken more than the allotted time of 10ms since we had 50 clients. |
| 961 |
if elapsed <= optsA.LameDuckDuration { |
| 962 |
t.Fatalf("Expected to take more than %v, got %v", optsA.LameDuckDuration, elapsed) |
| 963 |
} |
| 964 |
|
| 965 |
checkClientsCount(t, srvA, 0) |
| 966 |
checkClientsCount(t, srvB, total) |
| 967 |
|
| 968 |
// Check closed status on server A |
| 969 |
// Connections are saved in go routines, so although we have evaluated the number |
| 970 |
// of connections in the server A to be 0, the polling of connection closed may |
| 971 |
// need a bit more time. |
| 972 |
checkFor(t, time.Second, 15*time.Millisecond, func() error { |
| 973 |
cz := pollConnz(t, srvA, 1, "", &ConnzOptions{State: ConnClosed}) |
| 974 |
if n := len(cz.Conns); n != total { |
| 975 |
return fmt.Errorf("expected %v closed connections, got %v", total, n) |
| 976 |
} |
| 977 |
return nil |
| 978 |
}) |
| 979 |
cz := pollConnz(t, srvA, 1, "", &ConnzOptions{State: ConnClosed}) |
| 980 |
if n := len(cz.Conns); n != total { |
| 981 |
t.Fatalf("Expected %v closed connections, got %v", total, n) |
| 982 |
} |
| 983 |
for _, c := range cz.Conns { |
| 984 |
checkReason(t, c.Reason, ServerShutdown) |
| 985 |
} |
| 986 |
|
| 987 |
stopClientsAndSrvB(ncs) |
| 988 |
|
| 989 |
optsA.LameDuckDuration = time.Second |
| 990 |
srvA = RunServer(optsA) |
| 991 |
defer srvA.Shutdown() |
| 992 |
|
| 993 |
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 994 |
srvB = RunServer(optsB) |
| 995 |
defer srvB.Shutdown() |
| 996 |
|
| 997 |
checkClusterFormed(t, srvA, srvB) |
| 998 |
|
| 999 |
ncs = connectClients() |
| 1000 |
|
| 1001 |
checkClientsCount(t, srvA, total) |
| 1002 |
checkClientsCount(t, srvB, 0) |
| 1003 |
|
| 1004 |
start = time.Now() |
| 1005 |
go srvA.lameDuckMode() |
| 1006 |
// Check that while in lameDuckMode, it is not possible to connect |
| 1007 |
// to the server. Wait to be in LD mode first |
| 1008 |
checkFor(t, 500*time.Millisecond, 15*time.Millisecond, func() error { |
| 1009 |
srvA.mu.Lock() |
| 1010 |
ldm := srvA.ldm |
| 1011 |
srvA.mu.Unlock() |
| 1012 |
if !ldm { |
| 1013 |
return fmt.Errorf("Did not reach lame duck mode") |
| 1014 |
} |
| 1015 |
return nil |
| 1016 |
}) |
| 1017 |
if _, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port)); err != nats.ErrNoServers { |
| 1018 |
t.Fatalf("Expected %v, got %v", nats.ErrNoServers, err) |
| 1019 |
} |
| 1020 |
srvA.grWG.Wait() |
| 1021 |
elapsed = time.Since(start) |
| 1022 |
|
| 1023 |
checkClientsCount(t, srvA, 0) |
| 1024 |
checkClientsCount(t, srvB, total) |
| 1025 |
|
| 1026 |
if elapsed > time.Duration(float64(optsA.LameDuckDuration)*1.1) { |
| 1027 |
t.Fatalf("Expected to not take more than %v, got %v", optsA.LameDuckDuration, elapsed) |
| 1028 |
} |
| 1029 |
|
| 1030 |
stopClientsAndSrvB(ncs) |
| 1031 |
|
| 1032 |
// Now check that we can shutdown server while in LD mode. |
| 1033 |
optsA.LameDuckDuration = 60 * time.Second |
| 1034 |
srvA = RunServer(optsA) |
| 1035 |
defer srvA.Shutdown() |
| 1036 |
|
| 1037 |
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 1038 |
srvB = RunServer(optsB) |
| 1039 |
defer srvB.Shutdown() |
| 1040 |
|
| 1041 |
checkClusterFormed(t, srvA, srvB) |
| 1042 |
|
| 1043 |
ncs = connectClients() |
| 1044 |
|
| 1045 |
checkClientsCount(t, srvA, total) |
| 1046 |
checkClientsCount(t, srvB, 0) |
| 1047 |
|
| 1048 |
start = time.Now() |
| 1049 |
go srvA.lameDuckMode() |
| 1050 |
time.Sleep(100 * time.Millisecond) |
| 1051 |
srvA.Shutdown() |
| 1052 |
elapsed = time.Since(start) |
| 1053 |
// Make sure that it did not take that long |
| 1054 |
if elapsed > time.Second { |
| 1055 |
t.Fatalf("Took too long: %v", elapsed) |
| 1056 |
} |
| 1057 |
checkClientsCount(t, srvA, 0) |
| 1058 |
checkClientsCount(t, srvB, total) |
| 1059 |
|
| 1060 |
stopClientsAndSrvB(ncs) |
| 1061 |
|
| 1062 |
// Now test that we introduce delay before starting closing client connections. |
| 1063 |
// This allow to "signal" multiple servers and avoid their clients to reconnect |
| 1064 |
// to a server that is going to be going in LD mode. |
| 1065 |
testSetLDMGracePeriod(optsA, 100*time.Millisecond) |
| 1066 |
optsA.LameDuckDuration = 10 * time.Millisecond |
| 1067 |
srvA = RunServer(optsA) |
| 1068 |
defer srvA.Shutdown() |
| 1069 |
|
| 1070 |
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 1071 |
testSetLDMGracePeriod(optsB, 100*time.Millisecond) |
| 1072 |
optsB.LameDuckDuration = 10 * time.Millisecond |
| 1073 |
srvB = RunServer(optsB) |
| 1074 |
defer srvB.Shutdown() |
| 1075 |
|
| 1076 |
optsC := DefaultOptions() |
| 1077 |
optsC.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 1078 |
testSetLDMGracePeriod(optsC, 100*time.Millisecond) |
| 1079 |
optsC.LameDuckGracePeriod = -100 * time.Millisecond |
| 1080 |
optsC.LameDuckDuration = 10 * time.Millisecond |
| 1081 |
srvC := RunServer(optsC) |
| 1082 |
defer srvC.Shutdown() |
| 1083 |
|
| 1084 |
checkClusterFormed(t, srvA, srvB, srvC) |
| 1085 |
|
| 1086 |
rt := int32(0) |
| 1087 |
nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsA.Port), |
| 1088 |
nats.ReconnectWait(15*time.Millisecond), |
| 1089 |
nats.ReconnectHandler(func(*nats.Conn) { |
| 1090 |
atomic.AddInt32(&rt, 1) |
| 1091 |
})) |
| 1092 |
if err != nil { |
| 1093 |
t.Fatalf("Error on connect: %v", err) |
| 1094 |
} |
| 1095 |
defer nc.Close() |
| 1096 |
|
| 1097 |
go srvA.lameDuckMode() |
| 1098 |
// Wait a bit, but less than lameDuckModeInitialDelay that we set in this |
| 1099 |
// test to 100ms. |
| 1100 |
time.Sleep(30 * time.Millisecond) |
| 1101 |
go srvB.lameDuckMode() |
| 1102 |
|
| 1103 |
srvA.grWG.Wait() |
| 1104 |
srvB.grWG.Wait() |
| 1105 |
checkClientsCount(t, srvC, 1) |
| 1106 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 1107 |
if n := atomic.LoadInt32(&rt); n != 1 { |
| 1108 |
return fmt.Errorf("Expected client to reconnect only once, got %v", n) |
| 1109 |
} |
| 1110 |
return nil |
| 1111 |
}) |
| 1112 |
} |
| 1113 |
|
| 1114 |
func TestLameDuckModeInfo(t *testing.T) { |
| 1115 |
optsA := testWSOptions() |
| 1116 |
optsA.Cluster.Name = "abc" |
| 1117 |
optsA.Cluster.Host = "127.0.0.1" |
| 1118 |
optsA.Cluster.Port = -1 |
| 1119 |
// Ensure that initial delay is set very high so that we can |
| 1120 |
// check that some events occur as expected before the client |
| 1121 |
// is disconnected. |
| 1122 |
testSetLDMGracePeriod(optsA, 5*time.Second) |
| 1123 |
optsA.LameDuckDuration = 50 * time.Millisecond |
| 1124 |
optsA.DisableShortFirstPing = true |
| 1125 |
srvA := RunServer(optsA) |
| 1126 |
defer srvA.Shutdown() |
| 1127 |
|
| 1128 |
curla := fmt.Sprintf("127.0.0.1:%d", optsA.Port) |
| 1129 |
wscurla := fmt.Sprintf("127.0.0.1:%d", optsA.Websocket.Port) |
| 1130 |
c, err := net.Dial("tcp", curla) |
| 1131 |
if err != nil { |
| 1132 |
t.Fatalf("Error connecting: %v", err) |
| 1133 |
} |
| 1134 |
defer c.Close() |
| 1135 |
client := bufio.NewReaderSize(c, maxBufSize) |
| 1136 |
|
| 1137 |
wsconn, wsclient := testWSCreateClient(t, false, false, optsA.Websocket.Host, optsA.Websocket.Port) |
| 1138 |
defer wsconn.Close() |
| 1139 |
|
| 1140 |
getInfo := func(ws bool) *serverInfo { |
| 1141 |
t.Helper() |
| 1142 |
var l string |
| 1143 |
var err error |
| 1144 |
if ws { |
| 1145 |
l = string(testWSReadFrame(t, wsclient)) |
| 1146 |
} else { |
| 1147 |
l, err = client.ReadString('\n') |
| 1148 |
if err != nil { |
| 1149 |
t.Fatalf("Error receiving info from server: %v\n", err) |
| 1150 |
} |
| 1151 |
} |
| 1152 |
var info serverInfo |
| 1153 |
if err = json.Unmarshal([]byte(l[5:]), &info); err != nil { |
| 1154 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 1155 |
} |
| 1156 |
return &info |
| 1157 |
} |
| 1158 |
|
| 1159 |
getInfo(false) |
| 1160 |
c.Write([]byte("CONNECT {\"protocol\":1,\"verbose\":false}\r\nPING\r\n")) |
| 1161 |
// Consume both the first PONG and INFO in response to the Connect. |
| 1162 |
client.ReadString('\n') |
| 1163 |
client.ReadString('\n') |
| 1164 |
|
| 1165 |
optsB := testWSOptions() |
| 1166 |
optsB.Cluster.Name = "abc" |
| 1167 |
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 1168 |
srvB := RunServer(optsB) |
| 1169 |
defer srvB.Shutdown() |
| 1170 |
|
| 1171 |
checkClusterFormed(t, srvA, srvB) |
| 1172 |
|
| 1173 |
checkConnectURLs := func(expected [][]string) *serverInfo { |
| 1174 |
t.Helper() |
| 1175 |
var si *serverInfo |
| 1176 |
for i, ws := range []bool{false, true} { |
| 1177 |
slices.Sort(expected[i]) |
| 1178 |
si = getInfo(ws) |
| 1179 |
slices.Sort(si.ConnectURLs) |
| 1180 |
if !reflect.DeepEqual(expected[i], si.ConnectURLs) { |
| 1181 |
t.Fatalf("Expected %q, got %q", expected, si.ConnectURLs) |
| 1182 |
} |
| 1183 |
} |
| 1184 |
return si |
| 1185 |
} |
| 1186 |
|
| 1187 |
curlb := fmt.Sprintf("127.0.0.1:%d", optsB.Port) |
| 1188 |
wscurlb := fmt.Sprintf("127.0.0.1:%d", optsB.Websocket.Port) |
| 1189 |
expected := [][]string{{curla, curlb}, {wscurla, wscurlb}} |
| 1190 |
checkConnectURLs(expected) |
| 1191 |
|
| 1192 |
optsC := testWSOptions() |
| 1193 |
testSetLDMGracePeriod(optsA, 5*time.Second) |
| 1194 |
optsC.Cluster.Name = "abc" |
| 1195 |
optsC.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 1196 |
srvC := RunServer(optsC) |
| 1197 |
defer srvC.Shutdown() |
| 1198 |
|
| 1199 |
checkClusterFormed(t, srvA, srvB, srvC) |
| 1200 |
|
| 1201 |
curlc := fmt.Sprintf("127.0.0.1:%d", optsC.Port) |
| 1202 |
wscurlc := fmt.Sprintf("127.0.0.1:%d", optsC.Websocket.Port) |
| 1203 |
expected = [][]string{{curla, curlb, curlc}, {wscurla, wscurlb, wscurlc}} |
| 1204 |
checkConnectURLs(expected) |
| 1205 |
|
| 1206 |
optsD := testWSOptions() |
| 1207 |
optsD.Cluster.Name = "abc" |
| 1208 |
optsD.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srvA.ClusterAddr().Port)) |
| 1209 |
srvD := RunServer(optsD) |
| 1210 |
defer srvD.Shutdown() |
| 1211 |
|
| 1212 |
checkClusterFormed(t, srvA, srvB, srvC, srvD) |
| 1213 |
|
| 1214 |
curld := fmt.Sprintf("127.0.0.1:%d", optsD.Port) |
| 1215 |
wscurld := fmt.Sprintf("127.0.0.1:%d", optsD.Websocket.Port) |
| 1216 |
expected = [][]string{{curla, curlb, curlc, curld}, {wscurla, wscurlb, wscurlc, wscurld}} |
| 1217 |
checkConnectURLs(expected) |
| 1218 |
|
| 1219 |
// Now lame duck server A and C. We should have client connected to A |
| 1220 |
// receive info that A is in LDM without A's URL, but also receive |
| 1221 |
// an update with C's URL gone. |
| 1222 |
// But first we need to create a client to C because otherwise the |
| 1223 |
// LDM signal will just shut it down because it would have no client. |
| 1224 |
nc, err := nats.Connect(srvC.ClientURL()) |
| 1225 |
if err != nil { |
| 1226 |
t.Fatalf("Failed to connect: %v", err) |
| 1227 |
} |
| 1228 |
defer nc.Close() |
| 1229 |
nc.Flush() |
| 1230 |
|
| 1231 |
start := time.Now() |
| 1232 |
wg := sync.WaitGroup{} |
| 1233 |
wg.Add(2) |
| 1234 |
go func() { |
| 1235 |
defer wg.Done() |
| 1236 |
srvA.lameDuckMode() |
| 1237 |
}() |
| 1238 |
|
| 1239 |
expected = [][]string{{curlb, curlc, curld}, {wscurlb, wscurlc, wscurld}} |
| 1240 |
si := checkConnectURLs(expected) |
| 1241 |
if !si.LameDuckMode { |
| 1242 |
t.Fatal("Expected LameDuckMode to be true, it was not") |
| 1243 |
} |
| 1244 |
|
| 1245 |
// Start LDM for server C. This should send an update to A |
| 1246 |
// which in turn should remove C from the list of URLs and |
| 1247 |
// update its client. |
| 1248 |
go func() { |
| 1249 |
defer wg.Done() |
| 1250 |
srvC.lameDuckMode() |
| 1251 |
}() |
| 1252 |
|
| 1253 |
expected = [][]string{{curlb, curld}, {wscurlb, wscurld}} |
| 1254 |
si = checkConnectURLs(expected) |
| 1255 |
// This update should not say that it is LDM. |
| 1256 |
if si.LameDuckMode { |
| 1257 |
t.Fatal("Expected LameDuckMode to be false, it was true") |
| 1258 |
} |
| 1259 |
|
| 1260 |
// Now shutdown D, and we also should get an update. |
| 1261 |
srvD.Shutdown() |
| 1262 |
|
| 1263 |
expected = [][]string{{curlb}, {wscurlb}} |
| 1264 |
si = checkConnectURLs(expected) |
| 1265 |
// This update should not say that it is LDM. |
| 1266 |
if si.LameDuckMode { |
| 1267 |
t.Fatal("Expected LameDuckMode to be false, it was true") |
| 1268 |
} |
| 1269 |
if time.Since(start) > 2*time.Second { |
| 1270 |
t.Fatalf("Did not get the expected events prior of server A and C shutting down") |
| 1271 |
} |
| 1272 |
|
| 1273 |
// Now explicitly shutdown srvA. When a server shutdown, it closes all its |
| 1274 |
// connections. For routes, it means that it is going to remove the remote's |
| 1275 |
// URL from its map. We want to make sure that in that case, server does not |
| 1276 |
// actually send an updated INFO to its clients. |
| 1277 |
srvA.Shutdown() |
| 1278 |
|
| 1279 |
// Expect nothing to be received on the client connection. |
| 1280 |
if l, err := client.ReadString('\n'); err == nil { |
| 1281 |
t.Fatalf("Expected connection to fail, instead got %q", l) |
| 1282 |
} |
| 1283 |
|
| 1284 |
c.Close() |
| 1285 |
nc.Close() |
| 1286 |
// Don't need to wait for actual disconnect of clients. |
| 1287 |
srvC.Shutdown() |
| 1288 |
wg.Wait() |
| 1289 |
} |
| 1290 |
|
| 1291 |
func TestServerValidateGatewaysOptions(t *testing.T) { |
| 1292 |
baseOpt := testDefaultOptionsForGateway("A") |
| 1293 |
u, _ := url.Parse("host:5222") |
| 1294 |
g := &RemoteGatewayOpts{ |
| 1295 |
URLs: []*url.URL{u}, |
| 1296 |
} |
| 1297 |
baseOpt.Gateway.Gateways = append(baseOpt.Gateway.Gateways, g) |
| 1298 |
|
| 1299 |
for _, test := range []struct { |
| 1300 |
name string |
| 1301 |
opts func() *Options |
| 1302 |
expectedErr string |
| 1303 |
}{ |
| 1304 |
{ |
| 1305 |
name: "gateway_has_no_name", |
| 1306 |
opts: func() *Options { |
| 1307 |
o := baseOpt.Clone() |
| 1308 |
o.Gateway.Name = "" |
| 1309 |
return o |
| 1310 |
}, |
| 1311 |
expectedErr: "has no name", |
| 1312 |
}, |
| 1313 |
{ |
| 1314 |
name: "gateway_has_no_port", |
| 1315 |
opts: func() *Options { |
| 1316 |
o := baseOpt.Clone() |
| 1317 |
o.Gateway.Port = 0 |
| 1318 |
return o |
| 1319 |
}, |
| 1320 |
expectedErr: "no port specified", |
| 1321 |
}, |
| 1322 |
{ |
| 1323 |
name: "gateway_dst_has_no_name", |
| 1324 |
opts: func() *Options { |
| 1325 |
o := baseOpt.Clone() |
| 1326 |
return o |
| 1327 |
}, |
| 1328 |
expectedErr: "has no name", |
| 1329 |
}, |
| 1330 |
{ |
| 1331 |
name: "gateway_dst_urls_is_nil", |
| 1332 |
opts: func() *Options { |
| 1333 |
o := baseOpt.Clone() |
| 1334 |
o.Gateway.Gateways[0].Name = "B" |
| 1335 |
o.Gateway.Gateways[0].URLs = nil |
| 1336 |
return o |
| 1337 |
}, |
| 1338 |
expectedErr: "has no URL", |
| 1339 |
}, |
| 1340 |
{ |
| 1341 |
name: "gateway_dst_urls_is_empty", |
| 1342 |
opts: func() *Options { |
| 1343 |
o := baseOpt.Clone() |
| 1344 |
o.Gateway.Gateways[0].Name = "B" |
| 1345 |
o.Gateway.Gateways[0].URLs = []*url.URL{} |
| 1346 |
return o |
| 1347 |
}, |
| 1348 |
expectedErr: "has no URL", |
| 1349 |
}, |
| 1350 |
} { |
| 1351 |
t.Run(test.name, func(t *testing.T) { |
| 1352 |
if err := validateOptions(test.opts()); err == nil || !strings.Contains(err.Error(), test.expectedErr) { |
| 1353 |
t.Fatalf("Expected error about %q, got %v", test.expectedErr, err) |
| 1354 |
} |
| 1355 |
}) |
| 1356 |
} |
| 1357 |
} |
| 1358 |
|
| 1359 |
func TestAcceptError(t *testing.T) { |
| 1360 |
o := DefaultOptions() |
| 1361 |
s := New(o) |
| 1362 |
s.running.Store(true) |
| 1363 |
defer s.Shutdown() |
| 1364 |
orgDelay := time.Hour |
| 1365 |
delay := s.acceptError("Test", fmt.Errorf("any error"), orgDelay) |
| 1366 |
if delay != orgDelay { |
| 1367 |
t.Fatalf("With this type of error, delay should have stayed same, got %v", delay) |
| 1368 |
} |
| 1369 |
|
| 1370 |
// Create any net.Error and make it a temporary |
| 1371 |
ne := &net.DNSError{IsTemporary: true} |
| 1372 |
orgDelay = 10 * time.Millisecond |
| 1373 |
delay = s.acceptError("Test", ne, orgDelay) |
| 1374 |
if delay != 2*orgDelay { |
| 1375 |
t.Fatalf("Expected delay to double, got %v", delay) |
| 1376 |
} |
| 1377 |
// Now check the max |
| 1378 |
orgDelay = 60 * ACCEPT_MAX_SLEEP / 100 |
| 1379 |
delay = s.acceptError("Test", ne, orgDelay) |
| 1380 |
if delay != ACCEPT_MAX_SLEEP { |
| 1381 |
t.Fatalf("Expected delay to double, got %v", delay) |
| 1382 |
} |
| 1383 |
wg := sync.WaitGroup{} |
| 1384 |
wg.Add(1) |
| 1385 |
start := time.Now() |
| 1386 |
go func() { |
| 1387 |
s.acceptError("Test", ne, orgDelay) |
| 1388 |
wg.Done() |
| 1389 |
}() |
| 1390 |
time.Sleep(100 * time.Millisecond) |
| 1391 |
// This should kick out the sleep in acceptError |
| 1392 |
s.Shutdown() |
| 1393 |
if dur := time.Since(start); dur >= ACCEPT_MAX_SLEEP { |
| 1394 |
t.Fatalf("Shutdown took too long: %v", dur) |
| 1395 |
} |
| 1396 |
wg.Wait() |
| 1397 |
if d := s.acceptError("Test", ne, orgDelay); d >= 0 { |
| 1398 |
t.Fatalf("Expected delay to be negative, got %v", d) |
| 1399 |
} |
| 1400 |
} |
| 1401 |
|
| 1402 |
func TestServerShutdownDuringStart(t *testing.T) { |
| 1403 |
o := DefaultOptions() |
| 1404 |
o.ServerName = "server" |
| 1405 |
o.DisableShortFirstPing = true |
| 1406 |
o.Accounts = []*Account{NewAccount("$SYS")} |
| 1407 |
o.SystemAccount = "$SYS" |
| 1408 |
o.Cluster.Name = "abc" |
| 1409 |
o.Cluster.Host = "127.0.0.1" |
| 1410 |
o.Cluster.Port = -1 |
| 1411 |
o.Gateway.Name = "abc" |
| 1412 |
o.Gateway.Host = "127.0.0.1" |
| 1413 |
o.Gateway.Port = -1 |
| 1414 |
o.LeafNode.Host = "127.0.0.1" |
| 1415 |
o.LeafNode.Port = -1 |
| 1416 |
o.Websocket.Host = "127.0.0.1" |
| 1417 |
o.Websocket.Port = -1 |
| 1418 |
o.Websocket.HandshakeTimeout = 1 |
| 1419 |
o.Websocket.NoTLS = true |
| 1420 |
o.MQTT.Host = "127.0.0.1" |
| 1421 |
o.MQTT.Port = -1 |
| 1422 |
|
| 1423 |
// We are going to test that if the server is shutdown |
| 1424 |
// while Start() runs (in this case, before), we don't |
| 1425 |
// start the listeners and therefore leave accept loops |
| 1426 |
// hanging. |
| 1427 |
s, err := NewServer(o) |
| 1428 |
if err != nil { |
| 1429 |
t.Fatalf("Error creating server: %v", err) |
| 1430 |
} |
| 1431 |
s.Shutdown() |
| 1432 |
|
| 1433 |
// Start() should not block, but just in case, start in |
| 1434 |
// different go routine. |
| 1435 |
ch := make(chan struct{}, 1) |
| 1436 |
go func() { |
| 1437 |
s.Start() |
| 1438 |
close(ch) |
| 1439 |
}() |
| 1440 |
select { |
| 1441 |
case <-ch: |
| 1442 |
case <-time.After(time.Second): |
| 1443 |
t.Fatal("Start appear to have blocked after server was shutdown") |
| 1444 |
} |
| 1445 |
// Now make sure that none of the listeners have been created |
| 1446 |
listeners := []string{} |
| 1447 |
s.mu.Lock() |
| 1448 |
if s.listener != nil { |
| 1449 |
listeners = append(listeners, "client") |
| 1450 |
} |
| 1451 |
if s.routeListener != nil { |
| 1452 |
listeners = append(listeners, "route") |
| 1453 |
} |
| 1454 |
if s.gatewayListener != nil { |
| 1455 |
listeners = append(listeners, "gateway") |
| 1456 |
} |
| 1457 |
if s.leafNodeListener != nil { |
| 1458 |
listeners = append(listeners, "leafnode") |
| 1459 |
} |
| 1460 |
if s.websocket.listener != nil { |
| 1461 |
listeners = append(listeners, "websocket") |
| 1462 |
} |
| 1463 |
if s.mqtt.listener != nil { |
| 1464 |
listeners = append(listeners, "mqtt") |
| 1465 |
} |
| 1466 |
s.mu.Unlock() |
| 1467 |
if len(listeners) > 0 { |
| 1468 |
lst := "" |
| 1469 |
for i, l := range listeners { |
| 1470 |
if i > 0 { |
| 1471 |
lst += ", " |
| 1472 |
} |
| 1473 |
lst += l |
| 1474 |
} |
| 1475 |
t.Fatalf("Following listeners have been created: %s", lst) |
| 1476 |
} |
| 1477 |
} |
| 1478 |
|
| 1479 |
type myDummyDNSResolver struct { |
| 1480 |
ips []string |
| 1481 |
err error |
| 1482 |
} |
| 1483 |
|
| 1484 |
func (r *myDummyDNSResolver) LookupHost(ctx context.Context, host string) ([]string, error) { |
| 1485 |
if r.err != nil { |
| 1486 |
return nil, r.err |
| 1487 |
} |
| 1488 |
return r.ips, nil |
| 1489 |
} |
| 1490 |
|
| 1491 |
func TestGetRandomIP(t *testing.T) { |
| 1492 |
s := &Server{} |
| 1493 |
resolver := &myDummyDNSResolver{} |
| 1494 |
// no port... |
| 1495 |
if _, err := s.getRandomIP(resolver, "noport", nil); err == nil || !strings.Contains(err.Error(), "port") { |
| 1496 |
t.Fatalf("Expected error about port missing, got %v", err) |
| 1497 |
} |
| 1498 |
resolver.err = fmt.Errorf("on purpose") |
| 1499 |
if _, err := s.getRandomIP(resolver, "localhost:4222", nil); err == nil || !strings.Contains(err.Error(), "on purpose") { |
| 1500 |
t.Fatalf("Expected error about no port, got %v", err) |
| 1501 |
} |
| 1502 |
resolver.err = nil |
| 1503 |
a, err := s.getRandomIP(resolver, "localhost:4222", nil) |
| 1504 |
if err != nil { |
| 1505 |
t.Fatalf("Unexpected error: %v", err) |
| 1506 |
} |
| 1507 |
if a != "localhost:4222" { |
| 1508 |
t.Fatalf("Expected address to be %q, got %q", "localhost:4222", a) |
| 1509 |
} |
| 1510 |
resolver.ips = []string{"1.2.3.4"} |
| 1511 |
a, err = s.getRandomIP(resolver, "localhost:4222", nil) |
| 1512 |
if err != nil { |
| 1513 |
t.Fatalf("Unexpected error: %v", err) |
| 1514 |
} |
| 1515 |
if a != "1.2.3.4:4222" { |
| 1516 |
t.Fatalf("Expected address to be %q, got %q", "1.2.3.4:4222", a) |
| 1517 |
} |
| 1518 |
// Check for randomness |
| 1519 |
resolver.ips = []string{"1.2.3.4", "2.2.3.4", "3.2.3.4"} |
| 1520 |
dist := [3]int{} |
| 1521 |
for i := 0; i < 100; i++ { |
| 1522 |
ip, err := s.getRandomIP(resolver, "localhost:4222", nil) |
| 1523 |
if err != nil { |
| 1524 |
t.Fatalf("Unexpected error: %v", err) |
| 1525 |
} |
| 1526 |
v := int(ip[0]-'0') - 1 |
| 1527 |
dist[v]++ |
| 1528 |
} |
| 1529 |
low := 20 |
| 1530 |
high := 47 |
| 1531 |
for i, d := range dist { |
| 1532 |
if d == 0 || d == 100 { |
| 1533 |
t.Fatalf("Unexpected distribution for ip %v, got %v", i, d) |
| 1534 |
} else if d < low || d > high { |
| 1535 |
t.Logf("Warning: out of expected range [%v,%v] for ip %v, got %v", low, high, i, d) |
| 1536 |
} |
| 1537 |
} |
| 1538 |
|
| 1539 |
// Check IP exclusions |
| 1540 |
excludedIPs := map[string]struct{}{"1.2.3.4:4222": {}} |
| 1541 |
for i := 0; i < 100; i++ { |
| 1542 |
ip, err := s.getRandomIP(resolver, "localhost:4222", excludedIPs) |
| 1543 |
if err != nil { |
| 1544 |
t.Fatalf("Unexpected error: %v", err) |
| 1545 |
} |
| 1546 |
if ip[0] == '1' { |
| 1547 |
t.Fatalf("Should not have returned this ip: %q", ip) |
| 1548 |
} |
| 1549 |
} |
| 1550 |
excludedIPs["2.2.3.4:4222"] = struct{}{} |
| 1551 |
for i := 0; i < 100; i++ { |
| 1552 |
ip, err := s.getRandomIP(resolver, "localhost:4222", excludedIPs) |
| 1553 |
if err != nil { |
| 1554 |
t.Fatalf("Unexpected error: %v", err) |
| 1555 |
} |
| 1556 |
if ip[0] != '3' { |
| 1557 |
t.Fatalf("Should only have returned '3.2.3.4', got returned %q", ip) |
| 1558 |
} |
| 1559 |
} |
| 1560 |
excludedIPs["3.2.3.4:4222"] = struct{}{} |
| 1561 |
for i := 0; i < 100; i++ { |
| 1562 |
if _, err := s.getRandomIP(resolver, "localhost:4222", excludedIPs); err != errNoIPAvail { |
| 1563 |
t.Fatalf("Unexpected error: %v", err) |
| 1564 |
} |
| 1565 |
} |
| 1566 |
|
| 1567 |
// Now check that exclusion takes into account the port number. |
| 1568 |
resolver.ips = []string{"127.0.0.1"} |
| 1569 |
excludedIPs = map[string]struct{}{"127.0.0.1:4222": {}} |
| 1570 |
for i := 0; i < 100; i++ { |
| 1571 |
if _, err := s.getRandomIP(resolver, "localhost:4223", excludedIPs); err == errNoIPAvail { |
| 1572 |
t.Fatal("Should not have failed") |
| 1573 |
} |
| 1574 |
} |
| 1575 |
} |
| 1576 |
|
| 1577 |
type shortWriteConn struct { |
| 1578 |
net.Conn |
| 1579 |
} |
| 1580 |
|
| 1581 |
func (swc *shortWriteConn) Write(b []byte) (int, error) { |
| 1582 |
// Limit the write to 10 bytes at a time. |
| 1583 |
short := false |
| 1584 |
max := len(b) |
| 1585 |
if max > 10 { |
| 1586 |
max = 10 |
| 1587 |
short = true |
| 1588 |
} |
| 1589 |
n, err := swc.Conn.Write(b[:max]) |
| 1590 |
if err == nil && short { |
| 1591 |
return n, io.ErrShortWrite |
| 1592 |
} |
| 1593 |
return n, err |
| 1594 |
} |
| 1595 |
|
| 1596 |
func TestClientWriteLoopStall(t *testing.T) { |
| 1597 |
opts := DefaultOptions() |
| 1598 |
s := RunServer(opts) |
| 1599 |
defer s.Shutdown() |
| 1600 |
|
| 1601 |
errCh := make(chan error, 1) |
| 1602 |
|
| 1603 |
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) |
| 1604 |
nc, err := nats.Connect(url, |
| 1605 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, e error) { |
| 1606 |
select { |
| 1607 |
case errCh <- e: |
| 1608 |
default: |
| 1609 |
} |
| 1610 |
})) |
| 1611 |
if err != nil { |
| 1612 |
t.Fatalf("Error on connect: %v", err) |
| 1613 |
} |
| 1614 |
defer nc.Close() |
| 1615 |
sub, err := nc.SubscribeSync("foo") |
| 1616 |
if err != nil { |
| 1617 |
t.Fatalf("Error on subscribe: %v", err) |
| 1618 |
} |
| 1619 |
nc.Flush() |
| 1620 |
cid, _ := nc.GetClientID() |
| 1621 |
|
| 1622 |
sender, err := nats.Connect(url) |
| 1623 |
if err != nil { |
| 1624 |
t.Fatalf("Error on connect: %v", err) |
| 1625 |
} |
| 1626 |
defer sender.Close() |
| 1627 |
|
| 1628 |
c := s.getClient(cid) |
| 1629 |
c.mu.Lock() |
| 1630 |
c.nc = &shortWriteConn{Conn: c.nc} |
| 1631 |
c.mu.Unlock() |
| 1632 |
|
| 1633 |
sender.Publish("foo", make([]byte, 100)) |
| 1634 |
|
| 1635 |
if _, err := sub.NextMsg(3 * time.Second); err != nil { |
| 1636 |
t.Fatalf("WriteLoop has stalled!") |
| 1637 |
} |
| 1638 |
|
| 1639 |
// Make sure that we did not get any async error |
| 1640 |
select { |
| 1641 |
case e := <-errCh: |
| 1642 |
t.Fatalf("Got error: %v", e) |
| 1643 |
case <-time.After(250 * time.Millisecond): |
| 1644 |
} |
| 1645 |
} |
| 1646 |
|
| 1647 |
func TestInsecureSkipVerifyWarning(t *testing.T) { |
| 1648 |
checkWarnReported := func(t *testing.T, o *Options, expectedWarn string) { |
| 1649 |
t.Helper() |
| 1650 |
s, err := NewServer(o) |
| 1651 |
if err != nil { |
| 1652 |
t.Fatalf("Error on new server: %v", err) |
| 1653 |
} |
| 1654 |
l := &captureWarnLogger{warn: make(chan string, 1)} |
| 1655 |
s.SetLogger(l, false, false) |
| 1656 |
wg := sync.WaitGroup{} |
| 1657 |
wg.Add(1) |
| 1658 |
go func() { |
| 1659 |
s.Start() |
| 1660 |
wg.Done() |
| 1661 |
}() |
| 1662 |
if err := s.readyForConnections(time.Second); err != nil { |
| 1663 |
t.Fatal(err) |
| 1664 |
} |
| 1665 |
select { |
| 1666 |
case w := <-l.warn: |
| 1667 |
if !strings.Contains(w, expectedWarn) { |
| 1668 |
t.Fatalf("Expected warning %q, got %q", expectedWarn, w) |
| 1669 |
} |
| 1670 |
case <-time.After(2 * time.Second): |
| 1671 |
t.Fatalf("Did not get warning %q", expectedWarn) |
| 1672 |
} |
| 1673 |
s.Shutdown() |
| 1674 |
wg.Wait() |
| 1675 |
} |
| 1676 |
|
| 1677 |
tc := &TLSConfigOpts{} |
| 1678 |
tc.CertFile = "../test/configs/certs/server-cert.pem" |
| 1679 |
tc.KeyFile = "../test/configs/certs/server-key.pem" |
| 1680 |
tc.CaFile = "../test/configs/certs/ca.pem" |
| 1681 |
tc.Insecure = true |
| 1682 |
config, err := GenTLSConfig(tc) |
| 1683 |
if err != nil { |
| 1684 |
t.Fatalf("Error generating tls config: %v", err) |
| 1685 |
} |
| 1686 |
|
| 1687 |
o := DefaultOptions() |
| 1688 |
o.Cluster.Name = "A" |
| 1689 |
o.Cluster.Port = -1 |
| 1690 |
o.Cluster.TLSConfig = config.Clone() |
| 1691 |
checkWarnReported(t, o, clusterTLSInsecureWarning) |
| 1692 |
|
| 1693 |
// Remove the route setting |
| 1694 |
o.Cluster.Port = 0 |
| 1695 |
o.Cluster.TLSConfig = nil |
| 1696 |
|
| 1697 |
// Configure LeafNode with no TLS in the main block first, but only with remotes. |
| 1698 |
o.LeafNode.Port = -1 |
| 1699 |
rurl, _ := url.Parse("nats://127.0.0.1:1234") |
| 1700 |
o.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 1701 |
{ |
| 1702 |
URLs: []*url.URL{rurl}, |
| 1703 |
TLSConfig: config.Clone(), |
| 1704 |
}, |
| 1705 |
} |
| 1706 |
checkWarnReported(t, o, leafnodeTLSInsecureWarning) |
| 1707 |
|
| 1708 |
// Now add to main block. |
| 1709 |
o.LeafNode.TLSConfig = config.Clone() |
| 1710 |
checkWarnReported(t, o, leafnodeTLSInsecureWarning) |
| 1711 |
|
| 1712 |
// Now remove remote and check warning still reported |
| 1713 |
o.LeafNode.Remotes = nil |
| 1714 |
checkWarnReported(t, o, leafnodeTLSInsecureWarning) |
| 1715 |
|
| 1716 |
// Remove the LN setting |
| 1717 |
o.LeafNode.Port = 0 |
| 1718 |
o.LeafNode.TLSConfig = nil |
| 1719 |
|
| 1720 |
// Configure GW with no TLS in main block first, but only with remotes |
| 1721 |
o.Gateway.Name = "A" |
| 1722 |
o.Gateway.Host = "127.0.0.1" |
| 1723 |
o.Gateway.Port = -1 |
| 1724 |
o.Gateway.Gateways = []*RemoteGatewayOpts{ |
| 1725 |
{ |
| 1726 |
Name: "B", |
| 1727 |
URLs: []*url.URL{rurl}, |
| 1728 |
TLSConfig: config.Clone(), |
| 1729 |
}, |
| 1730 |
} |
| 1731 |
checkWarnReported(t, o, gatewayTLSInsecureWarning) |
| 1732 |
|
| 1733 |
// Now add to main block. |
| 1734 |
o.Gateway.TLSConfig = config.Clone() |
| 1735 |
checkWarnReported(t, o, gatewayTLSInsecureWarning) |
| 1736 |
|
| 1737 |
// Now remove remote and check warning still reported |
| 1738 |
o.Gateway.Gateways = nil |
| 1739 |
checkWarnReported(t, o, gatewayTLSInsecureWarning) |
| 1740 |
} |
| 1741 |
|
| 1742 |
func TestConnectErrorReports(t *testing.T) { |
| 1743 |
// On Windows, an attempt to connect to a port that has no listener will |
| 1744 |
// take whatever timeout specified in DialTimeout() before failing. |
| 1745 |
// So skip for now. |
| 1746 |
if runtime.GOOS == "windows" { |
| 1747 |
t.Skip() |
| 1748 |
} |
| 1749 |
// Check that default report attempts is as expected |
| 1750 |
opts := DefaultOptions() |
| 1751 |
s := RunServer(opts) |
| 1752 |
defer s.Shutdown() |
| 1753 |
|
| 1754 |
if ra := s.getOpts().ConnectErrorReports; ra != DEFAULT_CONNECT_ERROR_REPORTS { |
| 1755 |
t.Fatalf("Expected default value to be %v, got %v", DEFAULT_CONNECT_ERROR_REPORTS, ra) |
| 1756 |
} |
| 1757 |
|
| 1758 |
tmpFile := createTempFile(t, "") |
| 1759 |
log := tmpFile.Name() |
| 1760 |
tmpFile.Close() |
| 1761 |
|
| 1762 |
remoteURLs := RoutesFromStr("nats://127.0.0.1:1234") |
| 1763 |
|
| 1764 |
opts = DefaultOptions() |
| 1765 |
opts.ConnectErrorReports = 3 |
| 1766 |
opts.Cluster.Port = -1 |
| 1767 |
opts.Routes = remoteURLs |
| 1768 |
opts.NoLog = false |
| 1769 |
opts.LogFile = log |
| 1770 |
opts.Logtime = true |
| 1771 |
opts.Debug = true |
| 1772 |
s = RunServer(opts) |
| 1773 |
defer s.Shutdown() |
| 1774 |
|
| 1775 |
checkContent := func(t *testing.T, txt string, attempt int, shouldBeThere bool) { |
| 1776 |
t.Helper() |
| 1777 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 1778 |
content, err := os.ReadFile(log) |
| 1779 |
if err != nil { |
| 1780 |
return fmt.Errorf("Error reading log file: %v", err) |
| 1781 |
} |
| 1782 |
present := bytes.Contains(content, []byte(fmt.Sprintf("%s (attempt %d)", txt, attempt))) |
| 1783 |
if shouldBeThere && !present { |
| 1784 |
return fmt.Errorf("Did not find expected log statement (%s) for attempt %d: %s", txt, attempt, content) |
| 1785 |
} else if !shouldBeThere && present { |
| 1786 |
return fmt.Errorf("Log statement (%s) for attempt %d should not be present: %s", txt, attempt, content) |
| 1787 |
} |
| 1788 |
return nil |
| 1789 |
}) |
| 1790 |
} |
| 1791 |
|
| 1792 |
type testConnect struct { |
| 1793 |
name string |
| 1794 |
attempt int |
| 1795 |
errExpected bool |
| 1796 |
} |
| 1797 |
for _, test := range []testConnect{ |
| 1798 |
{"route_attempt_1", 1, true}, |
| 1799 |
{"route_attempt_2", 2, false}, |
| 1800 |
{"route_attempt_3", 3, true}, |
| 1801 |
{"route_attempt_4", 4, false}, |
| 1802 |
{"route_attempt_6", 6, true}, |
| 1803 |
{"route_attempt_7", 7, false}, |
| 1804 |
} { |
| 1805 |
t.Run(test.name, func(t *testing.T) { |
| 1806 |
debugExpected := !test.errExpected |
| 1807 |
checkContent(t, "[DBG] Error trying to connect to route", test.attempt, debugExpected) |
| 1808 |
checkContent(t, "[ERR] Error trying to connect to route", test.attempt, test.errExpected) |
| 1809 |
}) |
| 1810 |
} |
| 1811 |
|
| 1812 |
s.Shutdown() |
| 1813 |
removeFile(t, log) |
| 1814 |
|
| 1815 |
// Now try with leaf nodes |
| 1816 |
opts.Cluster.Port = 0 |
| 1817 |
opts.Routes = nil |
| 1818 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{remoteURLs[0]}}} |
| 1819 |
opts.LeafNode.ReconnectInterval = 15 * time.Millisecond |
| 1820 |
s = RunServer(opts) |
| 1821 |
defer s.Shutdown() |
| 1822 |
|
| 1823 |
checkLeafContent := func(t *testing.T, txt, host string, attempt int, shouldBeThere bool) { |
| 1824 |
t.Helper() |
| 1825 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 1826 |
content, err := os.ReadFile(log) |
| 1827 |
if err != nil { |
| 1828 |
return fmt.Errorf("Error reading log file: %v", err) |
| 1829 |
} |
| 1830 |
present := bytes.Contains(content, []byte(fmt.Sprintf("%s %q (attempt %d)", txt, host, attempt))) |
| 1831 |
if shouldBeThere && !present { |
| 1832 |
return fmt.Errorf("Did not find expected log statement (%s %q) for attempt %d: %s", txt, host, attempt, content) |
| 1833 |
} else if !shouldBeThere && present { |
| 1834 |
return fmt.Errorf("Log statement (%s %q) for attempt %d should not be present: %s", txt, host, attempt, content) |
| 1835 |
} |
| 1836 |
return nil |
| 1837 |
}) |
| 1838 |
} |
| 1839 |
|
| 1840 |
for _, test := range []testConnect{ |
| 1841 |
{"leafnode_attempt_1", 1, true}, |
| 1842 |
{"leafnode_attempt_2", 2, false}, |
| 1843 |
{"leafnode_attempt_3", 3, true}, |
| 1844 |
{"leafnode_attempt_4", 4, false}, |
| 1845 |
{"leafnode_attempt_6", 6, true}, |
| 1846 |
{"leafnode_attempt_7", 7, false}, |
| 1847 |
} { |
| 1848 |
t.Run(test.name, func(t *testing.T) { |
| 1849 |
debugExpected := !test.errExpected |
| 1850 |
checkLeafContent(t, "[DBG] Error trying to connect as leafnode to remote server", remoteURLs[0].Host, test.attempt, debugExpected) |
| 1851 |
checkLeafContent(t, "[ERR] Error trying to connect as leafnode to remote server", remoteURLs[0].Host, test.attempt, test.errExpected) |
| 1852 |
}) |
| 1853 |
} |
| 1854 |
|
| 1855 |
s.Shutdown() |
| 1856 |
removeFile(t, log) |
| 1857 |
|
| 1858 |
// Now try with gateways |
| 1859 |
opts.LeafNode.Remotes = nil |
| 1860 |
opts.Cluster.Name = "A" |
| 1861 |
opts.Gateway.Name = "A" |
| 1862 |
opts.Gateway.Port = -1 |
| 1863 |
opts.Gateway.Gateways = []*RemoteGatewayOpts{ |
| 1864 |
{ |
| 1865 |
Name: "B", |
| 1866 |
URLs: remoteURLs, |
| 1867 |
}, |
| 1868 |
} |
| 1869 |
opts.gatewaysSolicitDelay = 15 * time.Millisecond |
| 1870 |
s = RunServer(opts) |
| 1871 |
defer s.Shutdown() |
| 1872 |
|
| 1873 |
for _, test := range []testConnect{ |
| 1874 |
{"gateway_attempt_1", 1, true}, |
| 1875 |
{"gateway_attempt_2", 2, false}, |
| 1876 |
{"gateway_attempt_3", 3, true}, |
| 1877 |
{"gateway_attempt_4", 4, false}, |
| 1878 |
{"gateway_attempt_6", 6, true}, |
| 1879 |
{"gateway_attempt_7", 7, false}, |
| 1880 |
} { |
| 1881 |
t.Run(test.name, func(t *testing.T) { |
| 1882 |
debugExpected := !test.errExpected |
| 1883 |
infoExpected := test.errExpected |
| 1884 |
// For gateways, we also check our notice that we attempt to connect |
| 1885 |
checkContent(t, "[DBG] Connecting to explicit gateway \"B\" (127.0.0.1:1234) at 127.0.0.1:1234", test.attempt, debugExpected) |
| 1886 |
checkContent(t, "[INF] Connecting to explicit gateway \"B\" (127.0.0.1:1234) at 127.0.0.1:1234", test.attempt, infoExpected) |
| 1887 |
checkContent(t, "[DBG] Error connecting to explicit gateway \"B\" (127.0.0.1:1234) at 127.0.0.1:1234", test.attempt, debugExpected) |
| 1888 |
checkContent(t, "[ERR] Error connecting to explicit gateway \"B\" (127.0.0.1:1234) at 127.0.0.1:1234", test.attempt, test.errExpected) |
| 1889 |
}) |
| 1890 |
} |
| 1891 |
} |
| 1892 |
|
| 1893 |
func TestReconnectErrorReports(t *testing.T) { |
| 1894 |
// On Windows, an attempt to connect to a port that has no listener will |
| 1895 |
// take whatever timeout specified in DialTimeout() before failing. |
| 1896 |
// So skip for now. |
| 1897 |
if runtime.GOOS == "windows" { |
| 1898 |
t.Skip() |
| 1899 |
} |
| 1900 |
// Check that default report attempts is as expected |
| 1901 |
opts := DefaultOptions() |
| 1902 |
s := RunServer(opts) |
| 1903 |
defer s.Shutdown() |
| 1904 |
|
| 1905 |
if ra := s.getOpts().ReconnectErrorReports; ra != DEFAULT_RECONNECT_ERROR_REPORTS { |
| 1906 |
t.Fatalf("Expected default value to be %v, got %v", DEFAULT_RECONNECT_ERROR_REPORTS, ra) |
| 1907 |
} |
| 1908 |
|
| 1909 |
tmpFile := createTempFile(t, "") |
| 1910 |
log := tmpFile.Name() |
| 1911 |
tmpFile.Close() |
| 1912 |
|
| 1913 |
csOpts := DefaultOptions() |
| 1914 |
csOpts.Cluster.Port = -1 |
| 1915 |
cs := RunServer(csOpts) |
| 1916 |
defer cs.Shutdown() |
| 1917 |
|
| 1918 |
opts = DefaultOptions() |
| 1919 |
opts.ReconnectErrorReports = 3 |
| 1920 |
opts.Cluster.Port = -1 |
| 1921 |
opts.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", cs.ClusterAddr().Port)) |
| 1922 |
opts.NoLog = false |
| 1923 |
opts.LogFile = log |
| 1924 |
opts.Logtime = true |
| 1925 |
opts.Debug = true |
| 1926 |
s = RunServer(opts) |
| 1927 |
defer s.Shutdown() |
| 1928 |
|
| 1929 |
// Wait for cluster to be formed |
| 1930 |
checkClusterFormed(t, s, cs) |
| 1931 |
|
| 1932 |
// Now shutdown the server s connected to. |
| 1933 |
cs.Shutdown() |
| 1934 |
|
| 1935 |
// Specifically for route test, wait at least reconnect interval before checking logs |
| 1936 |
time.Sleep(DEFAULT_ROUTE_RECONNECT) |
| 1937 |
|
| 1938 |
checkContent := func(t *testing.T, txt string, attempt int, shouldBeThere bool) { |
| 1939 |
t.Helper() |
| 1940 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 1941 |
content, err := os.ReadFile(log) |
| 1942 |
if err != nil { |
| 1943 |
return fmt.Errorf("Error reading log file: %v", err) |
| 1944 |
} |
| 1945 |
present := bytes.Contains(content, []byte(fmt.Sprintf("%s (attempt %d)", txt, attempt))) |
| 1946 |
if shouldBeThere && !present { |
| 1947 |
return fmt.Errorf("Did not find expected log statement (%s) for attempt %d: %s", txt, attempt, content) |
| 1948 |
} else if !shouldBeThere && present { |
| 1949 |
return fmt.Errorf("Log statement (%s) for attempt %d should not be present: %s", txt, attempt, content) |
| 1950 |
} |
| 1951 |
return nil |
| 1952 |
}) |
| 1953 |
} |
| 1954 |
|
| 1955 |
type testConnect struct { |
| 1956 |
name string |
| 1957 |
attempt int |
| 1958 |
errExpected bool |
| 1959 |
} |
| 1960 |
for _, test := range []testConnect{ |
| 1961 |
{"route_attempt_1", 1, true}, |
| 1962 |
{"route_attempt_2", 2, false}, |
| 1963 |
{"route_attempt_3", 3, true}, |
| 1964 |
{"route_attempt_4", 4, false}, |
| 1965 |
{"route_attempt_6", 6, true}, |
| 1966 |
{"route_attempt_7", 7, false}, |
| 1967 |
} { |
| 1968 |
t.Run(test.name, func(t *testing.T) { |
| 1969 |
debugExpected := !test.errExpected |
| 1970 |
checkContent(t, "[DBG] Error trying to connect to route", test.attempt, debugExpected) |
| 1971 |
checkContent(t, "[ERR] Error trying to connect to route", test.attempt, test.errExpected) |
| 1972 |
}) |
| 1973 |
} |
| 1974 |
|
| 1975 |
s.Shutdown() |
| 1976 |
removeFile(t, log) |
| 1977 |
|
| 1978 |
// Now try with leaf nodes |
| 1979 |
csOpts.Cluster.Port = 0 |
| 1980 |
csOpts.Cluster.Name = _EMPTY_ |
| 1981 |
csOpts.LeafNode.Host = "127.0.0.1" |
| 1982 |
csOpts.LeafNode.Port = -1 |
| 1983 |
|
| 1984 |
cs = RunServer(csOpts) |
| 1985 |
defer cs.Shutdown() |
| 1986 |
|
| 1987 |
opts.Cluster.Port = 0 |
| 1988 |
opts.Cluster.Name = _EMPTY_ |
| 1989 |
opts.Routes = nil |
| 1990 |
u, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", csOpts.LeafNode.Port)) |
| 1991 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}} |
| 1992 |
opts.LeafNode.ReconnectInterval = 15 * time.Millisecond |
| 1993 |
s = RunServer(opts) |
| 1994 |
defer s.Shutdown() |
| 1995 |
|
| 1996 |
checkLeafNodeConnected(t, s) |
| 1997 |
|
| 1998 |
// Now shutdown the server s is connected to |
| 1999 |
cs.Shutdown() |
| 2000 |
|
| 2001 |
checkLeafContent := func(t *testing.T, txt, host string, attempt int, shouldBeThere bool) { |
| 2002 |
t.Helper() |
| 2003 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 2004 |
content, err := os.ReadFile(log) |
| 2005 |
if err != nil { |
| 2006 |
return fmt.Errorf("Error reading log file: %v", err) |
| 2007 |
} |
| 2008 |
present := bytes.Contains(content, []byte(fmt.Sprintf("%s %q (attempt %d)", txt, host, attempt))) |
| 2009 |
if shouldBeThere && !present { |
| 2010 |
return fmt.Errorf("Did not find expected log statement (%s %q) for attempt %d: %s", txt, host, attempt, content) |
| 2011 |
} else if !shouldBeThere && present { |
| 2012 |
return fmt.Errorf("Log statement (%s %q) for attempt %d should not be present: %s", txt, host, attempt, content) |
| 2013 |
} |
| 2014 |
return nil |
| 2015 |
}) |
| 2016 |
} |
| 2017 |
|
| 2018 |
for _, test := range []testConnect{ |
| 2019 |
{"leafnode_attempt_1", 1, true}, |
| 2020 |
{"leafnode_attempt_2", 2, false}, |
| 2021 |
{"leafnode_attempt_3", 3, true}, |
| 2022 |
{"leafnode_attempt_4", 4, false}, |
| 2023 |
{"leafnode_attempt_6", 6, true}, |
| 2024 |
{"leafnode_attempt_7", 7, false}, |
| 2025 |
} { |
| 2026 |
t.Run(test.name, func(t *testing.T) { |
| 2027 |
debugExpected := !test.errExpected |
| 2028 |
checkLeafContent(t, "[DBG] Error trying to connect as leafnode to remote server", u.Host, test.attempt, debugExpected) |
| 2029 |
checkLeafContent(t, "[ERR] Error trying to connect as leafnode to remote server", u.Host, test.attempt, test.errExpected) |
| 2030 |
}) |
| 2031 |
} |
| 2032 |
|
| 2033 |
s.Shutdown() |
| 2034 |
removeFile(t, log) |
| 2035 |
|
| 2036 |
// Now try with gateways |
| 2037 |
csOpts.LeafNode.Port = 0 |
| 2038 |
csOpts.Cluster.Name = "B" |
| 2039 |
csOpts.Gateway.Name = "B" |
| 2040 |
csOpts.Gateway.Port = -1 |
| 2041 |
cs = RunServer(csOpts) |
| 2042 |
|
| 2043 |
opts.LeafNode.Remotes = nil |
| 2044 |
opts.Cluster.Name = "A" |
| 2045 |
opts.Gateway.Name = "A" |
| 2046 |
opts.Gateway.Port = -1 |
| 2047 |
remoteGWPort := cs.GatewayAddr().Port |
| 2048 |
u, _ = url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", remoteGWPort)) |
| 2049 |
opts.Gateway.Gateways = []*RemoteGatewayOpts{ |
| 2050 |
{ |
| 2051 |
Name: "B", |
| 2052 |
URLs: []*url.URL{u}, |
| 2053 |
}, |
| 2054 |
} |
| 2055 |
opts.gatewaysSolicitDelay = 15 * time.Millisecond |
| 2056 |
s = RunServer(opts) |
| 2057 |
defer s.Shutdown() |
| 2058 |
|
| 2059 |
waitForOutboundGateways(t, s, 1, 2*time.Second) |
| 2060 |
waitForInboundGateways(t, s, 1, 2*time.Second) |
| 2061 |
|
| 2062 |
// Now stop server s is connecting to |
| 2063 |
cs.Shutdown() |
| 2064 |
|
| 2065 |
connTxt := fmt.Sprintf("Connecting to explicit gateway \"B\" (127.0.0.1:%d) at 127.0.0.1:%d", remoteGWPort, remoteGWPort) |
| 2066 |
dbgConnTxt := fmt.Sprintf("[DBG] %s", connTxt) |
| 2067 |
infConnTxt := fmt.Sprintf("[INF] %s", connTxt) |
| 2068 |
|
| 2069 |
errTxt := fmt.Sprintf("Error connecting to explicit gateway \"B\" (127.0.0.1:%d) at 127.0.0.1:%d", remoteGWPort, remoteGWPort) |
| 2070 |
dbgErrTxt := fmt.Sprintf("[DBG] %s", errTxt) |
| 2071 |
errErrTxt := fmt.Sprintf("[ERR] %s", errTxt) |
| 2072 |
|
| 2073 |
for _, test := range []testConnect{ |
| 2074 |
{"gateway_attempt_1", 1, true}, |
| 2075 |
{"gateway_attempt_2", 2, false}, |
| 2076 |
{"gateway_attempt_3", 3, true}, |
| 2077 |
{"gateway_attempt_4", 4, false}, |
| 2078 |
{"gateway_attempt_6", 6, true}, |
| 2079 |
{"gateway_attempt_7", 7, false}, |
| 2080 |
} { |
| 2081 |
t.Run(test.name, func(t *testing.T) { |
| 2082 |
debugExpected := !test.errExpected |
| 2083 |
infoExpected := test.errExpected |
| 2084 |
// For gateways, we also check our notice that we attempt to connect |
| 2085 |
checkContent(t, dbgConnTxt, test.attempt, debugExpected) |
| 2086 |
checkContent(t, infConnTxt, test.attempt, infoExpected) |
| 2087 |
checkContent(t, dbgErrTxt, test.attempt, debugExpected) |
| 2088 |
checkContent(t, errErrTxt, test.attempt, test.errExpected) |
| 2089 |
}) |
| 2090 |
} |
| 2091 |
} |
| 2092 |
|
| 2093 |
func TestServerLogsConfigurationFile(t *testing.T) { |
| 2094 |
file := createTempFile(t, "nats_server_log_") |
| 2095 |
file.Close() |
| 2096 |
|
| 2097 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 2098 |
port: -1 |
| 2099 |
logfile: '%s' |
| 2100 |
`, file.Name()))) |
| 2101 |
|
| 2102 |
o := LoadConfig(conf) |
| 2103 |
o.ConfigFile = file.Name() |
| 2104 |
o.NoLog = false |
| 2105 |
s := RunServer(o) |
| 2106 |
s.Shutdown() |
| 2107 |
|
| 2108 |
log, err := os.ReadFile(file.Name()) |
| 2109 |
if err != nil { |
| 2110 |
t.Fatalf("Error reading log file: %v", err) |
| 2111 |
} |
| 2112 |
if !bytes.Contains(log, []byte(fmt.Sprintf("Using configuration file: %s", file.Name()))) { |
| 2113 |
t.Fatalf("Config file location was not reported in log: %s", log) |
| 2114 |
} |
| 2115 |
} |
| 2116 |
|
| 2117 |
func TestServerRateLimitLogging(t *testing.T) { |
| 2118 |
s := RunServer(DefaultOptions()) |
| 2119 |
defer s.Shutdown() |
| 2120 |
|
| 2121 |
s.changeRateLimitLogInterval(100 * time.Millisecond) |
| 2122 |
|
| 2123 |
l := &captureWarnLogger{warn: make(chan string, 100)} |
| 2124 |
s.SetLogger(l, false, false) |
| 2125 |
|
| 2126 |
s.RateLimitWarnf("Warning number 1") |
| 2127 |
s.RateLimitWarnf("Warning number 2") |
| 2128 |
s.rateLimitFormatWarnf("warning value %d", 1) |
| 2129 |
s.RateLimitWarnf("Warning number 1") |
| 2130 |
s.RateLimitWarnf("Warning number 2") |
| 2131 |
s.rateLimitFormatWarnf("warning value %d", 2) |
| 2132 |
|
| 2133 |
checkLog := func(c1, c2 *client) { |
| 2134 |
t.Helper() |
| 2135 |
|
| 2136 |
nb1 := "Warning number 1" |
| 2137 |
nb2 := "Warning number 2" |
| 2138 |
nbv := "warning value" |
| 2139 |
gotOne := 0 |
| 2140 |
gotTwo := 0 |
| 2141 |
gotFormat := 0 |
| 2142 |
for done := false; !done; { |
| 2143 |
select { |
| 2144 |
case w := <-l.warn: |
| 2145 |
if strings.Contains(w, nb1) { |
| 2146 |
gotOne++ |
| 2147 |
} else if strings.Contains(w, nb2) { |
| 2148 |
gotTwo++ |
| 2149 |
} else if strings.Contains(w, nbv) { |
| 2150 |
gotFormat++ |
| 2151 |
} |
| 2152 |
case <-time.After(150 * time.Millisecond): |
| 2153 |
done = true |
| 2154 |
} |
| 2155 |
} |
| 2156 |
if gotOne != 1 { |
| 2157 |
t.Fatalf("Should have had only 1 warning for nb1, got %v", gotOne) |
| 2158 |
} |
| 2159 |
if gotTwo != 1 { |
| 2160 |
t.Fatalf("Should have had only 1 warning for nb2, got %v", gotTwo) |
| 2161 |
} |
| 2162 |
if gotFormat != 1 { |
| 2163 |
t.Fatalf("Should have had only 1 warning for format, got %v", gotFormat) |
| 2164 |
} |
| 2165 |
|
| 2166 |
// Wait for more than the expiration interval |
| 2167 |
time.Sleep(200 * time.Millisecond) |
| 2168 |
if c1 == nil { |
| 2169 |
s.RateLimitWarnf("%s", nb1) |
| 2170 |
s.rateLimitFormatWarnf("warning value %d", 1) |
| 2171 |
} else { |
| 2172 |
c1.RateLimitWarnf("%s", nb1) |
| 2173 |
c2.RateLimitWarnf("%s", nb1) |
| 2174 |
c1.rateLimitFormatWarnf("warning value %d", 1) |
| 2175 |
} |
| 2176 |
gotOne = 0 |
| 2177 |
gotFormat = 0 |
| 2178 |
for { |
| 2179 |
select { |
| 2180 |
case w := <-l.warn: |
| 2181 |
if strings.Contains(w, nb1) { |
| 2182 |
gotOne++ |
| 2183 |
} else if strings.Contains(w, nbv) { |
| 2184 |
gotFormat++ |
| 2185 |
} |
| 2186 |
case <-time.After(200 * time.Millisecond): |
| 2187 |
if gotOne == 0 { |
| 2188 |
t.Fatalf("Warning was still suppressed") |
| 2189 |
} else if gotOne > 1 { |
| 2190 |
t.Fatalf("Should have had only 1 warning for nb1, got %v", gotOne) |
| 2191 |
} else if gotFormat == 0 { |
| 2192 |
t.Fatalf("Warning was still suppressed") |
| 2193 |
} else if gotFormat > 1 { |
| 2194 |
t.Fatalf("Should have had only 1 warning for format, got %v", gotFormat) |
| 2195 |
} else { |
| 2196 |
// OK! we are done |
| 2197 |
return |
| 2198 |
} |
| 2199 |
} |
| 2200 |
} |
| 2201 |
} |
| 2202 |
|
| 2203 |
checkLog(nil, nil) |
| 2204 |
|
| 2205 |
nc1 := natsConnect(t, s.ClientURL(), nats.Name("c1")) |
| 2206 |
defer nc1.Close() |
| 2207 |
nc2 := natsConnect(t, s.ClientURL(), nats.Name("c2")) |
| 2208 |
defer nc2.Close() |
| 2209 |
|
| 2210 |
var c1 *client |
| 2211 |
var c2 *client |
| 2212 |
s.mu.Lock() |
| 2213 |
for _, cli := range s.clients { |
| 2214 |
cli.mu.Lock() |
| 2215 |
switch cli.opts.Name { |
| 2216 |
case "c1": |
| 2217 |
c1 = cli |
| 2218 |
case "c2": |
| 2219 |
c2 = cli |
| 2220 |
} |
| 2221 |
cli.mu.Unlock() |
| 2222 |
if c1 != nil && c2 != nil { |
| 2223 |
break |
| 2224 |
} |
| 2225 |
} |
| 2226 |
s.mu.Unlock() |
| 2227 |
if c1 == nil || c2 == nil { |
| 2228 |
t.Fatal("Did not find the clients") |
| 2229 |
} |
| 2230 |
|
| 2231 |
// Wait for more than the expiration interval |
| 2232 |
time.Sleep(200 * time.Millisecond) |
| 2233 |
|
| 2234 |
c1.RateLimitWarnf("Warning number 1") |
| 2235 |
c1.RateLimitWarnf("Warning number 2") |
| 2236 |
c1.rateLimitFormatWarnf("warning value %d", 1) |
| 2237 |
c2.RateLimitWarnf("Warning number 1") |
| 2238 |
c2.RateLimitWarnf("Warning number 2") |
| 2239 |
c2.rateLimitFormatWarnf("warning value %d", 2) |
| 2240 |
|
| 2241 |
checkLog(c1, c2) |
| 2242 |
} |
| 2243 |
|
| 2244 |
// https://github.com/nats-io/nats-server/discussions/4535 |
| 2245 |
func TestServerAuthBlockAndSysAccounts(t *testing.T) { |
| 2246 |
conf := createConfFile(t, []byte(` |
| 2247 |
listen: 127.0.0.1:-1 |
| 2248 |
server_name: s-test |
| 2249 |
authorization { |
| 2250 |
users = [ { user: "u", password: "pass"} ] |
| 2251 |
} |
| 2252 |
accounts { |
| 2253 |
$SYS: { users: [ { user: admin, password: pwd } ] } |
| 2254 |
} |
| 2255 |
`)) |
| 2256 |
|
| 2257 |
s, _ := RunServerWithConfig(conf) |
| 2258 |
defer s.Shutdown() |
| 2259 |
|
| 2260 |
// This should work of course. |
| 2261 |
nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("u", "pass")) |
| 2262 |
require_NoError(t, err) |
| 2263 |
defer nc.Close() |
| 2264 |
|
| 2265 |
// This should not. |
| 2266 |
_, err = nats.Connect(s.ClientURL()) |
| 2267 |
require_Error(t, err, nats.ErrAuthorization, errors.New("nats: Authorization Violation")) |
| 2268 |
} |
| 2269 |
|
| 2270 |
// https://github.com/nats-io/nats-server/issues/5396 |
| 2271 |
func TestServerConfigLastLineComments(t *testing.T) { |
| 2272 |
conf := createConfFile(t, []byte(` |
| 2273 |
{ |
| 2274 |
"listen": "0.0.0.0:4222" |
| 2275 |
} |
| 2276 |
# wibble |
| 2277 |
`)) |
| 2278 |
|
| 2279 |
s, _ := RunServerWithConfig(conf) |
| 2280 |
defer s.Shutdown() |
| 2281 |
|
| 2282 |
// This should work of course. |
| 2283 |
nc, err := nats.Connect(s.ClientURL()) |
| 2284 |
require_NoError(t, err) |
| 2285 |
defer nc.Close() |
| 2286 |
} |
| 2287 |
|
| 2288 |
func TestServerClusterAndGatewayNameNoSpace(t *testing.T) { |
| 2289 |
conf := createConfFile(t, []byte(` |
| 2290 |
port: -1 |
| 2291 |
server_name: "my server" |
| 2292 |
`)) |
| 2293 |
_, err := ProcessConfigFile(conf) |
| 2294 |
require_Error(t, err, ErrServerNameHasSpaces) |
| 2295 |
|
| 2296 |
o := DefaultOptions() |
| 2297 |
o.ServerName = "my server" |
| 2298 |
_, err = NewServer(o) |
| 2299 |
require_Error(t, err, ErrServerNameHasSpaces) |
| 2300 |
|
| 2301 |
conf = createConfFile(t, []byte(` |
| 2302 |
port: -1 |
| 2303 |
server_name: "myserver" |
| 2304 |
cluster { |
| 2305 |
port: -1 |
| 2306 |
name: "my cluster" |
| 2307 |
} |
| 2308 |
`)) |
| 2309 |
_, err = ProcessConfigFile(conf) |
| 2310 |
require_Error(t, err, ErrClusterNameHasSpaces) |
| 2311 |
|
| 2312 |
o = DefaultOptions() |
| 2313 |
o.Cluster.Name = "my cluster" |
| 2314 |
o.Cluster.Port = -1 |
| 2315 |
_, err = NewServer(o) |
| 2316 |
require_Error(t, err, ErrClusterNameHasSpaces) |
| 2317 |
|
| 2318 |
conf = createConfFile(t, []byte(` |
| 2319 |
port: -1 |
| 2320 |
server_name: "myserver" |
| 2321 |
gateway { |
| 2322 |
port: -1 |
| 2323 |
name: "my gateway" |
| 2324 |
} |
| 2325 |
`)) |
| 2326 |
_, err = ProcessConfigFile(conf) |
| 2327 |
require_Error(t, err, ErrGatewayNameHasSpaces) |
| 2328 |
|
| 2329 |
o = DefaultOptions() |
| 2330 |
o.Cluster.Name = _EMPTY_ |
| 2331 |
o.Cluster.Port = 0 |
| 2332 |
o.Gateway.Name = "my gateway" |
| 2333 |
o.Gateway.Port = -1 |
| 2334 |
_, err = NewServer(o) |
| 2335 |
require_Error(t, err, ErrGatewayNameHasSpaces) |
| 2336 |
} |
| 2337 |
|
| 2338 |
func TestServerClientURL(t *testing.T) { |
| 2339 |
for host, expected := range map[string]string{ |
| 2340 |
"host.com": "nats://host.com:12345", |
| 2341 |
"1.2.3.4": "nats://1.2.3.4:12345", |
| 2342 |
"2000::1": "nats://[2000::1]:12345", |
| 2343 |
} { |
| 2344 |
o := DefaultOptions() |
| 2345 |
o.Host = host |
| 2346 |
o.Port = 12345 |
| 2347 |
s, err := NewServer(o) |
| 2348 |
require_NoError(t, err) |
| 2349 |
require_Equal(t, s.ClientURL(), expected) |
| 2350 |
} |
| 2351 |
} |
| 2352 |
|
| 2353 |
// This is a test that guards against using goccy/go-json. |
| 2354 |
// At least until it's fully compatible with std encoding/json, and we've thoroughly tested it. |
| 2355 |
// This is just one bug (at the time of writing) that results in a panic. |
| 2356 |
// https://github.com/goccy/go-json/issues/519 |
| 2357 |
func TestServerJsonMarshalNestedStructsPanic(t *testing.T) { |
| 2358 |
type Item struct { |
| 2359 |
A string `json:"a"` |
| 2360 |
B string `json:"b,omitempty"` |
| 2361 |
} |
| 2362 |
|
| 2363 |
type Detail struct { |
| 2364 |
I Item `json:"i"` |
| 2365 |
} |
| 2366 |
|
| 2367 |
type Body struct { |
| 2368 |
Payload *Detail `json:"p,omitempty"` |
| 2369 |
} |
| 2370 |
|
| 2371 |
b, err := json.Marshal(Body{Payload: &Detail{I: Item{A: "a", B: "b"}}}) |
| 2372 |
require_NoError(t, err) |
| 2373 |
require_Equal(t, string(b), "{\"p\":{\"i\":{\"a\":\"a\",\"b\":\"b\"}}}") |
| 2374 |
} |
| 2375 |
|
| 2376 |
func TestBuildinfoFormatRevision(t *testing.T) { |
| 2377 |
tests := []struct { |
| 2378 |
name string |
| 2379 |
revision string |
| 2380 |
expected string |
| 2381 |
}{ |
| 2382 |
{ |
| 2383 |
name: "Git-like longer version", |
| 2384 |
revision: "abc123def456789", |
| 2385 |
expected: "abc123d", |
| 2386 |
}, |
| 2387 |
{ |
| 2388 |
name: "Git-like exactly 7 chars", |
| 2389 |
revision: "abc123d", |
| 2390 |
expected: "abc123d", |
| 2391 |
}, |
| 2392 |
{ |
| 2393 |
name: "SVN shorter revision", |
| 2394 |
revision: "1234", |
| 2395 |
expected: "1234", |
| 2396 |
}, |
| 2397 |
{ |
| 2398 |
name: "SVN single digit", |
| 2399 |
revision: "5", |
| 2400 |
expected: "5", |
| 2401 |
}, |
| 2402 |
{ |
| 2403 |
name: "Empty revision", |
| 2404 |
revision: "", |
| 2405 |
expected: "", |
| 2406 |
}, |
| 2407 |
{ |
| 2408 |
name: "6 character revision", |
| 2409 |
revision: "abc123", |
| 2410 |
expected: "abc123", |
| 2411 |
}, |
| 2412 |
} |
| 2413 |
|
| 2414 |
for _, tt := range tests { |
| 2415 |
t.Run(tt.name, func(t *testing.T) { |
| 2416 |
result := formatRevision(tt.revision) |
| 2417 |
if result != tt.expected { |
| 2418 |
t.Errorf("formatRevision(%q) = %q, expected %q", tt.revision, result, tt.expected) |
| 2419 |
} |
| 2420 |
}) |
| 2421 |
} |
| 2422 |
} |