Debian Codegraph @

server/jetstream.go

raw
1 // Copyright 2019-2026 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 "bytes"
18 "crypto/hmac"
19 "crypto/sha256"
20 "encoding/binary"
21 "encoding/hex"
22 "encoding/json"
23 "fmt"
24 "math"
25 "os"
26 "path/filepath"
27 "runtime/debug"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "time"
32
33 "github.com/minio/highwayhash"
34 "github.com/nats-io/nats-server/v2/server/gsl"
35 "github.com/nats-io/nats-server/v2/server/sysmem"
36 "github.com/nats-io/nats-server/v2/server/tpm"
37 "github.com/nats-io/nkeys"
38 "github.com/nats-io/nuid"
39 )
40
41 // JetStreamConfig determines this server's configuration.
42 // MaxMemory and MaxStore are in bytes.
43 type JetStreamConfig struct {
44 MaxMemory int64 `json:"max_memory"` // MaxMemory is the maximum size of memory type streams
45 MaxStore int64 `json:"max_storage"` // MaxStore is the maximum size of file store type streams
46 StoreDir string `json:"store_dir,omitempty"` // StoreDir is where storage files are stored
47 SyncInterval time.Duration `json:"sync_interval,omitempty"` // SyncInterval is how frequently we sync to disk in the background by calling fsync
48 SyncAlways bool `json:"sync_always,omitempty"` // SyncAlways indicates flushes are done after every write
49 Domain string `json:"domain,omitempty"` // Domain is the JetStream domain
50 CompressOK bool `json:"compress_ok,omitempty"` // CompressOK indicates if compression is supported
51 UniqueTag string `json:"unique_tag,omitempty"` // UniqueTag is the unique tag assigned to this instance
52 Strict bool `json:"strict,omitempty"` // Strict indicates if strict JSON parsing is performed
53
54 // maxStorePending is set when MaxStore was derived from the available disk
55 // space rather than configured, and has not been adjusted yet for the space
56 // that recovered streams already occupy. See finalizeDynamicMaxStore.
57 maxStorePending bool
58 }
59
60 // Statistics about JetStream for this server.
61 type JetStreamStats struct {
62 Memory uint64 `json:"memory"`
63 Store uint64 `json:"storage"`
64 ReservedMemory uint64 `json:"reserved_memory"`
65 ReservedStore uint64 `json:"reserved_storage"`
66 Accounts int `json:"accounts"`
67 HAAssets int `json:"ha_assets"`
68 API JetStreamAPIStats `json:"api"`
69 }
70
71 type JetStreamAccountLimits struct {
72 MaxMemory int64 `json:"max_memory"`
73 MaxStore int64 `json:"max_storage"`
74 MaxStreams int `json:"max_streams"`
75 MaxConsumers int `json:"max_consumers"`
76 MaxAckPending int `json:"max_ack_pending"`
77 MemoryMaxStreamBytes int64 `json:"memory_max_stream_bytes"`
78 StoreMaxStreamBytes int64 `json:"storage_max_stream_bytes"`
79 MaxBytesRequired bool `json:"max_bytes_required"`
80 }
81
82 type JetStreamTier struct {
83 Memory uint64 `json:"memory"`
84 Store uint64 `json:"storage"`
85 ReservedMemory uint64 `json:"reserved_memory"`
86 ReservedStore uint64 `json:"reserved_storage"`
87 Streams int `json:"streams"`
88 Consumers int `json:"consumers"`
89 Limits JetStreamAccountLimits `json:"limits"`
90 }
91
92 // JetStreamAccountStats returns current statistics about the account's JetStream usage.
93 type JetStreamAccountStats struct {
94 JetStreamTier // in case tiers are used, reflects totals with limits not set
95 Domain string `json:"domain,omitempty"`
96 API JetStreamAPIStats `json:"api"`
97 Tiers map[string]JetStreamTier `json:"tiers,omitempty"` // indexed by tier name
98 }
99
100 // JetStreamAPIStats holds stats about the API usage for this server
101 type JetStreamAPIStats struct {
102 Level int `json:"level"` // Level is the active API level this server implements
103 Total uint64 `json:"total"` // Total is the total API requests received since start
104 Errors uint64 `json:"errors"` // Errors is the total API requests that resulted in error responses
105 Inflight uint64 `json:"inflight,omitempty"` // Inflight are the number of API requests currently being served
106 }
107
108 // This is for internal accounting for JetStream for this server.
109 type jetStream struct {
110 // These are here first because of atomics on 32bit systems.
111 apiInflight int64
112 apiTotal int64
113 apiErrors int64
114 memMax int64
115 memReserved int64 // Requires JS lock to be held.
116 memUsed int64
117 storeMax int64
118 storeReserved int64 // Requires JS lock to be held.
119 storeUsed int64
120 queueLimit int64
121 infoQueueLimit int64
122 clustered int32
123 mu sync.RWMutex
124 srv *Server
125 config JetStreamConfig
126 cluster *jetStreamCluster
127 accounts map[string]*jsAccount
128 apiSubs *Sublist
129 infoSubs *gsl.SimpleSublist // Subjects for info-specific queue.
130 started time.Time
131
132 // System level request to purge a stream move
133 accountPurge *subscription
134
135 // Some bools regarding general state.
136 metaRecovering bool
137 standAlone bool
138 oos bool
139 shuttingDown bool
140
141 // Atomic versions
142 disabled atomic.Bool
143 }
144
145 type remoteUsage struct {
146 tiers map[string]*jsaUsage // indexed by tier name
147 api uint64
148 err uint64
149 }
150
151 type jsaStorage struct {
152 total jsaUsage
153 local jsaUsage
154 }
155
156 // This represents a jetstream enabled account.
157 // Worth noting that we include the jetstream pointer, this is because
158 // in general we want to be very efficient when receiving messages on
159 // an internal sub for a stream, so we will direct link to the stream
160 // and walk backwards as needed vs multiple hash lookups and locks, etc.
161 type jsAccount struct {
162 mu sync.RWMutex
163 js *jetStream
164 account *Account
165 storeDir string
166 inflight sync.Map
167 streams map[string]*stream
168
169 // From server
170 sendq *ipQueue[*pubMsg]
171
172 // For limiting only running one checkAndSync at a time.
173 sync atomic.Bool
174
175 // Usage/limits related fields that will be protected by usageMu
176 usageMu sync.RWMutex
177 limits map[string]JetStreamAccountLimits // indexed by tierName
178 usage map[string]*jsaStorage // indexed by tierName
179 rusage map[string]*remoteUsage // indexed by node id
180 apiTotal uint64
181 apiErrors uint64
182 usageApi uint64
183 usageErr uint64
184 updatesPub string
185 updatesSub *subscription
186 lupdate time.Time
187 utimer *time.Timer
188 }
189
190 // Track general usage for this account.
191 type jsaUsage struct {
192 mem int64
193 store int64
194 }
195
196 // EnableJetStream will enable JetStream support on this server with the given configuration.
197 // A nil configuration will dynamically choose the limits and temporary file storage directory.
198 func (s *Server) EnableJetStream(config *JetStreamConfig) error {
199 if s.JetStreamEnabled() {
200 return fmt.Errorf("jetstream already enabled")
201 }
202
203 s.Noticef("Starting JetStream")
204 start := time.Now()
205 defer func() {
206 s.Noticef("Took %s to start JetStream", time.Since(start))
207 }()
208
209 if config == nil || config.MaxMemory <= 0 || config.MaxStore <= 0 {
210 var storeDir, domain, uniqueTag string
211 var maxStore, maxMem int64
212 if config != nil {
213 storeDir, domain, uniqueTag = config.StoreDir, config.Domain, config.UniqueTag
214 maxStore, maxMem = config.MaxStore, config.MaxMemory
215 }
216 config = s.dynJetStreamConfig(storeDir, maxStore, maxMem)
217 if domain != _EMPTY_ {
218 config.Domain = domain
219 }
220 if uniqueTag != _EMPTY_ {
221 config.UniqueTag = uniqueTag
222 }
223 s.Debugf("JetStream creating dynamic configuration - %s memory, %s disk", friendlyBytes(config.MaxMemory), friendlyBytes(config.MaxStore))
224 } else if config.StoreDir != _EMPTY_ {
225 config.StoreDir = filepath.Join(config.StoreDir, JetStreamStoreDir)
226 }
227
228 cfg := *config
229 if cfg.StoreDir == _EMPTY_ {
230 cfg.StoreDir = filepath.Join(os.TempDir(), JetStreamStoreDir)
231 s.Warnf("Temporary storage directory used, data could be lost on system reboot")
232 }
233
234 // We will consistently place the 'jetstream' directory under the storedir that was handed to us. Prior to 2.2.3 though
235 // we could have a directory on disk without the 'jetstream' directory. This will check and fix if needed.
236 if err := s.checkStoreDir(&cfg); err != nil {
237 return err
238 }
239
240 return s.enableJetStream(cfg)
241 }
242
243 // Function signature to generate a key encryption key.
244 type keyGen func(context []byte) ([]byte, error)
245
246 // Return a key generation function or nil if encryption not enabled.
247 func (s *Server) jsKeyGen(jsKey, info string) keyGen {
248 if ek := jsKey; ek != _EMPTY_ {
249 return func(context []byte) ([]byte, error) {
250 h := hmac.New(sha256.New, []byte(ek))
251 if _, err := h.Write([]byte(info)); err != nil {
252 return nil, err
253 }
254 if _, err := h.Write(context); err != nil {
255 return nil, err
256 }
257 return h.Sum(nil), nil
258 }
259 }
260 return nil
261 }
262
263 // Decode the encrypted metafile.
264 func (s *Server) decryptMeta(sc StoreCipher, ekey, buf []byte, acc, context string) ([]byte, bool, error) {
265 if len(ekey) < minMetaKeySize {
266 return nil, false, errBadKeySize
267 }
268 var osc StoreCipher
269 switch sc {
270 case AES:
271 osc = ChaCha
272 case ChaCha:
273 osc = AES
274 }
275 type prfWithCipher struct {
276 keyGen
277 StoreCipher
278 }
279 var prfs []prfWithCipher
280 if prf := s.jsKeyGen(s.getOpts().JetStreamKey, acc); prf == nil {
281 return nil, false, errNoEncryption
282 } else {
283 // First of all, try our current encryption keys with both
284 // store cipher algorithms.
285 prfs = append(prfs, prfWithCipher{prf, sc})
286 prfs = append(prfs, prfWithCipher{prf, osc})
287 }
288 if prf := s.jsKeyGen(s.getOpts().JetStreamOldKey, acc); prf != nil {
289 // Then, if we have an old encryption key, try with also with
290 // both store cipher algorithms.
291 prfs = append(prfs, prfWithCipher{prf, sc})
292 prfs = append(prfs, prfWithCipher{prf, osc})
293 }
294
295 for i, prf := range prfs {
296 rb, err := prf.keyGen([]byte(context))
297 if err != nil {
298 continue
299 }
300 kek, err := genEncryptionKey(prf.StoreCipher, rb)
301 if err != nil {
302 continue
303 }
304 ns := kek.NonceSize()
305 seed, err := kek.Open(nil, ekey[:ns], ekey[ns:], nil)
306 if err != nil {
307 continue
308 }
309 aek, err := genEncryptionKey(prf.StoreCipher, seed)
310 if err != nil {
311 continue
312 }
313 if aek.NonceSize() != kek.NonceSize() {
314 continue
315 }
316 plain, err := aek.Open(nil, buf[:ns], buf[ns:], nil)
317 if err != nil {
318 continue
319 }
320 return plain, i > 0, nil
321 }
322 return nil, false, fmt.Errorf("unable to recover keys")
323 }
324
325 // Check to make sure directory has the jetstream directory.
326 // We will have it properly configured here now regardless, so need to look inside.
327 func (s *Server) checkStoreDir(cfg *JetStreamConfig) error {
328 fis, _ := os.ReadDir(cfg.StoreDir)
329 // If we have nothing underneath us, could be just starting new, but if we see this we can check.
330 if len(fis) != 0 {
331 return nil
332 }
333 // Let's check the directory above. If it has us 'jetstream' but also other stuff that we can
334 // identify as accounts then we can fix.
335 fis, _ = os.ReadDir(filepath.Dir(cfg.StoreDir))
336 // If just one that is us 'jetstream' and all is ok.
337 if len(fis) == 1 {
338 return nil
339 }
340
341 haveJetstreamDir := false
342 for _, fi := range fis {
343 if fi.Name() == JetStreamStoreDir {
344 haveJetstreamDir = true
345 break
346 }
347 }
348
349 for _, fi := range fis {
350 // Skip the 'jetstream' directory.
351 if fi.Name() == JetStreamStoreDir {
352 continue
353 }
354 // Let's see if this is an account.
355 if accName := fi.Name(); accName != _EMPTY_ {
356 _, ok := s.accounts.Load(accName)
357 if !ok && s.AccountResolver() != nil && nkeys.IsValidPublicAccountKey(accName) {
358 // Account is not local but matches the NKEY account public key,
359 // this is enough indication to move this directory, no need to
360 // fetch the account.
361 ok = true
362 }
363 // If this seems to be an account go ahead and move the directory. This will include all assets
364 // like streams and consumers.
365 if ok {
366 if !haveJetstreamDir {
367 err := os.Mkdir(filepath.Join(filepath.Dir(cfg.StoreDir), JetStreamStoreDir), defaultDirPerms)
368 if err != nil {
369 return err
370 }
371 haveJetstreamDir = true
372 }
373 old := filepath.Join(filepath.Dir(cfg.StoreDir), fi.Name())
374 new := filepath.Join(cfg.StoreDir, fi.Name())
375 s.Noticef("JetStream relocated account %q to %q", old, new)
376 if err := os.Rename(old, new); err != nil {
377 return err
378 }
379 }
380 }
381 }
382
383 return nil
384 }
385
386 // This function sets/updates the jetstream encryption key and cipher based
387 // on options. If the TPM options have been specified, a key is generated
388 // and sealed by the TPM.
389 func (s *Server) initJetStreamEncryption() (err error) {
390 opts := s.getOpts()
391
392 // The TPM settings and other encryption settings are mutually exclusive.
393 if opts.JetStreamKey != _EMPTY_ && opts.JetStreamTpm.KeysFile != _EMPTY_ {
394 return fmt.Errorf("JetStream encryption key may not be used with TPM options")
395 }
396 // if we are using the standard method to set the encryption key just return and carry on.
397 if opts.JetStreamKey != _EMPTY_ {
398 return nil
399 }
400 // if the tpm options are not used then no encryption has been configured and return.
401 if opts.JetStreamTpm.KeysFile == _EMPTY_ {
402 return nil
403 }
404
405 if opts.JetStreamTpm.Pcr == 0 {
406 // Default PCR to use in the TPM. Values can be 0-23, and most platforms
407 // reserve values 0-12 for the OS, boot locker, disc encryption, etc.
408 // 16 used for debugging. In sticking to NATS tradition, we'll use 22
409 // as the default with the option being configurable.
410 opts.JetStreamTpm.Pcr = 22
411 }
412
413 // Using the TPM to generate or get the encryption key and update the encryption options.
414 opts.JetStreamKey, err = tpm.LoadJetStreamEncryptionKeyFromTPM(opts.JetStreamTpm.SrkPassword,
415 opts.JetStreamTpm.KeysFile, opts.JetStreamTpm.KeyPassword, opts.JetStreamTpm.Pcr)
416
417 return err
418 }
419
420 // enableJetStream will start up the JetStream subsystem.
421 func (s *Server) enableJetStream(cfg JetStreamConfig) error {
422 js := &jetStream{srv: s, config: cfg, accounts: make(map[string]*jsAccount), apiSubs: NewSublistNoCache(), infoSubs: gsl.NewSimpleSublist()}
423 s.gcbMu.Lock()
424 if s.gcbOutMax = s.getOpts().JetStreamMaxCatchup; s.gcbOutMax == 0 {
425 s.gcbOutMax = defaultMaxTotalCatchupOutBytes
426 }
427 s.gcbMu.Unlock()
428
429 atomic.StoreInt64(&js.memMax, cfg.MaxMemory)
430 atomic.StoreInt64(&js.storeMax, cfg.MaxStore)
431
432 // TODO: Not currently reloadable.
433 atomic.StoreInt64(&js.queueLimit, s.getOpts().JetStreamRequestQueueLimit)
434 atomic.StoreInt64(&js.infoQueueLimit, s.getOpts().JetStreamInfoQueueLimit)
435
436 s.js.Store(js)
437
438 // FIXME(dlc) - Allow memory only operation?
439 if stat, err := os.Stat(cfg.StoreDir); os.IsNotExist(err) {
440 if err := os.MkdirAll(cfg.StoreDir, defaultDirPerms); err != nil {
441 return fmt.Errorf("could not create storage directory - %v", err)
442 }
443 } else {
444 // Make sure its a directory and that we can write to it.
445 if stat == nil || !stat.IsDir() {
446 return fmt.Errorf("storage directory is not a directory")
447 }
448 tmpfile, err := os.CreateTemp(cfg.StoreDir, "_test_")
449 if err != nil {
450 return fmt.Errorf("storage directory is not writable")
451 }
452 tmpfile.Close()
453 os.Remove(tmpfile.Name())
454 }
455
456 if err := s.initJetStreamEncryption(); err != nil {
457 return err
458 }
459
460 // JetStream is an internal service so we need to make sure we have a system account.
461 // This system account will export the JetStream service endpoints.
462 if s.SystemAccount() == nil {
463 s.SetDefaultSystemAccount()
464 }
465
466 opts := s.getOpts()
467 if !opts.DisableJetStreamBanner {
468 s.Noticef(" _ ___ _____ ___ _____ ___ ___ _ __ __")
469 s.Noticef(" _ | | __|_ _/ __|_ _| _ \\ __| /_\\ | \\/ |")
470 s.Noticef("| || | _| | | \\__ \\ | | | / _| / _ \\| |\\/| |")
471 s.Noticef(" \\__/|___| |_| |___/ |_| |_|_\\___/_/ \\_\\_| |_|")
472 s.Noticef("")
473 s.Noticef(" https://docs.nats.io/jetstream")
474 s.Noticef("")
475 }
476 s.Noticef("---------------- JETSTREAM ----------------")
477
478 if cfg.Strict {
479 s.Noticef(" Strict: %t", cfg.Strict)
480 }
481
482 s.Noticef(" Max Memory: %s", friendlyBytes(cfg.MaxMemory))
483 s.Noticef(" Max Storage: %s", friendlyBytes(cfg.MaxStore))
484 s.Noticef(" Store Directory: \"%s\"", cfg.StoreDir)
485 if cfg.Domain != _EMPTY_ {
486 s.Noticef(" Domain: %s", cfg.Domain)
487 }
488
489 if ek := opts.JetStreamKey; ek != _EMPTY_ {
490 s.Noticef(" Encryption: %s", opts.JetStreamCipher)
491 }
492 if opts.JetStreamTpm.KeysFile != _EMPTY_ {
493 s.Noticef(" TPM File: %q, Pcr: %d", opts.JetStreamTpm.KeysFile,
494 opts.JetStreamTpm.Pcr)
495 }
496 s.Noticef(" API Level: %d", JSApiLevel)
497 s.Noticef("-------------------------------------------")
498
499 // Setup our internal subscriptions.
500 if err := s.setJetStreamExportSubs(); err != nil {
501 return fmt.Errorf("setting up internal jetstream subscriptions failed: %v", err)
502 }
503
504 // Setup our internal system exports.
505 s.Debugf(" Exports:")
506 s.Debugf(" %s", jsAllAPI)
507 s.setupJetStreamExports()
508
509 standAlone, canExtend := s.standAloneMode(), s.canExtendOtherDomain()
510 if standAlone && canExtend && s.getOpts().JetStreamExtHint != jsWillExtend {
511 canExtend = false
512 s.Noticef("Standalone server started in clustered mode do not support extending domains")
513 s.Noticef(`Manually disable standalone mode by setting the JetStream Option "extension_hint: %s"`, jsWillExtend)
514 }
515
516 // Indicate if we will be standalone for checking resource reservations, etc.
517 js.setJetStreamStandAlone(standAlone && !canExtend)
518
519 // Enable accounts and restore state before starting clustering.
520 if err := s.enableJetStreamAccounts(); err != nil {
521 return err
522 }
523
524 // All file based streams have been recovered, so we now know how much of
525 // the disk we already occupy and can settle on a dynamic limit.
526 js.finalizeDynamicMaxStore()
527
528 // If we are in clustered mode go ahead and start the meta controller.
529 if !standAlone || canExtend {
530 if err := s.enableJetStreamClustering(); err != nil {
531 return err
532 }
533 // Set our atomic bool to clustered.
534 s.jsClustered.Store(true)
535 }
536
537 // Mark when we are up and running.
538 js.setStarted()
539
540 return nil
541 }
542
543 // finalizeDynamicMaxStore settles a dynamic max store limit once all file based
544 // streams have been recovered. diskAvailable only reports free space, so add back
545 // what we occupy ourselves to keep the limit stable across restarts.
546 func (js *jetStream) finalizeDynamicMaxStore() {
547 js.mu.Lock()
548 if !js.config.maxStorePending {
549 js.mu.Unlock()
550 return
551 }
552 // From here on the limit is real and can be enforced, see sufficientResources.
553 js.config.maxStorePending = false
554 recovered := atomic.LoadInt64(&js.storeUsed)
555 if recovered <= 0 {
556 js.mu.Unlock()
557 return
558 }
559 // diskAvailable is already scaled down to 75% of what is free, so scale the
560 // recovered bytes the same way before adding them back.
561 maxStore := addSaturate(js.config.MaxStore, recovered/4*3)
562 js.config.MaxStore = maxStore
563 atomic.StoreInt64(&js.storeMax, maxStore)
564 js.mu.Unlock()
565 }
566
567 const jsNoExtend = "no_extend"
568 const jsWillExtend = "will_extend"
569
570 // This will check if we have a solicited leafnode that shares the system account
571 // and extension is not manually disabled
572 func (s *Server) canExtendOtherDomain() bool {
573 opts := s.getOpts()
574 sysAcc := s.SystemAccount().GetName()
575 for _, r := range opts.LeafNode.Remotes {
576 if r.LocalAccount == sysAcc {
577 for _, denySub := range r.DenyImports {
578 if subjectIsSubsetMatch(denySub, raftAllSubj) {
579 return false
580 }
581 }
582 return true
583 }
584 }
585 return false
586 }
587
588 func (s *Server) updateJetStreamInfoStatus(enabled bool) {
589 s.mu.Lock()
590 s.info.JetStream = enabled
591 s.mu.Unlock()
592 }
593
594 // restartJetStream will try to re-enable JetStream during a reload if it had been disabled during runtime.
595 func (s *Server) restartJetStream() error {
596 opts := s.getOpts()
597 cfg := JetStreamConfig{
598 StoreDir: opts.StoreDir,
599 SyncInterval: opts.SyncInterval,
600 SyncAlways: opts.SyncAlways,
601 MaxMemory: opts.JetStreamMaxMemory,
602 MaxStore: opts.JetStreamMaxStore,
603 Domain: opts.JetStreamDomain,
604 Strict: !opts.NoJetStreamStrict,
605 }
606 s.Noticef("Restarting JetStream")
607 err := s.EnableJetStream(&cfg)
608 if err != nil {
609 s.Warnf("Can't start JetStream: %v", err)
610 return s.ShutdownJetStream()
611 }
612 s.updateJetStreamInfoStatus(true)
613 return nil
614 }
615
616 // checkJetStreamExports will check if we have the JS exports setup
617 // on the system account, and if not go ahead and set them up.
618 func (s *Server) checkJetStreamExports() {
619 if sacc := s.SystemAccount(); sacc != nil {
620 sacc.mu.RLock()
621 se := sacc.getServiceExport(jsAllAPI)
622 sacc.mu.RUnlock()
623 if se == nil {
624 s.setupJetStreamExports()
625 }
626 }
627 }
628
629 func (s *Server) setupJetStreamExports() {
630 // Setup our internal system export.
631 if err := s.SystemAccount().AddServiceExport(jsAllAPI, nil); err != nil {
632 s.Warnf("Error setting up jetstream service exports: %v", err)
633 }
634 }
635
636 func (s *Server) jetStreamOOSPending() (wasPending bool) {
637 if js := s.getJetStream(); js != nil {
638 js.mu.Lock()
639 wasPending = js.oos
640 js.oos = true
641 js.mu.Unlock()
642 }
643 return wasPending
644 }
645
646 func (s *Server) setJetStreamDisabled() {
647 if js := s.getJetStream(); js != nil {
648 js.disabled.Store(true)
649 }
650 }
651
652 func (s *Server) handleOutOfSpace(mset *stream) {
653 if s.JetStreamEnabled() && !s.jetStreamOOSPending() {
654 var stream string
655 if mset != nil {
656 stream = mset.name()
657 s.Errorf("JetStream out of %s resources, will be DISABLED", mset.Store().Type())
658 } else {
659 s.Errorf("JetStream out of resources, will be DISABLED")
660 }
661
662 go s.ShutdownJetStream()
663
664 adv := &JSServerOutOfSpaceAdvisory{
665 TypedEvent: TypedEvent{
666 Type: JSServerOutOfStorageAdvisoryType,
667 ID: nuid.Next(),
668 Time: time.Now().UTC(),
669 },
670 Server: s.Name(),
671 ServerID: s.ID(),
672 Stream: stream,
673 Cluster: s.cachedClusterName(),
674 Domain: s.getOpts().JetStreamDomain,
675 }
676 s.publishAdvisory(nil, JSAdvisoryServerOutOfStorage, adv)
677 }
678 }
679
680 // DisableJetStream will turn off JetStream and signals in clustered mode
681 // to have the metacontroller remove us from the peer list. Persistent
682 // meta-raft state on disk is removed. For transient runtime errors where
683 // the server should rejoin its existing meta group on restart, use
684 // ShutdownJetStream instead.
685 func (s *Server) DisableJetStream() error {
686 return s.disableJetStream(true)
687 }
688
689 // ShutdownJetStream is like DisableJetStream but preserves persistent
690 // meta-raft state on disk so the server can rejoin the existing meta
691 // group on restart. Use for transient runtime errors that the operator
692 // is expected to fix before restarting.
693 func (s *Server) ShutdownJetStream() error {
694 return s.disableJetStream(false)
695 }
696
697 func (s *Server) disableJetStream(deleteState bool) error {
698 if !s.JetStreamEnabled() {
699 return nil
700 }
701
702 s.setJetStreamDisabled()
703
704 if s.JetStreamIsClustered() {
705 isLeader := s.JetStreamIsLeader()
706 js, cc := s.getJetStreamCluster()
707 if js == nil {
708 s.shutdownJetStream()
709 return nil
710 }
711 js.mu.RLock()
712 meta := cc.meta
713 js.mu.RUnlock()
714
715 if meta != nil {
716 if isLeader {
717 s.Warnf("JetStream initiating meta leader transfer")
718 meta.StepDown()
719 select {
720 case <-s.quitCh:
721 return nil
722 case <-time.After(2 * time.Second):
723 }
724 if !s.JetStreamIsCurrent() {
725 s.Warnf("JetStream timeout waiting for meta leader transfer")
726 }
727 }
728 if deleteState {
729 meta.Delete()
730 } else {
731 meta.Stop()
732 meta.WaitForStop()
733 }
734 }
735 }
736
737 // Update our info status.
738 s.updateJetStreamInfoStatus(false)
739
740 // Normal shutdown.
741 s.shutdownJetStream()
742
743 // Shut down the RAFT groups.
744 s.shutdownRaftNodes()
745
746 return nil
747 }
748
749 func (s *Server) enableJetStreamAccounts() error {
750 // Reuse the same task workers across all accounts, so that we don't explode
751 // with a large number of goroutines on multi-account systems.
752 tq := parallelTaskQueue(min(64, s.diskIOSemaphore().cap()))
753 defer close(tq)
754
755 // If we have no configured accounts setup then setup imports on global account.
756 if s.globalAccountOnly() {
757 gacc := s.GlobalAccount()
758 gacc.mu.Lock()
759 if len(gacc.jsLimits) == 0 {
760 gacc.jsLimits = defaultJSAccountTiers
761 }
762 gacc.mu.Unlock()
763 if err := s.configJetStream(gacc, tq); err != nil {
764 return err
765 }
766 } else if err := s.configAllJetStreamAccounts(tq); err != nil {
767 return fmt.Errorf("Error enabling jetstream on configured accounts: %v", err)
768 }
769 return nil
770 }
771
772 // enableAllJetStreamServiceImportsAndMappings turns on all service imports and mappings for jetstream for this account.
773 func (a *Account) enableAllJetStreamServiceImportsAndMappings() error {
774 a.mu.RLock()
775 s := a.srv
776 a.mu.RUnlock()
777
778 if s == nil {
779 return fmt.Errorf("jetstream account not registered")
780 }
781
782 var dstAccName string
783 if sacc := s.SystemAccount(); sacc != nil {
784 dstAccName = sacc.Name
785 }
786
787 if !a.serviceImportExists(dstAccName, jsAllAPI) {
788 // Capture si so we can turn on implicit sharing with JetStream layer.
789 // Make sure to set "to" otherwise will incur performance slow down.
790 si, err := a.addServiceImport(s.SystemAccount(), jsAllAPI, jsAllAPI, nil)
791 if err != nil {
792 return fmt.Errorf("Error setting up jetstream service imports for account: %v", err)
793 }
794 a.mu.Lock()
795 si.share = true
796 a.mu.Unlock()
797 }
798
799 // Check if we have a Domain specified.
800 // If so add in a subject mapping that will allow local connected clients to reach us here as well.
801 if opts := s.getOpts(); opts.JetStreamDomain != _EMPTY_ {
802 mappings := generateJSMappingTable(opts.JetStreamDomain)
803 a.mu.RLock()
804 for _, m := range a.mappings {
805 delete(mappings, m.src)
806 }
807 a.mu.RUnlock()
808 for src, dest := range mappings {
809 if err := a.AddMapping(src, dest); err != nil {
810 s.Errorf("Error adding JetStream domain mapping: %v", err)
811 }
812 }
813 }
814
815 return nil
816 }
817
818 // enableJetStreamInfoServiceImportOnly will enable the single service import responder.
819 // Should we do them all regardless?
820 func (a *Account) enableJetStreamInfoServiceImportOnly() error {
821 // Check if this import would be overshadowed. This can happen when accounts
822 // are importing from another account for JS access.
823 if a.serviceImportShadowed(JSApiAccountInfo) {
824 return nil
825 }
826
827 return a.enableAllJetStreamServiceImportsAndMappings()
828 }
829
830 func (s *Server) configJetStream(acc *Account, tq chan<- func()) error {
831 if acc == nil {
832 return nil
833 }
834 acc.mu.RLock()
835 jsLimits := acc.jsLimits
836 acc.mu.RUnlock()
837 if jsLimits != nil {
838 // Check if already enabled. This can be during a reload.
839 if acc.JetStreamEnabled() {
840 if err := acc.enableAllJetStreamServiceImportsAndMappings(); err != nil {
841 return err
842 }
843 if err := acc.UpdateJetStreamLimits(jsLimits); err != nil {
844 return err
845 }
846 } else {
847 if err := acc.EnableJetStream(jsLimits, tq); err != nil {
848 return err
849 }
850 if s.gateway.enabled {
851 s.switchAccountToInterestMode(acc.GetName())
852 }
853 }
854 } else if acc != s.SystemAccount() {
855 if acc.JetStreamEnabled() {
856 acc.DisableJetStream()
857 }
858 // We will setup basic service imports to respond to
859 // requests if JS is enabled for this account.
860 if err := acc.enableJetStreamInfoServiceImportOnly(); err != nil {
861 return err
862 }
863 }
864 return nil
865 }
866
867 // configAllJetStreamAccounts walk all configured accounts and turn on jetstream if requested.
868 func (s *Server) configAllJetStreamAccounts(tq chan<- func()) error {
869 // Check to see if system account has been enabled. We could arrive here via reload and
870 // a non-default system account.
871 s.checkJetStreamExports()
872
873 // Bail if server not enabled. If it was enabled and a reload turns it off
874 // that will be handled elsewhere.
875 js := s.getJetStream()
876 if js == nil {
877 return nil
878 }
879
880 // Snapshot into our own list. Might not be needed.
881 s.mu.RLock()
882 if s.sys != nil {
883 // clustered stream removal will perform this cleanup as well
884 // this is mainly for initial cleanup
885 saccName := s.sys.account.Name
886 accStoreDirs, _ := os.ReadDir(js.config.StoreDir)
887 for _, acc := range accStoreDirs {
888 if accName := acc.Name(); accName != saccName {
889 // no op if not empty
890 accDir := filepath.Join(js.config.StoreDir, accName)
891 os.Remove(filepath.Join(accDir, streamsDir))
892 os.Remove(accDir)
893 }
894 }
895 }
896
897 var jsAccounts []*Account
898 s.accounts.Range(func(k, v any) bool {
899 jsAccounts = append(jsAccounts, v.(*Account))
900 return true
901 })
902 accounts := &s.accounts
903 s.mu.RUnlock()
904
905 // Process any jetstream enabled accounts here. These will be accounts we are
906 // already aware of at startup etc.
907 for _, acc := range jsAccounts {
908 if err := s.configJetStream(acc, tq); err != nil {
909 return err
910 }
911 }
912
913 // Now walk all the storage we have and resolve any accounts that we did not process already.
914 // This is important in resolver/operator models.
915 fis, _ := os.ReadDir(js.config.StoreDir)
916 for _, fi := range fis {
917 if accName := fi.Name(); accName != _EMPTY_ {
918 // Only load up ones not already loaded since they are processed above.
919 if _, ok := accounts.Load(accName); !ok {
920 if acc, err := s.lookupAccount(accName); err != nil && acc != nil {
921 if err := s.configJetStream(acc, tq); err != nil {
922 return err
923 }
924 }
925 }
926 }
927 }
928
929 return nil
930 }
931
932 // Mark our started time.
933 func (js *jetStream) setStarted() {
934 js.mu.Lock()
935 defer js.mu.Unlock()
936 js.started = time.Now()
937 }
938
939 func (js *jetStream) isEnabled() bool {
940 if js == nil {
941 return false
942 }
943 return !js.disabled.Load()
944 }
945
946 // Mark that we will be in standlone mode.
947 func (js *jetStream) setJetStreamStandAlone(isStandAlone bool) {
948 if js == nil {
949 return
950 }
951 js.mu.Lock()
952 defer js.mu.Unlock()
953 if js.standAlone = isStandAlone; js.standAlone {
954 // Update our server atomic.
955 js.srv.isMetaLeader.Store(true)
956 js.accountPurge, _ = js.srv.systemSubscribe(JSApiAccountPurge, _EMPTY_, false, nil, js.srv.jsLeaderAccountPurgeRequest)
957 } else if js.accountPurge != nil {
958 js.srv.sysUnsubscribe(js.accountPurge)
959 }
960 }
961
962 // JetStreamEnabled reports if jetstream is enabled for this server.
963 func (s *Server) JetStreamEnabled() bool {
964 return s.getJetStream().isEnabled()
965 }
966
967 // JetStreamEnabledForDomain will report if any servers have JetStream enabled within this domain.
968 func (s *Server) JetStreamEnabledForDomain() bool {
969 if s.JetStreamEnabled() {
970 return true
971 }
972
973 var jsFound bool
974 // If we are here we do not have JetStream enabled for ourselves, but we need to check all connected servers.
975 // TODO(dlc) - Could optimize and memoize this.
976 s.nodeToInfo.Range(func(k, v any) bool {
977 // This should not be dependent on online status, so only check js.
978 if v.(nodeInfo).js {
979 jsFound = true
980 return false
981 }
982 return true
983 })
984
985 return jsFound
986 }
987
988 // Will signal that all pull requests for consumers on this server are now invalid.
989 func (s *Server) signalPullConsumers() {
990 js := s.getJetStream()
991 if js == nil {
992 return
993 }
994
995 js.mu.RLock()
996 defer js.mu.RUnlock()
997
998 // In case we have stale pending requests.
999 const hdr = "NATS/1.0 409 Server Shutdown\r\n" + JSPullRequestPendingMsgs + ": %d\r\n" + JSPullRequestPendingBytes + ": %d\r\n\r\n"
1000 var didSend bool
1001
1002 for _, jsa := range js.accounts {
1003 jsa.mu.RLock()
1004 for _, stream := range jsa.streams {
1005 stream.mu.RLock()
1006 for _, o := range stream.consumers {
1007 o.mu.RLock()
1008 // Only signal on R1.
1009 if o.cfg.Replicas <= 1 {
1010 for reply, wr := range o.pendingRequests() {
1011 shdr := fmt.Sprintf(hdr, wr.n, wr.b)
1012 o.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, []byte(shdr), nil, nil, 0))
1013 didSend = true
1014 }
1015 }
1016 o.mu.RUnlock()
1017 }
1018 stream.mu.RUnlock()
1019 }
1020 jsa.mu.RUnlock()
1021 }
1022 // Give time for migration information to make it out of our server.
1023 if didSend {
1024 time.Sleep(50 * time.Millisecond)
1025 }
1026 }
1027
1028 // Helper for determining if we are shutting down.
1029 func (js *jetStream) isShuttingDown() bool {
1030 js.mu.RLock()
1031 defer js.mu.RUnlock()
1032 return js.shuttingDown
1033 }
1034
1035 // Shutdown jetstream for this server.
1036 func (s *Server) shutdownJetStream() {
1037 js := s.getJetStream()
1038 if js == nil {
1039 return
1040 }
1041
1042 s.Noticef("Initiating JetStream Shutdown...")
1043 defer s.Noticef("JetStream Shutdown")
1044
1045 // If we have folks blocked on sync requests, unblock.
1046 // Send 1 is enough, but use select in case they were all present.
1047 select {
1048 case s.syncOutSem <- struct{}{}:
1049 default:
1050 }
1051
1052 var _a [512]*Account
1053 accounts := _a[:0]
1054
1055 js.mu.Lock()
1056 // Collect accounts.
1057 for _, jsa := range js.accounts {
1058 if a := jsa.acc(); a != nil {
1059 accounts = append(accounts, a)
1060 }
1061 }
1062 accPurgeSub := js.accountPurge
1063 js.accountPurge = nil
1064 // Signal we are shutting down.
1065 js.shuttingDown = true
1066 js.mu.Unlock()
1067
1068 if accPurgeSub != nil {
1069 s.sysUnsubscribe(accPurgeSub)
1070 }
1071
1072 for _, a := range accounts {
1073 a.removeJetStream()
1074 }
1075
1076 s.js.Store(nil)
1077
1078 js.mu.Lock()
1079 js.accounts = nil
1080
1081 var qch chan struct{}
1082 var stopped chan struct{}
1083 if cc := js.cluster; cc != nil {
1084 if cc.qch != nil {
1085 qch, stopped = cc.qch, cc.stopped
1086 cc.qch, cc.stopped = nil, nil
1087 }
1088 js.stopUpdatesSub()
1089 if cc.c != nil {
1090 cc.c.closeConnection(ClientClosed)
1091 cc.c = nil
1092 }
1093 cc.meta = nil
1094 // Set our atomic bool to false.
1095 s.jsClustered.Store(false)
1096 }
1097 js.mu.Unlock()
1098
1099 // If we were clustered signal the monitor cluster go routine.
1100 // We will wait for a bit for it to close.
1101 // Do this without the lock.
1102 if qch != nil {
1103 close(qch) // Must be close() to signal *all* listeners
1104 select {
1105 case <-stopped:
1106 case <-time.After(10 * time.Second):
1107 s.Warnf("Did not receive signal for successful shutdown of cluster routine")
1108 }
1109 }
1110 }
1111
1112 // JetStreamConfig will return the current config. Useful if the system
1113 // created a dynamic configuration. A copy is returned.
1114 func (s *Server) JetStreamConfig() *JetStreamConfig {
1115 var c *JetStreamConfig
1116 if js := s.getJetStream(); js != nil {
1117 js.mu.RLock()
1118 copy := js.config
1119 c = &(copy)
1120 js.mu.RUnlock()
1121 }
1122 return c
1123 }
1124
1125 // StoreDir returns the current JetStream directory.
1126 func (s *Server) StoreDir() string {
1127 js := s.getJetStream()
1128 if js == nil {
1129 return _EMPTY_
1130 }
1131 return js.config.StoreDir
1132 }
1133
1134 // JetStreamNumAccounts returns the number of enabled accounts this server is tracking.
1135 func (s *Server) JetStreamNumAccounts() int {
1136 js := s.getJetStream()
1137 if js == nil {
1138 return 0
1139 }
1140 js.mu.Lock()
1141 defer js.mu.Unlock()
1142 return len(js.accounts)
1143 }
1144
1145 // JetStreamReservedResources returns the reserved resources if JetStream is enabled.
1146 func (s *Server) JetStreamReservedResources() (int64, int64, error) {
1147 js := s.getJetStream()
1148 if js == nil {
1149 return -1, -1, NewJSNotEnabledForAccountError()
1150 }
1151 js.mu.RLock()
1152 defer js.mu.RUnlock()
1153 return js.memReserved, js.storeReserved, nil
1154 }
1155
1156 func (s *Server) getJetStream() *jetStream {
1157 return s.js.Load()
1158 }
1159
1160 func (a *Account) assignJetStreamLimits(limits map[string]JetStreamAccountLimits) {
1161 a.mu.Lock()
1162 a.jsLimits = limits
1163 a.mu.Unlock()
1164 }
1165
1166 // EnableJetStream will enable JetStream on this account with the defined limits.
1167 // This is a helper for JetStreamEnableAccount.
1168 func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits, tq chan<- func()) error {
1169 a.mu.RLock()
1170 s := a.srv
1171 a.mu.RUnlock()
1172
1173 if s == nil {
1174 return fmt.Errorf("jetstream account not registered")
1175 }
1176
1177 if s.SystemAccount() == a {
1178 return fmt.Errorf("jetstream can not be enabled on the system account")
1179 }
1180
1181 s.mu.RLock()
1182 if s.sys == nil {
1183 s.mu.RUnlock()
1184 return ErrServerNotRunning
1185 }
1186 sendq := s.sys.sendq
1187 s.mu.RUnlock()
1188
1189 // No limits means we dynamically set up limits.
1190 // We also place limits here so we know that the account is configured for JetStream.
1191 if len(limits) == 0 {
1192 limits = defaultJSAccountTiers
1193 }
1194
1195 a.assignJetStreamLimits(limits)
1196
1197 js := s.getJetStream()
1198 if js == nil {
1199 return NewJSNotEnabledError()
1200 }
1201
1202 js.mu.Lock()
1203 // Accounts get reset to nil on shutdown, since we re-acquire the locks here, we need to check again.
1204 if js.accounts == nil {
1205 js.mu.Unlock()
1206 return NewJSNotEnabledError()
1207 }
1208
1209 if jsa, ok := js.accounts[a.Name]; ok {
1210 a.mu.Lock()
1211 a.js = jsa
1212 a.mu.Unlock()
1213 js.mu.Unlock()
1214 return a.enableAllJetStreamServiceImportsAndMappings()
1215 }
1216
1217 // Check the limits against existing reservations.
1218 if err := js.sufficientResources(limits); err != nil {
1219 js.mu.Unlock()
1220 return err
1221 }
1222
1223 sysNode := s.Node()
1224
1225 jsa := &jsAccount{js: js, account: a, limits: limits, streams: make(map[string]*stream), sendq: sendq, usage: make(map[string]*jsaStorage)}
1226 jsa.storeDir = filepath.Join(js.config.StoreDir, a.Name)
1227
1228 // A single server does not need to do the account updates at this point.
1229 if js.cluster != nil || !s.standAloneMode() {
1230 jsa.usageMu.Lock()
1231 jsa.utimer = time.AfterFunc(usageTick, jsa.sendClusterUsageUpdateTimer)
1232 // Cluster mode updates to resource usage. System internal prevents echos.
1233 jsa.updatesPub = fmt.Sprintf(jsaUpdatesPubT, a.Name, sysNode)
1234 jsa.updatesSub, _ = s.sysSubscribe(fmt.Sprintf(jsaUpdatesSubT, a.Name), jsa.remoteUpdateUsage)
1235 jsa.usageMu.Unlock()
1236 }
1237
1238 js.accounts[a.Name] = jsa
1239 // Stamp inside account as well. Needs to be done under js's lock.
1240 a.mu.Lock()
1241 a.js = jsa
1242 a.mu.Unlock()
1243 js.mu.Unlock()
1244
1245 // Create the proper imports here.
1246 if err := a.enableAllJetStreamServiceImportsAndMappings(); err != nil {
1247 return err
1248 }
1249
1250 s.Debugf("Enabled JetStream for account %q", a.Name)
1251 if l, ok := limits[_EMPTY_]; ok {
1252 s.Debugf(" Max Memory: %s", friendlyBytes(l.MaxMemory))
1253 s.Debugf(" Max Storage: %s", friendlyBytes(l.MaxStore))
1254 } else {
1255 for t, l := range limits {
1256 s.Debugf(" Tier: %s", t)
1257 s.Debugf(" Max Memory: %s", friendlyBytes(l.MaxMemory))
1258 s.Debugf(" Max Storage: %s", friendlyBytes(l.MaxStore))
1259 }
1260 }
1261
1262 // Clean up any old snapshots that were orphaned while staging.
1263 os.RemoveAll(filepath.Join(js.config.StoreDir, snapStagingDir))
1264
1265 sdir := filepath.Join(jsa.storeDir, streamsDir)
1266 if _, err := os.Stat(sdir); os.IsNotExist(err) {
1267 if err := os.MkdirAll(sdir, defaultDirPerms); err != nil {
1268 return fmt.Errorf("could not create storage streams directory - %v", err)
1269 }
1270 // Just need to make sure we can write to the directory.
1271 // Remove the directory will create later if needed.
1272 os.RemoveAll(sdir)
1273 // when empty remove parent directory, which may have been created as well
1274 os.Remove(jsa.storeDir)
1275 } else {
1276 // Restore any state here.
1277 s.Debugf("Recovering JetStream state for account %q", a.Name)
1278 }
1279
1280 // Remember if we should be encrypted and what cipher we think we should use.
1281 encrypted := s.getOpts().JetStreamKey != _EMPTY_
1282 sc := s.getOpts().JetStreamCipher
1283
1284 doConsumers := func(mset *stream, odir string) {
1285 ofis, _ := os.ReadDir(odir)
1286 if len(ofis) > 0 {
1287 s.Noticef(" Recovering %d consumers for stream - '%s > %s'", len(ofis), mset.accName(), mset.name())
1288 }
1289 for _, ofi := range ofis {
1290 metafile := filepath.Join(odir, ofi.Name(), JetStreamMetaFile)
1291 metasum := filepath.Join(odir, ofi.Name(), JetStreamMetaFileSum)
1292 if _, err := os.Stat(metafile); os.IsNotExist(err) {
1293 s.Warnf(" Missing consumer metafile %q", metafile)
1294 continue
1295 }
1296 buf, err := os.ReadFile(metafile)
1297 if err != nil {
1298 s.Warnf(" Error reading consumer metafile %q: %v", metafile, err)
1299 continue
1300 }
1301 if _, err := os.Stat(metasum); os.IsNotExist(err) {
1302 s.Warnf(" Missing consumer checksum for %q", metasum)
1303 continue
1304 }
1305
1306 // Check if we are encrypted.
1307 if key, err := os.ReadFile(filepath.Join(odir, ofi.Name(), JetStreamMetaFileKey)); err == nil {
1308 s.Debugf(" Consumer metafile is encrypted, reading encrypted keyfile")
1309 // Decode the buffer before proceeding.
1310 ctxName := mset.name() + tsep + ofi.Name()
1311 nbuf, _, err := s.decryptMeta(sc, key, buf, a.Name, ctxName)
1312 if err != nil {
1313 s.Warnf(" Error decrypting our consumer metafile: %v", err)
1314 continue
1315 }
1316 buf = nbuf
1317 }
1318
1319 var cfg FileConsumerInfo
1320 decoder := json.NewDecoder(bytes.NewReader(buf))
1321 decoder.DisallowUnknownFields()
1322 strictErr := decoder.Decode(&cfg)
1323 if strictErr != nil {
1324 cfg = FileConsumerInfo{}
1325 if err := json.Unmarshal(buf, &cfg); err != nil {
1326 s.Warnf(" Error unmarshalling consumer metafile %q: %v", metafile, err)
1327 continue
1328 }
1329 }
1330 if supported := supportsRequiredApiLevel(cfg.Metadata); !supported || strictErr != nil {
1331 var offlineReason string
1332 if !supported {
1333 apiLevel := getRequiredApiLevel(cfg.Metadata)
1334 if strictErr != nil {
1335 offlineReason = fmt.Sprintf("unsupported - config error: %s", strings.TrimPrefix(strictErr.Error(), "json: "))
1336 } else {
1337 offlineReason = fmt.Sprintf("unsupported - required API level: %s, current API level: %d", apiLevel, JSApiLevel)
1338 }
1339 s.Warnf(" Detected unsupported consumer '%s > %s > %s': %s", a.Name, mset.name(), cfg.Name, offlineReason)
1340 } else {
1341 offlineReason = fmt.Sprintf("decoding error: %v", strictErr)
1342 s.Warnf(" Error unmarshalling consumer metafile %q: %v", metafile, strictErr)
1343 }
1344 singleServerMode := !s.JetStreamIsClustered() && s.standAloneMode()
1345 if singleServerMode {
1346 if !mset.closed.Load() {
1347 s.Warnf(" Stopping unsupported stream '%s > %s'", a.Name, mset.name())
1348 mset.mu.Lock()
1349 mset.offlineReason = fmt.Sprintf("stopped - unsupported consumer %q", cfg.Name)
1350 mset.mu.Unlock()
1351 mset.stop(false, false)
1352 }
1353
1354 // Fake a consumer, so we can respond to API requests as single-server.
1355 o := &consumer{
1356 mset: mset,
1357 js: s.getJetStream(),
1358 acc: a,
1359 srv: s,
1360 cfg: cfg.ConsumerConfig,
1361 direct: cfg.Direct,
1362 sourcing: cfg.Sourcing,
1363 active: false,
1364 stream: mset.name(),
1365 name: cfg.Name,
1366 dseq: 1,
1367 sseq: 1,
1368 created: time.Now().UTC(),
1369 closed: true,
1370 offlineReason: offlineReason,
1371 }
1372 if !cfg.Created.IsZero() {
1373 o.created = cfg.Created
1374 }
1375
1376 mset.mu.Lock()
1377 mset.setConsumer(o)
1378 mset.mu.Unlock()
1379 }
1380 continue
1381 }
1382
1383 isEphemeral := !isDurableConsumer(&cfg.ConsumerConfig)
1384 if isEphemeral {
1385 // This is an ephemeral consumer and this could fail on restart until
1386 // the consumer can reconnect. We will create it as a durable and switch it.
1387 cfg.ConsumerConfig.Durable = ofi.Name()
1388 }
1389 obs, err := mset.addConsumerWithAssignment(&cfg.ConsumerConfig, _EMPTY_, nil, true, ActionCreateOrUpdate, false)
1390 if err != nil {
1391 s.Warnf(" Error adding consumer '%s > %s > %s': %v", a.Name, mset.name(), cfg.Name, err)
1392 continue
1393 }
1394 if isEphemeral {
1395 obs.switchToEphemeral()
1396 }
1397 if !cfg.Created.IsZero() {
1398 obs.setCreatedTime(cfg.Created)
1399 }
1400 }
1401 }
1402
1403 // Now recover the streams.
1404 fis, _ := os.ReadDir(sdir)
1405 doStream := func(fi os.DirEntry) error {
1406 plaintext := true
1407 mdir := filepath.Join(sdir, fi.Name())
1408 // Check for partially deleted streams. They are marked with "." prefix.
1409 if strings.HasPrefix(fi.Name(), tsep) {
1410 go os.RemoveAll(mdir)
1411 return nil
1412 }
1413 key := sha256.Sum256([]byte(fi.Name()))
1414 hh, err := highwayhash.NewDigest64(key[:])
1415 if err != nil {
1416 return err
1417 }
1418 metafile := filepath.Join(mdir, JetStreamMetaFile)
1419 metasum := filepath.Join(mdir, JetStreamMetaFileSum)
1420 if _, err := os.Stat(metafile); os.IsNotExist(err) {
1421 s.Warnf(" Missing stream metafile for %q", metafile)
1422 return nil
1423 }
1424 buf, err := os.ReadFile(metafile)
1425 if err != nil {
1426 s.Warnf(" Error reading metafile %q: %v", metafile, err)
1427 return nil
1428 }
1429 if _, err := os.Stat(metasum); os.IsNotExist(err) {
1430 s.Warnf(" Missing stream checksum file %q", metasum)
1431 return nil
1432 }
1433 sum, err := os.ReadFile(metasum)
1434 if err != nil {
1435 s.Warnf(" Error reading Stream metafile checksum %q: %v", metasum, err)
1436 return nil
1437 }
1438 hh.Write(buf)
1439 var hb [highwayhash.Size64]byte
1440 checksum := hex.EncodeToString(hh.Sum(hb[:0]))
1441 if checksum != string(sum) {
1442 s.Warnf(" Stream metafile %q: checksums do not match %q vs %q", metafile, sum, checksum)
1443 return nil
1444 }
1445
1446 // Track if we are converting ciphers.
1447 var convertingCiphers bool
1448
1449 // Check if we are encrypted.
1450 keyFile := filepath.Join(mdir, JetStreamMetaFileKey)
1451 keyBuf, err := os.ReadFile(keyFile)
1452 if err == nil {
1453 s.Debugf(" Stream metafile is encrypted, reading encrypted keyfile")
1454 if len(keyBuf) < minMetaKeySize {
1455 s.Warnf(" Bad stream encryption key length of %d", len(keyBuf))
1456 return nil
1457 }
1458 // Decode the buffer before proceeding.
1459 var nbuf []byte
1460 nbuf, convertingCiphers, err = s.decryptMeta(sc, keyBuf, buf, a.Name, fi.Name())
1461 if err != nil {
1462 s.Warnf(" Error decrypting our stream metafile: %v", err)
1463 return nil
1464 }
1465 buf = nbuf
1466 plaintext = false
1467 }
1468
1469 var cfg FileStreamInfo
1470 decoder := json.NewDecoder(bytes.NewReader(buf))
1471 decoder.DisallowUnknownFields()
1472 strictErr := decoder.Decode(&cfg)
1473 if strictErr != nil {
1474 cfg = FileStreamInfo{}
1475 if err := json.Unmarshal(buf, &cfg); err != nil {
1476 s.Warnf(" Error unmarshalling stream metafile %q: %v", metafile, err)
1477 return nil
1478 }
1479 }
1480 if supported := supportsRequiredApiLevel(cfg.Metadata); !supported || strictErr != nil {
1481 var offlineReason string
1482 if !supported {
1483 apiLevel := getRequiredApiLevel(cfg.Metadata)
1484 if strictErr != nil {
1485 offlineReason = fmt.Sprintf("unsupported - config error: %s", strings.TrimPrefix(strictErr.Error(), "json: "))
1486 } else {
1487 offlineReason = fmt.Sprintf("unsupported - required API level: %s, current API level: %d", apiLevel, JSApiLevel)
1488 }
1489 s.Warnf(" Detected unsupported stream '%s > %s': %s", a.Name, cfg.StreamConfig.Name, offlineReason)
1490 } else {
1491 offlineReason = fmt.Sprintf("decoding error: %v", strictErr)
1492 s.Warnf(" Error unmarshalling stream metafile %q: %v", metafile, strictErr)
1493 }
1494 singleServerMode := !s.JetStreamIsClustered() && s.standAloneMode()
1495 if singleServerMode {
1496 // Fake a stream, so we can respond to API requests as single-server.
1497 mset := &stream{
1498 acc: a,
1499 jsa: jsa,
1500 cfg: cfg.StreamConfig,
1501 js: js,
1502 srv: s,
1503 stype: cfg.Storage,
1504 consumers: make(map[string]*consumer),
1505 active: false,
1506 created: time.Now().UTC(),
1507 offlineReason: offlineReason,
1508 }
1509 if !cfg.Created.IsZero() {
1510 mset.created = cfg.Created
1511 }
1512 mset.closed.Store(true)
1513
1514 jsa.mu.Lock()
1515 jsa.streams[cfg.Name] = mset
1516 jsa.mu.Unlock()
1517
1518 // Now do the consumers.
1519 odir := filepath.Join(sdir, fi.Name(), consumerDir)
1520 doConsumers(mset, odir)
1521 }
1522 return nil
1523 }
1524
1525 // We had a bug that set a default de dupe window on mirror, despite that being not a valid config
1526 fixCfgMirrorWithDedupWindow(&cfg.StreamConfig)
1527
1528 // We had a bug that could allow subjects in that had prefix or suffix spaces. We check for that here
1529 // and will patch them on the fly for now. We will warn about them.
1530 var hadSubjErr bool
1531 for i, subj := range cfg.StreamConfig.Subjects {
1532 if !IsValidSubject(subj) {
1533 s.Warnf(" Detected bad subject %q while adding stream %q, will attempt to repair", subj, cfg.Name)
1534 if nsubj := strings.TrimSpace(subj); IsValidSubject(nsubj) {
1535 s.Warnf(" Bad subject %q repaired to %q", subj, nsubj)
1536 cfg.StreamConfig.Subjects[i] = nsubj
1537 } else {
1538 s.Warnf(" Error recreating stream %q: %v", cfg.Name, "invalid subject")
1539 hadSubjErr = true
1540 break
1541 }
1542 }
1543 }
1544 if hadSubjErr {
1545 return nil
1546 }
1547
1548 // The other possible bug is assigning subjects to mirrors, so check for that and patch as well.
1549 if cfg.StreamConfig.Mirror != nil && len(cfg.StreamConfig.Subjects) > 0 {
1550 s.Warnf(" Detected subjects on a mirrored stream %q, will remove", cfg.Name)
1551 cfg.StreamConfig.Subjects = nil
1552 }
1553
1554 s.Noticef(" Starting restore for stream '%s > %s'", a.Name, cfg.StreamConfig.Name)
1555 rt := time.Now()
1556
1557 // Log if we are converting from plaintext to encrypted.
1558 if encrypted {
1559 if plaintext {
1560 s.Noticef(" Encrypting stream '%s > %s'", a.Name, cfg.StreamConfig.Name)
1561 } else if convertingCiphers {
1562 s.Noticef(" Converting to %s for stream '%s > %s'", sc, a.Name, cfg.StreamConfig.Name)
1563 // Remove the key file to have system regenerate with the new cipher.
1564 os.Remove(keyFile)
1565 }
1566 }
1567
1568 // Add in the stream.
1569 mset, err := a.recoverStream(&cfg.StreamConfig)
1570 if err != nil {
1571 s.Warnf(" Error recreating stream %q: %v", cfg.Name, err)
1572 // If we removed a keyfile from above make sure to put it back.
1573 if convertingCiphers {
1574 err := os.WriteFile(keyFile, keyBuf, defaultFilePerms)
1575 if err != nil {
1576 s.Warnf(" Error replacing meta keyfile for stream %q: %v", cfg.Name, err)
1577 }
1578 }
1579 return nil
1580 }
1581 if !cfg.Created.IsZero() {
1582 mset.setCreatedTime(cfg.Created)
1583 }
1584
1585 // Might need to recover from a partial batch write, but only if a single replica stream.
1586 if cfg.AllowAtomicPublish && cfg.Replicas == 1 {
1587 var (
1588 ok bool
1589 smv StoreMsg
1590 batchId string
1591 batchSeq uint64
1592 commit bool
1593 commitEob bool
1594 batchStoreDir string
1595 store StreamStore
1596 state StreamState
1597 )
1598 // Check if the last message was part of a batch.
1599 sm, err := mset.store.LoadLastMsg(fwcs, &smv)
1600 if err != nil || sm == nil {
1601 goto SKIP
1602 }
1603 batchId = getBatchId(sm.hdr)
1604 batchSeq, ok = getBatchSequence(sm.hdr)
1605 commit = len(sliceHeader(JSBatchCommit, sm.hdr)) != 0
1606 if batchId == _EMPTY_ || !ok || commit {
1607 goto SKIP
1608 }
1609 // We've observed a partial batch write. Write the remainder of the batch.
1610 batchSeq++
1611 _, batchStoreDir = getBatchStoreDir(jsa.storeDir, cfg.Name, batchId)
1612 if _, err = os.Stat(batchStoreDir); err != nil {
1613 s.Errorf(" Failed restoring partial batch write for stream '%s > %s' at sequence %d: %v",
1614 mset.accName(), mset.name(), batchSeq, err)
1615 goto SKIP
1616 }
1617 store, err = newBatchStore(mset, batchId, cfg.Replicas, cfg.Storage, jsa.storeDir, cfg.Name)
1618 if err != nil {
1619 s.Errorf(" Failed restoring partial batch write for stream '%s > %s' at sequence %d: %v",
1620 mset.accName(), mset.name(), batchSeq, err)
1621 goto SKIP
1622 }
1623 store.FastState(&state)
1624 sm, err = store.LoadMsg(state.LastSeq, &smv)
1625 if err != nil || sm == nil {
1626 s.Errorf(" Failed restoring partial batch write for stream '%s > %s' at sequence %d: last msg not found %d",
1627 mset.accName(), mset.name(), batchSeq, state.LastSeq)
1628 goto SKIP
1629 }
1630 commitEob = bytes.Equal(sliceHeader(JSBatchCommit, sm.hdr), []byte("eob"))
1631 // If the commit ends with an "End Of Batch" message, we don't store this.
1632 if commitEob {
1633 state.LastSeq--
1634 }
1635 s.Noticef(" Restoring partial batch write for stream '%s > %s' (seq %d to %d)",
1636 mset.accName(), mset.name(), batchSeq, state.LastSeq)
1637 // Loop through items that weren't persisted yet.
1638 for seq := batchSeq; seq <= state.LastSeq; seq++ {
1639 sm, err = store.LoadMsg(seq, &smv)
1640 if err != nil || sm == nil {
1641 s.Errorf(" Failed restoring partial batch write for stream '%s > %s' at sequence %d: %v",
1642 mset.accName(), mset.name(), seq, err)
1643 break
1644 }
1645 hdr := sm.hdr
1646 // If committed by EOB, the last message must get the normal commit header.
1647 if commitEob && seq == state.LastSeq {
1648 hdr = genHeader(hdr, JSBatchCommit, "1")
1649 }
1650 mset.processJetStreamMsg(sm.subj, _EMPTY_, hdr, sm.msg, 0, 0, nil, false, true)
1651 }
1652 store.Delete(true)
1653 SKIP:
1654 os.RemoveAll(filepath.Join(sdir, fi.Name(), batchesDir))
1655 }
1656
1657 state := mset.state()
1658 s.Noticef(" Restored %s messages for stream '%s > %s' in %v",
1659 comma(int64(state.Msgs)), mset.accName(), mset.name(), time.Since(rt).Round(time.Millisecond))
1660
1661 // Now do the consumers.
1662 odir := filepath.Join(sdir, fi.Name(), consumerDir)
1663 doConsumers(mset, odir)
1664
1665 // Collect to check for dangling messages.
1666 // TODO(dlc) - Can be removed eventually.
1667 if cfg.StreamConfig.Retention == InterestPolicy {
1668 mset.checkForOrphanMsgs()
1669 mset.checkConsumerReplication()
1670 }
1671
1672 return nil
1673 }
1674
1675 if tq != nil {
1676 // If a parallelTaskQueue was provided then use that for concurrency.
1677 var wg sync.WaitGroup
1678 wg.Add(len(fis))
1679 for _, fi := range fis {
1680 tq <- func() {
1681 doStream(fi)
1682 wg.Done()
1683 }
1684 }
1685 wg.Wait()
1686 } else {
1687 // No parallelTaskQueue provided, do inline as before.
1688 for _, fi := range fis {
1689 doStream(fi)
1690 }
1691 }
1692
1693 // Make sure to cleanup any old remaining snapshots.
1694 os.RemoveAll(filepath.Join(jsa.storeDir, snapsDir))
1695
1696 s.Debugf("JetStream state for account %q recovered", a.Name)
1697
1698 return nil
1699 }
1700
1701 // Return whether we require MaxBytes to be set and if > 0 an upper limit for stream size exists
1702 // Both limits are independent of each other.
1703 func (a *Account) maxBytesLimits(cfg *StreamConfig) (bool, int64) {
1704 a.mu.RLock()
1705 jsa := a.js
1706 a.mu.RUnlock()
1707 if jsa == nil {
1708 return false, 0
1709 }
1710 jsa.usageMu.RLock()
1711 var replicas int
1712 if cfg != nil {
1713 replicas = cfg.Replicas
1714 }
1715 selectedLimits, _, ok := jsa.selectLimits(replicas)
1716 jsa.usageMu.RUnlock()
1717 if !ok {
1718 return false, 0
1719 }
1720 maxStreamBytes := int64(0)
1721 if cfg.Storage == MemoryStorage {
1722 maxStreamBytes = selectedLimits.MemoryMaxStreamBytes
1723 } else {
1724 maxStreamBytes = selectedLimits.StoreMaxStreamBytes
1725 }
1726 return selectedLimits.MaxBytesRequired, maxStreamBytes
1727 }
1728
1729 // NumStreams will return how many streams we have.
1730 func (a *Account) numStreams() int {
1731 a.mu.RLock()
1732 jsa := a.js
1733 a.mu.RUnlock()
1734 if jsa == nil {
1735 return 0
1736 }
1737 jsa.mu.Lock()
1738 n := len(jsa.streams)
1739 jsa.mu.Unlock()
1740 return n
1741 }
1742
1743 // Streams will return all known streams.
1744 func (a *Account) streams() []*stream {
1745 return a.filteredStreams(_EMPTY_)
1746 }
1747
1748 func (a *Account) filteredStreams(filter string) []*stream {
1749 a.mu.RLock()
1750 jsa := a.js
1751 a.mu.RUnlock()
1752
1753 if jsa == nil {
1754 return nil
1755 }
1756
1757 jsa.mu.RLock()
1758 defer jsa.mu.RUnlock()
1759
1760 var msets []*stream
1761 for _, mset := range jsa.streams {
1762 if filter != _EMPTY_ {
1763 mset.cfgMu.RLock()
1764 for _, subj := range mset.cfg.Subjects {
1765 if SubjectsCollide(filter, subj) {
1766 msets = append(msets, mset)
1767 break
1768 }
1769 }
1770 mset.cfgMu.RUnlock()
1771 } else {
1772 msets = append(msets, mset)
1773 }
1774 }
1775
1776 return msets
1777 }
1778
1779 // lookupStream will lookup a stream by name.
1780 func (a *Account) lookupStream(name string) (*stream, error) {
1781 a.mu.RLock()
1782 jsa := a.js
1783 a.mu.RUnlock()
1784
1785 if jsa == nil {
1786 return nil, NewJSNotEnabledForAccountError()
1787 }
1788 jsa.mu.RLock()
1789 defer jsa.mu.RUnlock()
1790
1791 mset, ok := jsa.streams[name]
1792 if !ok {
1793 return nil, NewJSStreamNotFoundError()
1794 }
1795 return mset, nil
1796 }
1797
1798 // UpdateJetStreamLimits will update the account limits for a JetStream enabled account.
1799 func (a *Account) UpdateJetStreamLimits(limits map[string]JetStreamAccountLimits) error {
1800 a.mu.RLock()
1801 s, jsa := a.srv, a.js
1802 a.mu.RUnlock()
1803
1804 if s == nil {
1805 return fmt.Errorf("jetstream account not registered")
1806 }
1807 js := s.getJetStream()
1808 if js == nil {
1809 return NewJSNotEnabledError()
1810 }
1811 if jsa == nil {
1812 return NewJSNotEnabledForAccountError()
1813 }
1814
1815 if len(limits) == 0 {
1816 limits = defaultJSAccountTiers
1817 }
1818
1819 // Calculate the delta between what we have and what we want.
1820 jsa.usageMu.RLock()
1821 dl := diffCheckedLimits(jsa.limits, limits)
1822 jsa.usageMu.RUnlock()
1823
1824 js.mu.Lock()
1825 // Check the limits against existing reservations.
1826 if err := js.sufficientResources(dl); err != nil {
1827 js.mu.Unlock()
1828 return err
1829 }
1830 js.mu.Unlock()
1831
1832 // Update
1833 jsa.usageMu.Lock()
1834 jsa.limits = limits
1835 jsa.usageMu.Unlock()
1836
1837 return nil
1838 }
1839
1840 func diffCheckedLimits(a, b map[string]JetStreamAccountLimits) map[string]JetStreamAccountLimits {
1841 diff := map[string]JetStreamAccountLimits{}
1842 for t, la := range a {
1843 // in a, not in b will return 0
1844 lb := b[t]
1845 diff[t] = JetStreamAccountLimits{
1846 MaxMemory: lb.MaxMemory - la.MaxMemory,
1847 MaxStore: lb.MaxStore - la.MaxStore,
1848 }
1849 }
1850 for t, lb := range b {
1851 if la, ok := a[t]; !ok {
1852 // only in b not in a. (in a and b already covered)
1853 diff[t] = JetStreamAccountLimits{
1854 MaxMemory: lb.MaxMemory - la.MaxMemory,
1855 MaxStore: lb.MaxStore - la.MaxStore,
1856 }
1857 }
1858 }
1859 return diff
1860 }
1861
1862 // Return reserved bytes for memory and file store streams for this account on this server.
1863 // Lock should be held.
1864 func (jsa *jsAccount) reservedStorage(tier string) (mem, store uint64) {
1865 for _, mset := range jsa.streams {
1866 mset.cfgMu.RLock()
1867 storage, replicas, maxBytes := mset.cfg.Storage, mset.cfg.Replicas, mset.cfg.MaxBytes
1868 mset.cfgMu.RUnlock()
1869 if (tier == _EMPTY_ || tier == tierName(replicas)) && maxBytes > 0 {
1870 switch storage {
1871 case FileStorage:
1872 store += uint64(maxBytes)
1873 case MemoryStorage:
1874 mem += uint64(maxBytes)
1875 }
1876 }
1877 }
1878 return mem, store
1879 }
1880
1881 // Return reserved bytes for memory and file store streams for this account in clustered mode.
1882 // js lock should be held.
1883 func reservedStorage(sas map[string]*streamAssignment, tier string) (mem, store uint64) {
1884 for _, sa := range sas {
1885 cfg := sa.Config
1886 if (tier == _EMPTY_ || tier == tierName(cfg.Replicas)) && cfg.MaxBytes > 0 {
1887 switch cfg.Storage {
1888 case FileStorage:
1889 store += uint64(cfg.MaxBytes)
1890 case MemoryStorage:
1891 mem += uint64(cfg.MaxBytes)
1892 }
1893 }
1894 }
1895 return mem, store
1896 }
1897
1898 // JetStreamUsage reports on JetStream usage and limits for an account.
1899 func (a *Account) JetStreamUsage() JetStreamAccountStats {
1900 a.mu.RLock()
1901 jsa, aname := a.js, a.Name
1902 accJsLimits := a.jsLimits
1903 a.mu.RUnlock()
1904
1905 var stats JetStreamAccountStats
1906 if jsa != nil {
1907 js := jsa.js
1908 js.mu.RLock()
1909 cc := js.cluster
1910 singleServer := cc == nil
1911 jsa.mu.RLock()
1912 jsa.usageMu.RLock()
1913 stats.Memory, stats.Store = jsa.storageTotals()
1914 stats.Domain = js.config.Domain
1915 stats.API = JetStreamAPIStats{
1916 Level: JSApiLevel,
1917 Total: jsa.apiTotal,
1918 Errors: jsa.apiErrors,
1919 }
1920 if singleServer {
1921 stats.ReservedMemory, stats.ReservedStore = jsa.reservedStorage(_EMPTY_)
1922 } else {
1923 stats.ReservedMemory, stats.ReservedStore = reservedStorage(cc.streams[aname], _EMPTY_)
1924 }
1925 l, defaultTier := jsa.limits[_EMPTY_]
1926 if defaultTier {
1927 stats.Limits = l
1928 } else {
1929 skipped := 0
1930 stats.Tiers = make(map[string]JetStreamTier)
1931 for t, total := range jsa.usage {
1932 if _, ok := jsa.limits[t]; !ok && (*total) == (jsaStorage{}) {
1933 // skip tiers not present that don't contain a count
1934 // In case this shows an empty stream, that tier will be added when iterating over streams
1935 skipped++
1936 } else {
1937 tier := JetStreamTier{
1938 Memory: uint64(total.total.mem),
1939 Store: uint64(total.total.store),
1940 Limits: jsa.limits[t],
1941 }
1942 if singleServer {
1943 tier.ReservedMemory, tier.ReservedStore = jsa.reservedStorage(t)
1944 } else {
1945 tier.ReservedMemory, tier.ReservedStore = reservedStorage(cc.streams[aname], t)
1946 }
1947 stats.Tiers[t] = tier
1948 }
1949 }
1950 if len(accJsLimits) != len(jsa.usage)-skipped {
1951 // insert unused limits
1952 for t, lim := range accJsLimits {
1953 if _, ok := stats.Tiers[t]; !ok {
1954 tier := JetStreamTier{Limits: lim}
1955 if singleServer {
1956 tier.ReservedMemory, tier.ReservedStore = jsa.reservedStorage(t)
1957 } else {
1958 tier.ReservedMemory, tier.ReservedStore = reservedStorage(cc.streams[aname], t)
1959 }
1960 stats.Tiers[t] = tier
1961 }
1962 }
1963 }
1964 }
1965 jsa.usageMu.RUnlock()
1966
1967 // Clustered
1968 if cc := js.cluster; cc != nil {
1969 sas := cc.streams[aname]
1970 if defaultTier {
1971 stats.Streams = len(sas)
1972 stats.ReservedMemory, stats.ReservedStore = reservedStorage(sas, _EMPTY_)
1973 }
1974 for _, sa := range sas {
1975 if defaultTier {
1976 stats.Consumers += len(sa.consumers)
1977 } else {
1978 stats.Streams++
1979 streamTier := tierName(sa.Config.Replicas)
1980 su, ok := stats.Tiers[streamTier]
1981 if !ok {
1982 su = JetStreamTier{}
1983 }
1984 su.Streams++
1985 stats.Tiers[streamTier] = su
1986
1987 // Now consumers, check each since could be different tiers.
1988 for _, ca := range sa.consumers {
1989 stats.Consumers++
1990 consumerTier := tierName(ca.Config.replicas(sa.Config))
1991 cu, ok := stats.Tiers[consumerTier]
1992 if !ok {
1993 cu = JetStreamTier{}
1994 }
1995 cu.Consumers++
1996 stats.Tiers[consumerTier] = cu
1997 }
1998 }
1999 }
2000 } else {
2001 if defaultTier {
2002 stats.Streams = len(jsa.streams)
2003 }
2004 for _, mset := range jsa.streams {
2005 consCount := mset.numConsumers()
2006 stats.Consumers += consCount
2007 if !defaultTier {
2008 u, ok := stats.Tiers[mset.tier]
2009 if !ok {
2010 u = JetStreamTier{}
2011 }
2012 u.Streams++
2013 stats.Streams++
2014 u.Consumers += consCount
2015 stats.Tiers[mset.tier] = u
2016 }
2017 }
2018 }
2019 jsa.mu.RUnlock()
2020 js.mu.RUnlock()
2021 }
2022 return stats
2023 }
2024
2025 // DisableJetStream will disable JetStream for this account.
2026 func (a *Account) DisableJetStream() error {
2027 return a.removeJetStream()
2028 }
2029
2030 // removeJetStream is called when JetStream has been disabled for this account.
2031 func (a *Account) removeJetStream() error {
2032 a.mu.Lock()
2033 s := a.srv
2034 a.js = nil
2035 a.mu.Unlock()
2036
2037 if s == nil {
2038 return fmt.Errorf("jetstream account not registered")
2039 }
2040
2041 js := s.getJetStream()
2042 if js == nil {
2043 return NewJSNotEnabledForAccountError()
2044 }
2045
2046 return js.disableJetStream(js.lookupAccount(a))
2047 }
2048
2049 // Disable JetStream for the account.
2050 func (js *jetStream) disableJetStream(jsa *jsAccount) error {
2051 if jsa == nil || jsa.account == nil {
2052 return NewJSNotEnabledForAccountError()
2053 }
2054
2055 js.mu.Lock()
2056 delete(js.accounts, jsa.account.Name)
2057 js.mu.Unlock()
2058
2059 jsa.delete()
2060
2061 return nil
2062 }
2063
2064 // jetStreamConfigured reports whether the account has JetStream configured, regardless of this
2065 // servers JetStream status.
2066 func (a *Account) jetStreamConfigured() bool {
2067 if a == nil {
2068 return false
2069 }
2070 a.mu.RLock()
2071 defer a.mu.RUnlock()
2072 return len(a.jsLimits) > 0
2073 }
2074
2075 // JetStreamEnabled is a helper to determine if jetstream is enabled for an account.
2076 func (a *Account) JetStreamEnabled() bool {
2077 if a == nil {
2078 return false
2079 }
2080 a.mu.RLock()
2081 enabled := a.js != nil
2082 a.mu.RUnlock()
2083 return enabled
2084 }
2085
2086 func (jsa *jsAccount) remoteUpdateUsage(sub *subscription, c *client, _ *Account, subject, _ string, msg []byte) {
2087 // jsa.js.srv is immutable and guaranteed to no be nil, so no lock needed.
2088 s := jsa.js.srv
2089
2090 jsa.usageMu.Lock()
2091 defer jsa.usageMu.Unlock()
2092
2093 if len(msg) < minUsageUpdateLen {
2094 s.Warnf("Ignoring remote usage update with size too short")
2095 return
2096 }
2097 var rnode string
2098 if li := strings.LastIndexByte(subject, btsep); li > 0 && li < len(subject) {
2099 rnode = subject[li+1:]
2100 }
2101 if rnode == _EMPTY_ {
2102 s.Warnf("Received remote usage update with no remote node")
2103 return
2104 }
2105 rUsage, ok := jsa.rusage[rnode]
2106 if !ok {
2107 if jsa.rusage == nil {
2108 jsa.rusage = make(map[string]*remoteUsage)
2109 }
2110 rUsage = &remoteUsage{tiers: make(map[string]*jsaUsage)}
2111 jsa.rusage[rnode] = rUsage
2112 }
2113 updateTotal := func(tierName string, memUsed, storeUsed int64) {
2114 total, ok := jsa.usage[tierName]
2115 if !ok {
2116 total = &jsaStorage{}
2117 jsa.usage[tierName] = total
2118 }
2119 // Update the usage for this remote.
2120 if usage := rUsage.tiers[tierName]; usage != nil {
2121 // Decrement our old values.
2122 total.total.mem -= usage.mem
2123 total.total.store -= usage.store
2124 usage.mem, usage.store = memUsed, storeUsed
2125 } else {
2126 rUsage.tiers[tierName] = &jsaUsage{memUsed, storeUsed}
2127 }
2128 total.total.mem += memUsed
2129 total.total.store += storeUsed
2130 }
2131
2132 var le = binary.LittleEndian
2133 apiTotal, apiErrors := le.Uint64(msg[16:]), le.Uint64(msg[24:])
2134 memUsed, storeUsed := int64(le.Uint64(msg[0:])), int64(le.Uint64(msg[8:]))
2135
2136 // We later extended the data structure to support multiple tiers
2137 var excessRecordCnt uint32
2138 var tierName string
2139
2140 if len(msg) >= usageMultiTiersLen {
2141 excessRecordCnt = le.Uint32(msg[minUsageUpdateLen:])
2142 length := le.Uint64(msg[minUsageUpdateLen+4:])
2143 // Need to protect past this point in case this is wrong.
2144 if length > uint64(len(msg))-usageMultiTiersLen {
2145 s.Warnf("Received corrupt remote usage update")
2146 return
2147 }
2148 tierName = string(msg[usageMultiTiersLen : usageMultiTiersLen+length])
2149 msg = msg[usageMultiTiersLen+length:]
2150 }
2151 updateTotal(tierName, memUsed, storeUsed)
2152 for ; excessRecordCnt > 0 && len(msg) >= usageRecordLen; excessRecordCnt-- {
2153 memUsed, storeUsed := int64(le.Uint64(msg[0:])), int64(le.Uint64(msg[8:]))
2154 length := le.Uint64(msg[16:])
2155 if length > uint64(len(msg))-usageRecordLen {
2156 s.Warnf("Received corrupt remote usage update on excess record")
2157 return
2158 }
2159 tierName = string(msg[usageRecordLen : usageRecordLen+length])
2160 msg = msg[usageRecordLen+length:]
2161 updateTotal(tierName, memUsed, storeUsed)
2162 }
2163 jsa.apiTotal -= rUsage.api
2164 jsa.apiErrors -= rUsage.err
2165 rUsage.api = apiTotal
2166 rUsage.err = apiErrors
2167 jsa.apiTotal += apiTotal
2168 jsa.apiErrors += apiErrors
2169 }
2170
2171 // When we detect a skew of some sort this will verify the usage reporting is correct.
2172 // No locks should be held.
2173 func (jsa *jsAccount) checkAndSyncUsage(tierName string, storeType StorageType) {
2174 // This will run in a separate go routine, so check that we are only running once.
2175 if !jsa.sync.CompareAndSwap(false, true) {
2176 return
2177 }
2178 defer jsa.sync.Store(false)
2179
2180 // Hold the account read lock and the usage lock while we calculate.
2181 // We scope by tier and storage type, but if R3 File has 200 streams etc. could
2182 // show a pause. I did test with > 100 non-active streams and was 80-200ns or so.
2183 // Should be rare this gets called as well.
2184 jsa.mu.RLock()
2185 defer jsa.mu.RUnlock()
2186 js := jsa.js
2187 if js == nil {
2188 return
2189 }
2190 s := js.srv
2191
2192 // We need to collect the stream stores before we acquire the usage lock since in storeUpdates the
2193 // stream lock could be held if deletion are inline with storing a new message, e.g. via limits.
2194 var stores []StreamStore
2195 for _, mset := range jsa.streams {
2196 mset.mu.RLock()
2197 if mset.tier == tierName && mset.stype == storeType && mset.store != nil {
2198 stores = append(stores, mset.store)
2199 }
2200 mset.mu.RUnlock()
2201 }
2202
2203 // Now range and qualify, hold usage lock to prevent updates.
2204 jsa.usageMu.Lock()
2205 defer jsa.usageMu.Unlock()
2206
2207 usage, ok := jsa.usage[tierName]
2208 if !ok {
2209 return
2210 }
2211
2212 // Collect current total for all stream stores that matched.
2213 var total int64
2214 var state StreamState
2215 for _, store := range stores {
2216 store.FastState(&state)
2217 total += int64(state.Bytes)
2218 }
2219
2220 var needClusterUpdate bool
2221 // If we do not match on our calculations compute delta and adjust.
2222 if storeType == MemoryStorage {
2223 if total != usage.local.mem {
2224 s.Warnf("MemStore usage drift of %v vs %v detected for account %q",
2225 friendlyBytes(total), friendlyBytes(usage.local.mem), jsa.account.GetName())
2226 delta := total - usage.local.mem
2227 usage.local.mem += delta
2228 usage.total.mem += delta
2229 atomic.AddInt64(&js.memUsed, delta)
2230 needClusterUpdate = true
2231 }
2232 } else {
2233 if total != usage.local.store {
2234 s.Warnf("FileStore usage drift of %v vs %v detected for account %q",
2235 friendlyBytes(total), friendlyBytes(usage.local.store), jsa.account.GetName())
2236 delta := total - usage.local.store
2237 usage.local.store += delta
2238 usage.total.store += delta
2239 atomic.AddInt64(&js.storeUsed, delta)
2240 needClusterUpdate = true
2241 }
2242 }
2243
2244 // Publish our local updates if in clustered mode.
2245 if needClusterUpdate && js.isClusteredNoLock() {
2246 jsa.sendClusterUsageUpdate()
2247 }
2248 }
2249
2250 // Updates accounting on in use memory and storage. This is called from locally
2251 // by the lower storage layers.
2252 func (jsa *jsAccount) updateUsage(tierName string, storeType StorageType, delta int64) {
2253 // jsa.js is immutable and cannot be nil, so ok w/o lock.
2254 js := jsa.js
2255 // updateUsage() may be invoked under the mset's lock, so we can't get
2256 // the js' lock to check if clustered. So use this function that make
2257 // use of an atomic to do the check without having data race reports.
2258 isClustered := js.isClusteredNoLock()
2259
2260 var needsCheck bool
2261 jsa.usageMu.Lock()
2262 s, ok := jsa.usage[tierName]
2263 if !ok {
2264 s = &jsaStorage{}
2265 jsa.usage[tierName] = s
2266 }
2267 if storeType == MemoryStorage {
2268 s.local.mem += delta
2269 s.total.mem += delta
2270 atomic.AddInt64(&js.memUsed, delta)
2271 needsCheck = s.local.mem < 0
2272 } else {
2273 s.local.store += delta
2274 s.total.store += delta
2275 atomic.AddInt64(&js.storeUsed, delta)
2276 needsCheck = s.local.store < 0
2277 }
2278 // Publish our local updates if in clustered mode.
2279 if isClustered {
2280 jsa.sendClusterUsageUpdate()
2281 }
2282 jsa.usageMu.Unlock()
2283
2284 if needsCheck {
2285 // We could be holding the stream lock from up in the stack, and this
2286 // will want the jsa lock, which would violate locking order.
2287 // So do this in a Go routine. The function will check if it is already running.
2288 go jsa.checkAndSyncUsage(tierName, storeType)
2289 }
2290 }
2291
2292 var usageTick = 1500 * time.Millisecond
2293
2294 func (jsa *jsAccount) sendClusterUsageUpdateTimer() {
2295 jsa.usageMu.Lock()
2296 defer jsa.usageMu.Unlock()
2297 jsa.sendClusterUsageUpdate()
2298 if jsa.utimer != nil {
2299 jsa.utimer.Reset(usageTick)
2300 }
2301 }
2302
2303 // For usage fields.
2304 const (
2305 minUsageUpdateLen = 32
2306 stackUsageUpdate = 72
2307 usageRecordLen = 24
2308 usageMultiTiersLen = 44
2309 apiStatsAndNumTiers = 20
2310 minUsageUpdateWindow = 250 * time.Millisecond
2311 )
2312
2313 // Send updates to our account usage for this server.
2314 // jsa.usageMu lock should be held.
2315 func (jsa *jsAccount) sendClusterUsageUpdate() {
2316 // These values are absolute so we can limit send rates.
2317 now := time.Now()
2318 if now.Sub(jsa.lupdate) < minUsageUpdateWindow {
2319 return
2320 }
2321 jsa.lupdate = now
2322
2323 lenUsage := len(jsa.usage)
2324 if lenUsage == 0 {
2325 return
2326 }
2327 // every base record contains mem/store/len(tier) as well as the tier name
2328 l := usageRecordLen * lenUsage
2329 for tier := range jsa.usage {
2330 l += len(tier)
2331 }
2332 // first record contains api/usage errors as well as count for extra base records
2333 l += apiStatsAndNumTiers
2334
2335 var raw [stackUsageUpdate]byte
2336 var b []byte
2337 if l > stackUsageUpdate {
2338 b = make([]byte, l)
2339 } else {
2340 b = raw[:l]
2341 }
2342
2343 var i int
2344 var le = binary.LittleEndian
2345 for tier, usage := range jsa.usage {
2346 le.PutUint64(b[i+0:], uint64(usage.local.mem))
2347 le.PutUint64(b[i+8:], uint64(usage.local.store))
2348 if i == 0 {
2349 le.PutUint64(b[16:], jsa.usageApi)
2350 le.PutUint64(b[24:], jsa.usageErr)
2351 le.PutUint32(b[32:], uint32(len(jsa.usage)-1))
2352 le.PutUint64(b[36:], uint64(len(tier)))
2353 copy(b[usageMultiTiersLen:], tier)
2354 i = usageMultiTiersLen + len(tier)
2355 } else {
2356 le.PutUint64(b[i+16:], uint64(len(tier)))
2357 copy(b[i+usageRecordLen:], tier)
2358 i += usageRecordLen + len(tier)
2359 }
2360 }
2361 jsa.sendq.push(newPubMsg(nil, jsa.updatesPub, _EMPTY_, nil, nil, b, noCompression, false, false))
2362 }
2363
2364 func (js *jetStream) wouldExceedLimits(storeType StorageType, sz int) bool {
2365 var (
2366 total *int64
2367 max *int64
2368 )
2369 if storeType == MemoryStorage {
2370 total, max = &js.memUsed, &js.memMax
2371 } else {
2372 total, max = &js.storeUsed, &js.storeMax
2373 }
2374 return (atomic.LoadInt64(total) + int64(sz)) > atomic.LoadInt64(max)
2375 }
2376
2377 func (js *jetStream) limitsExceeded(storeType StorageType) bool {
2378 return js.wouldExceedLimits(storeType, 0)
2379 }
2380
2381 func tierName(replicas int) string {
2382 // TODO (mh) this is where we could select based off a placement tag as well "qos:tier"
2383 if replicas == 0 {
2384 replicas = 1
2385 }
2386 return fmt.Sprintf("R%d", replicas)
2387 }
2388
2389 func isSameTier(replicasA, replicasB int) bool {
2390 a := max(1, replicasA)
2391 b := max(1, replicasB)
2392 // TODO (mh) this is where we could select based off a placement tag as well "qos:tier"
2393 return a == b
2394 }
2395
2396 func (jsa *jsAccount) jetStreamAndClustered() (*jetStream, bool) {
2397 jsa.mu.RLock()
2398 js := jsa.js
2399 jsa.mu.RUnlock()
2400 return js, js.isClustered()
2401 }
2402
2403 // jsa.usageMu read lock should be held.
2404 func (jsa *jsAccount) selectLimits(replicas int) (JetStreamAccountLimits, string, bool) {
2405 if selectedLimits, ok := jsa.limits[_EMPTY_]; ok {
2406 return selectedLimits, _EMPTY_, true
2407 }
2408 tier := tierName(replicas)
2409 if selectedLimits, ok := jsa.limits[tier]; ok {
2410 return selectedLimits, tier, true
2411 }
2412 return JetStreamAccountLimits{}, _EMPTY_, false
2413 }
2414
2415 // Lock should be held.
2416 func (jsa *jsAccount) countStreams(tier string, cfg *StreamConfig) (streams int) {
2417 for _, mset := range jsa.streams {
2418 mset.cfgMu.RLock()
2419 name, replicas := mset.cfg.Name, mset.cfg.Replicas
2420 mset.cfgMu.RUnlock()
2421 // Don't count the stream toward the limit if it already exists.
2422 if (tier == _EMPTY_ || isSameTier(replicas, cfg.Replicas)) && name != cfg.Name {
2423 streams++
2424 }
2425 }
2426 return streams
2427 }
2428
2429 // jsa.usageMu read lock (at least) should be held.
2430 func (jsa *jsAccount) storageTotals() (uint64, uint64) {
2431 mem := uint64(0)
2432 store := uint64(0)
2433 for _, sa := range jsa.usage {
2434 mem += uint64(sa.total.mem)
2435 store += uint64(sa.total.store)
2436 }
2437 return mem, store
2438 }
2439
2440 func (jsa *jsAccount) limitsExceeded(storeType StorageType, tierName string, replicas int) (bool, *ApiError) {
2441 return jsa.wouldExceedLimits(storeType, tierName, replicas, _EMPTY_, nil, nil)
2442 }
2443
2444 func (jsa *jsAccount) wouldExceedLimits(storeType StorageType, tierName string, replicas int, subj string, hdr, msg []byte) (bool, *ApiError) {
2445 jsa.usageMu.RLock()
2446 defer jsa.usageMu.RUnlock()
2447
2448 selectedLimits, ok := jsa.limits[tierName]
2449 if !ok {
2450 return true, NewJSNoLimitsError()
2451 }
2452 inUse := jsa.usage[tierName]
2453 if inUse == nil {
2454 // Imply totals of 0
2455 return false, nil
2456 }
2457 r := int64(replicas)
2458 // Make sure replicas is correct.
2459 if r < 1 {
2460 r = 1
2461 }
2462 // This is for limits. If we have no tier, consider all to be flat, vs tiers like R3 where we want to scale limit by replication.
2463 lr := r
2464 if tierName == _EMPTY_ {
2465 lr = 1
2466 }
2467
2468 // Since tiers are flat we need to scale limit up by replicas when checking.
2469 if storeType == MemoryStorage {
2470 totalMem := inUse.total.mem + (int64(memStoreMsgSize(subj, hdr, msg)) * r)
2471 if selectedLimits.MaxMemory >= 0 && totalMem > selectedLimits.MaxMemory*lr {
2472 return true, nil
2473 }
2474 } else {
2475 totalStore := inUse.total.store + (int64(fileStoreMsgSize(subj, hdr, msg)) * r)
2476 if selectedLimits.MaxStore >= 0 && totalStore > selectedLimits.MaxStore*lr {
2477 return true, nil
2478 }
2479 }
2480
2481 return false, nil
2482 }
2483
2484 // Check account limits.
2485 // Read Lock should be held
2486 func (js *jetStream) checkAccountLimits(selected *JetStreamAccountLimits, tier string, config *StreamConfig, currentRes int64) error {
2487 return js.checkLimits(selected, tier, config, false, currentRes, 0)
2488 }
2489
2490 // Check account and server limits.
2491 // Read Lock should be held
2492 func (js *jetStream) checkAllLimits(selected *JetStreamAccountLimits, tier string, config *StreamConfig, currentRes, maxBytesOffset int64) error {
2493 return js.checkLimits(selected, tier, config, true, currentRes, maxBytesOffset)
2494 }
2495
2496 // Check if a new proposed msg set while exceed our account limits.
2497 // Lock should be held.
2498 func (js *jetStream) checkLimits(selected *JetStreamAccountLimits, tier string, config *StreamConfig, checkServer bool, currentRes, maxBytesOffset int64) error {
2499 // Check MaxConsumers
2500 if config.MaxConsumers > 0 && selected.MaxConsumers > 0 && config.MaxConsumers > selected.MaxConsumers {
2501 return NewJSMaximumConsumersLimitError()
2502 }
2503 // stream limit is checked separately on stream create only!
2504 // Check storage, memory or disk.
2505 return js.checkBytesLimits(selected, tier, config.MaxBytes, config.Replicas, config.Storage, checkServer, currentRes, maxBytesOffset)
2506 }
2507
2508 // accountReservation returns how many bytes count against the account limit
2509 // for a stream with the given replica count. Un-tiered limits are flat, so R>1
2510 // is counted as Replicas*bytes; tiered limits already bake in replication.
2511 func accountReservation(tier string, replicas int, bytes int64) int64 {
2512 if bytes <= 0 {
2513 return 0
2514 }
2515 if tier == _EMPTY_ && replicas > 1 {
2516 return mulSaturate(int64(replicas), bytes)
2517 }
2518 return bytes
2519 }
2520
2521 // Check if additional bytes will exceed our account limits and optionally the server itself.
2522 // Read Lock should be held.
2523 func (js *jetStream) checkBytesLimits(selectedLimits *JetStreamAccountLimits, tier string, addBytes int64, replicas int, storage StorageType, checkServer bool, currentRes, maxBytesOffset int64) error {
2524 if addBytes < 0 {
2525 addBytes = 1
2526 }
2527 // The per-server footprint is a single replica's worth of bytes; the
2528 // account footprint additionally accounts for replication in un-tiered setups.
2529 serverBytes := addSaturate(addBytes, maxBytesOffset)
2530 accountBytes := accountReservation(tier, replicas, serverBytes)
2531
2532 switch storage {
2533 case MemoryStorage:
2534 // Account limits defined.
2535 if selectedLimits.MaxMemory >= 0 && (currentRes > selectedLimits.MaxMemory || accountBytes > selectedLimits.MaxMemory-currentRes) {
2536 return NewJSMemoryResourcesExceededError()
2537 }
2538 // Check if this server can handle request.
2539 if checkServer && (js.memReserved > js.config.MaxMemory || serverBytes > js.config.MaxMemory-js.memReserved) {
2540 return NewJSMemoryResourcesExceededError()
2541 }
2542 case FileStorage:
2543 // Account limits defined.
2544 if selectedLimits.MaxStore >= 0 && (currentRes > selectedLimits.MaxStore || accountBytes > selectedLimits.MaxStore-currentRes) {
2545 return NewJSStorageResourcesExceededError()
2546 }
2547 // Check if this server can handle request.
2548 if checkServer && (js.storeReserved > js.config.MaxStore || serverBytes > js.config.MaxStore-js.storeReserved) {
2549 return NewJSStorageResourcesExceededError()
2550 }
2551 }
2552
2553 return nil
2554 }
2555
2556 func (jsa *jsAccount) acc() *Account {
2557 return jsa.account
2558 }
2559
2560 // Delete the JetStream resources.
2561 func (jsa *jsAccount) delete() {
2562 var streams []*stream
2563
2564 jsa.mu.Lock()
2565 // The update timer and subs need to be protected by usageMu lock
2566 jsa.usageMu.Lock()
2567 if jsa.utimer != nil {
2568 jsa.utimer.Stop()
2569 jsa.utimer = nil
2570 }
2571 if jsa.updatesSub != nil && jsa.js.srv != nil {
2572 s := jsa.js.srv
2573 s.sysUnsubscribe(jsa.updatesSub)
2574 jsa.updatesSub = nil
2575 }
2576 jsa.usageMu.Unlock()
2577
2578 for _, ms := range jsa.streams {
2579 streams = append(streams, ms)
2580 }
2581 jsa.mu.Unlock()
2582
2583 for _, mset := range streams {
2584 mset.stop(false, false)
2585 }
2586 }
2587
2588 // Lookup the jetstream account for a given account.
2589 func (js *jetStream) lookupAccount(a *Account) *jsAccount {
2590 if a == nil {
2591 return nil
2592 }
2593 js.mu.RLock()
2594 jsa := js.accounts[a.Name]
2595 js.mu.RUnlock()
2596 return jsa
2597 }
2598
2599 // Report on JetStream stats and usage for this server.
2600 func (js *jetStream) usageStats() *JetStreamStats {
2601 var stats JetStreamStats
2602 js.mu.RLock()
2603 stats.Accounts = len(js.accounts)
2604 stats.ReservedMemory = uint64(js.memReserved)
2605 stats.ReservedStore = uint64(js.storeReserved)
2606 s := js.srv
2607 js.mu.RUnlock()
2608 stats.API.Level = JSApiLevel
2609 stats.API.Total = uint64(atomic.LoadInt64(&js.apiTotal))
2610 stats.API.Errors = uint64(atomic.LoadInt64(&js.apiErrors))
2611 stats.API.Inflight = uint64(atomic.LoadInt64(&js.apiInflight))
2612 // Make sure we do not report negative.
2613 used := atomic.LoadInt64(&js.memUsed)
2614 if used < 0 {
2615 used = 0
2616 }
2617 stats.Memory = uint64(used)
2618 used = atomic.LoadInt64(&js.storeUsed)
2619 if used < 0 {
2620 used = 0
2621 }
2622 stats.Store = uint64(used)
2623 stats.HAAssets = s.numRaftNodes()
2624 return &stats
2625 }
2626
2627 // Check to see if we have enough system resources for this account.
2628 // Lock should be held.
2629 func (js *jetStream) sufficientResources(limits map[string]JetStreamAccountLimits) error {
2630 // If we are clustered we do not really know how many resources will be ultimately available.
2631 // This needs to be handled out of band.
2632 // If we are a single server, we can make decisions here.
2633 if limits == nil || !js.standAlone {
2634 return nil
2635 }
2636
2637 totalMaxBytes := func(limits map[string]JetStreamAccountLimits) (int64, int64) {
2638 totalMaxMemory := int64(0)
2639 totalMaxStore := int64(0)
2640 for _, l := range limits {
2641 if l.MaxMemory > 0 {
2642 totalMaxMemory += l.MaxMemory
2643 }
2644 if l.MaxStore > 0 {
2645 totalMaxStore += l.MaxStore
2646 }
2647 }
2648 return totalMaxMemory, totalMaxStore
2649 }
2650
2651 totalMaxMemory, totalMaxStore := totalMaxBytes(limits)
2652
2653 // Reserved is now specific to the MaxBytes for streams.
2654 if js.memReserved+totalMaxMemory > js.config.MaxMemory {
2655 return NewJSMemoryResourcesExceededError()
2656 }
2657 // A dynamic limit is still provisional until recovery has run.
2658 recovering := js.config.maxStorePending
2659 if !recovering && js.storeReserved+totalMaxStore > js.config.MaxStore {
2660 return NewJSStorageResourcesExceededError()
2661 }
2662
2663 // Since we know if we are here we are single server mode, check the account reservations.
2664 var storeReserved, memReserved int64
2665 for _, jsa := range js.accounts {
2666 if jsa.account.IsExpired() {
2667 continue
2668 }
2669 jsa.usageMu.RLock()
2670 maxMemory, maxStore := totalMaxBytes(jsa.limits)
2671 jsa.usageMu.RUnlock()
2672 memReserved += maxMemory
2673 storeReserved += maxStore
2674 }
2675
2676 if memReserved+totalMaxMemory > js.config.MaxMemory {
2677 return NewJSMemoryResourcesExceededError()
2678 }
2679 if !recovering && storeReserved+totalMaxStore > js.config.MaxStore {
2680 return NewJSStorageResourcesExceededError()
2681 }
2682
2683 return nil
2684 }
2685
2686 // This will reserve the stream resources requested.
2687 // This will spin off off of MaxBytes.
2688 func (js *jetStream) reserveStreamResources(cfg *StreamConfig) {
2689 if cfg == nil || cfg.MaxBytes <= 0 {
2690 return
2691 }
2692
2693 js.mu.Lock()
2694 switch cfg.Storage {
2695 case MemoryStorage:
2696 js.memReserved += cfg.MaxBytes
2697 case FileStorage:
2698 js.storeReserved += cfg.MaxBytes
2699 }
2700 s, clustered := js.srv, !js.standAlone
2701 js.mu.Unlock()
2702 // If clustered send an update to the system immediately.
2703 if clustered {
2704 s.sendStatszUpdate()
2705 }
2706 }
2707
2708 // Release reserved resources held by a stream.
2709 func (js *jetStream) releaseStreamResources(cfg *StreamConfig) {
2710 if cfg == nil || cfg.MaxBytes <= 0 {
2711 return
2712 }
2713
2714 js.mu.Lock()
2715 switch cfg.Storage {
2716 case MemoryStorage:
2717 js.memReserved -= cfg.MaxBytes
2718 case FileStorage:
2719 js.storeReserved -= cfg.MaxBytes
2720 }
2721 s, clustered := js.srv, !js.standAlone
2722 js.mu.Unlock()
2723 // If clustered send an update to the system immediately.
2724 if clustered {
2725 s.sendStatszUpdate()
2726 }
2727 }
2728
2729 const (
2730 // JetStreamStoreDir is the prefix we use.
2731 JetStreamStoreDir = "jetstream"
2732 // JetStreamMaxStoreDefault is the default disk storage limit. 1TB
2733 JetStreamMaxStoreDefault = 1024 * 1024 * 1024 * 1024
2734 // JetStreamMaxMemDefault is only used when we can't determine system memory. 256MB
2735 JetStreamMaxMemDefault = 1024 * 1024 * 256
2736 // snapshot staging for restores.
2737 snapStagingDir = ".snap-staging"
2738 )
2739
2740 // Dynamically create a config with a tmp based directory (repeatable) and 75% of system memory.
2741 func (s *Server) dynJetStreamConfig(storeDir string, maxStore, maxMem int64) *JetStreamConfig {
2742 jsc := &JetStreamConfig{}
2743 if storeDir != _EMPTY_ {
2744 jsc.StoreDir = filepath.Join(storeDir, JetStreamStoreDir)
2745 } else {
2746 // Create one in tmp directory, but make it consistent for restarts.
2747 jsc.StoreDir = filepath.Join(os.TempDir(), "nats", JetStreamStoreDir)
2748 s.Warnf("Temporary storage directory used, data could be lost on system reboot")
2749 }
2750
2751 opts := s.getOpts()
2752
2753 // Strict mode.
2754 jsc.Strict = !opts.NoJetStreamStrict
2755
2756 // Sync options.
2757 jsc.SyncInterval = opts.SyncInterval
2758 jsc.SyncAlways = opts.SyncAlways
2759
2760 if maxStore > 0 || (opts.maxStoreSet && maxStore == 0) {
2761 jsc.MaxStore = maxStore
2762 } else {
2763 jsc.MaxStore = diskAvailable(jsc.StoreDir)
2764 jsc.maxStorePending = true
2765 }
2766
2767 if maxMem > 0 || (opts.maxMemSet && maxMem == 0) {
2768 jsc.MaxMemory = maxMem
2769 } else {
2770 // Estimate to 75% of total memory if we can determine system memory.
2771 if sysMem := sysmem.Memory(); sysMem > 0 {
2772 // Check if we have been limited with GOMEMLIMIT and if lower use that value.
2773 if gml := debug.SetMemoryLimit(-1); gml != math.MaxInt64 && gml < sysMem {
2774 s.Debugf("JetStream detected GOMEMLIMIT of %v", friendlyBytes(gml))
2775 sysMem = gml
2776 }
2777 jsc.MaxMemory = sysMem / 4 * 3
2778 } else {
2779 jsc.MaxMemory = JetStreamMaxMemDefault
2780 }
2781 }
2782
2783 return jsc
2784 }
2785
2786 // Helper function.
2787 func (a *Account) checkForJetStream() (*Server, *jsAccount, error) {
2788 a.mu.RLock()
2789 s := a.srv
2790 jsa := a.js
2791 a.mu.RUnlock()
2792
2793 if s == nil || jsa == nil {
2794 return nil, nil, NewJSNotEnabledForAccountError()
2795 }
2796
2797 return s, jsa, nil
2798 }
2799
2800 type Number interface {
2801 int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
2802 }
2803
2804 // friendlyBytes returns a string with the given bytes int64
2805 // represented as a size, such as 1KB, 10MB, etc...
2806 func friendlyBytes[T Number](bytes T) string {
2807 fbytes := float64(bytes)
2808 base := 1024
2809 pre := []string{"K", "M", "G", "T", "P", "E"}
2810 if fbytes < float64(base) {
2811 return fmt.Sprintf("%v B", fbytes)
2812 }
2813 exp := int(math.Log(fbytes) / math.Log(float64(base)))
2814 index := exp - 1
2815 return fmt.Sprintf("%.2f %sB", fbytes/math.Pow(float64(base), float64(exp)), pre[index])
2816 }
2817
2818 func isValidName(name string) bool {
2819 if name == _EMPTY_ {
2820 return false
2821 }
2822 return !strings.ContainsAny(name, " \t\r\n\f.*>")
2823 }
2824
2825 func isValidAssetName(name string) bool {
2826 if name == _EMPTY_ {
2827 return false
2828 }
2829 return !strings.ContainsAny(name, " \t\r\n\f.*>\\/")
2830 }
2831
2832 // To throttle the out of resources errors.
2833 func (s *Server) resourcesExceededError(storeType StorageType) {
2834 var didAlert bool
2835
2836 s.rerrMu.Lock()
2837 if now := time.Now(); now.Sub(s.rerrLast) > 10*time.Second {
2838 s.Errorf("JetStream %s resource limits exceeded for server", strings.ToLower(storeType.String()))
2839 s.rerrLast = now
2840 didAlert = true
2841 }
2842 s.rerrMu.Unlock()
2843
2844 // If we are meta leader we should relinquish that here.
2845 if didAlert {
2846 if js := s.getJetStream(); js != nil {
2847 js.mu.RLock()
2848 if cc := js.cluster; cc != nil && cc.meta != nil {
2849 cc.meta.StepDown()
2850 }
2851 js.mu.RUnlock()
2852 }
2853 }
2854 }
2855
2856 // For validating options.
2857 func validateJetStreamOptions(o *Options) error {
2858 // in non operator mode, the account names need to be configured
2859 if len(o.JsAccDefaultDomain) > 0 {
2860 if len(o.TrustedOperators) == 0 {
2861 for a, domain := range o.JsAccDefaultDomain {
2862 found := false
2863 if isReservedAccount(a) {
2864 found = true
2865 } else {
2866 for _, acc := range o.Accounts {
2867 if a == acc.GetName() {
2868 if len(acc.jsLimits) > 0 && domain != _EMPTY_ {
2869 return fmt.Errorf("default_js_domain contains account name %q with enabled JetStream", a)
2870 }
2871 found = true
2872 break
2873 }
2874 }
2875 }
2876 if !found {
2877 return fmt.Errorf("in non operator mode, `default_js_domain` references non existing account %q", a)
2878 }
2879 }
2880 } else {
2881 for a := range o.JsAccDefaultDomain {
2882 if !nkeys.IsValidPublicAccountKey(a) {
2883 return fmt.Errorf("default_js_domain contains account name %q, which is not a valid public account nkey", a)
2884 }
2885 }
2886 }
2887 for a, d := range o.JsAccDefaultDomain {
2888 sacc := DEFAULT_SYSTEM_ACCOUNT
2889 if o.SystemAccount != _EMPTY_ {
2890 sacc = o.SystemAccount
2891 }
2892 if a == sacc {
2893 return fmt.Errorf("system account %q can not be in default_js_domain", a)
2894 }
2895 if d == _EMPTY_ {
2896 continue
2897 }
2898 if sub := fmt.Sprintf(jsDomainAPI, d); !IsValidSubject(sub) {
2899 return fmt.Errorf("default_js_domain contains account %q with invalid domain name %q", a, d)
2900 }
2901 }
2902 }
2903 if o.JetStreamDomain != _EMPTY_ {
2904 if subj := fmt.Sprintf(jsDomainAPI, o.JetStreamDomain); !IsValidSubject(subj) {
2905 return fmt.Errorf("invalid domain name: derived %q is not a valid subject", subj)
2906 }
2907
2908 if !isValidName(o.JetStreamDomain) {
2909 return fmt.Errorf("invalid domain name: may not contain ., * or >")
2910 }
2911 }
2912 // If not clustered no checks needed past here.
2913 if !o.JetStream || o.Cluster.Port == 0 {
2914 return nil
2915 }
2916 if o.ServerName == _EMPTY_ {
2917 return fmt.Errorf("jetstream cluster requires `server_name` to be set")
2918 }
2919 if o.Cluster.Name == _EMPTY_ {
2920 return fmt.Errorf("jetstream cluster requires `cluster.name` to be set")
2921 }
2922
2923 h := strings.ToLower(o.JetStreamExtHint)
2924 switch h {
2925 case jsWillExtend, jsNoExtend, _EMPTY_:
2926 o.JetStreamExtHint = h
2927 default:
2928 return fmt.Errorf("expected 'no_extend' for string value, got '%s'", h)
2929 }
2930
2931 if o.JetStreamMaxCatchup < 0 {
2932 return fmt.Errorf("jetstream max catchup cannot be negative")
2933 }
2934 return nil
2935 }
2936
2937 // We had a bug that set a default de dupe window on mirror, despite that being not a valid config
2938 func fixCfgMirrorWithDedupWindow(cfg *StreamConfig) {
2939 if cfg == nil || cfg.Mirror == nil {
2940 return
2941 }
2942 if cfg.Duplicates != 0 {
2943 cfg.Duplicates = 0
2944 }
2945 }
2946
2947 func (s *Server) handleWritePermissionError() {
2948 //TODO Check if we should add s.jetStreamOOSPending in condition
2949 if s.JetStreamEnabled() {
2950 s.Errorf("File system permission denied while writing, disabling JetStream")
2951
2952 go s.ShutdownJetStream()
2953
2954 //TODO Send respective advisory if needed, same as in handleOutOfSpace
2955 }
2956 }