Debian Codegraph @

server/jetstream_cluster.go

raw
1 // Copyright 2020-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "cmp"
19 crand "crypto/rand"
20 "encoding/binary"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "iter"
25 "math"
26 "math/rand"
27 "os"
28 "path/filepath"
29 "reflect"
30 "slices"
31 "strconv"
32 "strings"
33 "sync"
34 "sync/atomic"
35 "time"
36
37 "github.com/antithesishq/antithesis-sdk-go/assert"
38 "github.com/klauspost/compress/s2"
39 "github.com/nats-io/nuid"
40 )
41
42 // jetStreamCluster holds information about the meta group and stream assignments.
43 type jetStreamCluster struct {
44 // The metacontroller raftNode.
45 meta RaftNode
46 // For stream and consumer assignments. All servers will have this be the same.
47 // ACCOUNT -> STREAM -> Stream Assignment -> Consumers
48 streams map[string]map[string]*streamAssignment
49 // These are inflight proposals and used to apply limits when there are
50 // concurrent requests that would otherwise be accepted.
51 // We also record the assignment for the stream/consumer. This is needed since if we have
52 // concurrent requests for same account and stream/consumer we need to let it process to get
53 // a response but they need to be same group, peers etc. and sync subjects.
54 inflightStreams map[string]map[string]*inflightStreamInfo
55 inflightConsumers map[string]map[string]map[string]*inflightConsumerInfo
56 // Tracks raft groups currently being started by createRaftGroup, so that
57 // concurrent callers for the same group can wait without holding js.mu
58 // across the disk I/O performed during startup.
59 creatingRaftGroups map[string]chan struct{}
60 // Holds a map of a peer ID to the reply subject, to only respond after gaining
61 // quorum on the peer-remove action.
62 peerRemoveReply map[string]peerRemoveInfo
63 // Raft term, used to determine if we are still the leader for the current term.
64 term uint64
65 // Signals meta-leader should check the stream assignments.
66 streamsCheck bool
67 // Server.
68 s *Server
69 // Internal client.
70 c *client
71 // Processing assignment results.
72 streamResults *subscription
73 consumerResults *subscription
74 // System level request to have the leader stepdown.
75 stepdown *subscription
76 // System level requests to remove a peer.
77 peerRemove *subscription
78 // System level request to move a stream
79 peerStreamMove *subscription
80 // System level request to cancel a stream move
81 peerStreamCancelMove *subscription
82 // To pop out the monitorCluster before the raft layer.
83 qch chan struct{}
84 // To notify others that monitorCluster has actually stopped.
85 stopped chan struct{}
86 // Track last meta snapshot time and duration for monitoring.
87 lastMetaSnapTime int64 // Unix nanoseconds
88 lastMetaSnapDuration int64 // Duration in nanoseconds
89 }
90
91 // Used to track inflight stream create/update/delete requests that have been proposed but not yet applied.
92 type inflightStreamInfo struct {
93 ops uint64 // Inflight operations, i.e. inflight stream creates/updates/deletes.
94 deleted bool // Whether the stream has been deleted.
95 *streamAssignment
96 }
97
98 // Used to track inflight consumer create/update/delete requests that have been proposed but not yet applied.
99 type inflightConsumerInfo struct {
100 ops uint64 // Inflight operations, i.e. inflight consumer creates/updates/deletes.
101 deleted bool // Whether the consumer has been deleted.
102 *consumerAssignment
103 }
104
105 // Used to track inflight peer-remove info to respond 'success' after quorum.
106 type peerRemoveInfo struct {
107 ci *ClientInfo
108 subject string
109 reply string
110 request string
111 }
112
113 // Used to guide placement of streams and meta controllers in clustered JetStream.
114 type Placement struct {
115 Cluster string `json:"cluster,omitempty"`
116 Tags []string `json:"tags,omitempty"`
117 Preferred string `json:"preferred,omitempty"`
118 }
119
120 // Define types of the entry.
121 type entryOp uint8
122
123 // ONLY ADD TO THE END, DO NOT INSERT IN BETWEEN WILL BREAK SERVER INTEROP.
124 const (
125 // Meta ops.
126 assignStreamOp entryOp = iota
127 assignConsumerOp
128 removeStreamOp
129 removeConsumerOp
130 // Stream ops.
131 streamMsgOp
132 purgeStreamOp
133 deleteMsgOp
134 // Consumer ops.
135 updateDeliveredOp
136 updateAcksOp
137 // Compressed consumer assignments.
138 assignCompressedConsumerOp
139 // Filtered Consumer skip.
140 updateSkipOp
141 // Update Stream.
142 updateStreamOp
143 // For updating information on pending pull requests.
144 addPendingRequest
145 removePendingRequest
146 // For sending compressed streams, either through RAFT or catchup.
147 compressedStreamMsgOp
148 // For sending deleted gaps on catchups for replicas.
149 deleteRangeOp
150 // Batch stream ops.
151 batchMsgOp
152 batchCommitMsgOp
153 // Consumer rest to specific starting sequence.
154 resetSeqOp
155 )
156
157 // raftGroups are controlled by the metagroup controller.
158 // The raftGroups will house streams and consumers.
159 type raftGroup struct {
160 Name string `json:"name"`
161 Peers []string `json:"peers"`
162 Storage StorageType `json:"store"`
163 Cluster string `json:"cluster,omitempty"`
164 Preferred string `json:"preferred,omitempty"`
165 ScaleUp bool `json:"scale_up,omitempty"`
166 // Internal
167 node RaftNode
168 }
169
170 // streamAssignment is what the meta controller uses to assign streams to peers.
171 type streamAssignment struct {
172 Client *ClientInfo `json:"client,omitempty"`
173 Created time.Time `json:"created"`
174 ConfigJSON json.RawMessage `json:"stream"`
175 Config *StreamConfig `json:"-"`
176 Group *raftGroup `json:"group"`
177 Sync string `json:"sync"`
178 Subject string `json:"subject,omitempty"`
179 Reply string `json:"reply,omitempty"`
180 Restore *StreamState `json:"restore_state,omitempty"`
181 // Internal
182 consumers map[string]*consumerAssignment
183 responded atomic.Bool // copied via clone() to satisfy go vet's noCopy check
184 recovering bool
185 reassigning bool // i.e. due to placement issues, lack of resources, etc.
186 resetting bool // i.e. there was an error, and we're stopping and starting the stream
187 err error
188 unsupported *unsupportedStreamAssignment
189 }
190
191 func (sa *streamAssignment) hasResponded() bool {
192 return sa.responded.Load()
193 }
194
195 // markResponded sets the responded flag and returns the prior value.
196 func (sa *streamAssignment) markResponded() bool {
197 return sa.responded.Swap(true)
198 }
199
200 func (sa *streamAssignment) clearResponded() {
201 sa.responded.Store(false)
202 }
203
204 // clone returns a copy of sa. Field-explicit (rather than `*sa`) and
205 // pointer-returning so the embedded atomic.Bool isn't value-copied;
206 // responded is transferred via Load/Store. Concurrent callers may write
207 // responded via markResponded/clearResponded without holding js.mu.
208 func (sa *streamAssignment) clone() *streamAssignment {
209 csa := &streamAssignment{
210 Client: sa.Client,
211 Created: sa.Created,
212 ConfigJSON: sa.ConfigJSON,
213 Config: sa.Config,
214 Group: sa.Group,
215 Sync: sa.Sync,
216 Subject: sa.Subject,
217 Reply: sa.Reply,
218 Restore: sa.Restore,
219 consumers: sa.consumers,
220 recovering: sa.recovering,
221 reassigning: sa.reassigning,
222 resetting: sa.resetting,
223 err: sa.err,
224 unsupported: sa.unsupported,
225 }
226 csa.responded.Store(sa.responded.Load())
227 return csa
228 }
229
230 type unsupportedStreamAssignment struct {
231 reason string
232 info StreamInfo
233 sysc *client
234 infoSub *subscription
235 }
236
237 func newUnsupportedStreamAssignment(s *Server, sa *streamAssignment, err error) *unsupportedStreamAssignment {
238 reason := "stopped"
239 if err != nil {
240 if errstr := err.Error(); strings.HasPrefix(errstr, "json:") {
241 reason = fmt.Sprintf("unsupported - config error: %s", strings.TrimPrefix(err.Error(), "json: "))
242 } else {
243 reason = fmt.Sprintf("stopped - %s", errstr)
244 }
245 } else if sa.Config != nil && !supportsRequiredApiLevel(sa.Config.Metadata) {
246 if req := getRequiredApiLevel(sa.Config.Metadata); req != _EMPTY_ {
247 reason = fmt.Sprintf("unsupported - required API level: %s, current API level: %d", req, JSApiLevel)
248 }
249 }
250 return &unsupportedStreamAssignment{
251 reason: reason,
252 info: StreamInfo{
253 Created: sa.Created,
254 Config: *setDynamicStreamMetadata(sa.Config),
255 Domain: s.getOpts().JetStreamDomain,
256 TimeStamp: time.Now().UTC(),
257 },
258 }
259 }
260
261 func (usa *unsupportedStreamAssignment) setupInfoSub(s *Server, sa *streamAssignment) {
262 if usa.infoSub != nil {
263 return
264 }
265
266 // Bind to the system account.
267 ic := s.createInternalJetStreamClient()
268 ic.registerWithAccount(s.SystemAccount())
269 usa.sysc = ic
270
271 // Note below the way we subscribe here is so that we can send requests to ourselves.
272 isubj := fmt.Sprintf(clusterStreamInfoT, sa.Client.serviceAccount(), sa.Config.Name)
273 usa.infoSub, _ = s.systemSubscribe(isubj, _EMPTY_, false, ic, usa.handleClusterStreamInfoRequest)
274 }
275
276 func (usa *unsupportedStreamAssignment) handleClusterStreamInfoRequest(_ *subscription, c *client, _ *Account, _, reply string, _ []byte) {
277 s, acc := c.srv, c.acc
278 info := streamInfoClusterResponse{OfflineReason: usa.reason, StreamInfo: usa.info}
279 s.sendDelayedErrResponse(acc, reply, nil, s.jsonResponse(&info), errRespDelay)
280 }
281
282 func (usa *unsupportedStreamAssignment) closeInfoSub(s *Server) {
283 if usa.infoSub != nil {
284 s.sysUnsubscribe(usa.infoSub)
285 usa.infoSub = nil
286 }
287 if usa.sysc != nil {
288 usa.sysc.closeConnection(ClientClosed)
289 usa.sysc = nil
290 }
291 }
292
293 // consumerAssignment is what the meta controller uses to assign consumers to streams.
294 type consumerAssignment struct {
295 Client *ClientInfo `json:"client,omitempty"`
296 Created time.Time `json:"created"`
297 Name string `json:"name"`
298 Stream string `json:"stream"`
299 ConfigJSON json.RawMessage `json:"consumer"`
300 Config *ConsumerConfig `json:"-"`
301 Group *raftGroup `json:"group"`
302 Subject string `json:"subject,omitempty"`
303 Reply string `json:"reply,omitempty"`
304 State *ConsumerState `json:"state,omitempty"`
305 // Internal
306 responded atomic.Bool // copied via clone() to satisfy go vet's noCopy check
307 recovering bool
308 err error
309 unsupported *unsupportedConsumerAssignment
310 }
311
312 func (ca *consumerAssignment) hasResponded() bool {
313 return ca.responded.Load()
314 }
315
316 // markResponded sets the responded flag and returns the prior value.
317 func (ca *consumerAssignment) markResponded() bool {
318 return ca.responded.Swap(true)
319 }
320
321 func (ca *consumerAssignment) clearResponded() {
322 ca.responded.Store(false)
323 }
324
325 // sameIdentity reports whether nca refers to the same logical consumer as ca.
326 // Only stable identity fields (Name, Stream, Group name, Created time) are
327 // compared; request-routing fields like Client/Reply and transient flags are
328 // intentionally excluded since processClusterCreateConsumer may set the
329 // per-object o.ca to a clone with the original requester's Client/Reply
330 // preserved while the meta-layer holds the newer values.
331 func (ca *consumerAssignment) sameIdentity(nca *consumerAssignment) bool {
332 return ca != nil && nca != nil &&
333 nca.Name == ca.Name &&
334 nca.Stream == ca.Stream &&
335 nca.Created.Equal(ca.Created) &&
336 nca.Group != nil && ca.Group != nil &&
337 nca.Group.Name == ca.Group.Name
338 }
339
340 // clone returns a copy of ca. Field-explicit (rather than `*ca`) and
341 // pointer-returning so the embedded atomic.Bool isn't value-copied;
342 // responded is transferred via Load/Store. Concurrent callers may write
343 // responded via markResponded/clearResponded without holding js.mu.
344 func (ca *consumerAssignment) clone() *consumerAssignment {
345 cca := &consumerAssignment{
346 Client: ca.Client,
347 Created: ca.Created,
348 Name: ca.Name,
349 Stream: ca.Stream,
350 ConfigJSON: ca.ConfigJSON,
351 Config: ca.Config,
352 Group: ca.Group,
353 Subject: ca.Subject,
354 Reply: ca.Reply,
355 State: ca.State,
356 recovering: ca.recovering,
357 err: ca.err,
358 unsupported: ca.unsupported,
359 }
360 cca.responded.Store(ca.responded.Load())
361 return cca
362 }
363
364 type unsupportedConsumerAssignment struct {
365 reason string
366 info ConsumerInfo
367 sysc *client
368 infoSub *subscription
369 }
370
371 func newUnsupportedConsumerAssignment(ca *consumerAssignment, err error) *unsupportedConsumerAssignment {
372 reason := "stopped"
373 if err != nil {
374 if errstr := err.Error(); strings.HasPrefix(errstr, "json:") {
375 reason = fmt.Sprintf("unsupported - config error: %s", strings.TrimPrefix(err.Error(), "json: "))
376 } else {
377 reason = fmt.Sprintf("stopped - %s", errstr)
378 }
379 } else if ca.Config != nil && !supportsRequiredApiLevel(ca.Config.Metadata) {
380 if req := getRequiredApiLevel(ca.Config.Metadata); req != _EMPTY_ {
381 reason = fmt.Sprintf("unsupported - required API level: %s, current API level: %d", getRequiredApiLevel(ca.Config.Metadata), JSApiLevel)
382 }
383 }
384 return &unsupportedConsumerAssignment{
385 reason: reason,
386 info: ConsumerInfo{
387 Stream: ca.Stream,
388 Name: ca.Name,
389 Created: ca.Created,
390 Config: setDynamicConsumerMetadata(ca.Config),
391 TimeStamp: time.Now().UTC(),
392 },
393 }
394 }
395
396 func (uca *unsupportedConsumerAssignment) setupInfoSub(s *Server, ca *consumerAssignment) {
397 if uca.infoSub != nil {
398 return
399 }
400
401 // Bind to the system account.
402 ic := s.createInternalJetStreamClient()
403 ic.registerWithAccount(s.SystemAccount())
404 uca.sysc = ic
405
406 // Note below the way we subscribe here is so that we can send requests to ourselves.
407 isubj := fmt.Sprintf(clusterConsumerInfoT, ca.Client.serviceAccount(), ca.Stream, ca.Name)
408 uca.infoSub, _ = s.systemSubscribe(isubj, _EMPTY_, false, ic, uca.handleClusterConsumerInfoRequest)
409 }
410
411 func (uca *unsupportedConsumerAssignment) handleClusterConsumerInfoRequest(_ *subscription, c *client, _ *Account, _, reply string, _ []byte) {
412 s, acc := c.srv, c.acc
413 info := consumerInfoClusterResponse{OfflineReason: uca.reason, ConsumerInfo: uca.info}
414 s.sendDelayedErrResponse(acc, reply, nil, s.jsonResponse(&info), errRespDelay)
415 }
416
417 func (uca *unsupportedConsumerAssignment) closeInfoSub(s *Server) {
418 if uca.infoSub != nil {
419 s.sysUnsubscribe(uca.infoSub)
420 uca.infoSub = nil
421 }
422 if uca.sysc != nil {
423 uca.sysc.closeConnection(ClientClosed)
424 uca.sysc = nil
425 }
426 }
427
428 type writeableConsumerAssignment struct {
429 Client *ClientInfo `json:"client,omitempty"`
430 Created time.Time `json:"created"`
431 Name string `json:"name"`
432 Stream string `json:"stream"`
433 ConfigJSON json.RawMessage `json:"consumer"`
434 Group *raftGroup `json:"group"`
435 }
436
437 // streamPurge is what the stream leader will replicate when purging a stream.
438 type streamPurge struct {
439 Client *ClientInfo `json:"client,omitempty"`
440 Stream string `json:"stream"`
441 LastSeq uint64 `json:"last_seq"`
442 Subject string `json:"subject"`
443 Reply string `json:"reply"`
444 Request *JSApiStreamPurgeRequest `json:"request,omitempty"`
445 }
446
447 // streamMsgDelete is what the stream leader will replicate when deleting a message.
448 type streamMsgDelete struct {
449 Client *ClientInfo `json:"client,omitempty"`
450 Stream string `json:"stream"`
451 Seq uint64 `json:"seq"`
452 NoErase bool `json:"no_erase,omitempty"`
453 Subject string `json:"subject"`
454 Reply string `json:"reply"`
455 }
456
457 const (
458 defaultStoreDirName = "_js_"
459 defaultMetaGroupName = "_meta_"
460 defaultMetaFSBlkSize = 1024 * 1024
461 jsExcludePlacement = "!jetstream"
462 )
463
464 // Returns information useful in mixed mode.
465 func (s *Server) trackedJetStreamServers() (js, total int) {
466 s.mu.RLock()
467 defer s.mu.RUnlock()
468 if !s.isRunning() || !s.eventsEnabled() {
469 return -1, -1
470 }
471 s.nodeToInfo.Range(func(k, v any) bool {
472 si := v.(nodeInfo)
473 if si.js {
474 js++
475 }
476 total++
477 return true
478 })
479 return js, total
480 }
481
482 func (s *Server) getJetStreamCluster() (*jetStream, *jetStreamCluster) {
483 if s.isShuttingDown() {
484 return nil, nil
485 }
486
487 js := s.getJetStream()
488 if js == nil {
489 return nil, nil
490 }
491
492 // Only set once, do not need a lock.
493 return js, js.cluster
494 }
495
496 func (s *Server) JetStreamIsClustered() bool {
497 return s.jsClustered.Load()
498 }
499
500 func (s *Server) JetStreamIsLeader() bool {
501 return s.isMetaLeader.Load()
502 }
503
504 func (s *Server) JetStreamIsCurrent() bool {
505 js := s.getJetStream()
506 if js == nil {
507 return false
508 }
509 // Grab what we need and release js lock.
510 js.mu.RLock()
511 var meta RaftNode
512 cc := js.cluster
513 if cc != nil {
514 meta = cc.meta
515 }
516 js.mu.RUnlock()
517
518 if cc == nil {
519 // Non-clustered mode
520 return true
521 }
522 return meta.Current()
523 }
524
525 func (s *Server) JetStreamSnapshotMeta() error {
526 js := s.getJetStream()
527 if js == nil {
528 return NewJSNotEnabledError()
529 }
530 js.mu.RLock()
531 cc := js.cluster
532 isLeader := cc.isLeader()
533 meta := cc.meta
534 js.mu.RUnlock()
535
536 if !isLeader {
537 return errNotLeader
538 }
539
540 snap, _, _, err := js.metaSnapshot()
541 if err != nil {
542 return err
543 }
544
545 return meta.InstallSnapshot(snap, false)
546 }
547
548 func (s *Server) JetStreamStepdownStream(account, stream string) error {
549 js, cc := s.getJetStreamCluster()
550 if js == nil {
551 return NewJSNotEnabledError()
552 }
553 if cc == nil {
554 return NewJSClusterNotActiveError()
555 }
556 // Grab account
557 acc, err := s.LookupAccount(account)
558 if err != nil {
559 return err
560 }
561 // Grab stream
562 mset, err := acc.lookupStream(stream)
563 if err != nil {
564 return err
565 }
566
567 if node := mset.raftNode(); node != nil {
568 node.StepDown()
569 }
570
571 return nil
572 }
573
574 func (s *Server) JetStreamStepdownConsumer(account, stream, consumer string) error {
575 js, cc := s.getJetStreamCluster()
576 if js == nil {
577 return NewJSNotEnabledError()
578 }
579 if cc == nil {
580 return NewJSClusterNotActiveError()
581 }
582 // Grab account
583 acc, err := s.LookupAccount(account)
584 if err != nil {
585 return err
586 }
587 // Grab stream
588 mset, err := acc.lookupStream(stream)
589 if err != nil {
590 return err
591 }
592
593 o := mset.lookupConsumer(consumer)
594 if o == nil {
595 return NewJSConsumerNotFoundError()
596 }
597
598 if node := o.raftNode(); node != nil {
599 node.StepDown()
600 }
601
602 return nil
603 }
604
605 func (s *Server) JetStreamSnapshotStream(account, stream string) error {
606 js, cc := s.getJetStreamCluster()
607 if js == nil {
608 return NewJSNotEnabledForAccountError()
609 }
610 if cc == nil {
611 return NewJSClusterNotActiveError()
612 }
613 // Grab account
614 acc, err := s.LookupAccount(account)
615 if err != nil {
616 return err
617 }
618 // Grab stream
619 mset, err := acc.lookupStream(stream)
620 if err != nil {
621 return err
622 }
623
624 // Hold lock when installing snapshot.
625 mset.mu.Lock()
626 if mset.node == nil {
627 mset.mu.Unlock()
628 return nil
629 }
630 err = mset.node.InstallSnapshot(mset.stateSnapshotLocked(), false)
631 mset.mu.Unlock()
632
633 return err
634 }
635
636 func (s *Server) JetStreamClusterPeers() []string {
637 js := s.getJetStream()
638 if js == nil {
639 return nil
640 }
641 js.mu.RLock()
642 defer js.mu.RUnlock()
643
644 cc := js.cluster
645 if !cc.isLeader() || cc.meta == nil {
646 return nil
647 }
648 peers := cc.meta.Peers()
649 var nodes []string
650 for _, p := range peers {
651 si, ok := s.nodeToInfo.Load(p.ID)
652 if !ok || si == nil {
653 continue
654 }
655 ni := si.(nodeInfo)
656 // Ignore if offline, no JS, or no current stats have been received.
657 if ni.offline || !ni.js || ni.stats == nil {
658 continue
659 }
660 nodes = append(nodes, si.(nodeInfo).name)
661 }
662 return nodes
663 }
664
665 // Read lock should be held.
666 func (cc *jetStreamCluster) isLeader() bool {
667 if cc == nil {
668 // Non-clustered mode
669 return true
670 }
671 return cc.meta != nil && cc.meta.Leader()
672 }
673
674 // isStreamCurrent will determine if the stream is up to date.
675 // For R1 it will make sure the stream is present on this server.
676 // Read lock should be held.
677 func (cc *jetStreamCluster) isStreamCurrent(account, stream string) bool {
678 if cc == nil {
679 // Non-clustered mode
680 return true
681 }
682 as := cc.streams[account]
683 if as == nil {
684 return false
685 }
686 sa := as[stream]
687 if sa == nil {
688 return false
689 }
690 rg := sa.Group
691 if rg == nil {
692 return false
693 }
694
695 if rg.node == nil || rg.node.Current() {
696 // Check if we are processing a snapshot and are catching up.
697 acc, err := cc.s.LookupAccount(account)
698 if err != nil {
699 return false
700 }
701 mset, err := acc.lookupStream(stream)
702 if err != nil {
703 return false
704 }
705 if mset.isCatchingUp() {
706 return false
707 }
708 // Success.
709 return true
710 }
711
712 return false
713 }
714
715 // isStreamHealthy will determine if the stream is up to date or very close.
716 // For R1 it will make sure the stream is present on this server.
717 func (js *jetStream) isStreamHealthy(acc *Account, sa *streamAssignment) error {
718 js.mu.RLock()
719 if sa != nil && sa.unsupported != nil {
720 js.mu.RUnlock()
721 return nil
722 }
723 s, cc := js.srv, js.cluster
724 if cc == nil {
725 // Non-clustered mode
726 js.mu.RUnlock()
727 return nil
728 }
729 if sa == nil || sa.Group == nil {
730 js.mu.RUnlock()
731 return errors.New("stream assignment or group missing")
732 }
733 // Surface any persisted assignment-level error (e.g. failed create on this
734 // peer due to account limits) so the health check reflects the broken state
735 // instead of falling through to runtime-only checks.
736 if sa.err != nil {
737 err := sa.err
738 js.mu.RUnlock()
739 return fmt.Errorf("stream assignment error: %w", err)
740 }
741 streamName := sa.Config.Name
742 node := sa.Group.node
743 js.mu.RUnlock()
744
745 // First lookup stream and make sure its there.
746 mset, err := acc.lookupStream(streamName)
747 if err != nil {
748 return errors.New("stream not found")
749 }
750
751 msetNode := mset.raftNode()
752 mset.cfgMu.RLock()
753 replicas := mset.cfg.Replicas
754 mset.cfgMu.RUnlock()
755 var nrgWerr error
756 if node != nil {
757 nrgWerr = node.GetWriteErr()
758 }
759 streamWerr := mset.getWriteErr()
760 switch {
761 case replicas <= 1:
762 return nil // No further checks for R=1 streams
763
764 case node == nil:
765 return errors.New("group node missing")
766
767 case msetNode == nil:
768 // Can happen when the stream's node is not yet initialized.
769 return errors.New("stream node missing")
770
771 case node != msetNode:
772 s.Warnf("Detected stream cluster node skew '%s > %s'", acc.GetName(), streamName)
773 return errors.New("cluster node skew detected")
774
775 case nrgWerr != nil:
776 return fmt.Errorf("node write error: %v", nrgWerr)
777
778 case streamWerr != nil:
779 return fmt.Errorf("stream write error: %v", streamWerr)
780
781 case !mset.isMonitorRunning():
782 return errors.New("monitor goroutine not running")
783
784 case mset.isCatchingUp():
785 return errors.New("stream catching up")
786
787 case !node.Healthy():
788 return errors.New("group node unhealthy")
789
790 default:
791 return nil
792 }
793 }
794
795 // isConsumerHealthy will determine if the consumer is up to date.
796 // For R1 it will make sure the consunmer is present on this server.
797 func (js *jetStream) isConsumerHealthy(mset *stream, consumer string, ca *consumerAssignment) error {
798 js.mu.RLock()
799 if ca != nil && ca.unsupported != nil {
800 js.mu.RUnlock()
801 return nil
802 }
803 if mset == nil {
804 js.mu.RUnlock()
805 return errors.New("stream missing")
806 }
807 s, cc := js.srv, js.cluster
808 if cc == nil {
809 // Non-clustered mode
810 js.mu.RUnlock()
811 return nil
812 }
813 if ca == nil || ca.Group == nil {
814 js.mu.RUnlock()
815 return errors.New("consumer assignment or group missing")
816 }
817 // Surface any persisted assignment-level error (e.g. failed create on this
818 // peer) so the health check reflects the broken state instead of falling
819 // through to runtime-only checks.
820 if ca.err != nil {
821 err := ca.err
822 js.mu.RUnlock()
823 return fmt.Errorf("consumer assignment error: %w", err)
824 }
825 created := ca.Created
826 node := ca.Group.node
827 js.mu.RUnlock()
828
829 // Check if not running at all.
830 o := mset.lookupConsumer(consumer)
831 if o == nil {
832 if time.Since(created) < 5*time.Second {
833 // No further checks, consumer is not available yet but should be soon.
834 // We'll start erroring once we're sure this consumer is actually broken.
835 return nil
836 }
837 return errors.New("consumer not found")
838 }
839
840 oNode := o.raftNode()
841 rc, _ := o.replica()
842 var nrgWerr error
843 if node != nil {
844 nrgWerr = node.GetWriteErr()
845 }
846 switch {
847 case rc <= 1:
848 return nil // No further checks for R=1 consumers
849
850 case node == nil:
851 return errors.New("group node missing")
852
853 case oNode == nil:
854 // Can happen when the consumer's node is not yet initialized.
855 return errors.New("consumer node missing")
856
857 case node != oNode:
858 mset.mu.RLock()
859 accName, streamName := mset.acc.GetName(), mset.cfg.Name
860 mset.mu.RUnlock()
861 s.Warnf("Detected consumer cluster node skew '%s > %s > %s'", accName, streamName, consumer)
862 return errors.New("cluster node skew detected")
863
864 case nrgWerr != nil:
865 return fmt.Errorf("node write error: %v", nrgWerr)
866
867 case !o.isMonitorRunning():
868 return errors.New("monitor goroutine not running")
869
870 case !node.Healthy():
871 return errors.New("group node unhealthy")
872
873 default:
874 return nil
875 }
876 }
877
878 // subjectsOverlap checks all existing stream assignments for the account cross-cluster for subject overlap
879 // Use only for clustered JetStream
880 // Read lock should be held.
881 func (js *jetStream) subjectsOverlap(acc string, subjects []string, osa *streamAssignment) bool {
882 for sa := range js.streamAssignmentsOrInflightSeq(acc) {
883 // can't overlap yourself, assume osa pre-checked for deep equal if passed
884 if osa != nil && sa.Config.Name == osa.Config.Name {
885 continue
886 }
887 for _, subj := range sa.Config.Subjects {
888 for _, tsubj := range subjects {
889 if SubjectsCollide(tsubj, subj) {
890 return true
891 }
892 }
893 }
894 }
895 return false
896 }
897
898 func (a *Account) getJetStreamFromAccount() (*Server, *jetStream, *jsAccount) {
899 a.mu.RLock()
900 jsa := a.js
901 a.mu.RUnlock()
902 if jsa == nil {
903 return nil, nil, nil
904 }
905 jsa.mu.RLock()
906 js := jsa.js
907 jsa.mu.RUnlock()
908 if js == nil {
909 return nil, nil, nil
910 }
911 // Lock not needed, set on creation.
912 s := js.srv
913 return s, js, jsa
914 }
915
916 func (s *Server) JetStreamIsStreamLeader(account, stream string) bool {
917 js, cc := s.getJetStreamCluster()
918 if js == nil || cc == nil {
919 return false
920 }
921 js.mu.RLock()
922 defer js.mu.RUnlock()
923 return cc.isStreamLeader(account, stream)
924 }
925
926 func (a *Account) JetStreamIsStreamLeader(stream string) bool {
927 s, js, jsa := a.getJetStreamFromAccount()
928 if s == nil || js == nil || jsa == nil {
929 return false
930 }
931 js.mu.RLock()
932 defer js.mu.RUnlock()
933 return js.cluster.isStreamLeader(a.Name, stream)
934 }
935
936 func (s *Server) JetStreamIsStreamCurrent(account, stream string) bool {
937 js, cc := s.getJetStreamCluster()
938 if js == nil {
939 return false
940 }
941 js.mu.RLock()
942 defer js.mu.RUnlock()
943 return cc.isStreamCurrent(account, stream)
944 }
945
946 func (a *Account) JetStreamIsConsumerLeader(stream, consumer string) bool {
947 s, js, jsa := a.getJetStreamFromAccount()
948 if s == nil || js == nil || jsa == nil {
949 return false
950 }
951 js.mu.RLock()
952 defer js.mu.RUnlock()
953 return js.cluster.isConsumerLeader(a.Name, stream, consumer)
954 }
955
956 func (s *Server) JetStreamIsConsumerLeader(account, stream, consumer string) bool {
957 js, cc := s.getJetStreamCluster()
958 if js == nil || cc == nil {
959 return false
960 }
961 js.mu.RLock()
962 defer js.mu.RUnlock()
963 return cc.isConsumerLeader(account, stream, consumer)
964 }
965
966 func (s *Server) enableJetStreamClustering() error {
967 if !s.isRunning() {
968 return nil
969 }
970 js := s.getJetStream()
971 if js == nil {
972 return NewJSNotEnabledForAccountError()
973 }
974 // Already set.
975 if js.cluster != nil {
976 return nil
977 }
978
979 s.Noticef("Starting JetStream cluster")
980 // We need to determine if we have a stable cluster name and expected number of servers.
981 s.Debugf("JetStream cluster checking for stable cluster name and peers")
982
983 hasLeafNodeSystemShare := s.canExtendOtherDomain()
984 if s.isClusterNameDynamic() && !hasLeafNodeSystemShare {
985 return errors.New("JetStream cluster requires cluster name")
986 }
987 if s.configuredRoutes() == 0 && !hasLeafNodeSystemShare {
988 return errors.New("JetStream cluster requires configured routes or solicited leafnode for the system account")
989 }
990
991 return js.setupMetaGroup()
992 }
993
994 // isClustered returns if we are clustered.
995 // Lock should not be held.
996 func (js *jetStream) isClustered() bool {
997 // This is only ever set, no need for lock here.
998 return js.cluster != nil
999 }
1000
1001 // isClusteredNoLock returns if we are clustered, but unlike isClustered() does
1002 // not use the jetstream's lock, instead, uses an atomic operation.
1003 // There are situations where some code wants to know if we are clustered but
1004 // can't use js.isClustered() without causing a lock inversion.
1005 func (js *jetStream) isClusteredNoLock() bool {
1006 return atomic.LoadInt32(&js.clustered) == 1
1007 }
1008
1009 func (js *jetStream) setupMetaGroup() error {
1010 s := js.srv
1011 s.Noticef("Creating JetStream metadata controller")
1012
1013 // Setup our WAL for the metagroup.
1014 sysAcc := s.SystemAccount()
1015 if sysAcc == nil {
1016 return ErrNoSysAccount
1017 }
1018 storeDir := filepath.Join(js.config.StoreDir, sysAcc.Name, defaultStoreDirName, defaultMetaGroupName)
1019
1020 js.srv.optsMu.RLock()
1021 syncAlways := js.srv.opts.SyncAlways
1022 syncInterval := js.srv.opts.SyncInterval
1023 js.srv.optsMu.RUnlock()
1024 fs, err := newFileStoreWithCreated(
1025 FileStoreConfig{StoreDir: storeDir, BlockSize: defaultMetaFSBlkSize, AsyncFlush: false, SyncAlways: syncAlways, SyncInterval: syncInterval, srv: s},
1026 StreamConfig{Name: defaultMetaGroupName, Storage: FileStorage},
1027 time.Now().UTC(),
1028 s.jsKeyGen(s.getOpts().JetStreamKey, defaultMetaGroupName),
1029 s.jsKeyGen(s.getOpts().JetStreamOldKey, defaultMetaGroupName),
1030 )
1031 if err != nil {
1032 s.Errorf("Error creating filestore: %v", err)
1033 return err
1034 }
1035
1036 cfg := &RaftConfig{Name: defaultMetaGroupName, Store: storeDir, Log: fs, Recovering: true}
1037
1038 // If we are soliciting leafnode connections and we are sharing a system account and do not disable it with a hint,
1039 // we want to move to observer mode so that we extend the solicited cluster or supercluster but do not form our own.
1040 cfg.Observer = s.canExtendOtherDomain() && s.getOpts().JetStreamExtHint != jsNoExtend
1041
1042 var bootstrap bool
1043 if ps, err := readPeerState(s.diskIOSemaphore(), storeDir); err != nil {
1044 s.Noticef("JetStream cluster bootstrapping")
1045 bootstrap = true
1046 peers := s.ActivePeers()
1047 s.Debugf("JetStream cluster initial peers: %+v", peers)
1048 if err := s.bootstrapRaftNode(cfg, peers, false); err != nil {
1049 return err
1050 }
1051 if cfg.Observer {
1052 s.Noticef("Turning JetStream metadata controller Observer Mode on")
1053 s.Noticef("In cases where the JetStream domain is not intended to be extended through a SYS account leaf node connection")
1054 s.Noticef("and waiting for leader election until first contact is not acceptable,")
1055 s.Noticef(`manually disable Observer Mode by setting the JetStream Option "extension_hint: %s"`, jsNoExtend)
1056 }
1057 } else {
1058 s.Noticef("JetStream cluster recovering state")
1059 // correlate the value of observer with observations from a previous run.
1060 if cfg.Observer {
1061 switch ps.domainExt {
1062 case extExtended:
1063 s.Noticef("Keeping JetStream metadata controller Observer Mode on - due to previous contact")
1064 case extNotExtended:
1065 s.Noticef("Turning JetStream metadata controller Observer Mode off - due to previous contact")
1066 cfg.Observer = false
1067 case extUndetermined:
1068 s.Noticef("Turning JetStream metadata controller Observer Mode on - no previous contact")
1069 s.Noticef("In cases where the JetStream domain is not intended to be extended through a SYS account leaf node connection")
1070 s.Noticef("and waiting for leader election until first contact is not acceptable,")
1071 s.Noticef(`manually disable Observer Mode by setting the JetStream Option "extension_hint: %s"`, jsNoExtend)
1072 }
1073 } else {
1074 // To track possible configuration changes, responsible for an altered value of cfg.Observer,
1075 // set extension state to undetermined.
1076 ps.domainExt = extUndetermined
1077 if err := writePeerState(s.diskIOSemaphore(), storeDir, ps); err != nil {
1078 return err
1079 }
1080 }
1081 }
1082
1083 // Start up our meta node.
1084 n, err := s.startRaftNode(sysAcc.GetName(), cfg, pprofLabels{
1085 "type": "metaleader",
1086 "account": sysAcc.Name,
1087 })
1088 if err != nil {
1089 s.Warnf("Could not start metadata controller: %v", err)
1090 return err
1091 }
1092
1093 // If we are bootstrapped with no state, start campaign early.
1094 if bootstrap {
1095 n.Campaign()
1096 }
1097
1098 c := s.createInternalJetStreamClient()
1099
1100 js.mu.Lock()
1101 defer js.mu.Unlock()
1102 js.cluster = &jetStreamCluster{
1103 meta: n,
1104 streams: make(map[string]map[string]*streamAssignment),
1105 s: s,
1106 c: c,
1107 qch: make(chan struct{}),
1108 stopped: make(chan struct{}),
1109 }
1110 atomic.StoreInt32(&js.clustered, 1)
1111 c.registerWithAccount(sysAcc)
1112
1113 // Set to true before we start.
1114 js.metaRecovering = true
1115 js.srv.startGoRoutine(
1116 js.monitorCluster,
1117 pprofLabels{
1118 "type": "metaleader",
1119 "account": sysAcc.Name,
1120 },
1121 )
1122 return nil
1123 }
1124
1125 func (js *jetStream) getMetaGroup() RaftNode {
1126 js.mu.RLock()
1127 defer js.mu.RUnlock()
1128 if js.cluster == nil {
1129 return nil
1130 }
1131 return js.cluster.meta
1132 }
1133
1134 func (js *jetStream) server() *Server {
1135 // Lock not needed, only set once on creation.
1136 return js.srv
1137 }
1138
1139 // Will respond if we do not think we have a metacontroller leader.
1140 func (js *jetStream) isLeaderless() bool {
1141 js.mu.RLock()
1142 cc := js.cluster
1143 if cc == nil || cc.meta == nil {
1144 js.mu.RUnlock()
1145 return false
1146 }
1147 meta := cc.meta
1148 js.mu.RUnlock()
1149
1150 // If we don't have a leader.
1151 // Make sure we have been running for enough time.
1152 if meta.Leaderless() && time.Since(meta.Created()) > lostQuorumIntervalDefault {
1153 return true
1154 }
1155 return false
1156 }
1157
1158 // Will respond iff we are a member and we know we have no leader.
1159 func (js *jetStream) isGroupLeaderless(rg *raftGroup) bool {
1160 if rg == nil || js == nil {
1161 return false
1162 }
1163 js.mu.RLock()
1164 cc := js.cluster
1165 started := js.started
1166
1167 // If we are not a member we can not say..
1168 if cc.meta == nil {
1169 js.mu.RUnlock()
1170 return false
1171 }
1172 if !rg.isMember(cc.meta.ID()) {
1173 js.mu.RUnlock()
1174 return false
1175 }
1176 // Single peer groups always have a leader if we are here.
1177 if rg.node == nil {
1178 js.mu.RUnlock()
1179 return false
1180 }
1181 node := rg.node
1182 js.mu.RUnlock()
1183 // If we don't have a leader.
1184 if node.Leaderless() {
1185 // Threshold for jetstream startup.
1186 const startupThreshold = 10 * time.Second
1187
1188 if node.HadPreviousLeader() {
1189 // Make sure we have been running long enough to intelligently determine this.
1190 if time.Since(started) > startupThreshold {
1191 return true
1192 }
1193 }
1194 // Make sure we have been running for enough time.
1195 if time.Since(node.Created()) > lostQuorumIntervalDefault {
1196 return true
1197 }
1198 }
1199
1200 return false
1201 }
1202
1203 func (s *Server) JetStreamIsStreamAssigned(account, stream string) bool {
1204 js, cc := s.getJetStreamCluster()
1205 if js == nil || cc == nil {
1206 return false
1207 }
1208 acc, _ := s.LookupAccount(account)
1209 if acc == nil {
1210 return false
1211 }
1212 js.mu.RLock()
1213 assigned := cc.isStreamAssigned(acc, stream)
1214 js.mu.RUnlock()
1215 return assigned
1216 }
1217
1218 // streamAssigned informs us if this server has this stream assigned.
1219 func (jsa *jsAccount) streamAssigned(stream string) bool {
1220 jsa.mu.RLock()
1221 js, acc := jsa.js, jsa.account
1222 jsa.mu.RUnlock()
1223
1224 if js == nil {
1225 return false
1226 }
1227 js.mu.RLock()
1228 assigned := js.cluster.isStreamAssigned(acc, stream)
1229 js.mu.RUnlock()
1230 return assigned
1231 }
1232
1233 // Read lock should be held.
1234 func (cc *jetStreamCluster) isStreamAssigned(a *Account, stream string) bool {
1235 // Non-clustered mode always return true.
1236 if cc == nil {
1237 return true
1238 }
1239 if cc.meta == nil {
1240 return false
1241 }
1242 as := cc.streams[a.Name]
1243 if as == nil {
1244 return false
1245 }
1246 sa := as[stream]
1247 if sa == nil {
1248 return false
1249 }
1250 return sa.Group.isMember(cc.meta.ID())
1251 }
1252
1253 // Read lock should be held.
1254 func (cc *jetStreamCluster) isStreamLeader(account, stream string) bool {
1255 // Non-clustered mode always return true.
1256 if cc == nil {
1257 return true
1258 }
1259 if cc.meta == nil {
1260 return false
1261 }
1262
1263 var sa *streamAssignment
1264 if as := cc.streams[account]; as != nil {
1265 sa = as[stream]
1266 }
1267 if sa == nil {
1268 return false
1269 }
1270 rg := sa.Group
1271 if rg == nil {
1272 return false
1273 }
1274 // Check if we are the leader of this raftGroup assigned to the stream.
1275 ourID := cc.meta.ID()
1276 for _, peer := range rg.Peers {
1277 if peer == ourID {
1278 if len(rg.Peers) == 1 || (rg.node != nil && rg.node.Leader()) {
1279 return true
1280 }
1281 }
1282 }
1283 return false
1284 }
1285
1286 // Read lock should be held.
1287 func (cc *jetStreamCluster) isConsumerLeader(account, stream, consumer string) bool {
1288 // Non-clustered mode always return true.
1289 if cc == nil {
1290 return true
1291 }
1292 if cc.meta == nil {
1293 return false
1294 }
1295
1296 var sa *streamAssignment
1297 if as := cc.streams[account]; as != nil {
1298 sa = as[stream]
1299 }
1300 if sa == nil {
1301 return false
1302 }
1303 // Check if we are the leader of this raftGroup assigned to this consumer.
1304 ca := sa.consumers[consumer]
1305 if ca == nil {
1306 return false
1307 }
1308 rg := ca.Group
1309 ourID := cc.meta.ID()
1310 for _, peer := range rg.Peers {
1311 if peer == ourID {
1312 if len(rg.Peers) == 1 || (rg.node != nil && rg.node.Leader()) {
1313 return true
1314 }
1315 }
1316 }
1317 return false
1318 }
1319
1320 // Track the stream for the account `accName` in the inflight proposals map.
1321 // This is done after proposing a stream change.
1322 // (Write) Lock held on entry.
1323 func (cc *jetStreamCluster) trackInflightStreamProposal(accName string, sa *streamAssignment, deleted bool) {
1324 if cc.inflightStreams == nil {
1325 cc.inflightStreams = make(map[string]map[string]*inflightStreamInfo)
1326 }
1327 streams, ok := cc.inflightStreams[accName]
1328 if !ok {
1329 streams = make(map[string]*inflightStreamInfo)
1330 cc.inflightStreams[accName] = streams
1331 }
1332 if inflight, ok := streams[sa.Config.Name]; ok {
1333 inflight.ops++
1334 inflight.deleted = deleted
1335 inflight.streamAssignment = sa
1336 } else {
1337 streams[sa.Config.Name] = &inflightStreamInfo{1, deleted, sa}
1338 }
1339 }
1340
1341 // Remove the stream `streamName` for the account `accName` from the inflight proposals map.
1342 // This is done after successful create/update/delete.
1343 // (Write) Lock held on entry.
1344 func (cc *jetStreamCluster) removeInflightStreamProposal(accName, streamName string) {
1345 if streams, ok := cc.inflightStreams[accName]; !ok {
1346 return // No accounts.
1347 } else if inflight, ok := streams[streamName]; !ok {
1348 return // No changes for this stream.
1349 } else if inflight.ops > 1 {
1350 // Decrement one pending operation.
1351 inflight.ops--
1352 } else {
1353 // No pending operations left, clean up.
1354 delete(streams, streamName)
1355 if len(streams) == 0 {
1356 delete(cc.inflightStreams, accName)
1357 }
1358 }
1359 }
1360
1361 // Track the consumer for the `streamName` and account `accName` in the inflight proposals map.
1362 // This is done after proposing a consumer change.
1363 // (Write) Lock held on entry.
1364 func (cc *jetStreamCluster) trackInflightConsumerProposal(accName, streamName string, ca *consumerAssignment, deleted bool) {
1365 if cc.inflightConsumers == nil {
1366 cc.inflightConsumers = make(map[string]map[string]map[string]*inflightConsumerInfo)
1367 }
1368 streams, ok := cc.inflightConsumers[accName]
1369 if !ok {
1370 streams = make(map[string]map[string]*inflightConsumerInfo)
1371 cc.inflightConsumers[accName] = streams
1372 }
1373 consumers, ok := streams[streamName]
1374 if !ok {
1375 consumers = make(map[string]*inflightConsumerInfo)
1376 streams[streamName] = consumers
1377 }
1378 if inflight, ok := consumers[ca.Name]; ok {
1379 inflight.ops++
1380 inflight.deleted = deleted
1381 inflight.consumerAssignment = ca
1382 } else {
1383 consumers[ca.Name] = &inflightConsumerInfo{1, deleted, ca}
1384 }
1385 }
1386
1387 // Remove the consumer `consumerName` for the `streamName` and account `accName` from the inflight proposals map.
1388 // This is done after successful create/update/delete.
1389 // (Write) Lock held on entry.
1390 func (cc *jetStreamCluster) removeInflightConsumerProposal(accName, streamName, consumerName string) {
1391 if streams, ok := cc.inflightConsumers[accName]; !ok {
1392 return // No accounts.
1393 } else if consumers, ok := streams[streamName]; !ok {
1394 return // No streams.
1395 } else if inflight, ok := consumers[consumerName]; !ok {
1396 return // No changes for this consumer.
1397 } else if inflight.ops > 1 {
1398 // Decrement one pending operation.
1399 inflight.ops--
1400 } else {
1401 // No pending operations left, clean up.
1402 delete(consumers, consumerName)
1403 if len(consumers) == 0 {
1404 delete(streams, streamName)
1405 }
1406 if len(streams) == 0 {
1407 delete(cc.inflightConsumers, accName)
1408 }
1409 }
1410 }
1411
1412 // Return the cluster quit chan.
1413 func (js *jetStream) clusterQuitC() chan struct{} {
1414 js.mu.RLock()
1415 defer js.mu.RUnlock()
1416 if js.cluster != nil {
1417 return js.cluster.qch
1418 }
1419 return nil
1420 }
1421
1422 // Return the cluster stopped chan.
1423 func (js *jetStream) clusterStoppedC() chan struct{} {
1424 js.mu.RLock()
1425 defer js.mu.RUnlock()
1426 if js.cluster != nil {
1427 return js.cluster.stopped
1428 }
1429 return nil
1430 }
1431
1432 // Mark that the meta layer is recovering.
1433 func (js *jetStream) setMetaRecovering() {
1434 js.mu.Lock()
1435 defer js.mu.Unlock()
1436 if js.cluster != nil {
1437 // metaRecovering
1438 js.metaRecovering = true
1439 }
1440 }
1441
1442 // Mark that the meta layer is no longer recovering.
1443 func (js *jetStream) clearMetaRecovering() {
1444 js.mu.Lock()
1445 defer js.mu.Unlock()
1446 js.metaRecovering = false
1447 }
1448
1449 // Return whether the meta layer is recovering.
1450 func (js *jetStream) isMetaRecovering() bool {
1451 js.mu.RLock()
1452 defer js.mu.RUnlock()
1453 return js.metaRecovering
1454 }
1455
1456 // During recovery track any stream and consumer delete and update operations.
1457 type recoveryUpdates struct {
1458 removeStreams map[string]*streamAssignment
1459 removeConsumers map[string]map[string]*consumerAssignment
1460 addStreams map[string]*streamAssignment
1461 updateStreams map[string]*streamAssignment
1462 updateConsumers map[string]map[string]*consumerAssignment
1463 }
1464
1465 func (ru *recoveryUpdates) removeStream(sa *streamAssignment) {
1466 key := sa.recoveryKey()
1467 ru.removeStreams[key] = sa
1468 delete(ru.addStreams, key)
1469 delete(ru.updateStreams, key)
1470 delete(ru.updateConsumers, key)
1471 delete(ru.removeConsumers, key)
1472 }
1473
1474 func (ru *recoveryUpdates) addStream(sa *streamAssignment) {
1475 key := sa.recoveryKey()
1476 ru.addStreams[key] = sa
1477 // A fresh add supersedes any earlier staged update for this stream.
1478 delete(ru.updateStreams, key)
1479 }
1480
1481 func (ru *recoveryUpdates) updateStream(sa *streamAssignment) {
1482 key := sa.recoveryKey()
1483 ru.updateStreams[key] = sa
1484 }
1485
1486 func (ru *recoveryUpdates) removeConsumer(ca *consumerAssignment) {
1487 key := ca.recoveryKey()
1488 skey := ca.streamRecoveryKey()
1489 if _, ok := ru.removeConsumers[skey]; !ok {
1490 ru.removeConsumers[skey] = map[string]*consumerAssignment{}
1491 }
1492 ru.removeConsumers[skey][key] = ca
1493 if consumers, ok := ru.updateConsumers[skey]; ok {
1494 delete(consumers, key)
1495 }
1496 }
1497
1498 func (ru *recoveryUpdates) addOrUpdateConsumer(ca *consumerAssignment) {
1499 key := ca.recoveryKey()
1500 skey := ca.streamRecoveryKey()
1501 if _, ok := ru.updateConsumers[skey]; !ok {
1502 ru.updateConsumers[skey] = map[string]*consumerAssignment{}
1503 }
1504 ru.updateConsumers[skey][key] = ca
1505 }
1506
1507 // Called after recovery of the cluster on startup to check for any orphans.
1508 // Streams and consumers are recovered from disk, and the meta layer's mappings
1509 // should clean them up, but under crash scenarios there could be orphans.
1510 func (js *jetStream) checkForOrphans() {
1511 // Can not hold jetstream lock while trying to delete streams or consumers.
1512 js.mu.Lock()
1513 s, cc := js.srv, js.cluster
1514 s.Debugf("JetStream cluster checking for orphans")
1515
1516 // We only want to cleanup any orphans if we know we are current with the meta-leader.
1517 meta := cc.meta
1518 if meta == nil || meta.Leaderless() {
1519 js.mu.Unlock()
1520 s.Debugf("JetStream cluster skipping check for orphans, no meta-leader")
1521 return
1522 }
1523 if !meta.Healthy() {
1524 js.mu.Unlock()
1525 s.Debugf("JetStream cluster skipping check for orphans, not current with the meta-leader")
1526 return
1527 }
1528 streams, consumers := js.getOrphans()
1529 js.mu.Unlock()
1530
1531 for _, mset := range streams {
1532 mset.mu.RLock()
1533 accName, stream := mset.acc.Name, mset.cfg.Name
1534 mset.mu.RUnlock()
1535 s.Warnf("Detected orphaned stream '%s > %s', will cleanup", accName, stream)
1536 if err := mset.delete(); err != nil {
1537 s.Warnf("Deleting stream encountered an error: %v", err)
1538 }
1539 }
1540 for _, o := range consumers {
1541 o.mu.RLock()
1542 accName, mset, consumer := o.acc.Name, o.mset, o.name
1543 o.mu.RUnlock()
1544 stream := "N/A"
1545 if mset != nil {
1546 mset.mu.RLock()
1547 stream = mset.cfg.Name
1548 mset.mu.RUnlock()
1549 }
1550 if o.isDurable() {
1551 s.Warnf("Detected orphaned durable consumer '%s > %s > %s', will cleanup", accName, stream, consumer)
1552 } else {
1553 s.Debugf("Detected orphaned consumer '%s > %s > %s', will cleanup", accName, stream, consumer)
1554 }
1555
1556 if err := o.delete(); err != nil {
1557 s.Warnf("Deleting consumer encountered an error: %v", err)
1558 }
1559 }
1560 }
1561
1562 // Returns orphaned streams and consumers that were recovered from disk, but don't
1563 // exist as clustered stream/consumer assignments.
1564 // Lock should be held.
1565 func (js *jetStream) getOrphans() (streams []*stream, consumers []*consumer) {
1566 cc := js.cluster
1567 for accName, jsa := range js.accounts {
1568 asa := cc.streams[accName]
1569 jsa.mu.RLock()
1570 for stream, mset := range jsa.streams {
1571 if sa := asa[stream]; sa == nil {
1572 streams = append(streams, mset)
1573 } else {
1574 // This one is good, check consumers now.
1575 for _, o := range mset.getPublicConsumers() {
1576 if sa.consumers[o.String()] == nil {
1577 consumers = append(consumers, o)
1578 }
1579 }
1580 }
1581 }
1582 jsa.mu.RUnlock()
1583 }
1584 return streams, consumers
1585 }
1586
1587 func (js *jetStream) monitorCluster() {
1588 s, n := js.server(), js.getMetaGroup()
1589 qch, stopped, rqch, lch, aq := js.clusterQuitC(), js.clusterStoppedC(), n.QuitC(), n.LeadChangeC(), n.ApplyQ()
1590
1591 defer s.grWG.Done()
1592 defer close(stopped)
1593
1594 s.Debugf("Starting metadata monitor")
1595 defer s.Debugf("Exiting metadata monitor")
1596
1597 // Make sure to stop the raft group on exit to prevent accidental memory bloat.
1598 defer n.Stop()
1599 defer s.isMetaLeader.Store(false)
1600
1601 const compactInterval = time.Minute
1602 const compactMinInterval = 15 * time.Second
1603 t := time.NewTicker(compactInterval)
1604 defer t.Stop()
1605
1606 // Used to check cold boot cluster when possibly in mixed mode.
1607 const leaderCheckInterval = time.Second
1608 lt := time.NewTicker(leaderCheckInterval)
1609 defer lt.Stop()
1610
1611 // Check the general health once an hour.
1612 const healthCheckInterval = 1 * time.Hour
1613 ht := time.NewTicker(healthCheckInterval)
1614 defer ht.Stop()
1615
1616 // Utility to check health.
1617 checkHealth := func() {
1618 if hs := s.healthz(nil); hs.Error != _EMPTY_ {
1619 s.Warnf("%v", hs.Error)
1620 }
1621 }
1622
1623 var (
1624 isLeader bool
1625 lastSnapTime time.Time
1626 compactSizeMin = uint64(8 * 1024 * 1024) // 8MB
1627 minSnapDelta = 30 * time.Second
1628 )
1629
1630 // Highwayhash key for generating hashes.
1631 key := make([]byte, 32)
1632 crand.Read(key)
1633
1634 // Set to true to start.
1635 js.setMetaRecovering()
1636 recovering := true
1637
1638 // Snapshotting function.
1639 var (
1640 snapMu sync.Mutex
1641 snapshotting bool
1642 // The first snapshot we do after recovery should clean up most of the log.
1643 fallbackSnapshot = true
1644 // Suppress non-forced snapshots after an error. Timer-based snapshots will become forced.
1645 // If failures continue, we force a snapshot even if we were catching up others
1646 // (otherwise we might indefinitely stall and grow log size).
1647 failedSnapshots atomic.Uint32
1648 )
1649 doSnapshot := func(force bool) {
1650 // Suppress during recovery.
1651 // If snapshots have failed, and we're not forced to, we'll wait for the timer since it'll now be forced.
1652 if recovering || (!force && failedSnapshots.Load() > 0) {
1653 return
1654 }
1655 // Suppress if an async snapshot is already in progress.
1656 snapMu.Lock()
1657 if snapshotting {
1658 snapMu.Unlock()
1659 return
1660 }
1661 // Look up what the threshold is for compaction. Re-reading from config here as it is reloadable.
1662 js.srv.optsMu.RLock()
1663 ethresh := js.srv.opts.JetStreamMetaCompact
1664 szthresh := js.srv.opts.JetStreamMetaCompactSize
1665 // Allows reverting to sync/blocking snapshots instead of the default async snapshots.
1666 syncSnapshot := js.srv.opts.JetStreamMetaCompactSync
1667 js.srv.optsMu.RUnlock()
1668 // Work out our criteria for snapshotting.
1669 byEntries, bySize := ethresh > 0, szthresh > 0
1670 byNeither := !byEntries && !bySize
1671 // For the meta layer we want to snapshot when over the above threshold (which could be 0 by default).
1672 ne, nsz := n.Size()
1673 createSnapshot := force || byNeither || (byEntries && ne > ethresh) || (bySize && nsz > szthresh) || n.NeedSnapshot()
1674 if !createSnapshot {
1675 snapMu.Unlock()
1676 return
1677 }
1678
1679 // Start a checkpoint, we can either install the snapshot sync or async from here.
1680 // If we had a significant number of failed snapshots, start relaxing Raft-layer checks
1681 // to force it through. We might have been catching up a peer for a long period, and this
1682 // protects our log size from growing indefinitely.
1683 forceSnapshot := failedSnapshots.Load() > 4
1684 c, err := n.CreateSnapshotCheckpoint(forceSnapshot)
1685 if err != nil {
1686 if err != errNoSnapAvailable && err != errNodeClosed {
1687 s.Warnf("Error snapshotting JetStream cluster state: %v", err)
1688 // If this is the first failure, reduce the interval of the snapshot timer.
1689 // This ensures we're not waiting too long for snapshotting to eventually become forced.
1690 if failedSnapshots.Load() == 0 {
1691 t.Reset(compactMinInterval)
1692 }
1693 failedSnapshots.Add(1)
1694 }
1695 snapMu.Unlock()
1696 return
1697 }
1698
1699 // If we're meant to install an async snapshot, check if the underlying log has grown way too large.
1700 // In that case, we fall back to a synchronous/blocking snapshot after all. This is a protective
1701 // measure to prevent the log from growing faster than we can asynchronously compact.
1702 if !fallbackSnapshot && !syncSnapshot {
1703 if szthresh == 0 {
1704 szthresh = compactSizeMin
1705 }
1706 if thresh := 10 * szthresh; nsz >= thresh {
1707 s.rateLimitFormatWarnf("JetStream cluster metalayer log size has exceeded async threshold (%s), will fall back to blocking snapshot", friendlyBytes(thresh))
1708 fallbackSnapshot = true
1709 }
1710 }
1711
1712 // Check if we should fall back to a blocking snapshot, either due to failures or extreme log size.
1713 if fallbackSnapshot || syncSnapshot {
1714 if !syncSnapshot {
1715 s.rateLimitFormatWarnf("Metalayer blocking snapshot starting")
1716 }
1717 start := time.Now()
1718 snap, nsa, nca, err := js.metaSnapshot()
1719 if err != nil {
1720 s.Warnf("Error generating JetStream cluster snapshot: %v", err)
1721 c.Abort()
1722 } else if csz, err := c.InstallSnapshot(snap); err == nil {
1723 lastSnapTime = time.Now()
1724 // If there was a failed snapshot before, we reduced the timer's interval.
1725 // Reset it back to the original interval now.
1726 if failedSnapshots.Load() > 0 {
1727 t.Reset(compactInterval)
1728 }
1729 failedSnapshots.Store(0)
1730 // Fallback snapshot was successful, the next one can be async again.
1731 fallbackSnapshot = false
1732 took := time.Since(start)
1733 if !syncSnapshot || took > 2*time.Second {
1734 s.rateLimitFormatWarnf("Metalayer blocking snapshot took %.3fs (streams: %d, consumers: %d, compacted: %s)",
1735 took.Seconds(), nsa, nca, friendlyBytes(csz))
1736 }
1737 } else {
1738 c.Abort()
1739 if err != errNoSnapAvailable && err != errNodeClosed && err != errSnapAborted {
1740 s.Warnf("Error snapshotting JetStream cluster state: %v", err)
1741 // If this is the first failure, reduce the interval of the snapshot timer.
1742 // This ensures we're not waiting too long for snapshotting to eventually become forced.
1743 if failedSnapshots.Load() == 0 {
1744 t.Reset(compactMinInterval)
1745 }
1746 failedSnapshots.Add(1)
1747 }
1748 }
1749 snapMu.Unlock()
1750 return
1751 }
1752
1753 // Perform the snapshot asynchronously.
1754 start := time.Now()
1755 snapshotting = true
1756 snapMu.Unlock()
1757 s.startGoRoutine(func() {
1758 defer s.grWG.Done()
1759
1760 abort := func(err error) {
1761 snapMu.Lock()
1762 c.Abort()
1763 if err != errNoSnapAvailable && err != errNodeClosed && err != errSnapAborted {
1764 s.Warnf("Error snapshotting JetStream cluster state: %v, will fall back to blocking snapshot", err)
1765 fallbackSnapshot = true
1766 // If this is the first failure, reduce the interval of the snapshot timer.
1767 // This ensures we're not waiting too long for snapshotting to eventually become forced.
1768 if failedSnapshots.Load() == 0 {
1769 t.Reset(compactMinInterval)
1770 }
1771 failedSnapshots.Add(1)
1772 }
1773 snapshotting = false
1774 snapMu.Unlock()
1775 }
1776
1777 // The strategy of asynchronous snapshotting:
1778 // - Not holding any locks. Only minimal for the Raft node itself, importantly not the JS lock.
1779 // - Load the last snapshot.
1780 // - Replay stream/consumer changes through the assignment state machine.
1781 // - Encode and install as the new snapshot.
1782 if data, err := c.LoadLastSnapshot(); err != nil && err != errNoSnapAvailable {
1783 abort(err)
1784 } else if streams, err := js.decodeMetaSnapshot(data); err != nil {
1785 abort(err)
1786 } else if err = js.collectStreamAndConsumerChanges(c, streams); err != nil {
1787 abort(err)
1788 } else if snap, nsa, nca, err := js.encodeMetaSnapshot(streams); err != nil {
1789 abort(err)
1790 } else if csz, err := c.InstallSnapshot(snap); err != nil {
1791 abort(err)
1792 } else {
1793 // Successful snapshot.
1794 // If there was a failed snapshot before, we reduced the timer's interval.
1795 // Reset it back to the original interval now.
1796 if failedSnapshots.Load() > 0 {
1797 t.Reset(compactInterval)
1798 }
1799 failedSnapshots.Store(0)
1800 if took := time.Since(start); took > 2*time.Second {
1801 s.rateLimitFormatWarnf("Metalayer async snapshot took %.3fs (streams: %d, consumers: %d, compacted: %s)",
1802 took.Seconds(), nsa, nca, friendlyBytes(csz))
1803 }
1804 snapMu.Lock()
1805 lastSnapTime = time.Now()
1806 snapshotting = false
1807 snapMu.Unlock()
1808 }
1809 })
1810 }
1811
1812 var ru *recoveryUpdates
1813
1814 // Make sure to cancel any pending checkForOrphans calls if the
1815 // monitor goroutine exits.
1816 var oc *time.Timer
1817 defer stopAndClearTimer(&oc)
1818
1819 for {
1820 select {
1821 case <-s.quitCh:
1822 // Server shutting down, but we might receive this before qch, so try to snapshot.
1823 snapMu.Lock()
1824 fallbackSnapshot = true
1825 snapMu.Unlock()
1826 doSnapshot(false)
1827 return
1828 case <-rqch:
1829 // Raft node is closed, no use in trying to snapshot.
1830 return
1831 case <-qch:
1832 // Clean signal from shutdown routine so do best effort attempt to snapshot meta layer.
1833 snapMu.Lock()
1834 fallbackSnapshot = true
1835 snapMu.Unlock()
1836 doSnapshot(false)
1837 return
1838 case <-aq.ch:
1839 ces := aq.pop()
1840 for _, ce := range ces {
1841 if recovering && ru == nil {
1842 ru = &recoveryUpdates{
1843 removeStreams: make(map[string]*streamAssignment),
1844 removeConsumers: make(map[string]map[string]*consumerAssignment),
1845 addStreams: make(map[string]*streamAssignment),
1846 updateStreams: make(map[string]*streamAssignment),
1847 updateConsumers: make(map[string]map[string]*consumerAssignment),
1848 }
1849 }
1850 if ce == nil {
1851 if ru != nil {
1852 // Process any removes that are still valid after recovery.
1853 for _, cas := range ru.removeConsumers {
1854 for _, ca := range cas {
1855 js.processConsumerRemoval(ca)
1856 }
1857 }
1858 for _, sa := range ru.removeStreams {
1859 js.processStreamRemoval(sa)
1860 }
1861 // Process stream additions.
1862 for _, sa := range ru.addStreams {
1863 js.processStreamAssignment(sa)
1864 }
1865 // Process pending updates.
1866 for _, sa := range ru.updateStreams {
1867 js.processUpdateStreamAssignment(sa)
1868 }
1869 // Now consumers.
1870 for _, cas := range ru.updateConsumers {
1871 for _, ca := range cas {
1872 js.processConsumerAssignment(ca)
1873 }
1874 }
1875 }
1876 // Signals we have replayed all of our metadata.
1877 wasMetaRecovering := js.isMetaRecovering()
1878 js.clearMetaRecovering()
1879 recovering = false
1880 // Clear.
1881 ru = nil
1882 s.Debugf("Recovered JetStream cluster metadata")
1883 // Snapshot now so we start with freshly compacted log.
1884 doSnapshot(true)
1885 if wasMetaRecovering {
1886 // Reset, it could be we didn't need to install a snapshot. This ensures we don't degrade
1887 // to a blocking snapshot if we install our first snapshot during normal operations.
1888 snapMu.Lock()
1889 fallbackSnapshot = false
1890 snapMu.Unlock()
1891 oc = time.AfterFunc(30*time.Second, js.checkForOrphans)
1892 // Do a health check here as well.
1893 go checkHealth()
1894 }
1895 continue
1896 }
1897 if isRecovering, didSnap, err := js.applyMetaEntries(ce.Entries, ru); err == nil {
1898 var nb uint64
1899 // Some entries can fail without an error when shutting down, don't move applied forward.
1900 if !js.isShuttingDown() {
1901 _, nb = n.Applied(ce.Index)
1902 }
1903 if js.hasPeerEntries(ce.Entries) || (didSnap && !isLeader) {
1904 doSnapshot(true)
1905 } else if nb > compactSizeMin {
1906 snapMu.Lock()
1907 expired := time.Since(lastSnapTime) > minSnapDelta
1908 snapMu.Unlock()
1909 if expired {
1910 doSnapshot(false)
1911 }
1912 }
1913 recovering = isRecovering
1914 } else {
1915 s.Warnf("Error applying JetStream cluster entries: %v", err)
1916 }
1917 ce.ReturnToPool()
1918 }
1919 aq.recycle(&ces)
1920
1921 case lc := <-lch:
1922 isLeader = lc.isLeader
1923 // Process the change.
1924 js.processLeaderChange(isLeader, lc.term)
1925 if isLeader {
1926 s.sendInternalMsgLocked(serverStatsPingReqSubj, _EMPTY_, nil, nil)
1927 // Install a snapshot as we become leader.
1928 js.checkClusterSize()
1929 doSnapshot(false)
1930 }
1931
1932 case <-t.C:
1933 // Start forcing snapshots if they failed previously.
1934 forceIfFailed := failedSnapshots.Load() > 0
1935 doSnapshot(forceIfFailed)
1936 // Periodically check the cluster size.
1937 if n.Leader() {
1938 js.checkClusterSize()
1939 }
1940 case <-ht.C:
1941 // Do this in a separate go routine.
1942 go checkHealth()
1943
1944 case <-lt.C:
1945 s.Debugf("Checking JetStream cluster state")
1946 // If we have a current leader or had one in the past we can cancel this here since the metaleader
1947 // will be in charge of all peer state changes.
1948 // For cold boot only.
1949 if !n.Leaderless() || n.HadPreviousLeader() {
1950 lt.Stop()
1951 continue
1952 }
1953 // If we are here we do not have a leader and we did not have a previous one, so cold start.
1954 // Check to see if we can adjust our cluster size down iff we are in mixed mode and we have
1955 // seen a total that is what our original estimate was.
1956 cs := n.ClusterSize()
1957 if js, total := s.trackedJetStreamServers(); js < total && total >= cs && js != cs {
1958 s.Noticef("Adjusting JetStream expected peer set size to %d from original %d", js, cs)
1959 n.AdjustBootClusterSize(js)
1960 }
1961 }
1962 }
1963 }
1964
1965 // This is called on first leader transition to double check the peers and cluster set size.
1966 func (js *jetStream) checkClusterSize() {
1967 s, n := js.server(), js.getMetaGroup()
1968 if n == nil {
1969 return
1970 }
1971 // We will check that we have a correct cluster set size by checking for any non-js servers
1972 // which can happen in mixed mode.
1973 ps := n.(*raft).currentPeerState()
1974 if len(ps.knownPeers) >= ps.clusterSize {
1975 return
1976 }
1977
1978 // Grab our active peers.
1979 peers := s.ActivePeers()
1980
1981 // If we have not registered all of our peers yet we can't do
1982 // any adjustments based on a mixed mode. We will periodically check back.
1983 if len(peers) < ps.clusterSize {
1984 return
1985 }
1986
1987 s.Debugf("Checking JetStream cluster size")
1988
1989 // If we are here our known set as the leader is not the same as the cluster size.
1990 // Check to see if we have a mixed mode setup.
1991 var totalJS int
1992 for _, p := range peers {
1993 if si, ok := s.nodeToInfo.Load(p); ok && si != nil {
1994 if si.(nodeInfo).js {
1995 totalJS++
1996 }
1997 }
1998 }
1999 // If we have less then our cluster size adjust that here. Can not do individual peer removals since
2000 // they will not be in the tracked peers.
2001 if totalJS < ps.clusterSize {
2002 s.Debugf("Adjusting JetStream cluster size from %d to %d", ps.clusterSize, totalJS)
2003 if err := n.AdjustClusterSize(totalJS); err != nil {
2004 s.Warnf("Error adjusting JetStream cluster size: %v", err)
2005 }
2006 }
2007 }
2008
2009 // Represents our stable meta state that we can write out.
2010 type writeableStreamAssignment struct {
2011 Client *ClientInfo `json:"client,omitempty"`
2012 Created time.Time `json:"created"`
2013 ConfigJSON json.RawMessage `json:"stream"`
2014 Group *raftGroup `json:"group"`
2015 Sync string `json:"sync"`
2016 Consumers []*writeableConsumerAssignment
2017 }
2018
2019 // Returns the stream config as registered in the meta layer, from an inflight
2020 // proposal that has not been applied yet, or from an applied assignment otherwise.
2021 func (js *jetStream) clusterStreamConfig(accName, streamName string) (StreamConfig, bool) {
2022 js.mu.RLock()
2023 defer js.mu.RUnlock()
2024 if sa := js.streamAssignmentOrInflight(accName, streamName); sa != nil {
2025 return *sa.Config, true
2026 }
2027 return StreamConfig{}, false
2028 }
2029
2030 func (js *jetStream) metaSnapshot() ([]byte, int, int, error) {
2031 js.mu.RLock()
2032 defer js.mu.RUnlock()
2033 cc := js.cluster
2034 return js.encodeMetaSnapshot(cc.streams)
2035 }
2036
2037 func (js *jetStream) applyMetaSnapshot(buf []byte, ru *recoveryUpdates, isRecovering bool) error {
2038 streams, err := js.decodeMetaSnapshot(buf)
2039 if err != nil {
2040 return err
2041 }
2042
2043 js.mu.Lock()
2044 cc := js.cluster
2045
2046 var saAdd, saDel, saChk []*streamAssignment
2047 // Walk through the old list to generate the delete list.
2048 for account, asa := range cc.streams {
2049 nasa := streams[account]
2050 for sn, sa := range asa {
2051 if nsa := nasa[sn]; nsa == nil {
2052 // Stream was removed.
2053 saDel = append(saDel, sa)
2054 } else if !nsa.Created.Equal(sa.Created) && (nsa.Group == nil || sa.Group == nil || nsa.Group.Name != sa.Group.Name) {
2055 // Stream was recreated.
2056 saDel = append(saDel, sa)
2057 saAdd = append(saAdd, nsa)
2058 } else {
2059 saChk = append(saChk, nsa)
2060 }
2061 }
2062 }
2063 // Walk through the new list to generate the add list.
2064 for account, nasa := range streams {
2065 asa := cc.streams[account]
2066 for sn, sa := range nasa {
2067 if asa[sn] == nil {
2068 saAdd = append(saAdd, sa)
2069 }
2070 }
2071 }
2072
2073 // Now walk the ones to check and process consumers.
2074 var caAdd, caDel []*consumerAssignment
2075 for _, sa := range saChk {
2076 // Make sure to add in all the new ones from sa.
2077 for _, ca := range sa.consumers {
2078 caAdd = append(caAdd, ca)
2079 }
2080 if osa := js.streamAssignment(sa.Client.serviceAccount(), sa.Config.Name); osa != nil {
2081 for _, ca := range osa.consumers {
2082 // Consumer was either removed or recreated.
2083 if nca := sa.consumers[ca.Name]; nca == nil {
2084 caDel = append(caDel, ca)
2085 } else if !nca.Created.Equal(ca.Created) && (nca.Group == nil || ca.Group == nil || nca.Group.Name != ca.Group.Name) {
2086 caDel = append(caDel, ca)
2087 }
2088 }
2089 }
2090 }
2091 js.mu.Unlock()
2092
2093 // Reconcile the staged recoveryUpdates against this snapshot. Any staged operations that the
2094 // snapshot does not contain should be dropped, otherwise deleted assets could be revived.
2095 if isRecovering && ru != nil {
2096 supersededStream := func(sa *streamAssignment) bool {
2097 acc := sa.Client.serviceAccount()
2098 return streams[acc] == nil || streams[acc][sa.Config.Name] == nil
2099 }
2100 supersededConsumer := func(ca *consumerAssignment) bool {
2101 nsa := streams[ca.Client.serviceAccount()][ca.Stream]
2102 return nsa == nil || nsa.consumers[ca.Name] == nil
2103 }
2104 for key, sa := range ru.addStreams {
2105 if supersededStream(sa) {
2106 delete(ru.addStreams, key)
2107 delete(ru.updateStreams, key)
2108 delete(ru.updateConsumers, key)
2109 delete(ru.removeConsumers, key)
2110 }
2111 }
2112 for key, sa := range ru.updateStreams {
2113 if supersededStream(sa) {
2114 delete(ru.updateStreams, key)
2115 delete(ru.updateConsumers, key)
2116 delete(ru.removeConsumers, key)
2117 }
2118 }
2119 for skey, consumers := range ru.updateConsumers {
2120 for ckey, ca := range consumers {
2121 if supersededConsumer(ca) {
2122 delete(consumers, ckey)
2123 }
2124 }
2125 if len(consumers) == 0 {
2126 delete(ru.updateConsumers, skey)
2127 }
2128 }
2129 }
2130
2131 // Do removals first.
2132 for _, sa := range saDel {
2133 js.setStreamAssignmentRecovering(sa)
2134 if isRecovering {
2135 ru.removeStream(sa)
2136 } else {
2137 js.processStreamRemoval(sa)
2138 }
2139 }
2140 // Now do add for the streams. Also add in all consumers.
2141 for _, sa := range saAdd {
2142 consumers := sa.consumers
2143 js.setStreamAssignmentRecovering(sa)
2144 if isRecovering {
2145 // Since we're recovering and storing up changes, we'll need to clear out these consumers.
2146 // Some might be removed, and we'll recover those later, must not be able to remember them.
2147 sa.consumers = nil
2148 ru.addStream(sa)
2149 } else {
2150 js.processStreamAssignment(sa)
2151 }
2152
2153 // We can simply process the consumers.
2154 for _, ca := range consumers {
2155 js.setConsumerAssignmentRecovering(ca)
2156 if isRecovering {
2157 ru.addOrUpdateConsumer(ca)
2158 } else {
2159 js.processConsumerAssignment(ca)
2160 }
2161 }
2162 }
2163
2164 // Perform updates on those in saChk. These were existing so make
2165 // sure to process any changes.
2166 for _, sa := range saChk {
2167 js.setStreamAssignmentRecovering(sa)
2168 if isRecovering {
2169 ru.updateStream(sa)
2170 } else {
2171 js.processUpdateStreamAssignment(sa)
2172 }
2173 }
2174
2175 // Now do the deltas for existing stream's consumers.
2176 for _, ca := range caDel {
2177 js.setConsumerAssignmentRecovering(ca)
2178 if isRecovering {
2179 ru.removeConsumer(ca)
2180 } else {
2181 js.processConsumerRemoval(ca)
2182 }
2183 }
2184 for _, ca := range caAdd {
2185 js.setConsumerAssignmentRecovering(ca)
2186 if isRecovering {
2187 ru.addOrUpdateConsumer(ca)
2188 } else {
2189 js.processConsumerAssignment(ca)
2190 }
2191 }
2192
2193 // If we're not recovering, we need to check if we have any left-over streams or consumers that aren't
2194 // tracked in our assignments. This could happen if we've restarted and recovered streams or consumers
2195 // from disk, but then got sent a snapshot to catch up from the meta-leader.
2196 if !isRecovering {
2197 // This logic is similar to that of checkForOrphans. But, this cleanup is focused on aligning with
2198 // a snapshot from a meta leader as a result of catchup. We silently delete them here, instead of
2199 // logging and sending out advisories.
2200 js.mu.RLock()
2201 deleteStreams, deleteConsumers := js.getOrphans()
2202 js.mu.RUnlock()
2203 for _, mset := range deleteStreams {
2204 mset.stop(true, false)
2205 }
2206 for _, o := range deleteConsumers {
2207 o.deleteWithoutAdvisory()
2208 }
2209 }
2210 return nil
2211 }
2212
2213 // Decode the meta snapshot from buf into the relevant stream and consumer assignments.
2214 func (js *jetStream) decodeMetaSnapshot(buf []byte) (map[string]map[string]*streamAssignment, error) {
2215 var wsas []writeableStreamAssignment
2216 if len(buf) > 0 {
2217 jse, err := s2.Decode(nil, buf)
2218 if err != nil {
2219 return nil, err
2220 }
2221 if err = json.Unmarshal(jse, &wsas); err != nil {
2222 return nil, err
2223 }
2224 }
2225
2226 // Build our new version here outside of js.
2227 streams := make(map[string]map[string]*streamAssignment)
2228 for _, wsa := range wsas {
2229 as := streams[wsa.Client.serviceAccount()]
2230 if as == nil {
2231 as = make(map[string]*streamAssignment)
2232 streams[wsa.Client.serviceAccount()] = as
2233 }
2234 sa := &streamAssignment{Client: wsa.Client, Created: wsa.Created, ConfigJSON: wsa.ConfigJSON, Group: wsa.Group, Sync: wsa.Sync}
2235 if err := decodeStreamAssignmentConfig(js.srv, sa); err != nil {
2236 return nil, err
2237 }
2238 if len(wsa.Consumers) > 0 {
2239 sa.consumers = make(map[string]*consumerAssignment)
2240 for _, wca := range wsa.Consumers {
2241 if wca.Stream == _EMPTY_ {
2242 wca.Stream = sa.Config.Name // Rehydrate from the stream name.
2243 }
2244 ca := &consumerAssignment{Client: wca.Client, Created: wca.Created, Name: wca.Name, Stream: wca.Stream, ConfigJSON: wca.ConfigJSON, Group: wca.Group}
2245 if err := decodeConsumerAssignmentConfig(ca); err != nil {
2246 return nil, err
2247 }
2248 sa.consumers[ca.Name] = ca
2249 }
2250 }
2251 as[sa.Config.Name] = sa
2252 }
2253 return streams, nil
2254 }
2255
2256 // Encode the meta assignments into an encoded and compressed buffer.
2257 // Returns the snapshot itself, and the amount of streams and consumers.
2258 func (js *jetStream) encodeMetaSnapshot(streams map[string]map[string]*streamAssignment) ([]byte, int, int, error) {
2259 start := time.Now()
2260 nsa := 0
2261 nca := 0
2262 for _, asa := range streams {
2263 nsa += len(asa)
2264 }
2265 out := make([]writeableStreamAssignment, 0, nsa)
2266 for _, asa := range streams {
2267 for _, sa := range asa {
2268 wsa := writeableStreamAssignment{
2269 Client: sa.Client.forAssignmentSnap(),
2270 Created: sa.Created,
2271 ConfigJSON: sa.ConfigJSON,
2272 Group: sa.Group,
2273 Sync: sa.Sync,
2274 Consumers: make([]*writeableConsumerAssignment, 0, len(sa.consumers)),
2275 }
2276 for _, ca := range sa.consumers {
2277 wca := writeableConsumerAssignment{
2278 Client: ca.Client.forAssignmentSnap(),
2279 Created: ca.Created,
2280 Name: ca.Name,
2281 Stream: ca.Stream,
2282 ConfigJSON: ca.ConfigJSON,
2283 Group: ca.Group,
2284 }
2285 wsa.Consumers = append(wsa.Consumers, &wca)
2286 nca++
2287 }
2288 out = append(out, wsa)
2289 }
2290 }
2291
2292 if len(out) == 0 {
2293 return nil, nsa, nca, nil
2294 }
2295
2296 // Track how long it took to marshal the JSON
2297 mstart := time.Now()
2298 b, err := json.Marshal(out)
2299 mend := time.Since(mstart)
2300
2301 // Must not be possible for a JSON marshaling error to result
2302 // in an empty snapshot.
2303 if err != nil {
2304 return nil, nsa, nca, err
2305 }
2306
2307 // Track how long it took to compress the JSON.
2308 cstart := time.Now()
2309 snap := s2.Encode(nil, b)
2310 cend := time.Since(cstart)
2311 took := time.Since(start)
2312
2313 if took > 2*time.Second {
2314 js.srv.rateLimitFormatWarnf("Metalayer snapshot generation took %.3fs (streams: %d, consumers: %d, marshal: %.3fs, s2: %.3fs, uncompressed: %s, compressed: %s)",
2315 took.Seconds(), nsa, nca, mend.Seconds(), cend.Seconds(), friendlyBytes(len(b)), friendlyBytes(len(snap)))
2316 }
2317
2318 // Track in jsz monitoring as well.
2319 if cc := js.cluster; cc != nil {
2320 atomic.StoreInt64(&cc.lastMetaSnapTime, start.UnixNano())
2321 atomic.StoreInt64(&cc.lastMetaSnapDuration, int64(took))
2322 }
2323
2324 return snap, nsa, nca, nil
2325 }
2326
2327 // Given a checkpoint, collects all relevant append entries that can be snapshotted.
2328 func (js *jetStream) collectStreamAndConsumerChanges(c RaftNodeCheckpoint, streams map[string]map[string]*streamAssignment) error {
2329 ru := &recoveryUpdates{
2330 removeStreams: make(map[string]*streamAssignment),
2331 removeConsumers: make(map[string]map[string]*consumerAssignment),
2332 addStreams: make(map[string]*streamAssignment),
2333 updateStreams: make(map[string]*streamAssignment),
2334 updateConsumers: make(map[string]map[string]*consumerAssignment),
2335 }
2336 for ae, err := range c.AppendEntriesSeq() {
2337 if err != nil {
2338 return err
2339 }
2340 for _, e := range ae.entries {
2341 if e.Type == EntryNormal {
2342 buf := e.Data
2343 if len(buf) == 0 {
2344 return errBadEntryOp
2345 }
2346 op := entryOp(buf[0])
2347 switch op {
2348 case assignStreamOp, updateStreamOp, removeStreamOp:
2349 sa, err := decodeStreamAssignment(js.srv, buf[1:])
2350 if err != nil {
2351 js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
2352 panic(err)
2353 }
2354 if op == removeStreamOp {
2355 ru.removeStream(sa)
2356 } else {
2357 ru.addStream(sa)
2358 }
2359 case assignConsumerOp:
2360 ca, err := decodeConsumerAssignment(buf[1:])
2361 if err != nil {
2362 js.srv.Errorf("JetStream cluster failed to decode consumer assignment: %q", buf[1:])
2363 panic(err)
2364 }
2365 ru.addOrUpdateConsumer(ca)
2366 case assignCompressedConsumerOp:
2367 ca, err := decodeConsumerAssignmentCompressed(buf[1:])
2368 if err != nil {
2369 js.srv.Errorf("JetStream cluster failed to decode compressed consumer assignment: %q", buf[1:])
2370 panic(err)
2371 }
2372 ru.addOrUpdateConsumer(ca)
2373 case removeConsumerOp:
2374 ca, err := decodeConsumerAssignment(buf[1:])
2375 if err != nil {
2376 js.srv.Errorf("JetStream cluster failed to decode consumer assignment: %q", buf[1:])
2377 panic(err)
2378 }
2379 ru.removeConsumer(ca)
2380 default:
2381 panic(fmt.Sprintf("JetStream Cluster Unknown meta entry op type: %v", entryOp(buf[0])))
2382 }
2383 }
2384 }
2385 }
2386
2387 // With our recovery structure, apply the stream/consumer diff.
2388 for _, cas := range ru.removeConsumers {
2389 for _, ca := range cas {
2390 if asa, ok := streams[ca.Client.serviceAccount()]; ok {
2391 if sa, ok := asa[ca.Stream]; ok {
2392 delete(sa.consumers, ca.Name)
2393 }
2394 }
2395 }
2396 }
2397 for _, sa := range ru.removeStreams {
2398 if asa, ok := streams[sa.Client.serviceAccount()]; ok {
2399 delete(asa, sa.Config.Name)
2400 }
2401 }
2402 for _, sa := range ru.addStreams {
2403 as := streams[sa.Client.serviceAccount()]
2404 if as == nil {
2405 as = make(map[string]*streamAssignment)
2406 streams[sa.Client.serviceAccount()] = as
2407 }
2408 // Preserve consumers from the previous assignment.
2409 if osa := as[sa.Config.Name]; osa != nil {
2410 sa.consumers = osa.consumers
2411 }
2412 as[sa.Config.Name] = sa
2413 }
2414 for _, cas := range ru.updateConsumers {
2415 for _, ca := range cas {
2416 if asa, ok := streams[ca.Client.serviceAccount()]; ok {
2417 if sa, ok := asa[ca.Stream]; ok {
2418 if sa.consumers == nil {
2419 sa.consumers = make(map[string]*consumerAssignment)
2420 }
2421 sa.consumers[ca.Name] = ca
2422 }
2423 }
2424 }
2425 }
2426 return nil
2427 }
2428
2429 // Called on recovery to make sure we do not process like original.
2430 func (js *jetStream) setStreamAssignmentRecovering(sa *streamAssignment) {
2431 js.mu.Lock()
2432 defer js.mu.Unlock()
2433 sa.markResponded()
2434 sa.recovering = true
2435 sa.Restore = nil
2436 if sa.Group != nil {
2437 sa.Group.Preferred = _EMPTY_
2438 sa.Group.ScaleUp = false
2439 }
2440 }
2441
2442 // Called on recovery to make sure we do not process like original.
2443 func (js *jetStream) setConsumerAssignmentRecovering(ca *consumerAssignment) {
2444 js.mu.Lock()
2445 defer js.mu.Unlock()
2446 ca.markResponded()
2447 ca.recovering = true
2448 if ca.Group != nil {
2449 ca.Group.Preferred = _EMPTY_
2450 ca.Group.ScaleUp = false
2451 }
2452 }
2453
2454 // Just copies over and changes out the group so it can be encoded.
2455 // Lock should be held.
2456 func (sa *streamAssignment) copyGroup() *streamAssignment {
2457 csa, cg := sa.clone(), *sa.Group
2458 csa.Group = &cg
2459 csa.Group.Peers = copyStrings(sa.Group.Peers)
2460 return csa
2461 }
2462
2463 // Just copies over and changes out the group so it can be encoded.
2464 // Lock should be held.
2465 func (ca *consumerAssignment) copyGroup() *consumerAssignment {
2466 cca, cg := ca.clone(), *ca.Group
2467 cca.Group = &cg
2468 cca.Group.Peers = copyStrings(ca.Group.Peers)
2469 return cca
2470 }
2471
2472 // Lock should be held.
2473 func (sa *streamAssignment) missingPeers() bool {
2474 return len(sa.Group.Peers) < sa.Config.Replicas
2475 }
2476
2477 // Called when we detect a new peer. Only the leader will process checking
2478 // for any streams, and consequently any consumers.
2479 func (js *jetStream) processAddPeer(peer string) {
2480 js.mu.Lock()
2481 defer js.mu.Unlock()
2482
2483 s, cc := js.srv, js.cluster
2484 if cc == nil || cc.meta == nil {
2485 return
2486 }
2487 isLeader := cc.isLeader()
2488
2489 // Now check if we are meta-leader. We will check for any re-assignments.
2490 if !isLeader {
2491 return
2492 }
2493
2494 sir, ok := s.nodeToInfo.Load(peer)
2495 if !ok || sir == nil {
2496 return
2497 }
2498 si := sir.(nodeInfo)
2499
2500 for accName, sa := range js.streamAssignmentsOrInflightSeqAllAccounts() {
2501 if sa.unsupported != nil {
2502 continue
2503 }
2504 if sa.missingPeers() {
2505 // Make sure the right cluster etc.
2506 if si.cluster != sa.Client.Cluster {
2507 continue
2508 }
2509 // If we are here we can add in this peer.
2510 csa := sa.copyGroup()
2511 csa.Group.Peers = append(csa.Group.Peers, peer)
2512 // Send our proposal for this csa. Also use same group definition for all the consumers as well.
2513 if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(csa)); err != nil {
2514 return
2515 }
2516 cc.trackInflightStreamProposal(accName, csa, false)
2517 for ca := range js.consumerAssignmentsOrInflightSeq(accName, csa.Config.Name) {
2518 if ca.unsupported != nil {
2519 continue
2520 }
2521 // Ephemerals are R=1, so only auto-remap durables, or R>1.
2522 if ca.Config.Durable != _EMPTY_ || len(ca.Group.Peers) > 1 {
2523 cca := ca.copyGroup()
2524 cca.Group.Peers = csa.Group.Peers
2525 if err := cc.meta.Propose(cc.term, encodeAddConsumerAssignment(cca)); err != nil {
2526 return
2527 }
2528 cc.trackInflightConsumerProposal(accName, csa.Config.Name, cca, false)
2529 }
2530 }
2531 }
2532 }
2533 }
2534
2535 func (js *jetStream) processRemovePeer(peer string) {
2536 // We may be already disabled.
2537 if js == nil || js.disabled.Load() {
2538 return
2539 }
2540
2541 js.mu.Lock()
2542 s, cc := js.srv, js.cluster
2543 if cc == nil || cc.meta == nil {
2544 js.mu.Unlock()
2545 return
2546 }
2547 isLeader := cc.isLeader()
2548 // All nodes will check if this is them.
2549 isUs := cc.meta.ID() == peer
2550 js.mu.Unlock()
2551
2552 if isUs {
2553 s.Errorf("JetStream being DISABLED, our server was removed from the cluster")
2554 adv := &JSServerRemovedAdvisory{
2555 TypedEvent: TypedEvent{
2556 Type: JSServerRemovedAdvisoryType,
2557 ID: nuid.Next(),
2558 Time: time.Now().UTC(),
2559 },
2560 Server: s.Name(),
2561 ServerID: s.ID(),
2562 Cluster: s.cachedClusterName(),
2563 Domain: s.getOpts().JetStreamDomain,
2564 }
2565 s.publishAdvisory(nil, JSAdvisoryServerRemoved, adv)
2566
2567 go s.DisableJetStream()
2568 }
2569
2570 // Now check if we are meta-leader. We will attempt re-assignment.
2571 if !isLeader {
2572 return
2573 }
2574
2575 js.mu.Lock()
2576 defer js.mu.Unlock()
2577
2578 for _, sa := range js.streamAssignmentsOrInflightSeqAllAccounts() {
2579 if sa.unsupported != nil {
2580 continue
2581 }
2582 if rg := sa.Group; rg.isMember(peer) {
2583 js.removePeerFromStreamLocked(sa, peer)
2584 }
2585 }
2586 }
2587
2588 // Assumes all checks have already been done.
2589 func (js *jetStream) removePeerFromStream(sa *streamAssignment, peer string) bool {
2590 js.mu.Lock()
2591 defer js.mu.Unlock()
2592 return js.removePeerFromStreamLocked(sa, peer)
2593 }
2594
2595 // Lock should be held.
2596 func (js *jetStream) removePeerFromStreamLocked(sa *streamAssignment, peer string) bool {
2597 if rg := sa.Group; !rg.isMember(peer) {
2598 return false
2599 }
2600
2601 s, cc, csa := js.srv, js.cluster, sa.copyGroup()
2602 if cc == nil || cc.meta == nil {
2603 return false
2604 }
2605 replaced := cc.remapStreamAssignment(csa, peer)
2606 accName := sa.Client.serviceAccount()
2607 if !replaced {
2608 s.Warnf("JetStream cluster could not replace peer for stream '%s > %s'", accName, sa.Config.Name)
2609 }
2610
2611 // Send our proposal for this csa. Also use same group definition for all the consumers as well.
2612 if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(csa)); err != nil {
2613 return false
2614 }
2615 cc.trackInflightStreamProposal(accName, csa, false)
2616 rg := csa.Group
2617 for ca := range js.consumerAssignmentsOrInflightSeq(accName, sa.Config.Name) {
2618 if ca.unsupported != nil {
2619 continue
2620 }
2621 // Ephemerals are R=1, so only auto-remap durables, or R>1.
2622 if ca.Config.Durable != _EMPTY_ {
2623 cca := ca.copyGroup()
2624 cca.Group.Peers, cca.Group.Preferred = rg.Peers, _EMPTY_
2625 if err := cc.meta.Propose(cc.term, encodeAddConsumerAssignment(cca)); err != nil {
2626 return false
2627 }
2628 cc.trackInflightConsumerProposal(accName, csa.Config.Name, cca, false)
2629 } else if ca.Group.isMember(peer) {
2630 // These are ephemerals. Check to see if we deleted this peer.
2631 if err := cc.meta.Propose(cc.term, encodeDeleteConsumerAssignment(ca)); err != nil {
2632 return false
2633 }
2634 cc.trackInflightConsumerProposal(accName, csa.Config.Name, ca, true)
2635 }
2636 }
2637 return replaced
2638 }
2639
2640 // Check if we have peer related entries.
2641 func (js *jetStream) hasPeerEntries(entries []*Entry) bool {
2642 for _, e := range entries {
2643 if e.Type == EntryRemovePeer || e.Type == EntryAddPeer {
2644 return true
2645 }
2646 }
2647 return false
2648 }
2649
2650 const ksep = ":"
2651
2652 func (sa *streamAssignment) recoveryKey() string {
2653 if sa == nil {
2654 return _EMPTY_
2655 }
2656 return sa.Client.serviceAccount() + ksep + sa.Config.Name
2657 }
2658
2659 func (ca *consumerAssignment) streamRecoveryKey() string {
2660 if ca == nil {
2661 return _EMPTY_
2662 }
2663 return ca.Client.serviceAccount() + ksep + ca.Stream
2664 }
2665
2666 func (ca *consumerAssignment) recoveryKey() string {
2667 if ca == nil {
2668 return _EMPTY_
2669 }
2670 return ca.Client.serviceAccount() + ksep + ca.Stream + ksep + ca.Name
2671 }
2672
2673 func (js *jetStream) applyMetaEntries(entries []*Entry, ru *recoveryUpdates) (bool, bool, error) {
2674 var didSnap bool
2675 isRecovering := ru != nil
2676
2677 for _, e := range entries {
2678 // If we received a lower-level catchup entry, mark that we're recovering.
2679 // We can optimize by staging all meta operations until we're caught up.
2680 // At that point we can apply the diff in one go.
2681 if e.Type == EntryCatchup {
2682 isRecovering = true
2683 // A catchup entry only contains this, so we can exit now and have the
2684 // recoveryUpdates struct be populated for the next invocation of applyMetaEntries.
2685 return isRecovering, didSnap, nil
2686 }
2687
2688 if e.Type == EntrySnapshot {
2689 if err := js.applyMetaSnapshot(e.Data, ru, isRecovering); err != nil {
2690 return isRecovering, didSnap, err
2691 }
2692 didSnap = true
2693 } else if e.Type == EntryRemovePeer {
2694 if !js.isMetaRecovering() {
2695 peer := string(e.Data)
2696 js.processRemovePeer(peer)
2697
2698 // The meta leader can now respond to the peer-removal,
2699 // since a quorum of nodes has this in their log.
2700 s := js.srv
2701 if s.JetStreamIsLeader() {
2702 var (
2703 info peerRemoveInfo
2704 ok bool
2705 )
2706 js.mu.Lock()
2707 if cc := js.cluster; cc != nil && cc.peerRemoveReply != nil {
2708 if info, ok = cc.peerRemoveReply[peer]; ok {
2709 delete(cc.peerRemoveReply, peer)
2710 }
2711 if len(cc.peerRemoveReply) == 0 {
2712 cc.peerRemoveReply = nil
2713 }
2714 }
2715 js.mu.Unlock()
2716
2717 if info.reply != _EMPTY_ {
2718 sysAcc := s.SystemAccount()
2719 var resp = JSApiMetaServerRemoveResponse{ApiResponse: ApiResponse{Type: JSApiMetaServerRemoveResponseType}}
2720 resp.Success = true
2721 s.sendAPIResponse(info.ci, sysAcc, info.subject, info.reply, info.request, s.jsonResponse(&resp))
2722 }
2723 }
2724 }
2725 } else if e.Type == EntryAddPeer {
2726 if !js.isMetaRecovering() {
2727 js.processAddPeer(string(e.Data))
2728 }
2729 } else {
2730 buf := e.Data
2731 if len(buf) == 0 {
2732 return isRecovering, didSnap, errBadEntryOp
2733 }
2734 switch entryOp(buf[0]) {
2735 case assignStreamOp:
2736 sa, err := decodeStreamAssignment(js.srv, buf[1:])
2737 if err != nil {
2738 js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
2739 return isRecovering, didSnap, err
2740 }
2741 if isRecovering {
2742 js.setStreamAssignmentRecovering(sa)
2743 ru.addStream(sa)
2744 } else {
2745 js.processStreamAssignment(sa)
2746 }
2747 case removeStreamOp:
2748 sa, err := decodeStreamAssignment(js.srv, buf[1:])
2749 if err != nil {
2750 js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
2751 return isRecovering, didSnap, err
2752 }
2753 if isRecovering {
2754 js.setStreamAssignmentRecovering(sa)
2755 ru.removeStream(sa)
2756 } else {
2757 js.processStreamRemoval(sa)
2758 }
2759 case assignConsumerOp:
2760 ca, err := decodeConsumerAssignment(buf[1:])
2761 if err != nil {
2762 js.srv.Errorf("JetStream cluster failed to decode consumer assignment: %q", buf[1:])
2763 return isRecovering, didSnap, err
2764 }
2765 if isRecovering {
2766 js.setConsumerAssignmentRecovering(ca)
2767 ru.addOrUpdateConsumer(ca)
2768 } else {
2769 js.processConsumerAssignment(ca)
2770 }
2771 case assignCompressedConsumerOp:
2772 ca, err := decodeConsumerAssignmentCompressed(buf[1:])
2773 if err != nil {
2774 js.srv.Errorf("JetStream cluster failed to decode compressed consumer assignment: %q", buf[1:])
2775 return isRecovering, didSnap, err
2776 }
2777 if isRecovering {
2778 js.setConsumerAssignmentRecovering(ca)
2779 ru.addOrUpdateConsumer(ca)
2780 } else {
2781 js.processConsumerAssignment(ca)
2782 }
2783 case removeConsumerOp:
2784 ca, err := decodeConsumerAssignment(buf[1:])
2785 if err != nil {
2786 js.srv.Errorf("JetStream cluster failed to decode consumer assignment: %q", buf[1:])
2787 return isRecovering, didSnap, err
2788 }
2789 if isRecovering {
2790 js.setConsumerAssignmentRecovering(ca)
2791 ru.removeConsumer(ca)
2792 } else {
2793 js.processConsumerRemoval(ca)
2794 }
2795 case updateStreamOp:
2796 sa, err := decodeStreamAssignment(js.srv, buf[1:])
2797 if err != nil {
2798 js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
2799 return isRecovering, didSnap, err
2800 }
2801 if isRecovering {
2802 js.setStreamAssignmentRecovering(sa)
2803 ru.updateStream(sa)
2804 } else {
2805 js.processUpdateStreamAssignment(sa)
2806 }
2807 default:
2808 panic(fmt.Sprintf("JetStream Cluster Unknown meta entry op type: %v", entryOp(buf[0])))
2809 }
2810 }
2811 }
2812 return isRecovering, didSnap, nil
2813 }
2814
2815 func (rg *raftGroup) isMember(id string) bool {
2816 if rg == nil {
2817 return false
2818 }
2819 for _, peer := range rg.Peers {
2820 if peer == id {
2821 return true
2822 }
2823 }
2824 return false
2825 }
2826
2827 func (rg *raftGroup) setPreferred(s *Server) {
2828 if rg == nil || len(rg.Peers) == 0 {
2829 return
2830 }
2831 if len(rg.Peers) == 1 {
2832 rg.Preferred = rg.Peers[0]
2833 } else {
2834 var online []string
2835 for _, p := range rg.Peers {
2836 si, ok := s.nodeToInfo.Load(p)
2837 if !ok || si == nil {
2838 continue
2839 }
2840 ni := si.(nodeInfo)
2841 if ni.offline {
2842 continue
2843 }
2844 online = append(online, p)
2845 }
2846
2847 if len(online) == 0 {
2848 // No online servers, just randomly select a peer for the preferred.
2849 pi := rand.Int31n(int32(len(rg.Peers)))
2850 rg.Preferred = rg.Peers[pi]
2851 } else if len(online) == 1 {
2852 // Only one online server.
2853 rg.Preferred = online[0]
2854 } else {
2855 // Randomly select an online peer.
2856 pi := rand.Int31n(int32(len(online)))
2857 rg.Preferred = online[pi]
2858 }
2859 }
2860 }
2861
2862 // createRaftGroup is called to spin up this raft group if needed.
2863 func (js *jetStream) createRaftGroup(accName string, rg *raftGroup, recovering bool, storage StorageType, labels pprofLabels) (RaftNode, error) {
2864 // js.mu protects the lookup/registration of raft groups so that two parallel
2865 // calls for the same identifier can't end up creating duplicate instances.
2866 // It is released around blocking work (waiting for a previous instance to
2867 // shut down, and the disk I/O inside startRaftNode); concurrent callers for
2868 // the same rg.Name are gated through cc.creatingRaftGroups instead.
2869 js.mu.Lock()
2870 defer js.mu.Unlock()
2871
2872 s, cc := js.srv, js.cluster
2873 if cc == nil || cc.meta == nil {
2874 return nil, NewJSClusterNotActiveError()
2875 }
2876
2877 // If this is a single peer raft group or we are not a member return.
2878 if len(rg.Peers) <= 1 || !rg.isMember(cc.meta.ID()) {
2879 // Nothing to do here.
2880 return nil, nil
2881 }
2882
2883 retry:
2884 // If another goroutine is mid-creation for this raft group, wait for it
2885 // to finish (without holding js.mu) and then retry the lookup.
2886 if ch, ok := cc.creatingRaftGroups[rg.Name]; ok {
2887 js.mu.Unlock()
2888 <-ch
2889 js.mu.Lock()
2890 // js.cluster could have been swapped out (shutdown).
2891 if js.cluster == nil || js.cluster.meta == nil {
2892 return nil, NewJSClusterNotActiveError()
2893 }
2894 cc = js.cluster
2895 goto retry
2896 }
2897 // Check if we already have this assigned.
2898 if node := s.lookupRaftNode(rg.Name); node != nil {
2899 if node.State() == Closed {
2900 // We're waiting for this node to finish shutting down before we replace it.
2901 js.mu.Unlock()
2902 node.WaitForStop()
2903 js.mu.Lock()
2904 goto retry
2905 }
2906 s.Debugf("JetStream cluster already has raft group %q assigned", rg.Name)
2907 // Check and see if the group has the same peers. If not then we
2908 // will update the known peers, which will send a peerstate if leader.
2909 groupPeerIDs := append([]string{}, rg.Peers...)
2910 var samePeers bool
2911 if nodePeers := node.Peers(); len(rg.Peers) == len(nodePeers) {
2912 nodePeerIDs := make([]string, 0, len(nodePeers))
2913 for _, n := range nodePeers {
2914 nodePeerIDs = append(nodePeerIDs, n.ID)
2915 }
2916 slices.Sort(groupPeerIDs)
2917 slices.Sort(nodePeerIDs)
2918 samePeers = slices.Equal(groupPeerIDs, nodePeerIDs)
2919 }
2920 if !samePeers {
2921 // At this point we have no way of knowing:
2922 // 1. Whether the group has lost enough nodes to cause a quorum
2923 // loss, in which case a proposal may fail, therefore we will
2924 // force a peerstate write;
2925 // 2. Whether nodes in the group have other applies queued up
2926 // that could change the peerstate again, therefore the leader
2927 // should send out a new proposal anyway too just to make sure
2928 // that this change gets captured in the log.
2929 node.UpdateKnownPeers(groupPeerIDs)
2930
2931 // If the peers changed as a result of an update by the meta layer, we must reflect that in the log of
2932 // this group. Otherwise, a new peer would come up and instantly reset the peer state back to whatever is
2933 // in the log at that time, overwriting what the meta layer told it.
2934 // Will need to address this properly later on, by for example having the meta layer decide the new
2935 // placement, but have the leader of this group propose it through its own log instead.
2936 if node.Leader() {
2937 node.ProposeKnownPeers(groupPeerIDs)
2938 }
2939 }
2940 rg.node = node
2941 return node, nil
2942 }
2943
2944 s.Debugf("JetStream cluster creating raft group:%+v", rg)
2945
2946 sysAcc := s.SystemAccount()
2947 if sysAcc == nil {
2948 s.Debugf("JetStream cluster detected shutdown processing raft group: %+v", rg)
2949 return nil, errors.New("shutting down")
2950 }
2951
2952 // Check here to see if we have a max HA Assets limit set.
2953 if maxHaAssets := s.getOpts().JetStreamLimits.MaxHAAssets; maxHaAssets > 0 {
2954 if s.numRaftNodes()+len(cc.creatingRaftGroups) > maxHaAssets {
2955 s.Warnf("Maximum HA Assets limit reached: %d", maxHaAssets)
2956 // Since the meta leader assigned this, send a statsz update to them to get them up to date.
2957 go s.sendStatszUpdate()
2958 return nil, errors.New("system limit reached")
2959 }
2960 }
2961
2962 // Register an in-flight sentinel so concurrent callers for the same group
2963 // will wait for us. Then drop js.mu around all the blocking work below
2964 // (file store creation, peer state read, snapshot replay, fsyncs) so we
2965 // don't serialize every stream/consumer assignment behind one disk fsync.
2966 if cc.creatingRaftGroups == nil {
2967 cc.creatingRaftGroups = make(map[string]chan struct{})
2968 }
2969 doneCh := make(chan struct{})
2970 cc.creatingRaftGroups[rg.Name] = doneCh
2971
2972 // Snapshot rg fields; we drop js.mu below and rg is shared.
2973 rgName, rgScaleUp := rg.Name, rg.ScaleUp
2974 rgPeers := copyStrings(rg.Peers)
2975 storeDir := filepath.Join(js.config.StoreDir, sysAcc.Name, defaultStoreDirName, rg.Name)
2976 js.mu.Unlock()
2977
2978 n, err := func() (RaftNode, error) {
2979 var store StreamStore
2980 if storage == FileStorage {
2981 opts := s.getOpts()
2982 fs, err := newFileStoreWithCreated(
2983 FileStoreConfig{StoreDir: storeDir, BlockSize: defaultMediumBlockSize, AsyncFlush: false, SyncAlways: opts.SyncAlways, SyncInterval: opts.SyncInterval, srv: s},
2984 StreamConfig{Name: rgName, Storage: FileStorage, Metadata: labels},
2985 time.Now().UTC(),
2986 s.jsKeyGen(opts.JetStreamKey, rgName),
2987 s.jsKeyGen(opts.JetStreamOldKey, rgName),
2988 )
2989 if err != nil {
2990 s.Errorf("Error creating filestore WAL: %v", err)
2991 return nil, err
2992 }
2993 store = fs
2994 } else {
2995 ms, err := newMemStore(&StreamConfig{Name: rgName, Storage: MemoryStorage})
2996 if err != nil {
2997 s.Errorf("Error creating memstore WAL: %v", err)
2998 return nil, err
2999 }
3000 store = ms
3001 }
3002
3003 cfg := &RaftConfig{Name: rgName, Store: storeDir, Log: store, Track: true, Recovering: recovering, ScaleUp: rgScaleUp}
3004
3005 if _, err := readPeerState(s.diskIOSemaphore(), storeDir); err != nil {
3006 s.bootstrapRaftNode(cfg, rgPeers, true)
3007 }
3008
3009 n, err := s.startRaftNode(accName, cfg, labels)
3010 if err != nil || n == nil {
3011 s.Debugf("Error creating raft group: %v", err)
3012 return nil, err
3013 }
3014 return n, nil
3015 }()
3016
3017 js.mu.Lock()
3018 delete(cc.creatingRaftGroups, rg.Name)
3019 close(doneCh)
3020 if err != nil || n == nil {
3021 return nil, err
3022 }
3023 if js.cluster == nil || js.cluster.meta == nil {
3024 // Cluster was torn down while we were creating; let n be reaped at shutdown.
3025 return nil, NewJSClusterNotActiveError()
3026 }
3027 // Need JS lock to be held for the assignment to avoid data-race reports
3028 rg.node = n
3029 // See if we are preferred and should start campaign immediately.
3030 if n.ID() == rg.Preferred && n.Term() == 0 {
3031 n.CampaignImmediately()
3032 }
3033 return n, nil
3034 }
3035
3036 func (mset *stream) raftGroup() *raftGroup {
3037 if mset == nil {
3038 return nil
3039 }
3040 mset.mu.RLock()
3041 defer mset.mu.RUnlock()
3042 if mset.sa == nil {
3043 return nil
3044 }
3045 return mset.sa.Group
3046 }
3047
3048 func (mset *stream) raftNode() RaftNode {
3049 if mset == nil {
3050 return nil
3051 }
3052 mset.mu.RLock()
3053 defer mset.mu.RUnlock()
3054 return mset.node
3055 }
3056
3057 func (mset *stream) removeNode() {
3058 mset.mu.Lock()
3059 defer mset.mu.Unlock()
3060 if n := mset.node; n != nil {
3061 n.Delete()
3062 mset.node = nil
3063 }
3064 }
3065
3066 // Helper function to generate peer info.
3067 // lists and sets for old and new.
3068 func genPeerInfo(peers []string, split int) (newPeers, oldPeers []string, newPeerSet, oldPeerSet map[string]bool) {
3069 newPeers = peers[split:]
3070 oldPeers = peers[:split]
3071 newPeerSet = make(map[string]bool, len(newPeers))
3072 oldPeerSet = make(map[string]bool, len(oldPeers))
3073 for i, peer := range peers {
3074 if i < split {
3075 oldPeerSet[peer] = true
3076 } else {
3077 newPeerSet[peer] = true
3078 }
3079 }
3080 return
3081 }
3082
3083 // This will wait for a period of time until all consumers are registered and have
3084 // their consumer assignments assigned.
3085 // Should only be called from monitorStream.
3086 func (mset *stream) waitOnConsumerAssignments() {
3087 mset.mu.RLock()
3088 s, js, acc, sa, name, replicas := mset.srv, mset.js, mset.acc, mset.sa, mset.cfg.Name, mset.cfg.Replicas
3089 mset.mu.RUnlock()
3090
3091 if s == nil || js == nil || acc == nil || sa == nil {
3092 return
3093 }
3094
3095 js.mu.RLock()
3096 numExpectedConsumers := len(sa.consumers)
3097 js.mu.RUnlock()
3098
3099 // Max to wait.
3100 const maxWaitTime = 10 * time.Second
3101 const sleepTime = 500 * time.Millisecond
3102
3103 // Wait up to 10s
3104 timeout := time.Now().Add(maxWaitTime)
3105 for time.Now().Before(timeout) {
3106 var numReady int
3107 for _, o := range mset.getConsumers() {
3108 // Make sure we are registered with our consumer assignment.
3109 if ca := o.consumerAssignment(); ca != nil {
3110 if replicas > 1 && !o.isMonitorRunning() {
3111 break
3112 }
3113 numReady++
3114 } else {
3115 break
3116 }
3117 }
3118 // Check if we are good.
3119 if numReady >= numExpectedConsumers {
3120 break
3121 }
3122
3123 s.Debugf("Waiting for consumers for interest based stream '%s > %s'", acc.Name, name)
3124 select {
3125 case <-s.quitCh:
3126 return
3127 case <-mset.monitorQuitC():
3128 return
3129 case <-time.After(sleepTime):
3130 }
3131 }
3132
3133 if actual := mset.numConsumers(); actual < numExpectedConsumers {
3134 s.Warnf("All consumers not online for '%s > %s': expected %d but only have %d", acc.Name, name, numExpectedConsumers, actual)
3135 }
3136 }
3137
3138 // Monitor our stream node for this stream.
3139 func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnapshot bool) {
3140 s, cc := js.server(), js.cluster
3141 defer s.grWG.Done()
3142 if mset != nil {
3143 defer mset.monitorWg.Done()
3144 }
3145 js.mu.RLock()
3146 n := sa.Group.node
3147 meta := cc.meta
3148 js.mu.RUnlock()
3149
3150 if n == nil || meta == nil {
3151 s.Warnf("No RAFT group for '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
3152 return
3153 }
3154
3155 // Make sure only one is running.
3156 if mset != nil {
3157 if mset.checkInMonitor() {
3158 return
3159 }
3160 defer mset.clearMonitorRunning()
3161 }
3162
3163 // Make sure to stop the raft group on exit to prevent accidental memory bloat.
3164 // This should be below the checkInMonitor call though to avoid stopping it out
3165 // from underneath the one that is running since it will be the same raft node.
3166 defer func() {
3167 // We might be closing during shutdown, don't pre-emptively stop here since we'll still want to install snapshots.
3168 if mset != nil && !mset.closed.Load() {
3169 n.Stop()
3170 }
3171 }()
3172
3173 qch, mqch, lch, aq, uch := n.QuitC(), mset.monitorQuitC(), n.LeadChangeC(), n.ApplyQ(), mset.updateC()
3174
3175 s.Debugf("Starting stream monitor for '%s > %s' [%s]", sa.Client.serviceAccount(), sa.Config.Name, n.Group())
3176 defer s.Debugf("Exiting stream monitor for '%s > %s' [%s]", sa.Client.serviceAccount(), sa.Config.Name, n.Group())
3177
3178 // Make sure we do not leave the apply channel to fill up and block the raft layer.
3179 defer func() {
3180 if n.State() == Closed {
3181 return
3182 }
3183 n.StepDown()
3184 // Drain the commit queue...
3185 aq.drain()
3186 }()
3187
3188 const (
3189 compactInterval = 2 * time.Minute
3190 compactMinInterval = 15 * time.Second
3191 compactSizeMin = 8 * 1024 * 1024
3192 compactNumMin = 65536
3193 )
3194
3195 // Spread these out for large numbers on server restart.
3196 rci := time.Duration(rand.Int63n(int64(time.Minute)))
3197 t := time.NewTicker(compactInterval + rci)
3198 defer t.Stop()
3199
3200 js.mu.RLock()
3201 isLeader := cc.isStreamLeader(sa.Client.serviceAccount(), sa.Config.Name)
3202 isRestore := sa.Restore != nil
3203 js.mu.RUnlock()
3204
3205 acc, err := s.LookupAccount(sa.Client.serviceAccount())
3206 if err != nil {
3207 s.Warnf("Could not retrieve account for stream '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
3208 return
3209 }
3210 accName := acc.GetName()
3211
3212 // Don't allow the upper layer to install snapshots until we have
3213 // fully recovered from disk.
3214 isRecovering := true
3215
3216 var (
3217 snapMu sync.Mutex
3218 snapshotting bool
3219 fallbackSnapshot bool
3220 failedSnapshots int
3221 )
3222
3223 // Make sure all pending data is flushed before allowing snapshots. Returns false if
3224 // it couldn't be flushed, in which case we have no safe way to continue.
3225 flushPending := func() bool {
3226 err := mset.flushAllPending()
3227 if err == nil {
3228 return true
3229 }
3230 s.Errorf("Failed to flush pending data for '%s > %s' [%s]: %v", accName, mset.name(), n.Group(), err)
3231 assert.Unreachable("Stream snapshot flush failed", map[string]any{
3232 "account": accName,
3233 "stream": mset.name(),
3234 "group": n.Group(),
3235 "err": err,
3236 })
3237 mset.setWriteErr(err)
3238 n.Stop()
3239 return false
3240 }
3241
3242 doSnapshot := func(force bool) {
3243 // Suppress during recovery.
3244 if mset == nil || isRecovering || isRestore {
3245 return
3246 }
3247 snapMu.Lock()
3248 defer snapMu.Unlock()
3249
3250 // Don't suppress a snapshot during shutdown.
3251 if js.isShuttingDown() {
3252 if !flushPending() {
3253 return
3254 }
3255 if err := n.InstallSnapshot(mset.stateSnapshot(), true); err != nil &&
3256 err != errNoSnapAvailable && err != errNodeClosed {
3257 s.RateLimitWarnf("Failed to install snapshot for '%s > %s' [%s]: %v",
3258 mset.acc.Name, mset.name(), n.Group(), err)
3259 }
3260 return
3261 }
3262
3263 // If snapshots have failed, and we're not forced to, we'll wait for the timer since it'll now be forced.
3264 if !force && failedSnapshots > 0 {
3265 return
3266 }
3267 // Suppress if an async snapshot is already in progress.
3268 if snapshotting {
3269 return
3270 }
3271
3272 // If we had a significant number of failed snapshots, start relaxing Raft-layer checks
3273 // to force it through. We might have been catching up a peer for a long period, and this
3274 // protects our log size from growing indefinitely.
3275 forceSnapshot := failedSnapshots > 4
3276 c, err := n.CreateSnapshotCheckpoint(forceSnapshot)
3277 if err != nil {
3278 if err != errNoSnapAvailable && err != errNodeClosed {
3279 s.RateLimitWarnf("Failed to install snapshot for '%s > %s' [%s]: %v",
3280 mset.acc.Name, mset.name(), n.Group(), err)
3281 // If this is the first failure, reduce the interval of the snapshot timer.
3282 // This ensures we're not waiting too long for snapshotting to eventually become forced.
3283 if failedSnapshots == 0 {
3284 t.Reset(compactMinInterval)
3285 }
3286 failedSnapshots++
3287 }
3288 return
3289 }
3290 if !flushPending() {
3291 c.Abort()
3292 return
3293 }
3294
3295 snap := mset.stateSnapshot()
3296
3297 handleInstallResult := func(err error) {
3298 snapshotting = false
3299 if err == nil {
3300 // If there was a failed snapshot before, we reduced the timer's interval.
3301 // Reset it back to the original interval now.
3302 if failedSnapshots > 0 {
3303 t.Reset(compactInterval + rci)
3304 }
3305 failedSnapshots = 0
3306 fallbackSnapshot = false
3307 } else {
3308 c.Abort()
3309
3310 if err == errNoSnapAvailable || err == errNodeClosed || err == errCatchupsRunning || err == errSnapAborted {
3311 return
3312 }
3313
3314 s.RateLimitWarnf("Failed to install snapshot for '%s > %s' [%s]: %v, will fall back to blocking snapshot",
3315 mset.acc.Name, mset.name(), n.Group(), err)
3316 fallbackSnapshot = true
3317 // If this is the first failure, reduce the interval of the snapshot timer.
3318 // This ensures we're not waiting too long for snapshotting to eventually become forced.
3319 if failedSnapshots == 0 {
3320 t.Reset(compactMinInterval)
3321 }
3322 failedSnapshots++
3323 }
3324 }
3325
3326 snapshotting = true
3327 if fallbackSnapshot {
3328 _, err = c.InstallSnapshot(snap)
3329 handleInstallResult(err)
3330 } else {
3331 started := s.startGoRoutine(func() {
3332 defer s.grWG.Done()
3333
3334 _, err := c.InstallSnapshot(snap)
3335
3336 snapMu.Lock()
3337 defer snapMu.Unlock()
3338 handleInstallResult(err)
3339 })
3340 if !started {
3341 snapshotting = false
3342 c.Abort()
3343 }
3344 }
3345 }
3346
3347 // We will establish a restoreDoneCh no matter what. Will never be triggered unless
3348 // we replace with the restore chan.
3349 restoreDoneCh := make(<-chan error)
3350
3351 // For migration tracking.
3352 mmtd := 500 * time.Millisecond
3353 var mmt *time.Ticker
3354 var mmtc <-chan time.Time
3355
3356 startMigrationMonitoring := func() {
3357 if mmt == nil {
3358 mmt = time.NewTicker(mmtd)
3359 mmtc = mmt.C
3360 }
3361 }
3362
3363 stopMigrationMonitoring := func() {
3364 if mmt != nil {
3365 mmt.Stop()
3366 mmt, mmtc = nil, nil
3367 }
3368 }
3369 defer stopMigrationMonitoring()
3370
3371 // This is to optionally track when we are ready as a non-leader for direct access participation.
3372 // Either direct or if we are a direct mirror, or both.
3373 var dat *time.Ticker
3374 var datc <-chan time.Time
3375
3376 startDirectAccessMonitoring := func() {
3377 if dat == nil {
3378 dat = time.NewTicker(2 * time.Second)
3379 datc = dat.C
3380 }
3381 }
3382
3383 stopDirectMonitoring := func() {
3384 if dat != nil {
3385 dat.Stop()
3386 dat, datc = nil, nil
3387 }
3388 }
3389 defer stopDirectMonitoring()
3390
3391 // For checking interest state if applicable.
3392 var cist *time.Ticker
3393 var cistc <-chan time.Time
3394
3395 checkInterestInterval := checkInterestStateT + time.Duration(rand.Intn(checkInterestStateJ))*time.Second
3396
3397 if mset != nil && mset.isInterestRetention() {
3398 // Wait on our consumers to be assigned and running before proceeding.
3399 // This can become important when a server has lots of assets
3400 // since we process streams first then consumers as an asset class.
3401 mset.waitOnConsumerAssignments()
3402 // Setup our periodic check here. We will check once we have restored right away.
3403 cist = time.NewTicker(checkInterestInterval)
3404 cistc = cist.C
3405 }
3406
3407 // This is triggered during a scale up from R1 to clustered mode. We need the new followers to catchup,
3408 // similar to how we trigger the catchup mechanism post a backup/restore.
3409 // We can arrive here NOT being the leader, so we send the snapshot only if we are, and in this case
3410 // reset the notion that we need to send the snapshot. If we are not, then the first time the server
3411 // will switch to leader (in the loop below), we will send the snapshot.
3412 if sendSnapshot && isLeader && mset != nil && n != nil && !isRecovering {
3413 n.SendSnapshot(mset.stateSnapshot())
3414 sendSnapshot = false
3415 }
3416
3417 // State to check for atomic batch completeness before applying it.
3418 batch := &batchApply{}
3419 defer func() {
3420 for _, bce := range batch.entries {
3421 bce.ReturnToPool()
3422 }
3423 batch.clearBatchState()
3424 }()
3425
3426 for {
3427 select {
3428 case <-s.quitCh:
3429 // Server shutting down, but we might receive this before qch, so try to snapshot.
3430 doSnapshot(false)
3431 return
3432 case <-mqch:
3433 // Clean signal from shutdown routine so do best effort attempt to snapshot.
3434 // Don't snapshot if not shutting down, monitor goroutine could be going away
3435 // on a scale down or a remove for example.
3436 if js.isShuttingDown() {
3437 doSnapshot(false)
3438 }
3439 return
3440 case <-qch:
3441 // Raft node is closed, no use in trying to snapshot.
3442 return
3443 case <-aq.ch:
3444 var ne, nb uint64
3445 // If we bump clfs we will want to write out snapshot if within our time window.
3446 pclfs := mset.getCLFS()
3447
3448 ces := aq.pop()
3449 for _, ce := range ces {
3450 // No special processing needed for when we are caught up on restart.
3451 if ce == nil {
3452 if !isRecovering {
3453 continue
3454 }
3455 isRecovering = false
3456 // If we are interest based make sure to check consumers if interest retention policy.
3457 // This is to make sure we process any outstanding acks from all consumers.
3458 if mset != nil && mset.isInterestRetention() {
3459 fire := time.Duration(rand.Intn(5)+5) * time.Second
3460 time.AfterFunc(fire, mset.checkInterestState)
3461 }
3462 // If we became leader during this time and we need to send a snapshot to our
3463 // followers, i.e. as a result of a scale-up from R1, do it now.
3464 if sendSnapshot && isLeader && mset != nil && n != nil {
3465 n.SendSnapshot(mset.stateSnapshot())
3466 sendSnapshot = false
3467 }
3468 continue
3469 } else if len(ce.Entries) == 0 {
3470 // If we have a partial batch, it needs to be rejected to ensure CLFS is correct.
3471 if mset != nil && batch != nil && batch.id != _EMPTY_ {
3472 batch.rejectBatchState(mset)
3473 }
3474
3475 // Entry could be empty on a restore when mset is nil.
3476 ne, nb = n.Applied(ce.Index)
3477 ce.ReturnToPool()
3478 continue
3479 }
3480
3481 // Apply our entries.
3482 if maxApplied, err := js.applyStreamEntries(mset, n, ce, isRecovering, batch); err == nil {
3483 // Update our applied.
3484 if maxApplied > 0 {
3485 // Indicate we've processed (but not applied) everything up to this point.
3486 ne, nb = n.Processed(ce.Index, min(maxApplied, ce.Index))
3487 // Don't return entry to the pool, this is handled by the in-progress batch.
3488 } else {
3489 ne, nb = n.Applied(ce.Index)
3490 ce.ReturnToPool()
3491 }
3492 } else {
3493 // Make sure to clean up.
3494 ce.ReturnToPool()
3495 // Our stream was closed out from underneath of us, simply return here.
3496 if err == errStreamClosed || err == errCatchupStreamStopped || err == ErrServerNotRunning {
3497 aq.recycle(&ces)
3498 return
3499 }
3500 s.Errorf("Error applying entries to '%s > %s': %v", accName, sa.Config.Name, err)
3501 if isClusterResetErr(err) {
3502 if mset.isMirror() && mset.IsLeader() {
3503 mset.retryMirrorConsumer()
3504 continue
3505 }
3506 // If the error signals we timed out of a snapshot, we should try to replay the snapshot
3507 // instead of fully resetting the state. Resetting the clustered state may result in
3508 // race conditions and should only be used as a last effort attempt.
3509 if errors.Is(err, errCatchupAbortedNoLeader) || err == errCatchupTooManyRetries || err == errAlreadyLeader {
3510 if n.DrainAndReplaySnapshot() {
3511 break
3512 } else if n.IsDeleted() {
3513 // The only reason we can't replay is our node being deleted, which
3514 // means the meta layer is deliberately tearing this monitor down.
3515 // Don't fall through to a reset, that would resurrect this group.
3516 s.Warnf("Will not reset stream '%s > %s', raft group %q was removed",
3517 accName, sa.Config.Name, n.Group())
3518 aq.recycle(&ces)
3519 return
3520 }
3521 }
3522 // We will attempt to reset our cluster state.
3523 if mset.resetClusteredState(n, err) {
3524 aq.recycle(&ces)
3525 return
3526 }
3527 } else if isOutOfSpaceErr(err) {
3528 // If applicable this will tear all of this down, but don't assume so and return.
3529 s.handleOutOfSpace(mset)
3530 } else {
3531 // Encountered an unexpected error, can't continue.
3532 mset.setWriteErr(err)
3533 aq.recycle(&ces)
3534 return
3535 }
3536 }
3537 }
3538 aq.recycle(&ces)
3539
3540 // Check about snapshotting
3541 // If we have at least min entries to compact, go ahead and try to snapshot/compact.
3542 if ne >= compactNumMin || nb > compactSizeMin || mset.getCLFS() > pclfs {
3543 doSnapshot(false)
3544 }
3545
3546 case lc := <-lch:
3547 isLeader = lc.isLeader
3548 // Process our leader change.
3549 js.processStreamLeaderChange(mset, isLeader, lc.term)
3550
3551 if isLeader {
3552 if mset != nil && n != nil && sendSnapshot && !isRecovering {
3553 // If we *are* recovering at the time then this will get done when the apply queue
3554 // handles the nil guard to show the catchup ended.
3555 n.SendSnapshot(mset.stateSnapshot())
3556 sendSnapshot = false
3557 }
3558 if isRestore {
3559 acc, _ := s.LookupAccount(sa.Client.serviceAccount())
3560 restoreDoneCh = s.processStreamRestore(sa.Client, acc, sa.Config, _EMPTY_, sa.Reply, _EMPTY_)
3561 continue
3562 } else if n != nil && n.NeedSnapshot() {
3563 doSnapshot(false)
3564 }
3565 // Always cancel if this was running.
3566 stopDirectMonitoring()
3567 } else if !n.Leaderless() {
3568 js.setStreamAssignmentRecovering(sa)
3569 }
3570
3571 // We may receive a leader change after the stream assignment which would cancel us
3572 // monitoring for this closely. So re-assess our state here as well.
3573 // Or the old leader is no longer part of the set and transferred leadership
3574 // for this leader to resume with removal
3575 migrating := mset.isMigrating()
3576
3577 // Check for migrations here. We set the state on the stream assignment update below.
3578 if isLeader && migrating {
3579 startMigrationMonitoring()
3580 } else {
3581 stopMigrationMonitoring()
3582 }
3583
3584 // Here we are checking if we are not the leader but we have been asked to allow
3585 // direct access. We now allow non-leaders to participate in the queue group.
3586 if !isLeader && mset != nil {
3587 mset.mu.RLock()
3588 ad, md := mset.cfg.AllowDirect, mset.cfg.MirrorDirect
3589 mset.mu.RUnlock()
3590 if ad || md {
3591 startDirectAccessMonitoring()
3592 }
3593 }
3594
3595 case <-cistc:
3596 cist.Reset(checkInterestInterval)
3597 // We may be adjusting some things with consumers so do this in its own go routine.
3598 go mset.checkInterestState()
3599
3600 case <-datc:
3601 if mset == nil || isRecovering {
3602 continue
3603 }
3604 // If we are leader we can stop, we know this is setup now.
3605 if isLeader {
3606 stopDirectMonitoring()
3607 continue
3608 }
3609
3610 mset.mu.Lock()
3611 ad, md, current := mset.cfg.AllowDirect, mset.cfg.MirrorDirect, mset.isCurrent()
3612 if !current {
3613 const syncThreshold = 90.0
3614 // We are not current, but current means exactly caught up. Under heavy publish
3615 // loads we may never reach this, so check if we are within 90% caught up.
3616 _, c, a := mset.node.Progress()
3617 if c == 0 {
3618 mset.mu.Unlock()
3619 continue
3620 }
3621 if p := float64(a) / float64(c) * 100.0; p < syncThreshold {
3622 mset.mu.Unlock()
3623 continue
3624 } else {
3625 s.Debugf("Stream '%s > %s' enabling direct gets at %.0f%% synchronized",
3626 sa.Client.serviceAccount(), sa.Config.Name, p)
3627 }
3628 }
3629 // We are current, cancel monitoring and create the direct subs as needed.
3630 if ad {
3631 mset.subscribeToDirect()
3632 }
3633 if md {
3634 mset.subscribeToMirrorDirect()
3635 }
3636 mset.mu.Unlock()
3637 // Stop direct monitoring.
3638 stopDirectMonitoring()
3639
3640 case <-t.C:
3641 // Start forcing snapshots if they failed previously.
3642 snapMu.Lock()
3643 forceIfFailed := failedSnapshots > 0
3644 snapMu.Unlock()
3645 doSnapshot(forceIfFailed)
3646
3647 case <-uch:
3648 // keep stream assignment current
3649 sa = mset.streamAssignment()
3650
3651 // We get this when we have a new stream assignment caused by an update.
3652 // We want to know if we are migrating.
3653 migrating := mset.isMigrating()
3654 if isLeader && migrating {
3655 startMigrationMonitoring()
3656 } else {
3657 stopMigrationMonitoring()
3658 }
3659 case <-mmtc:
3660 if !isLeader {
3661 // We are no longer leader, so not our job.
3662 stopMigrationMonitoring()
3663 continue
3664 }
3665 if done := js.runStreamMigration(mset, sa, n); done {
3666 stopMigrationMonitoring()
3667 continue
3668 }
3669
3670 case err := <-restoreDoneCh:
3671 // We have completed a restore from snapshot on this server. The stream assignment has
3672 // already been assigned but the replicas will need to catch up out of band. Consumers
3673 // will need to be assigned by forwarding the proposal and stamping the initial state.
3674 s.Debugf("Stream restore for '%s > %s' completed", sa.Client.serviceAccount(), sa.Config.Name)
3675 if err != nil {
3676 s.Debugf("Stream restore failed: %v", err)
3677 }
3678 isRestore = false
3679 sa.Restore = nil
3680 // If we were successful lookup up our stream now.
3681 if err == nil {
3682 if mset, err = acc.lookupStream(sa.Config.Name); mset != nil {
3683 mset.startMonitorWg()
3684 defer mset.monitorWg.Done()
3685 mset.checkInMonitor()
3686 mset.setStreamAssignment(sa)
3687 // Make sure to update our updateC which would have been nil.
3688 uch = mset.updateC()
3689 // Also update our mqch
3690 mqch = mset.monitorQuitC()
3691 // Setup a periodic check here if we are interest based as well.
3692 if mset.isInterestRetention() {
3693 cist = time.NewTicker(checkInterestInterval)
3694 cistc = cist.C
3695 }
3696 }
3697 }
3698 // We may have lost leadership while the restore was running.
3699 if err == nil && !isLeader {
3700 err = errNotLeader
3701 }
3702 if err != nil {
3703 if mset != nil {
3704 mset.delete()
3705 }
3706 js.mu.Lock()
3707 s.Warnf("Stream restore failed for '%s > %s': %v", sa.Client.serviceAccount(), sa.Config.Name, err)
3708 sa.err = err
3709 if n != nil {
3710 n.Delete()
3711 }
3712 result := &streamAssignmentResult{
3713 Account: sa.Client.serviceAccount(),
3714 Stream: sa.Config.Name,
3715 Restore: &JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}},
3716 }
3717 result.Restore.Error = NewJSStreamAssignmentError(err, Unless(err))
3718 js.mu.Unlock()
3719 // Send response to the metadata leader. They will forward to the user as needed.
3720 s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
3721 return
3722 }
3723 // Trigger the stream followers to catchup.
3724 var term uint64
3725 if n = mset.raftNode(); n != nil {
3726 n.SendSnapshot(mset.stateSnapshot())
3727 term = n.Term()
3728 }
3729 js.processStreamLeaderChange(mset, isLeader, term)
3730
3731 // Check to see if we have restored consumers here.
3732 // These are not currently assigned so we will need to do so here.
3733 if consumers := mset.getPublicConsumers(); len(consumers) > 0 {
3734 // Need to read meta under the js lock, it's set to nil on shutdown.
3735 js.mu.RLock()
3736 meta := cc.meta
3737 js.mu.RUnlock()
3738 if meta == nil {
3739 // We are shutting down.
3740 continue
3741 }
3742 for _, o := range consumers {
3743 name, cfg := o.String(), o.config()
3744 rg, err := cc.createGroupForConsumer(&cfg, sa)
3745 if err != nil {
3746 s.Warnf("Could not create group for consumer '%s > %s > %s': %v",
3747 sa.Client.serviceAccount(), sa.Config.Name, name, err)
3748 continue
3749 }
3750 // Pick a preferred leader.
3751 rg.setPreferred(s)
3752
3753 // Place our initial state here as well for assignment distribution.
3754 state, _ := o.store.State()
3755 ca := &consumerAssignment{
3756 Group: rg,
3757 Stream: sa.Config.Name,
3758 Name: name,
3759 Config: &cfg,
3760 Client: sa.Client,
3761 Created: o.createdTime(),
3762 State: state,
3763 }
3764
3765 // We make these compressed in case state is complex.
3766 addEntry := encodeAddConsumerAssignmentCompressed(ca)
3767 meta.ForwardProposal(addEntry)
3768
3769 // Check to make sure we see the assignment.
3770 go func() {
3771 ticker := time.NewTicker(time.Second)
3772 defer ticker.Stop()
3773 for range ticker.C {
3774 js.mu.RLock()
3775 ca, meta := js.consumerAssignment(ca.Client.serviceAccount(), sa.Config.Name, name), cc.meta
3776 js.mu.RUnlock()
3777 if ca == nil {
3778 s.Warnf("Consumer assignment has not been assigned, retrying")
3779 if meta != nil {
3780 meta.ForwardProposal(addEntry)
3781 } else {
3782 return
3783 }
3784 } else {
3785 return
3786 }
3787 }
3788 }()
3789 }
3790 }
3791 }
3792 }
3793 }
3794
3795 // Migrate a stream from peer set A to peer set B. Returns true when migration is done.
3796 func (js *jetStream) runStreamMigration(mset *stream, sa *streamAssignment, n RaftNode) bool {
3797 ourPeerId, cc, s := n.ID(), js.cluster, js.srv
3798
3799 js.mu.RLock()
3800 // We are shutting down.
3801 if cc == nil || cc.meta == nil {
3802 js.mu.RUnlock()
3803 return true
3804 }
3805 meta := cc.meta
3806 accName, streamName := sa.Client.serviceAccount(), sa.Config.Name
3807 js.mu.RUnlock()
3808
3809 // Check to see where we are..
3810 rg := mset.raftGroup()
3811
3812 // Track the new peers and check the ones that are current.
3813 mset.mu.RLock()
3814 replicas := mset.cfg.Replicas
3815 mset.mu.RUnlock()
3816 if len(rg.Peers) <= replicas {
3817 // Migration no longer happening, so not our job anymore
3818 return true
3819 }
3820
3821 // Make sure we have correct cluster information on the other peers.
3822 ci := js.clusterInfo(rg)
3823 mset.checkClusterInfo(ci)
3824
3825 newPeers, _, newPeerSet, oldPeerSet := genPeerInfo(rg.Peers, len(rg.Peers)-replicas)
3826
3827 // If we are part of the new peerset and we have been passed the baton.
3828 // We will handle scale down.
3829 if newPeerSet[ourPeerId] {
3830 // First need to check on any consumers and make sure they have moved properly before scaling down ourselves.
3831 js.mu.RLock()
3832 var needToWait bool
3833 for name, c := range sa.consumers {
3834 if c.unsupported != nil {
3835 continue
3836 }
3837 for _, peer := range c.Group.Peers {
3838 // If we have peers still in the old set block.
3839 if oldPeerSet[peer] {
3840 s.Debugf("Scale down of '%s > %s' blocked by consumer '%s'", accName, streamName, name)
3841 needToWait = true
3842 break
3843 }
3844 }
3845 if needToWait {
3846 break
3847 }
3848 }
3849 js.mu.RUnlock()
3850 if needToWait {
3851 return false
3852 }
3853 // We are good to go, can scale down here.
3854 n.ProposeKnownPeers(newPeers)
3855
3856 csa := sa.copyGroup()
3857 csa.Group.Peers = newPeers
3858 csa.Group.Preferred = ourPeerId
3859 csa.Group.Cluster = s.cachedClusterName()
3860 meta.ForwardProposal(encodeUpdateStreamAssignment(csa))
3861 s.Noticef("Scaling down '%s > %s' to %+v", accName, streamName, s.peerSetToNames(newPeers))
3862 } else {
3863 // We are the old leader here, from the original peer set.
3864 // We are simply waiting on the new peerset to be caught up so we can transfer leadership.
3865 var newLeaderPeer, newLeader string
3866 neededCurrent, current := replicas/2+1, 0
3867
3868 for _, r := range ci.Replicas {
3869 if r.Current && newPeerSet[r.Peer] {
3870 current++
3871 if newLeader == _EMPTY_ {
3872 newLeaderPeer, newLeader = r.Peer, r.Name
3873 }
3874 }
3875 }
3876 // Check if we have a quorom.
3877 if current >= neededCurrent {
3878 s.Noticef("Transfer of stream leader for '%s > %s' to '%s'", accName, streamName, newLeader)
3879 n.ProposeKnownPeers(newPeers)
3880 n.StepDown(newLeaderPeer)
3881 }
3882 }
3883 return false
3884 }
3885
3886 // Determine if we are migrating
3887 func (mset *stream) isMigrating() bool {
3888 if mset == nil {
3889 return false
3890 }
3891
3892 mset.mu.RLock()
3893 js, sa := mset.js, mset.sa
3894 mset.mu.RUnlock()
3895
3896 js.mu.RLock()
3897 defer js.mu.RUnlock()
3898
3899 // During migration we will always be R>1, even when we start R1.
3900 // So if we do not have a group or node, we know we are not migrating.
3901 if sa == nil || sa.Group == nil || sa.Group.node == nil {
3902 return false
3903 }
3904 // The sign of migration is if our group peer count != configured replica count.
3905 if sa.Config.Replicas != len(sa.Group.Peers) {
3906 return true
3907 }
3908 return false
3909 }
3910
3911 // resetClusteredState is called when a clustered stream had an error (e.g sequence mismatch, bad snapshot) and needs to be reset.
3912 func (mset *stream) resetClusteredState(n RaftNode, err error) bool {
3913 mset.mu.RLock()
3914 s, js, jsa, sa, acc, node, name := mset.srv, mset.js, mset.jsa, mset.sa, mset.acc, mset.node, mset.nameLocked(false)
3915 stype, tierName, replicas := mset.cfg.Storage, mset.tier, mset.cfg.Replicas
3916 mset.mu.RUnlock()
3917
3918 // The stream might already be deleted and not assigned to us anymore.
3919 // In any case, don't revive the stream if it's already closed.
3920 // A nil node means it was removed out from underneath us, which only happens
3921 // when the meta layer is deliberately tearing this monitor down.
3922 if mset.closed.Load() || node == nil || node.IsDeleted() {
3923 s.Warnf("Will not reset stream '%s > %s', stream is closed", acc, mset.name())
3924 // Explicitly returning true here, we want the outside to break out of the monitoring loop as well.
3925 return true
3926 }
3927
3928 // The node we were monitoring is no longer this stream's node. The meta layer has
3929 // remapped us into a different group and is tearing this monitor down, so resetting
3930 // here would resurrect a group that has already been replaced.
3931 if n != nil && n != node {
3932 s.Warnf("Will not reset stream '%s > %s', raft group %q was replaced by %q",
3933 acc, mset.name(), n.Group(), node.Group())
3934 // Explicitly returning true here, we want the outside to break out of the monitoring loop as well.
3935 return true
3936 }
3937
3938 assert.Unreachable("Reset clustered state", map[string]any{
3939 "stream": name,
3940 "account": acc.Name,
3941 "err": err,
3942 })
3943
3944 // Stepdown regardless if we are the leader here.
3945 node.StepDown()
3946
3947 // If we detect we are shutting down just return.
3948 if js != nil && js.isShuttingDown() {
3949 s.Debugf("Will not reset stream '%s > %s', JetStream shutting down", acc, mset.name())
3950 return false
3951 }
3952
3953 // Server
3954 if js.limitsExceeded(stype) {
3955 s.Warnf("Will not reset stream '%s > %s', server resources exceeded", acc, mset.name())
3956 return false
3957 }
3958
3959 // Account
3960 if exceeded, _ := jsa.limitsExceeded(stype, tierName, replicas); exceeded {
3961 s.Warnf("Stream '%s > %s' errored, account resources exceeded", acc, mset.name())
3962 return false
3963 }
3964
3965 if errors.Is(err, errCatchupAbortedNoLeader) || err == errCatchupTooManyRetries {
3966 // Don't delete all state, could've just been temporarily unable to reach the leader.
3967 node.Stop()
3968 } else {
3969 // We delete our raft state. Will recreate.
3970 node.Delete()
3971 }
3972
3973 // Preserve our current state and messages unless we have a first sequence mismatch.
3974 shouldDelete := err == errFirstSequenceMismatch
3975
3976 // Need to do the rest in a separate Go routine.
3977 go func() {
3978 mset.stopMonitoring()
3979 mset.resetAndWaitOnConsumers()
3980 // Stop our stream.
3981 mset.stop(shouldDelete, false)
3982
3983 if sa != nil {
3984 js.mu.Lock()
3985 if js.shuttingDown {
3986 js.mu.Unlock()
3987 return
3988 }
3989
3990 s.Warnf("Resetting stream cluster state for '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
3991 // Mark stream assignment as resetting, so we don't double-account reserved resources.
3992 // But only if we're not also releasing the resources as part of the delete.
3993 sa.resetting = !shouldDelete
3994 // Now wipe groups from assignments.
3995 sa.Group.node = nil
3996 var consumers []*consumerAssignment
3997 if cc := js.cluster; cc != nil && cc.meta != nil {
3998 ourID := cc.meta.ID()
3999 for _, ca := range sa.consumers {
4000 if ca.unsupported != nil {
4001 continue
4002 }
4003 if rg := ca.Group; rg != nil && rg.isMember(ourID) {
4004 rg.node = nil // Erase group raft/node state.
4005 consumers = append(consumers, ca)
4006 }
4007 }
4008 }
4009 js.mu.Unlock()
4010
4011 // This will reset the stream and consumers.
4012 // Reset stream.
4013 js.processClusterCreateStream(acc, sa)
4014 // Reset consumers.
4015 for _, ca := range consumers {
4016 js.processClusterCreateConsumer(nil, ca, nil, false)
4017 }
4018 }
4019 }()
4020
4021 return true
4022 }
4023
4024 func isControlHdr(hdr []byte) bool {
4025 return bytes.HasPrefix(hdr, []byte("NATS/1.0 100 "))
4026 }
4027
4028 // Apply our stream entries.
4029 // Return maximum allowed applied value, if currently inside a batch, zero otherwise.
4030 func (js *jetStream) applyStreamEntries(mset *stream, n RaftNode, ce *CommittedEntry, isRecovering bool, batch *batchApply) (uint64, error) {
4031 for i, e := range ce.Entries {
4032 // Ignore if lower-level catchup is started.
4033 // We don't need to optimize during this, all entries are handled as normal.
4034 if e.Type == EntryCatchup {
4035 continue
4036 }
4037
4038 // Check if a batch is abandoned.
4039 if e.Type != EntryNormal && batch != nil && batch.id != _EMPTY_ {
4040 batch.rejectBatchState(mset)
4041 }
4042
4043 if e.Type == EntryNormal {
4044 if len(e.Data) == 0 {
4045 return 0, errBadEntryOp
4046 }
4047 buf, op := e.Data, entryOp(e.Data[0])
4048 if op == batchMsgOp {
4049 batchId, batchSeq, _, _, err := decodeBatchMsg(buf[1:])
4050 if err != nil {
4051 panic(err.Error())
4052 }
4053
4054 // Need to grab the stream lock first.
4055 if isRecovering {
4056 mset.mu.Lock()
4057 }
4058
4059 // Previous batch (if any) was abandoned.
4060 if batch.id != _EMPTY_ && batchId != batch.id {
4061 batch.rejectBatchState(mset)
4062 }
4063 if batchSeq == 1 {
4064 // If this is the first message in the batch, need to mark the start index.
4065 // We'll continue to check batch-completeness and try to find the commit.
4066 // At that point we'll commit the whole batch.
4067 batch.rejectBatchState(mset)
4068 batch.entryStart = i
4069 batch.maxApplied = ce.Index - 1
4070 }
4071 batch.id = batchId
4072
4073 // While recovering, we could come up in the middle of a compacted batch that has already been applied.
4074 // This is possible if two batches are part of the same append entry, and the first batch was fully
4075 // applied but the second wasn't.
4076 // If we still see the first message of the batch, we don't skip any messages of the batch here.
4077 if isRecovering {
4078 if batchSeq > 1 && batch.count == 0 {
4079 if skip, err := mset.skipBatchIfRecovering(batch, buf); err != nil || skip {
4080 mset.mu.Unlock()
4081 if err != nil {
4082 panic(err.Error())
4083 }
4084 continue
4085 }
4086 }
4087 mset.mu.Unlock()
4088 }
4089
4090 batch.count++
4091 // If the sequence is not monotonically increasing/we identify gaps, the batch can't be accepted.
4092 if batchSeq != batch.count {
4093 batch.rejectBatchState(mset)
4094 continue
4095 }
4096 continue
4097 } else if op == batchCommitMsgOp {
4098 batchId, batchSeq, _, _, err := decodeBatchMsg(buf[1:])
4099 if err != nil {
4100 panic(err.Error())
4101 }
4102 mset.mu.Lock()
4103 // Previous batch (if any) was abandoned.
4104 if batch.id != _EMPTY_ && batchId != batch.id {
4105 batch.rejectBatchState(mset)
4106 }
4107 if batchSeq == 1 {
4108 // If this is the first message in the batch, need to mark the start index.
4109 // This is a batch of size one that immediately commits.
4110 batch.rejectBatchState(mset)
4111 batch.entryStart = i
4112 batch.maxApplied = ce.Index - 1
4113 }
4114 batch.id = batchId
4115
4116 // While recovering, we could come up in the middle of a compacted batch that has already been applied.
4117 // This is possible if two batches are part of the same append entry, and the first batch was fully
4118 // applied but the second wasn't.
4119 // If we still see the first message of the batch, we don't skip any messages of the batch here.
4120 if isRecovering && batchSeq > 1 && batch.count == 0 {
4121 if skip, err := mset.skipBatchIfRecovering(batch, buf); err != nil || skip {
4122 mset.mu.Unlock()
4123 if err != nil {
4124 panic(err.Error())
4125 }
4126 continue
4127 }
4128 }
4129
4130 batch.count++
4131 // Detected a gap, reject the batch.
4132 if batchSeq != batch.count {
4133 batch.rejectBatchState(mset)
4134 mset.mu.Unlock()
4135 continue
4136 }
4137
4138 // Ensure the whole batch is fully isolated, and reads
4139 // can only happen after the full batch is committed.
4140 mset.mu.Unlock()
4141 mset.isolateMu.Lock()
4142
4143 // Process any entries that are part of this batch but prior to the current one.
4144 var entries []*Entry
4145 for j, bce := range batch.entries {
4146 if j == 0 {
4147 // The first needs only the entries when the batch is started.
4148 entries = bce.Entries[batch.entryStart:]
4149 } else {
4150 // Otherwise, all entries are used.
4151 entries = bce.Entries
4152 }
4153 clearAndUnlock := func() {
4154 // Make sure to return remaining entries to the pool on an error.
4155 for _, nce := range batch.entries[j:] {
4156 nce.ReturnToPool()
4157 }
4158 // Important to clear, otherwise we could return the entries to the pool multiple times.
4159 batch.clearBatchState()
4160 mset.isolateMu.Unlock()
4161 }
4162 for _, entry := range entries {
4163 // Non-normal entries (e.g. EntryCatchup) can be buffered but must be ignored.
4164 if entry.Type != EntryNormal {
4165 continue
4166 }
4167 _, _, op, buf, err = decodeBatchMsg(entry.Data[1:])
4168 if err != nil {
4169 clearAndUnlock()
4170 panic(err.Error())
4171 }
4172 if err = js.applyStreamMsgOp(mset, op, buf, isRecovering, false); err != nil {
4173 clearAndUnlock()
4174 return 0, err
4175 }
4176 }
4177 // Return the entry to the pool now.
4178 bce.ReturnToPool()
4179 }
4180 if len(batch.entries) == 0 {
4181 // Get within the same entry, but within the range of this batch.
4182 entries = ce.Entries[batch.entryStart : i+1]
4183 } else {
4184 // Get all entries up to and including the current one.
4185 entries = ce.Entries[:i+1]
4186 }
4187 clearAndUnlock := func() {
4188 // Important to clear, otherwise we could return the entries to the pool multiple times.
4189 batch.clearBatchState()
4190 mset.isolateMu.Unlock()
4191 }
4192 // Process remaining entries in the current entry.
4193 for _, entry := range entries {
4194 // Non-normal entries (e.g. EntryCatchup) can be buffered but must be ignored.
4195 if entry.Type != EntryNormal {
4196 continue
4197 }
4198 _, _, op, buf, err = decodeBatchMsg(entry.Data[1:])
4199 if err != nil {
4200 clearAndUnlock()
4201 panic(err.Error())
4202 }
4203 if err = js.applyStreamMsgOp(mset, op, buf, isRecovering, false); err != nil {
4204 clearAndUnlock()
4205 return 0, err
4206 }
4207 }
4208 // Clear state, batch was successful.
4209 batch.clearBatchState()
4210 mset.isolateMu.Unlock()
4211 continue
4212 } else if batch != nil && batch.id != _EMPTY_ {
4213 // If a batch is abandoned without a commit, reject it.
4214 batch.rejectBatchState(mset)
4215 }
4216
4217 switch op {
4218 case streamMsgOp, compressedStreamMsgOp:
4219 mbuf := buf[1:]
4220 if err := js.applyStreamMsgOp(mset, op, mbuf, isRecovering, true); err != nil {
4221 return 0, err
4222 }
4223
4224 case deleteRangeOp:
4225 dr, err := decodeDeleteRange(buf[1:])
4226 if err != nil {
4227 if node := mset.raftNode(); node != nil {
4228 s := js.srv
4229 s.Errorf("JetStream cluster could not decode delete range for '%s > %s' [%s]",
4230 mset.account(), mset.name(), node.Group())
4231 }
4232 panic(err.Error())
4233 }
4234 if dr.Num == 0 {
4235 continue
4236 }
4237 // Delete ranges mutate message state, so hold the isolation lock like any other write.
4238 mset.isolateMu.Lock()
4239 mset.mu.Lock()
4240 first, num := dr.First, dr.Num
4241 lseq := first + num - 1
4242 if mset.lseq >= lseq {
4243 mset.mu.Unlock()
4244 mset.isolateMu.Unlock()
4245 continue
4246 }
4247 // Trim any prefix already applied so we only skip the uncovered tail.
4248 if mset.lseq >= first {
4249 first = mset.lseq + 1
4250 num = lseq - mset.lseq
4251 }
4252 if err = mset.store.SkipMsgs(first, num); err != nil {
4253 mset.mu.Unlock()
4254 mset.isolateMu.Unlock()
4255 js.srv.RateLimitWarnf("JetStream cluster failed to apply delete range [%d..%d] for '%s > %s': %v",
4256 first, lseq, mset.account().Name, mset.cfg.Name, err)
4257 return 0, err
4258 }
4259 mset.clearAllPreAcksInRange(first, lseq)
4260 mset.lseq = lseq
4261 mset.mu.Unlock()
4262 mset.isolateMu.Unlock()
4263
4264 case deleteMsgOp:
4265 md, err := decodeMsgDelete(buf[1:])
4266 if err != nil {
4267 if node := mset.raftNode(); node != nil {
4268 s := js.srv
4269 s.Errorf("JetStream cluster could not decode delete msg for '%s > %s' [%s]",
4270 mset.account(), mset.name(), node.Group())
4271 }
4272 panic(err.Error())
4273 }
4274 s := js.server()
4275
4276 var removed bool
4277 if md.NoErase {
4278 removed, err = mset.removeMsg(md.Seq)
4279 } else {
4280 removed, err = mset.eraseMsg(md.Seq)
4281 }
4282 // Only respond for deletes that originated from a client request.
4283 isClientReq := md.Client != nil
4284
4285 var isLeader bool
4286 if node := mset.raftNode(); node != nil && node.Leader() {
4287 isLeader = true
4288 }
4289
4290 if err == ErrStoreEOF {
4291 if isClientReq && isLeader && !isRecovering {
4292 var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
4293 resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err))
4294 s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
4295 }
4296 continue
4297 }
4298
4299 if err != nil && !isRecovering {
4300 s.Debugf("JetStream cluster failed to delete stream msg %d from '%s > %s': %v",
4301 md.Seq, md.Client.serviceAccount(), md.Stream, err)
4302 }
4303
4304 if isClientReq && isLeader && !isRecovering {
4305 var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
4306 if err != nil {
4307 resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err))
4308 s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
4309 } else if !removed {
4310 resp.Error = NewJSSequenceNotFoundError(md.Seq)
4311 s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
4312 } else {
4313 resp.Success = true
4314 s.sendAPIResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
4315 }
4316 }
4317 case purgeStreamOp:
4318 sp, err := decodeStreamPurge(buf[1:])
4319 if err != nil {
4320 if node := mset.raftNode(); node != nil {
4321 s := js.srv
4322 s.Errorf("JetStream cluster could not decode purge msg for '%s > %s' [%s]",
4323 mset.account(), mset.name(), node.Group())
4324 }
4325 panic(err.Error())
4326 }
4327 // If no explicit request, fill in with leader stamped last sequence to protect ourselves on replay during server start.
4328 if sp.Request == nil || sp.Request.Sequence == 0 {
4329 purgeSeq := sp.LastSeq + 1
4330 if sp.Request == nil {
4331 sp.Request = &JSApiStreamPurgeRequest{Sequence: purgeSeq}
4332 } else if sp.Request.Keep == 0 {
4333 sp.Request.Sequence = purgeSeq
4334 } else if isRecovering {
4335 continue
4336 }
4337 }
4338
4339 s := js.server()
4340 purged, err := mset.purge(sp.Request)
4341 if err != nil {
4342 s.Warnf("JetStream cluster failed to purge stream %q for account %q: %v", sp.Stream, sp.Client.serviceAccount(), err)
4343 }
4344
4345 js.mu.RLock()
4346 isLeader := js.cluster.isStreamLeader(sp.Client.serviceAccount(), sp.Stream)
4347 js.mu.RUnlock()
4348
4349 if isLeader && !isRecovering {
4350 var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
4351 if err != nil {
4352 resp.Error = NewJSStreamGeneralError(err, Unless(err))
4353 s.sendAPIErrResponse(sp.Client, mset.account(), sp.Subject, sp.Reply, _EMPTY_, s.jsonResponse(resp))
4354 } else {
4355 resp.Purged = purged
4356 resp.Success = true
4357 s.sendAPIResponse(sp.Client, mset.account(), sp.Subject, sp.Reply, _EMPTY_, s.jsonResponse(resp))
4358 }
4359 }
4360 default:
4361 panic(fmt.Sprintf("JetStream Cluster Unknown group entry op type: %v", op))
4362 }
4363 } else if e.Type == EntrySnapshot {
4364 // Everything operates on new replicated state. Will convert legacy snapshots to this for processing.
4365 var ss *StreamReplicatedState
4366
4367 onBadState := func(err error) {
4368 // If we are the leader or recovering, meaning we own the snapshot,
4369 // we should stepdown and clear our raft state since our snapshot is bad.
4370 if isRecovering || mset.IsLeader() {
4371 mset.mu.RLock()
4372 s, accName, streamName := mset.srv, mset.acc.GetName(), mset.cfg.Name
4373 mset.mu.RUnlock()
4374 s.Warnf("Detected bad stream state, resetting '%s > %s'", accName, streamName)
4375 mset.resetClusteredState(n, err)
4376 }
4377 }
4378
4379 // Check if we are the new binary encoding.
4380 if IsEncodedStreamState(e.Data) {
4381 var err error
4382 ss, err = DecodeStreamState(e.Data)
4383 if err != nil {
4384 onBadState(err)
4385 return 0, err
4386 }
4387 } else {
4388 var snap streamSnapshot
4389 if err := json.Unmarshal(e.Data, &snap); err != nil {
4390 onBadState(err)
4391 return 0, err
4392 }
4393 // Convert over to StreamReplicatedState
4394 ss = &StreamReplicatedState{
4395 Msgs: snap.Msgs,
4396 Bytes: snap.Bytes,
4397 FirstSeq: snap.FirstSeq,
4398 LastSeq: snap.LastSeq,
4399 Failed: snap.Failed,
4400 }
4401 if len(snap.Deleted) > 0 {
4402 ss.Deleted = append(ss.Deleted, DeleteSlice(snap.Deleted))
4403 }
4404 }
4405
4406 if err := mset.processSnapshot(ss, ce.Index); err != nil {
4407 return 0, err
4408 }
4409 } else if e.Type == EntryRemovePeer {
4410 js.mu.RLock()
4411 var ourID string
4412 if js.cluster != nil && js.cluster.meta != nil {
4413 ourID = js.cluster.meta.ID()
4414 }
4415 js.mu.RUnlock()
4416 // We only need to do processing if this is us.
4417 if peer := string(e.Data); peer == ourID && mset != nil {
4418 // Double check here with the registered stream assignment.
4419 shouldRemove := true
4420 if sa := mset.streamAssignment(); sa != nil && sa.Group != nil {
4421 js.mu.RLock()
4422 shouldRemove = !sa.Group.isMember(ourID)
4423 js.mu.RUnlock()
4424 }
4425 if shouldRemove {
4426 mset.stop(true, false)
4427 }
4428 }
4429 }
4430 }
4431
4432 // If we're still actively processing a batch, must store the entry in-memory
4433 // to come back to it later once we find the commit.
4434 if batch != nil && batch.id != _EMPTY_ {
4435 if batch.entries == nil {
4436 batch.entries = []*CommittedEntry{ce}
4437 } else {
4438 batch.entries = append(batch.entries, ce)
4439 }
4440 maxApplied := batch.maxApplied
4441 return maxApplied, nil
4442 }
4443 return 0, nil
4444 }
4445
4446 // skipBatchIfRecovering returns whether the batched message can be skipped because the batch was already fully applied.
4447 // Stream lock should be held.
4448 func (mset *stream) skipBatchIfRecovering(batch *batchApply, buf []byte) (bool, error) {
4449 _, _, op, mbuf, err := decodeBatchMsg(buf[1:])
4450 if err != nil {
4451 return false, err
4452 }
4453
4454 if op == compressedStreamMsgOp {
4455 if mbuf, err = s2.Decode(nil, mbuf); err != nil {
4456 return false, err
4457 }
4458 }
4459
4460 _, _, _, _, lseq, _, _, err := decodeStreamMsg(mbuf)
4461 if err != nil {
4462 return false, err
4463 }
4464
4465 // Grab last sequence and CLFS.
4466 last, clfs := mset.lastSeqAndCLFS()
4467
4468 // We can skip if we know this is less than what we already have.
4469 if lseq-clfs < last {
4470 mset.srv.Debugf("Apply stream entries for '%s > %s' skipping message with sequence %d with last of %d",
4471 mset.accountLocked(false), mset.nameLocked(false), lseq+1-clfs, last)
4472 // Check for any preAcks in case we are interest based.
4473 mset.clearAllPreAcks(lseq + 1 - clfs)
4474 batch.clearBatchState()
4475 return true, nil
4476 }
4477 return false, nil
4478 }
4479
4480 // needIsolation should be false only if the caller already holds isolateMu
4481 // across a whole atomic batch; mset.mu must NOT be held by the caller.
4482 func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isRecovering bool, needIsolation bool) error {
4483 s := js.srv
4484
4485 if op == compressedStreamMsgOp {
4486 var err error
4487 mbuf, err = s2.Decode(nil, mbuf)
4488 if err != nil {
4489 panic(err.Error())
4490 }
4491 }
4492
4493 subject, reply, hdr, msg, lseq, ts, sourced, err := decodeStreamMsg(mbuf)
4494 if err != nil {
4495 // We're going to panic below, we're not holding the stream lock, so
4496 // we'll not deadlock when trying to get the raft node.
4497 if node := mset.raftNode(); node != nil {
4498 s.Errorf("JetStream cluster could not decode stream msg for '%s > %s' [%s]",
4499 mset.account(), mset.name(), node.Group())
4500 }
4501 panic(err.Error())
4502 }
4503
4504 // Check for flowcontrol here.
4505 if len(msg) == 0 && len(hdr) > 0 && reply != _EMPTY_ && isControlHdr(hdr) {
4506 if !isRecovering {
4507 mset.mu.RLock()
4508 mset.sendFlowControlReply(reply, hdr)
4509 mset.mu.RUnlock()
4510 }
4511 return nil
4512 }
4513
4514 mset.mu.RLock()
4515 // Grab last sequence and CLFS.
4516 last, clfs := mset.lastSeqAndCLFS()
4517 mset.mu.RUnlock()
4518
4519 // We can skip if we know this is less than what we already have.
4520 if lseq-clfs < last {
4521 mset.mu.Lock()
4522 s.Debugf("Apply stream entries for '%s > %s' skipping message with sequence %d with last of %d",
4523 mset.accountLocked(false), mset.nameLocked(false), lseq+1-clfs, last)
4524 // Check for any preAcks in case we are interest based.
4525 mset.clearAllPreAcks(lseq + 1 - clfs)
4526 mset.mu.Unlock()
4527 return nil
4528 }
4529
4530 // Skip by hand here since first msg special case.
4531 // Reason is sequence is unsigned and for lseq being 0
4532 // the lseq under stream would have to be -1.
4533 if lseq == 0 && last != 0 {
4534 return nil
4535 }
4536
4537 // Messages to be skipped have no subject or timestamp or msg or hdr.
4538 if subject == _EMPTY_ && ts == 0 && len(msg) == 0 && len(hdr) == 0 {
4539 // Skip and update our lseq.
4540 last, err := mset.store.SkipMsg(0)
4541 if err != nil {
4542 return err
4543 }
4544 mset.mu.Lock()
4545 mset.lseq = last
4546 mset.clearAllPreAcks(last)
4547 mset.mu.Unlock()
4548 return nil
4549 }
4550
4551 var mt *msgTrace
4552 // If not recovering, see if we find a message trace object for this
4553 // sequence. Only the leader that has proposed this entry will have
4554 // stored the trace info.
4555 if !isRecovering {
4556 mt = mset.getAndDeleteMsgTrace(lseq)
4557 }
4558 // Process the actual message here.
4559 err = mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts, mt, sourced, needIsolation)
4560
4561 // Take into account subject transforms, if any.
4562 // The untransformed subject is replicated, but the transformed subject is used for consistency checks below.
4563 csubject := subject
4564 if mset.inflightTransform != nil {
4565 mset.clMu.Lock()
4566 if subj, found := mset.inflightTransform[lseq]; found {
4567 csubject = subj
4568 delete(mset.inflightTransform, lseq)
4569 }
4570 mset.clMu.Unlock()
4571 }
4572
4573 // If we have inflight make sure to clear after processing.
4574 // TODO(dlc) - technically check on inflight != nil could cause datarace.
4575 // But do not want to acquire lock since tracking this will be rare.
4576 if mset.inflight != nil {
4577 mset.clMu.Lock()
4578 if i, found := mset.inflight[csubject]; found {
4579 // Decrement from pending operations. Once it reaches zero, it can be deleted.
4580 if i.ops > 0 {
4581 var sz uint64
4582 if mset.store.Type() == FileStorage {
4583 sz = fileStoreMsgSizeRaw(len(csubject), len(hdr), len(msg))
4584 } else {
4585 sz = memStoreMsgSizeRaw(len(csubject), len(hdr), len(msg))
4586 }
4587 if i.bytes >= sz {
4588 i.bytes -= sz
4589 } else {
4590 i.bytes = 0
4591 }
4592 i.ops--
4593 }
4594 if i.ops == 0 {
4595 delete(mset.inflight, csubject)
4596 }
4597 }
4598 mset.clMu.Unlock()
4599 }
4600
4601 // Update running total for counter.
4602 if mset.clusteredCounterTotal != nil {
4603 mset.clMu.Lock()
4604 if counter, found := mset.clusteredCounterTotal[csubject]; found {
4605 // Decrement from pending operations. Once it reaches zero, it can be deleted.
4606 if counter.ops > 0 {
4607 counter.ops--
4608 }
4609 if counter.ops == 0 {
4610 delete(mset.clusteredCounterTotal, csubject)
4611 }
4612 }
4613 mset.clMu.Unlock()
4614 }
4615
4616 // Clear expected per subject state after processing.
4617 if mset.expectedPerSubjectSequence != nil {
4618 mset.clMu.Lock()
4619 if subj, found := mset.expectedPerSubjectSequence[lseq]; found {
4620 delete(mset.expectedPerSubjectSequence, lseq)
4621 delete(mset.expectedPerSubjectInProcess, subj)
4622 }
4623 mset.clMu.Unlock()
4624 }
4625
4626 if err != nil {
4627 if err == errLastSeqMismatch {
4628
4629 var state StreamState
4630 mset.store.FastState(&state)
4631
4632 // If we have no msgs and the other side is delivering us a sequence past where we
4633 // should be reset. This is possible if the other side has a stale snapshot and no longer
4634 // has those messages. So compact and retry to reset.
4635 if state.Msgs == 0 {
4636 _, err = mset.store.Compact(lseq + 1)
4637 if err == nil {
4638 // Retry
4639 err = mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts, mt, sourced, needIsolation)
4640 }
4641 }
4642 // FIXME(dlc) - We could just run a catchup with a request defining the span between what we expected
4643 // and what we got.
4644 }
4645
4646 // Only return in place if we are going to reset our stream or we are out of space, or we are closed.
4647 if isClusterResetErr(err) || isOutOfSpaceErr(err) || err == errStreamClosed {
4648 return err
4649 }
4650 s.Debugf("Apply stream entries for '%s > %s' got error processing message: %v",
4651 mset.accountLocked(true), mset.nameLocked(true), err)
4652
4653 // There are some errors that we can't recover from.
4654 if err != ErrMaxMsgs && err != ErrMaxBytes && err != ErrMaxMsgsPerSubject && err != ErrMsgTooLarge && err != ErrStoreClosed {
4655 return err
4656 }
4657 }
4658 return nil
4659 }
4660
4661 // Returns the PeerInfo for all replicas of a raft node. This is different than node.Peers()
4662 // and is used for external facing advisories.
4663 func (s *Server) replicas(node RaftNode) []*PeerInfo {
4664 var replicas []*PeerInfo
4665 for _, rp := range node.Peers() {
4666 if sir, ok := s.nodeToInfo.Load(rp.ID); ok && sir != nil {
4667 si := sir.(nodeInfo)
4668 pi := &PeerInfo{Peer: rp.ID, Name: si.name, Current: rp.Current, Offline: si.offline, Lag: rp.Lag}
4669 if !rp.Last.IsZero() {
4670 pi.Active = time.Since(rp.Last)
4671 }
4672 replicas = append(replicas, pi)
4673 }
4674 }
4675 return replicas
4676 }
4677
4678 // Process a leader change for the clustered stream.
4679 func (js *jetStream) processStreamLeaderChange(mset *stream, isLeader bool, term uint64) {
4680 if mset == nil {
4681 return
4682 }
4683 sa := mset.streamAssignment()
4684 if sa == nil {
4685 return
4686 }
4687
4688 // Acquire clMu before ddMu so any inflight proposals finish first, and we can
4689 // clean up if they added new dedupe IDs.
4690 mset.clMu.Lock()
4691
4692 // Clear inflight dedupe IDs, where seq=0.
4693 mset.ddMu.Lock()
4694 var removed int
4695 for i := len(mset.ddarr) - 1; i >= mset.ddindex; i-- {
4696 dde := mset.ddarr[i]
4697 if dde.seq != 0 {
4698 break
4699 }
4700 removed++
4701 delete(mset.ddmap, dde.id)
4702 }
4703 if removed > 0 {
4704 if len(mset.ddmap) > 0 {
4705 mset.ddarr = mset.ddarr[:len(mset.ddarr)-removed]
4706 } else {
4707 mset.ddmap = nil
4708 mset.ddarr = nil
4709 mset.ddindex = 0
4710 }
4711 }
4712 mset.ddMu.Unlock()
4713
4714 // Clear inflight if we have it.
4715 mset.inflight = nil
4716 mset.inflightTransform = nil
4717 // Clear running counter totals.
4718 mset.clusteredCounterTotal = nil
4719 // Clear expected per subject state.
4720 mset.expectedPerSubjectSequence = nil
4721 mset.expectedPerSubjectInProcess = nil
4722
4723 // Clear clseq on every leader transition. recalculateClusteredSeq
4724 // repopulates it on the next proposal.
4725 if mset.clseq > 0 {
4726 mset.clseq = 0
4727 }
4728 mset.clMu.Unlock()
4729
4730 js.mu.RLock()
4731 s, account, err := js.srv, sa.Client.serviceAccount(), sa.err
4732 client, subject, reply := sa.Client, sa.Subject, sa.Reply
4733 hasResponded := sa.markResponded()
4734 js.mu.RUnlock()
4735
4736 streamName := mset.name()
4737
4738 if isLeader {
4739 s.Noticef("JetStream cluster new stream leader for '%s > %s'", account, streamName)
4740 s.sendStreamLeaderElectAdvisory(mset)
4741 } else {
4742 // We are stepping down.
4743 // Make sure if we are doing so because we have lost quorum that we send the appropriate advisories.
4744 if node := mset.raftNode(); node != nil && !node.Quorum() && time.Since(node.Created()) > 5*time.Second {
4745 s.sendStreamLostQuorumAdvisory(mset)
4746 }
4747 }
4748
4749 // Tell stream to switch leader status.
4750 mset.setLeader(isLeader, term)
4751
4752 if !isLeader || hasResponded {
4753 return
4754 }
4755
4756 acc, _ := s.LookupAccount(account)
4757 if acc == nil {
4758 return
4759 }
4760
4761 // Send our response.
4762 var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}}
4763 if err != nil {
4764 resp.Error = NewJSStreamCreateError(err, Unless(err))
4765 s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
4766 } else {
4767 msetCfg := mset.config()
4768 resp.StreamInfo = &StreamInfo{
4769 Created: mset.createdTime(),
4770 State: mset.state(),
4771 Config: *setDynamicStreamMetadata(&msetCfg),
4772 Cluster: js.clusterInfo(mset.raftGroup()),
4773 Sources: mset.sourcesInfo(),
4774 Mirror: mset.mirrorInfo(),
4775 TimeStamp: time.Now().UTC(),
4776 }
4777 resp.DidCreate = true
4778 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
4779 if node := mset.raftNode(); node != nil {
4780 mset.sendCreateAdvisory()
4781 }
4782 }
4783 }
4784
4785 // Fixed value ok for now.
4786 const lostQuorumAdvInterval = 10 * time.Second
4787
4788 // Determines if we should send lost quorum advisory. We throttle these after first one.
4789 func (mset *stream) shouldSendLostQuorum() bool {
4790 mset.mu.Lock()
4791 defer mset.mu.Unlock()
4792 if time.Since(mset.lqsent) >= lostQuorumAdvInterval {
4793 mset.lqsent = time.Now()
4794 return true
4795 }
4796 return false
4797 }
4798
4799 func (s *Server) sendStreamLostQuorumAdvisory(mset *stream) {
4800 if mset == nil {
4801 return
4802 }
4803 node, stream, acc := mset.raftNode(), mset.name(), mset.account()
4804 if node == nil {
4805 return
4806 }
4807 if !mset.shouldSendLostQuorum() {
4808 return
4809 }
4810
4811 s.Warnf("JetStream cluster stream '%s > %s' has NO quorum, stalled", acc.GetName(), stream)
4812
4813 subj := JSAdvisoryStreamQuorumLostPre + "." + stream
4814 adv := &JSStreamQuorumLostAdvisory{
4815 TypedEvent: TypedEvent{
4816 Type: JSStreamQuorumLostAdvisoryType,
4817 ID: nuid.Next(),
4818 Time: time.Now().UTC(),
4819 },
4820 Stream: stream,
4821 Replicas: s.replicas(node),
4822 Domain: s.getOpts().JetStreamDomain,
4823 }
4824
4825 // Send to the user's account if not the system account.
4826 if acc != s.SystemAccount() {
4827 s.publishAdvisory(acc, subj, adv)
4828 }
4829 // Now do system level one. Place account info in adv, and nil account means system.
4830 adv.Account = acc.GetName()
4831 s.publishAdvisory(nil, subj, adv)
4832 }
4833
4834 func (s *Server) sendStreamLeaderElectAdvisory(mset *stream) {
4835 if mset == nil {
4836 return
4837 }
4838 node, stream, acc := mset.raftNode(), mset.name(), mset.account()
4839 if node == nil {
4840 return
4841 }
4842 subj := JSAdvisoryStreamLeaderElectedPre + "." + stream
4843 adv := &JSStreamLeaderElectedAdvisory{
4844 TypedEvent: TypedEvent{
4845 Type: JSStreamLeaderElectedAdvisoryType,
4846 ID: nuid.Next(),
4847 Time: time.Now().UTC(),
4848 },
4849 Stream: stream,
4850 Leader: s.serverNameForNode(node.GroupLeader()),
4851 Replicas: s.replicas(node),
4852 Domain: s.getOpts().JetStreamDomain,
4853 }
4854
4855 // Send to the user's account if not the system account.
4856 if acc != s.SystemAccount() {
4857 s.publishAdvisory(acc, subj, adv)
4858 }
4859 // Now do system level one. Place account info in adv, and nil account means system.
4860 adv.Account = acc.GetName()
4861 s.publishAdvisory(nil, subj, adv)
4862 }
4863
4864 // Will look up a stream assignment.
4865 // Lock should be held.
4866 func (js *jetStream) streamAssignment(account, stream string) (sa *streamAssignment) {
4867 cc := js.cluster
4868 if cc == nil {
4869 return nil
4870 }
4871
4872 if as := cc.streams[account]; as != nil {
4873 sa = as[stream]
4874 }
4875 return sa
4876 }
4877
4878 // Will look up a stream assignment, either an applied or inflight assignment.
4879 // Lock should be held.
4880 func (js *jetStream) streamAssignmentOrInflight(account, stream string) *streamAssignment {
4881 cc := js.cluster
4882 if cc == nil {
4883 return nil
4884 }
4885 if streams, ok := cc.inflightStreams[account]; ok {
4886 if inflight, ok := streams[stream]; ok {
4887 if !inflight.deleted {
4888 return inflight.streamAssignment
4889 } else {
4890 return nil
4891 }
4892 }
4893 }
4894
4895 if as := cc.streams[account]; as != nil {
4896 return as[stream]
4897 }
4898 return nil
4899 }
4900
4901 // Will gather all stream assignments for a specific account, both applied and inflight assignments.
4902 // Lock should be held.
4903 func (js *jetStream) streamAssignmentsOrInflightSeq(account string) iter.Seq[*streamAssignment] {
4904 return func(yield func(*streamAssignment) bool) {
4905 cc := js.cluster
4906 if cc == nil {
4907 return
4908 }
4909 inflight := cc.inflightStreams[account]
4910 for _, i := range inflight {
4911 if !i.deleted && !yield(i.streamAssignment) {
4912 return
4913 }
4914 }
4915 for _, sa := range cc.streams[account] {
4916 // Skip if we already iterated over it as inflight.
4917 if _, ok := inflight[sa.Config.Name]; ok {
4918 continue
4919 }
4920 if !yield(sa) {
4921 return
4922 }
4923 }
4924 }
4925 }
4926
4927 // Will gather all stream assignments for all accounts, both applied and inflight assignments.
4928 // Lock should be held.
4929 func (js *jetStream) streamAssignmentsOrInflightSeqAllAccounts() iter.Seq2[string, *streamAssignment] {
4930 return func(yield func(string, *streamAssignment) bool) {
4931 cc := js.cluster
4932 if cc == nil {
4933 return
4934 }
4935 for accName, inflight := range cc.inflightStreams {
4936 for _, i := range inflight {
4937 if !i.deleted && !yield(accName, i.streamAssignment) {
4938 return
4939 }
4940 }
4941 }
4942 for accName, asa := range cc.streams {
4943 for _, sa := range asa {
4944 // Skip if we already iterated over it as inflight.
4945 if inflight, ok := cc.inflightStreams[accName]; ok {
4946 if _, ok := inflight[sa.Config.Name]; ok {
4947 continue
4948 }
4949 }
4950 if !yield(accName, sa) {
4951 return
4952 }
4953 }
4954 }
4955 }
4956 }
4957
4958 // processStreamAssignment is called when followers have replicated an assignment.
4959 func (js *jetStream) processStreamAssignment(sa *streamAssignment) {
4960 js.mu.Lock()
4961 s, cc := js.srv, js.cluster
4962 accName, stream := sa.Client.serviceAccount(), sa.Config.Name
4963 noMeta := cc == nil || cc.meta == nil
4964 var ourID string
4965 if !noMeta {
4966 ourID = cc.meta.ID()
4967 }
4968 var isMember bool
4969 if sa.Group != nil && ourID != _EMPTY_ {
4970 isMember = sa.Group.isMember(ourID)
4971 }
4972
4973 if s == nil || noMeta {
4974 js.mu.Unlock()
4975 return
4976 }
4977
4978 // Remove this stream from the inflight proposals
4979 cc.removeInflightStreamProposal(accName, sa.Config.Name)
4980
4981 accStreams := cc.streams[accName]
4982 if accStreams == nil {
4983 accStreams = make(map[string]*streamAssignment)
4984 } else if osa := accStreams[stream]; osa != nil {
4985 if osa != sa {
4986 // Copy over private existing state from former SA.
4987 if sa.Group != nil {
4988 sa.Group.node = osa.Group.node
4989 }
4990 sa.consumers = osa.consumers
4991 if osa.hasResponded() {
4992 sa.markResponded()
4993 }
4994 sa.err = osa.err
4995 }
4996 // Unsubscribe if it was previously unsupported.
4997 if osa.unsupported != nil {
4998 osa.unsupported.closeInfoSub(js.srv)
4999 // If we've seen unsupported once, it remains for the lifetime of this server process.
5000 if sa.unsupported == nil {
5001 sa.unsupported = osa.unsupported
5002 }
5003 }
5004 }
5005
5006 // Update our state.
5007 accStreams[stream] = sa
5008 cc.streams[accName] = accStreams
5009 hasResponded := sa.hasResponded()
5010
5011 // If unsupported, we can't register any further.
5012 if sa.unsupported != nil {
5013 sa.unsupported.setupInfoSub(s, sa)
5014 s.Warnf("Detected unsupported stream '%s > %s': %s", accName, stream, sa.unsupported.reason)
5015 js.mu.Unlock()
5016
5017 // Need to stop the stream, we can't keep running with an old config.
5018 acc, err := s.lookupOrFetchAccount(accName, isMember)
5019 if err != nil {
5020 return
5021 }
5022 mset, err := acc.lookupStream(stream)
5023 if err != nil || mset.closed.Load() {
5024 return
5025 }
5026 s.Warnf("Stopping unsupported stream '%s > %s'", accName, stream)
5027 mset.stop(false, false)
5028 return
5029 }
5030 js.mu.Unlock()
5031
5032 acc, err := s.lookupOrFetchAccount(accName, isMember)
5033 if err != nil {
5034 ll := fmt.Sprintf("Account [%s] lookup for stream create failed: %v", accName, err)
5035 if isMember {
5036 if !hasResponded {
5037 // If we can not lookup the account and we are a member, send this result back to the metacontroller leader.
5038 result := &streamAssignmentResult{
5039 Account: accName,
5040 Stream: stream,
5041 Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
5042 }
5043 result.Response.Error = NewJSNoAccountError()
5044 s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
5045 }
5046 s.Warnf(ll)
5047 } else {
5048 s.Debugf(ll)
5049 }
5050 return
5051 }
5052
5053 // Check if this is for us..
5054 if isMember {
5055 js.processClusterCreateStream(acc, sa)
5056 } else if mset, _ := acc.lookupStream(sa.Config.Name); mset != nil {
5057 // We have one here even though we are not a member. This can happen on re-assignment.
5058 s.removeStream(mset, sa)
5059 }
5060
5061 // If this stream assignment does not have a sync subject (bug) set that the meta-leader should check when elected.
5062 if sa.Sync == _EMPTY_ {
5063 js.mu.Lock()
5064 cc.streamsCheck = true
5065 js.mu.Unlock()
5066 }
5067 }
5068
5069 // processUpdateStreamAssignment is called when followers have replicated an updated assignment.
5070 func (js *jetStream) processUpdateStreamAssignment(sa *streamAssignment) {
5071 js.mu.RLock()
5072 s, cc := js.srv, js.cluster
5073 js.mu.RUnlock()
5074 if s == nil || cc == nil {
5075 // TODO(dlc) - debug at least
5076 return
5077 }
5078
5079 accName := sa.Client.serviceAccount()
5080 stream := sa.Config.Name
5081
5082 js.mu.Lock()
5083 if cc.meta == nil {
5084 js.mu.Unlock()
5085 return
5086 }
5087
5088 // Remove this stream from the inflight proposals
5089 cc.removeInflightStreamProposal(accName, sa.Config.Name)
5090
5091 ourID := cc.meta.ID()
5092
5093 var isMember bool
5094 if sa.Group != nil {
5095 isMember = sa.Group.isMember(ourID)
5096 }
5097
5098 accStreams := cc.streams[accName]
5099 if accStreams == nil {
5100 js.mu.Unlock()
5101 return
5102 }
5103 osa := accStreams[stream]
5104 if osa == nil {
5105 js.mu.Unlock()
5106 return
5107 }
5108
5109 // Copy over private existing state from former SA.
5110 if sa.Group != nil {
5111 sa.Group.node = osa.Group.node
5112 }
5113 sa.consumers = osa.consumers
5114 sa.err = osa.err
5115
5116 // If we detect we are scaling down to 1, non-clustered, and we had a previous node, clear it here.
5117 if sa.Config.Replicas == 1 && sa.Group.node != nil {
5118 sa.Group.node = nil
5119 }
5120
5121 // Update our state.
5122 accStreams[stream] = sa
5123 cc.streams[accName] = accStreams
5124
5125 // Make sure we respond if we are a member.
5126 if isMember {
5127 sa.clearResponded()
5128 } else {
5129 // Make sure to clean up any old node in case this stream moves back here.
5130 if sa.Group != nil {
5131 sa.Group.node = nil
5132 }
5133 }
5134
5135 // Unsubscribe if it was previously unsupported.
5136 if osa.unsupported != nil {
5137 osa.unsupported.closeInfoSub(js.srv)
5138 // If we've seen unsupported once, it remains for the lifetime of this server process.
5139 if sa.unsupported == nil {
5140 sa.unsupported = osa.unsupported
5141 }
5142 }
5143
5144 // If unsupported, we can't register any further.
5145 if sa.unsupported != nil {
5146 sa.unsupported.setupInfoSub(s, sa)
5147 s.Warnf("Detected unsupported stream '%s > %s': %s", accName, stream, sa.unsupported.reason)
5148 js.mu.Unlock()
5149
5150 // Need to stop the stream, we can't keep running with an old config.
5151 acc, err := s.lookupOrFetchAccount(accName, isMember)
5152 if err != nil {
5153 return
5154 }
5155 mset, err := acc.lookupStream(stream)
5156 if err != nil || mset.closed.Load() {
5157 return
5158 }
5159 s.Warnf("Stopping unsupported stream '%s > %s'", accName, stream)
5160 mset.stop(false, false)
5161 return
5162 }
5163 js.mu.Unlock()
5164
5165 acc, err := s.lookupOrFetchAccount(accName, isMember)
5166 if err != nil {
5167 ll := fmt.Sprintf("Update Stream Account %s, error on lookup: %v", accName, err)
5168 if isMember {
5169 s.Warnf(ll)
5170 } else {
5171 s.Debugf(ll)
5172 }
5173 return
5174 }
5175
5176 // Check if this is for us..
5177 if isMember {
5178 js.processClusterUpdateStream(acc, osa, sa)
5179 } else if mset, _ := acc.lookupStream(sa.Config.Name); mset != nil {
5180 // We have one here even though we are not a member. This can happen on re-assignment.
5181 s.removeStream(mset, sa)
5182 }
5183 }
5184
5185 // Common function to remove ourselves from this server.
5186 // This can happen on re-assignment, move, etc
5187 func (s *Server) removeStream(mset *stream, nsa *streamAssignment) {
5188 if mset == nil {
5189 return
5190 }
5191 // Make sure to use the new stream assignment, not our own.
5192 s.Debugf("JetStream removing stream '%s > %s' from this server", nsa.Client.serviceAccount(), nsa.Config.Name)
5193 if node := mset.raftNode(); node != nil {
5194 node.StepDown(nsa.Group.Preferred)
5195 // shutdown monitor by shutting down raft.
5196 node.Delete()
5197 }
5198
5199 var isShuttingDown bool
5200 // Make sure this node is no longer attached to our stream assignment.
5201 if js, _ := s.getJetStreamCluster(); js != nil {
5202 js.mu.Lock()
5203 nsa.Group.node = nil
5204 nsa.err = nil
5205 isShuttingDown = js.shuttingDown
5206 js.mu.Unlock()
5207 }
5208
5209 if !isShuttingDown {
5210 // wait for monitor to be shutdown.
5211 mset.stopMonitoring()
5212 }
5213 mset.stop(true, false)
5214 }
5215
5216 // processClusterUpdateStream is called when we have a stream assignment that
5217 // has been updated for an existing assignment and we are a member.
5218 func (js *jetStream) processClusterUpdateStream(acc *Account, osa, sa *streamAssignment) {
5219 if sa == nil {
5220 return
5221 }
5222
5223 js.mu.RLock()
5224 s, rg := js.srv, sa.Group
5225 client, subject, reply := sa.Client, sa.Subject, sa.Reply
5226 alreadyRunning, oldNumReplicas, numReplicas := osa.Group.node != nil, len(osa.Group.Peers), len(rg.Peers)
5227 needsNode := rg.node == nil
5228 storage, cfg := sa.Config.Storage, sa.Config
5229 recovering := sa.recovering
5230 hasResponded := sa.markResponded()
5231 hadErr := sa.err != nil
5232 js.mu.RUnlock()
5233
5234 mset, err := acc.lookupStream(cfg.Name)
5235 if err == nil && mset != nil {
5236 // Make sure we have not had a new group assigned to us.
5237 if osa.Group.Name != sa.Group.Name {
5238 s.Warnf("JetStream cluster detected stream remapping for '%s > %s' from %q to %q",
5239 acc, cfg.Name, osa.Group.Name, sa.Group.Name)
5240 mset.removeNode()
5241 mset.stopMonitoring()
5242 alreadyRunning, needsNode = false, true
5243 // Make sure to clear from original.
5244 js.mu.Lock()
5245 osa.Group.node = nil
5246 js.mu.Unlock()
5247 }
5248
5249 if !alreadyRunning && numReplicas > 1 {
5250 if needsNode {
5251 // Must run before startClusterSubs reads mset.sa.Sync.
5252 mset.setStreamAssignment(sa)
5253
5254 // Since we are scaling up we want to make sure our sync subject
5255 // is registered before we start our raft node.
5256 mset.mu.Lock()
5257 mset.startClusterSubs()
5258 mset.mu.Unlock()
5259
5260 js.createRaftGroup(acc.GetName(), rg, recovering, storage, pprofLabels{
5261 "type": "stream",
5262 "account": mset.accName(),
5263 "stream": mset.name(),
5264 })
5265 }
5266 mset.startMonitorWg()
5267 // Start monitoring..
5268 started := s.startGoRoutine(
5269 func() { js.monitorStream(mset, sa, needsNode) },
5270 pprofLabels{
5271 "type": "stream",
5272 "account": mset.accName(),
5273 "stream": mset.name(),
5274 },
5275 )
5276 if !started {
5277 mset.monitorWg.Done()
5278 }
5279 } else if numReplicas == 1 && alreadyRunning {
5280 // We downgraded to R1. Make sure we cleanup the raft node and the stream monitor.
5281 mset.removeNode()
5282 mset.stopMonitoring()
5283 // In case we need to shutdown the cluster specific subs, etc.
5284 mset.mu.Lock()
5285 // Stop responding to sync requests.
5286 mset.stopClusterSubs()
5287 // Clear catchup state
5288 mset.clearAllCatchupPeers()
5289 mset.mu.Unlock()
5290 // Remove from meta layer.
5291 js.mu.Lock()
5292 rg.node = nil
5293 js.mu.Unlock()
5294 }
5295 // Set the new stream assignment.
5296 mset.setStreamAssignment(sa)
5297
5298 // Call update.
5299 err = mset.updateWithAdvisory(cfg, !recovering, false)
5300 }
5301
5302 // If not found we must be expanding into this node since if we are here we know we are a member.
5303 if err == ErrJetStreamStreamNotFound {
5304 js.processStreamAssignment(sa)
5305 return
5306 }
5307
5308 if err != nil {
5309 js.mu.Lock()
5310 s.Warnf("Stream update failed for '%s > %s': %v", sa.Client.serviceAccount(), sa.Config.Name, err)
5311 sa.err = err
5312 result := &streamAssignmentResult{
5313 Account: sa.Client.serviceAccount(),
5314 Stream: sa.Config.Name,
5315 Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
5316 Update: true,
5317 }
5318 result.Response.Error = NewJSStreamGeneralError(err, Unless(err))
5319 js.mu.Unlock()
5320
5321 // Send response to the metadata leader. They will forward to the user as needed.
5322 s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
5323 return
5324 } else if hadErr {
5325 js.mu.Lock()
5326 sa.err = nil
5327 js.mu.Unlock()
5328 }
5329
5330 isLeader := mset.IsLeader()
5331
5332 // If the stream is scaled down, there is a chance we weren't already the leader.
5333 if isLeader && numReplicas == 1 && oldNumReplicas > 1 {
5334 js.processStreamLeaderChange(mset, true, 0)
5335 }
5336
5337 // Check for missing syncSubject bug.
5338 if isLeader && osa != nil && osa.Sync == _EMPTY_ {
5339 if node := mset.raftNode(); node != nil {
5340 node.StepDown()
5341 }
5342 return
5343 }
5344
5345 // If we were a single node being promoted assume leadership role for purpose of responding.
5346 if !hasResponded && !isLeader && !alreadyRunning {
5347 isLeader = true
5348 }
5349
5350 // Check if we should bail.
5351 if !isLeader || hasResponded || recovering {
5352 return
5353 }
5354
5355 // Send our response.
5356 var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}}
5357 msetCfg := mset.config()
5358 resp.StreamInfo = &StreamInfo{
5359 Created: mset.createdTime(),
5360 State: mset.state(),
5361 Config: *setDynamicStreamMetadata(&msetCfg),
5362 Cluster: js.clusterInfo(mset.raftGroup()),
5363 Mirror: mset.mirrorInfo(),
5364 Sources: mset.sourcesInfo(),
5365 TimeStamp: time.Now().UTC(),
5366 }
5367
5368 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
5369 }
5370
5371 // processClusterCreateStream is called when we have a stream assignment that
5372 // has been committed and this server is a member of the peer group.
5373 func (js *jetStream) processClusterCreateStream(acc *Account, sa *streamAssignment) {
5374 if sa == nil {
5375 return
5376 }
5377
5378 js.mu.RLock()
5379 s, rg, created := js.srv, sa.Group, sa.Created
5380 alreadyRunning := rg.node != nil
5381 storage := sa.Config.Storage
5382 restore := sa.Restore
5383 recovering := sa.recovering
5384 hadErr := sa.err != nil
5385 js.mu.RUnlock()
5386
5387 // Process the raft group and make sure it's running if needed.
5388 _, err := js.createRaftGroup(acc.GetName(), rg, recovering, storage, pprofLabels{
5389 "type": "stream",
5390 "account": acc.Name,
5391 "stream": sa.Config.Name,
5392 })
5393
5394 // If we are restoring, create the stream if we are R>1 and not the preferred who handles the
5395 // receipt of the snapshot itself.
5396 shouldCreate := true
5397 if restore != nil {
5398 if len(rg.Peers) == 1 || rg.node != nil && rg.node.ID() == rg.Preferred {
5399 shouldCreate = false
5400 } else {
5401 js.mu.Lock()
5402 sa.Restore = nil
5403 js.mu.Unlock()
5404 }
5405 }
5406
5407 // Our stream.
5408 var mset *stream
5409
5410 // Process here if not restoring or not the leader.
5411 if shouldCreate && err == nil {
5412 // Go ahead and create or update the stream.
5413 mset, err = acc.lookupStream(sa.Config.Name)
5414 if err == nil && mset != nil {
5415 osa := mset.streamAssignment()
5416 // If we already have a stream assignment and they are the same exact config, short circuit here.
5417 if osa != nil {
5418 if reflect.DeepEqual(osa.Config, sa.Config) {
5419 if sa.Group.Name == osa.Group.Name && reflect.DeepEqual(sa.Group.Peers, osa.Group.Peers) {
5420 // Since this already exists we know it succeeded, just respond to this caller.
5421 js.mu.RLock()
5422 client, subject, reply, recovering := sa.Client, sa.Subject, sa.Reply, sa.recovering
5423 js.mu.RUnlock()
5424
5425 if !recovering {
5426 var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}}
5427 msetCfg := mset.config()
5428 resp.StreamInfo = &StreamInfo{
5429 Created: mset.createdTime(),
5430 State: mset.state(),
5431 Config: *setDynamicStreamMetadata(&msetCfg),
5432 Cluster: js.clusterInfo(mset.raftGroup()),
5433 Sources: mset.sourcesInfo(),
5434 Mirror: mset.mirrorInfo(),
5435 TimeStamp: time.Now().UTC(),
5436 }
5437 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
5438 }
5439 return
5440 } else {
5441 // We had a bug where we could have multiple assignments for the same
5442 // stream but with different group assignments, including multiple raft
5443 // groups. So check for that here. We can only bet on the last one being
5444 // consistent in the long run, so let it continue if we see this condition.
5445 s.Warnf("JetStream cluster detected duplicate assignment for stream %q for account %q", sa.Config.Name, acc.Name)
5446 if osa.Group.node != nil && osa.Group.node != sa.Group.node {
5447 osa.Group.node.Delete()
5448 osa.Group.node = nil
5449 }
5450 }
5451 }
5452 }
5453 mset.setStreamAssignment(sa)
5454 // Check if our config has really been updated.
5455 cfg := mset.config()
5456 if !reflect.DeepEqual(&cfg, sa.Config) {
5457 if err = mset.updateWithAdvisory(sa.Config, false, false); err != nil {
5458 if js.isShuttingDown() {
5459 s.Debugf("Could not update stream, JetStream shutting down")
5460 return
5461 }
5462 s.Warnf("JetStream cluster error updating stream %q for account %q: %v", sa.Config.Name, acc.Name, err)
5463 js.mu.Lock()
5464 sa.err = err
5465 // Detach the node from the assignment; we stop (not delete) it below,
5466 // and it unregisters itself once its goroutines exit.
5467 if sa.Group != nil {
5468 sa.Group.node = nil
5469 }
5470 js.mu.Unlock()
5471 // Stop the monitor and raft node without deleting any state.
5472 mset.stopMonitoring()
5473 mset.stop(false, false)
5474 return
5475 }
5476 }
5477 } else if err == NewJSStreamNotFoundError() {
5478 // Add in the stream here.
5479 mset, err = acc.addStreamWithAssignment(sa.Config, nil, sa, false, true)
5480 }
5481 if mset != nil {
5482 mset.setCreatedTime(created)
5483 }
5484 }
5485
5486 // This is an error condition.
5487 if err != nil {
5488 // If we're shutting down we could get a variety of errors, for example:
5489 // 'JetStream not enabled for account' when looking up the stream.
5490 // Normally we can continue and delete state, but need to be careful when shutting down.
5491 if js.isShuttingDown() {
5492 s.Debugf("Could not create stream, JetStream shutting down")
5493 return
5494 }
5495
5496 s.Warnf("Stream create failed for '%s > %s': %v", sa.Client.serviceAccount(), sa.Config.Name, err)
5497 if IsNatsErr(err, JSStreamStoreFailedF) {
5498 err = errStreamStoreFailed
5499 }
5500 js.mu.Lock()
5501
5502 sa.err = err
5503 hasResponded := sa.hasResponded()
5504
5505 // If out of space do nothing for now.
5506 if isOutOfSpaceErr(err) {
5507 hasResponded = true
5508 }
5509
5510 if rg.node != nil {
5511 rg.node.Delete()
5512 }
5513
5514 var result *streamAssignmentResult
5515 if !hasResponded {
5516 result = &streamAssignmentResult{
5517 Account: sa.Client.serviceAccount(),
5518 Stream: sa.Config.Name,
5519 Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
5520 }
5521 result.Response.Error = NewJSStreamCreateError(err, Unless(err))
5522 }
5523 js.mu.Unlock()
5524
5525 // Send response to the metadata leader. They will forward to the user as needed.
5526 if result != nil {
5527 s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
5528 }
5529 return
5530 } else if hadErr {
5531 js.mu.Lock()
5532 sa.err = nil
5533 js.mu.Unlock()
5534 }
5535
5536 // Re-capture node.
5537 js.mu.RLock()
5538 node := rg.node
5539 js.mu.RUnlock()
5540
5541 // Start our monitoring routine.
5542 if node != nil {
5543 if !alreadyRunning {
5544 if mset != nil {
5545 mset.startMonitorWg()
5546 }
5547 started := s.startGoRoutine(
5548 func() { js.monitorStream(mset, sa, false) },
5549 pprofLabels{
5550 "type": "stream",
5551 "account": mset.accName(),
5552 "stream": mset.name(),
5553 },
5554 )
5555 if !started && mset != nil {
5556 mset.monitorWg.Done()
5557 }
5558 }
5559 } else {
5560 // Single replica stream, process manually here.
5561 // If we are restoring, process that first.
5562 if sa.Restore != nil {
5563 // We are restoring a stream here.
5564 restoreDoneCh := s.processStreamRestore(sa.Client, acc, sa.Config, _EMPTY_, sa.Reply, _EMPTY_)
5565 s.startGoRoutine(func() {
5566 defer s.grWG.Done()
5567 select {
5568 case err := <-restoreDoneCh:
5569 if err == nil {
5570 mset, err = acc.lookupStream(sa.Config.Name)
5571 if mset != nil {
5572 mset.setStreamAssignment(sa)
5573 mset.setCreatedTime(created)
5574 }
5575 }
5576 if err != nil {
5577 if mset != nil {
5578 mset.delete()
5579 }
5580 js.mu.Lock()
5581 s.Warnf("Stream restore failed for '%s > %s': %v", sa.Client.serviceAccount(), sa.Config.Name, err)
5582 sa.err = err
5583 result := &streamAssignmentResult{
5584 Account: sa.Client.serviceAccount(),
5585 Stream: sa.Config.Name,
5586 Restore: &JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}},
5587 }
5588 result.Restore.Error = NewJSStreamRestoreError(err, Unless(err))
5589 js.mu.Unlock()
5590 // Send response to the metadata leader. They will forward to the user as needed.
5591 b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
5592 s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, b)
5593 return
5594 }
5595 js.processStreamLeaderChange(mset, true, 0)
5596
5597 // Check to see if we have restored consumers here.
5598 // These are not currently assigned so we will need to do so here.
5599 if consumers := mset.getPublicConsumers(); len(consumers) > 0 {
5600 // Need to read meta under the js lock, it's set to nil on shutdown.
5601 js.mu.RLock()
5602 cc := js.cluster
5603 meta := cc.meta
5604 js.mu.RUnlock()
5605 if meta == nil {
5606 // We are shutting down.
5607 return
5608 }
5609
5610 for _, o := range consumers {
5611 name, cfg := o.String(), o.config()
5612 rg, err := cc.createGroupForConsumer(&cfg, sa)
5613 if err != nil {
5614 s.Warnf("Could not create group for consumer '%s > %s > %s': %v",
5615 sa.Client.serviceAccount(), sa.Config.Name, name, err)
5616 continue
5617 }
5618
5619 // Place our initial state here as well for assignment distribution.
5620 ca := &consumerAssignment{
5621 Group: rg,
5622 Stream: sa.Config.Name,
5623 Name: name,
5624 Config: &cfg,
5625 Client: sa.Client,
5626 Created: o.createdTime(),
5627 }
5628
5629 addEntry := encodeAddConsumerAssignment(ca)
5630 meta.ForwardProposal(addEntry)
5631
5632 // Check to make sure we see the assignment.
5633 go func() {
5634 ticker := time.NewTicker(time.Second)
5635 defer ticker.Stop()
5636 for range ticker.C {
5637 js.mu.RLock()
5638 ca, meta := js.consumerAssignment(ca.Client.serviceAccount(), sa.Config.Name, name), cc.meta
5639 js.mu.RUnlock()
5640 if ca == nil {
5641 s.Warnf("Consumer assignment has not been assigned, retrying")
5642 if meta != nil {
5643 meta.ForwardProposal(addEntry)
5644 } else {
5645 return
5646 }
5647 } else {
5648 return
5649 }
5650 }
5651 }()
5652 }
5653 }
5654 case <-s.quitCh:
5655 return
5656 }
5657 })
5658 } else {
5659 js.processStreamLeaderChange(mset, true, 0)
5660 }
5661 }
5662 }
5663
5664 // processStreamRemoval is called when followers have replicated an assignment.
5665 func (js *jetStream) processStreamRemoval(sa *streamAssignment) {
5666 js.mu.Lock()
5667 s, cc := js.srv, js.cluster
5668 if s == nil || cc == nil || cc.meta == nil {
5669 // TODO(dlc) - debug at least
5670 js.mu.Unlock()
5671 return
5672 }
5673 accName, stream, created := sa.Client.serviceAccount(), sa.Config.Name, sa.Created
5674 var isMember bool
5675 if sa.Group != nil {
5676 isMember = sa.Group.isMember(cc.meta.ID())
5677 }
5678 wasLeader := cc.isStreamLeader(accName, stream)
5679
5680 // Check if we already have this assigned.
5681 accStreams := cc.streams[accName]
5682 needDelete := accStreams != nil && accStreams[stream] != nil
5683 if needDelete {
5684 if osa := accStreams[stream]; osa != nil && osa.unsupported != nil {
5685 osa.unsupported.closeInfoSub(js.srv)
5686 // Remember we used to be unsupported, just so we can send a successful delete response.
5687 if sa.unsupported == nil {
5688 sa.unsupported = osa.unsupported
5689 }
5690 }
5691 delete(accStreams, stream)
5692 if len(accStreams) == 0 {
5693 delete(cc.streams, accName)
5694 }
5695 }
5696 cc.removeInflightStreamProposal(accName, sa.Config.Name)
5697 js.mu.Unlock()
5698
5699 // During initial/startup recovery we'll not have registered the stream assignment,
5700 // but might have recovered the stream from disk. We'll need to make sure that we only
5701 // delete the stream if it wasn't created after this delete.
5702 if !needDelete && !created.IsZero() {
5703 if acc, err := s.lookupOrFetchAccount(accName, isMember); err == nil {
5704 if mset, err := acc.lookupStream(stream); err == nil {
5705 needDelete = !mset.createdTime().After(created)
5706 }
5707 }
5708 }
5709
5710 if needDelete {
5711 js.processClusterDeleteStream(sa, isMember, wasLeader)
5712 }
5713 }
5714
5715 func (js *jetStream) processClusterDeleteStream(sa *streamAssignment, isMember, wasLeader bool) {
5716 if sa == nil {
5717 return
5718 }
5719 js.mu.RLock()
5720 s := js.srv
5721 node := sa.Group.node
5722 hadLeader := node == nil || !node.Leaderless()
5723 offline := s.allPeersOffline(sa.Group) || sa.unsupported != nil
5724 var isMetaLeader bool
5725 if cc := js.cluster; cc != nil {
5726 isMetaLeader = cc.isLeader()
5727 }
5728 recovering := sa.recovering
5729 js.mu.RUnlock()
5730
5731 stopped := false
5732 var resp = JSApiStreamDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamDeleteResponseType}}
5733 var err error
5734 var acc *Account
5735
5736 // Go ahead and delete the stream if we have it and the account here.
5737 if acc, _ = s.LookupAccount(sa.Client.serviceAccount()); acc != nil {
5738 if mset, _ := acc.lookupStream(sa.Config.Name); mset != nil {
5739 // shut down monitor by shutting down raft
5740 if n := mset.raftNode(); n != nil {
5741 n.Delete()
5742 }
5743 // wait for monitor to be shut down
5744 mset.stopMonitoring()
5745 err = mset.stop(true, wasLeader)
5746 stopped = true
5747 } else if isMember {
5748 s.Warnf("JetStream failed to lookup running stream while removing stream '%s > %s' from this server",
5749 sa.Client.serviceAccount(), sa.Config.Name)
5750 }
5751 } else if isMember {
5752 s.Warnf("JetStream failed to lookup account while removing stream '%s > %s' from this server", sa.Client.serviceAccount(), sa.Config.Name)
5753 }
5754
5755 // Always delete the node if present.
5756 if node != nil {
5757 node.Delete()
5758 }
5759
5760 // This is a stop gap cleanup in case
5761 // 1) the account or mset does not exist and/or
5762 // 2) node was nil (and couldn't be deleted)
5763 if !stopped || node == nil {
5764 if sacc := s.SystemAccount(); sacc != nil {
5765 saccName := sacc.GetName()
5766 os.RemoveAll(filepath.Join(js.config.StoreDir, saccName, defaultStoreDirName, sa.Group.Name))
5767 // cleanup dependent consumer groups
5768 if !stopped {
5769 for _, ca := range sa.consumers {
5770 // Make sure we cleanup any possible running nodes for the consumers.
5771 if isMember && ca.Group != nil && ca.Group.node != nil {
5772 ca.Group.node.Delete()
5773 }
5774 os.RemoveAll(filepath.Join(js.config.StoreDir, saccName, defaultStoreDirName, ca.Group.Name))
5775 }
5776 }
5777 }
5778 }
5779 accDir := filepath.Join(js.config.StoreDir, sa.Client.serviceAccount())
5780 streamDir := filepath.Join(accDir, streamsDir)
5781 os.RemoveAll(filepath.Join(streamDir, sa.Config.Name))
5782
5783 // no op if not empty
5784 os.Remove(streamDir)
5785 os.Remove(accDir)
5786
5787 // Normally we want only the leader to respond here, but if we had no leader then all members will respond to make
5788 // sure we get feedback to the user.
5789 if !isMember || (hadLeader && !wasLeader) {
5790 // If all the peers are offline and we are the meta leader we will also respond, so suppress returning here.
5791 if !(offline && isMetaLeader) {
5792 return
5793 }
5794 }
5795
5796 // Do not respond if the account does not exist any longer
5797 if acc == nil || recovering {
5798 return
5799 }
5800
5801 if err != nil {
5802 resp.Error = NewJSStreamGeneralError(err, Unless(err))
5803 s.sendAPIErrResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, s.jsonResponse(resp))
5804 } else {
5805 resp.Success = true
5806 s.sendAPIResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, s.jsonResponse(resp))
5807 }
5808 }
5809
5810 // processConsumerAssignment is called when followers have replicated an assignment for a consumer.
5811 func (js *jetStream) processConsumerAssignment(ca *consumerAssignment) {
5812 js.mu.RLock()
5813 s, cc := js.srv, js.cluster
5814 accName, stream, consumerName := ca.Client.serviceAccount(), ca.Stream, ca.Name
5815 noMeta := cc == nil || cc.meta == nil
5816 shuttingDown := js.shuttingDown
5817 var ourID string
5818 if !noMeta {
5819 ourID = cc.meta.ID()
5820 }
5821 var isMember bool
5822 if ca.Group != nil && ourID != _EMPTY_ {
5823 isMember = ca.Group.isMember(ourID)
5824 }
5825 js.mu.RUnlock()
5826
5827 if s == nil || noMeta || shuttingDown {
5828 return
5829 }
5830
5831 js.mu.Lock()
5832 sa := js.streamAssignment(accName, stream)
5833 if sa == nil {
5834 js.mu.Unlock()
5835 s.Debugf("Consumer create failed, could not locate stream '%s > %s'", accName, stream)
5836 return
5837 }
5838
5839 // Track if this existed already.
5840 var wasExisting bool
5841
5842 // Check if we have an existing consumer assignment.
5843 if sa.consumers == nil {
5844 sa.consumers = make(map[string]*consumerAssignment)
5845 }
5846 oca := sa.consumers[ca.Name]
5847 if oca != nil {
5848 wasExisting = true
5849 // Copy over private existing state from former CA.
5850 if ca.Group != nil {
5851 ca.Group.node = oca.Group.node
5852 }
5853 if oca.hasResponded() {
5854 ca.markResponded()
5855 }
5856 ca.err = oca.err
5857
5858 // Unsubscribe if it was previously unsupported.
5859 if oca.unsupported != nil {
5860 oca.unsupported.closeInfoSub(s)
5861 // If we've seen unsupported once, it remains for the lifetime of this server process.
5862 if ca.unsupported == nil {
5863 ca.unsupported = oca.unsupported
5864 }
5865 }
5866 }
5867
5868 // Capture the optional state. We will pass it along if we are a member to apply.
5869 // This is only applicable when restoring a stream with consumers.
5870 state := ca.State
5871 ca.State = nil
5872
5873 // Place into our internal map under the stream assignment.
5874 // Ok to replace an existing one, we check on process call below.
5875 sa.consumers[ca.Name] = ca
5876 cc.removeInflightConsumerProposal(accName, stream, consumerName)
5877
5878 // If unsupported, we can't register any further.
5879 if ca.unsupported != nil {
5880 ca.unsupported.setupInfoSub(s, ca)
5881 s.Warnf("Detected unsupported consumer '%s > %s > %s': %s", accName, stream, ca.Name, ca.unsupported.reason)
5882
5883 // Mark stream as unsupported as well
5884 if sa.unsupported == nil {
5885 sa.unsupported = newUnsupportedStreamAssignment(s, sa, fmt.Errorf("unsupported consumer %q", ca.Name))
5886 }
5887 sa.unsupported.setupInfoSub(s, sa)
5888 js.mu.Unlock()
5889
5890 // Be conservative by protecting the whole stream, even if just one consumer is unsupported.
5891 // This ensures it's safe, even with Interest-based retention where it would otherwise
5892 // continue accepting but dropping messages.
5893 acc, err := s.lookupOrFetchAccount(accName, isMember)
5894 if err != nil {
5895 return
5896 }
5897 mset, err := acc.lookupStream(stream)
5898 if err != nil || mset.closed.Load() {
5899 return
5900 }
5901 s.Warnf("Stopping unsupported stream '%s > %s'", accName, stream)
5902 mset.stop(false, false)
5903 return
5904 }
5905 js.mu.Unlock()
5906
5907 acc, err := s.lookupOrFetchAccount(accName, isMember)
5908 if err != nil {
5909 ll := fmt.Sprintf("Account [%s] lookup for consumer create failed: %v", accName, err)
5910 if isMember {
5911 if !js.isMetaRecovering() {
5912 // If we can not lookup the account and we are a member, send this result back to the metacontroller leader.
5913 result := &consumerAssignmentResult{
5914 Account: accName,
5915 Stream: stream,
5916 Consumer: consumerName,
5917 Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
5918 }
5919 result.Response.Error = NewJSNoAccountError()
5920 s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, result)
5921 }
5922 s.Warnf(ll)
5923 } else {
5924 s.Debugf(ll)
5925 }
5926 return
5927 }
5928
5929 // Check if this is for us..
5930 if isMember {
5931 js.processClusterCreateConsumer(oca, ca, state, wasExisting)
5932 } else if mset, _ := acc.lookupStream(sa.Config.Name); mset != nil {
5933 if o := mset.lookupConsumer(ca.Name); o != nil {
5934 // We have one here even though we are not a member. This can happen on re-assignment.
5935 s.removeConsumer(o, ca)
5936 }
5937 }
5938 }
5939
5940 // Common function to remove ourselves from this server.
5941 // This can happen on re-assignment, move, etc
5942 func (s *Server) removeConsumer(o *consumer, nca *consumerAssignment) {
5943 if o == nil {
5944 return
5945 }
5946 // Make sure to use the new stream assignment, not our own.
5947 s.Debugf("JetStream removing consumer '%s > %s > %s' from this server", nca.Client.serviceAccount(), nca.Stream, nca.Name)
5948 if node := o.raftNode(); node != nil {
5949 node.StepDown(nca.Group.Preferred)
5950 // shutdown monitor by shutting down raft.
5951 node.Delete()
5952 }
5953
5954 var isShuttingDown bool
5955 // Make sure this node is no longer attached to our consumer assignment.
5956 if js, _ := s.getJetStreamCluster(); js != nil {
5957 js.mu.Lock()
5958 nca.Group.node = nil
5959 nca.err = nil
5960 isShuttingDown = js.shuttingDown
5961 js.mu.Unlock()
5962 }
5963
5964 if !isShuttingDown {
5965 // wait for monitor to be shutdown.
5966 o.stopMonitoring()
5967 }
5968 o.deleteWithoutAdvisory()
5969 }
5970
5971 func (js *jetStream) processConsumerRemoval(ca *consumerAssignment) {
5972 js.mu.Lock()
5973 s, cc := js.srv, js.cluster
5974 if s == nil || cc == nil || cc.meta == nil {
5975 // TODO(dlc) - debug at least
5976 js.mu.Unlock()
5977 return
5978 }
5979
5980 accName, stream, name, created := ca.Client.serviceAccount(), ca.Stream, ca.Name, ca.Created
5981 wasLeader := cc.isConsumerLeader(accName, stream, name)
5982
5983 // Delete from our state.
5984 var needDelete bool
5985 if accStreams := cc.streams[accName]; accStreams != nil {
5986 if sa := accStreams[ca.Stream]; sa != nil && sa.consumers != nil && sa.consumers[ca.Name] != nil {
5987 oca := sa.consumers[ca.Name]
5988 // Make sure this removal is for what we have, otherwise ignore.
5989 if ca.Group != nil && oca.Group != nil && ca.Group.Name == oca.Group.Name {
5990 needDelete = true
5991 delete(sa.consumers, ca.Name)
5992 // Remember we used to be unsupported, just so we can send a successful delete response.
5993 if ca.unsupported == nil {
5994 ca.unsupported = oca.unsupported
5995 }
5996 }
5997 }
5998 }
5999 cc.removeInflightConsumerProposal(accName, stream, name)
6000 js.mu.Unlock()
6001
6002 // During initial/startup recovery we'll not have registered the consumer assignment,
6003 // but might have recovered the consumer from disk. We'll need to make sure that we only
6004 // delete the consumer if it wasn't created after this delete.
6005 if !needDelete && !created.IsZero() {
6006 if acc, err := s.LookupAccount(accName); err == nil {
6007 if mset, err := acc.lookupStream(stream); err == nil {
6008 if o := mset.lookupConsumer(name); o != nil {
6009 needDelete = !o.createdTime().After(created)
6010 }
6011 }
6012 }
6013 }
6014
6015 if needDelete {
6016 js.processClusterDeleteConsumer(ca, wasLeader)
6017 }
6018 }
6019
6020 type consumerAssignmentResult struct {
6021 Account string `json:"account"`
6022 Stream string `json:"stream"`
6023 Consumer string `json:"consumer"`
6024 Response *JSApiConsumerCreateResponse `json:"response,omitempty"`
6025 }
6026
6027 // processClusterCreateConsumer is when we are a member of the group and need to create the consumer.
6028 func (js *jetStream) processClusterCreateConsumer(oca, ca *consumerAssignment, state *ConsumerState, wasExisting bool) {
6029 if ca == nil {
6030 return
6031 }
6032 js.mu.RLock()
6033 s := js.srv
6034 rg := ca.Group
6035 alreadyRunning := rg != nil && rg.node != nil
6036 accName, stream, consumer := ca.Client.serviceAccount(), ca.Stream, ca.Name
6037 recovering := ca.recovering
6038 js.mu.RUnlock()
6039
6040 acc, err := s.LookupAccount(accName)
6041 if err != nil {
6042 s.Warnf("JetStream cluster failed to lookup account %q: %v", accName, err)
6043 return
6044 }
6045
6046 // Go ahead and create or update the consumer.
6047 mset, err := acc.lookupStream(stream)
6048 if err != nil {
6049 if !js.isMetaRecovering() {
6050 js.mu.Lock()
6051 s.Warnf("Consumer create failed, could not locate stream '%s > %s > %s'", ca.Client.serviceAccount(), ca.Stream, ca.Name)
6052 ca.err = NewJSStreamNotFoundError()
6053 result := &consumerAssignmentResult{
6054 Account: ca.Client.serviceAccount(),
6055 Stream: ca.Stream,
6056 Consumer: ca.Name,
6057 Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
6058 }
6059 result.Response.Error = NewJSStreamNotFoundError()
6060 s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, result)
6061 js.mu.Unlock()
6062 }
6063 return
6064 }
6065
6066 // Check if we already have this consumer running.
6067 o := mset.lookupConsumer(consumer)
6068
6069 if o != nil && oca != nil && oca.Group.Name != ca.Group.Name {
6070 s.Warnf("JetStream cluster detected consumer remapping for '%s > %s' from %q to %q",
6071 acc, ca.Name, oca.Group.Name, ca.Group.Name)
6072 o.clearNode()
6073 o.stopMonitoring()
6074 alreadyRunning = false
6075 // Make sure to clear from original.
6076 js.mu.Lock()
6077 oca.Group.node = nil
6078 js.mu.Unlock()
6079 }
6080
6081 // Process the raft group and make sure it's running if needed.
6082 storage := mset.config().Storage
6083 if ca.Config.MemoryStorage {
6084 storage = MemoryStorage
6085 }
6086 // No-op if R1.
6087 js.createRaftGroup(accName, rg, recovering, storage, pprofLabels{
6088 "type": "consumer",
6089 "account": mset.accName(),
6090 "stream": ca.Stream,
6091 "consumer": ca.Name,
6092 })
6093
6094 // Check if we already have this consumer running.
6095 var didCreate, isConfigUpdate, needsLocalResponse bool
6096 if o == nil {
6097 // Add in the consumer if needed.
6098 if o, err = mset.addConsumerWithAssignment(ca.Config, ca.Name, ca, js.isMetaRecovering(), ActionCreateOrUpdate, false); err == nil {
6099 didCreate = true
6100 }
6101 } else {
6102 // This consumer exists.
6103 // Only update if config is really different.
6104 cfg := o.config()
6105 if isConfigUpdate = !reflect.DeepEqual(&cfg, ca.Config); isConfigUpdate {
6106 // Call into update, ignore consumer exists error here since this means an old deliver subject is bound
6107 // which can happen on restart etc.
6108 // JS lock needed as this can mutate the consumer assignments and race with updateInactivityThreshold.
6109 js.mu.Lock()
6110 err := o.updateConfig(ca.Config)
6111 js.mu.Unlock()
6112 if err != nil && err != NewJSConsumerNameExistError() {
6113 // This is essentially an update that has failed. Respond back to metaleader if we are not recovering.
6114 js.mu.RLock()
6115 if !js.metaRecovering {
6116 result := &consumerAssignmentResult{
6117 Account: accName,
6118 Stream: stream,
6119 Consumer: consumer,
6120 Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
6121 }
6122 result.Response.Error = NewJSConsumerNameExistError()
6123 s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, result)
6124 }
6125 s.Warnf("Consumer create failed during update for '%s > %s > %s': %v", ca.Client.serviceAccount(), ca.Stream, ca.Name, err)
6126 js.mu.RUnlock()
6127 return
6128 }
6129 }
6130
6131 var sendState bool
6132 js.mu.RLock()
6133 n := rg.node
6134 // Check if we already had a consumer assignment and its still pending.
6135 cca, oca := ca, o.consumerAssignment()
6136 if oca != nil {
6137 if !oca.hasResponded() {
6138 // We can't override info for replying here otherwise leader once elected can not respond.
6139 // So copy over original client and the reply from the old ca.
6140 cac := ca.clone()
6141 cac.Client = oca.Client
6142 cac.Reply = oca.Reply
6143 cca = cac
6144 needsLocalResponse = true
6145 }
6146 // If we look like we are scaling up, let's send our current state to the group.
6147 sendState = len(ca.Group.Peers) > len(oca.Group.Peers) && o.IsLeader() && n != nil
6148 // Signal that this is an update
6149 if ca.Reply != _EMPTY_ {
6150 isConfigUpdate = true
6151 }
6152 }
6153 js.mu.RUnlock()
6154
6155 if sendState {
6156 if snap, err := o.store.EncodedState(); err == nil {
6157 n.SendSnapshot(snap)
6158 }
6159 }
6160
6161 // Set CA for our consumer.
6162 o.setConsumerAssignment(cca)
6163 s.Debugf("JetStream cluster, consumer '%s > %s > %s' was already running", ca.Client.serviceAccount(), ca.Stream, ca.Name)
6164 }
6165
6166 // If we have an initial state set apply that now.
6167 if state != nil && o != nil {
6168 o.mu.Lock()
6169 err = o.setStoreState(state)
6170 o.mu.Unlock()
6171 }
6172
6173 if err != nil {
6174 // If we're shutting down we could get a variety of errors.
6175 // Normally we can continue and delete state, but need to be careful when shutting down.
6176 if js.isShuttingDown() {
6177 s.Debugf("Could not create consumer, JetStream shutting down")
6178 return
6179 }
6180
6181 s.Warnf("Consumer create failed for '%s > %s > %s': %v", ca.Client.serviceAccount(), ca.Stream, ca.Name, err)
6182 if IsNatsErr(err, JSConsumerStoreFailedErrF) {
6183 err = errConsumerStoreFailed
6184 }
6185
6186 js.mu.Lock()
6187 ca.err = err
6188 hasResponded := ca.hasResponded()
6189
6190 // If out of space do nothing for now.
6191 if isOutOfSpaceErr(err) {
6192 hasResponded = true
6193 }
6194
6195 if rg.node != nil {
6196 rg.node.Delete()
6197 // Clear the node here.
6198 rg.node = nil
6199 }
6200
6201 // If we did seem to create a consumer make sure to stop it.
6202 if o != nil {
6203 o.stop()
6204 }
6205
6206 var result *consumerAssignmentResult
6207 if !hasResponded && !js.metaRecovering {
6208 result = &consumerAssignmentResult{
6209 Account: ca.Client.serviceAccount(),
6210 Stream: ca.Stream,
6211 Consumer: ca.Name,
6212 Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
6213 }
6214 result.Response.Error = NewJSConsumerCreateError(err, Unless(err))
6215 } else if err == errNoInterest {
6216 // This is a stranded ephemeral, let's clean this one up.
6217 subject := fmt.Sprintf(JSApiConsumerDeleteT, ca.Stream, ca.Name)
6218 mset.outq.send(newJSPubMsg(subject, _EMPTY_, _EMPTY_, nil, nil, nil, 0))
6219 }
6220 js.mu.Unlock()
6221
6222 if result != nil {
6223 // Send response to the metadata leader. They will forward to the user as needed.
6224 b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
6225 s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, b)
6226 }
6227 } else {
6228 js.mu.RLock()
6229 hadErr := ca.err != nil
6230 node := rg.node
6231 js.mu.RUnlock()
6232 if hadErr {
6233 js.mu.Lock()
6234 ca.err = nil
6235 js.mu.Unlock()
6236 }
6237
6238 if didCreate {
6239 o.setCreatedTime(ca.Created)
6240 } else {
6241 // Check for scale down to 1..
6242 if node != nil && len(rg.Peers) == 1 {
6243 o.clearNode()
6244 o.stopMonitoring()
6245 // Need to clear from rg too.
6246 js.mu.Lock()
6247 rg.node = nil
6248 client, subject, reply := ca.Client, ca.Subject, ca.Reply
6249 js.mu.Unlock()
6250 // Perform the leader change in a goroutine, otherwise we could block meta operations.
6251 if o.shouldStartMonitor() {
6252 started := s.startGoRoutine(
6253 func() {
6254 defer s.grWG.Done()
6255 defer o.clearMonitorRunning()
6256 err = o.setLeader(true, 0)
6257 var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
6258 if err != nil {
6259 resp.Error = NewJSConsumerCreateError(err, Unless(err))
6260 s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
6261 } else {
6262 resp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.info())
6263 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
6264 }
6265 },
6266 pprofLabels{
6267 "type": "consumer",
6268 "account": mset.accName(),
6269 "stream": mset.name(),
6270 "consumer": ca.Name,
6271 },
6272 )
6273 if !started {
6274 o.clearMonitorRunning()
6275 }
6276 }
6277 return
6278 }
6279 }
6280
6281 if node == nil {
6282 // Wait for the previous routine to stop running.
6283 o.stopMonitoring()
6284 // Single replica consumer, process manually here.
6285 // Force response in case we think this is an update.
6286 if !js.isMetaRecovering() && isConfigUpdate {
6287 ca.clearResponded()
6288 }
6289 cca := o.consumerAssignment()
6290 // Perform the leader change in a goroutine, otherwise we could block meta operations.
6291 if o.shouldStartMonitor() {
6292 started := s.startGoRoutine(
6293 func() {
6294 defer s.grWG.Done()
6295 defer o.clearMonitorRunning()
6296 js.processConsumerLeaderChangeWithAssignment(o, cca, true, 0)
6297 },
6298 pprofLabels{
6299 "type": "consumer",
6300 "account": mset.accName(),
6301 "stream": mset.name(),
6302 "consumer": ca.Name,
6303 },
6304 )
6305 if !started {
6306 o.clearMonitorRunning()
6307 }
6308 }
6309 } else {
6310 // Clustered consumer.
6311 // Start our monitoring routine if needed.
6312 if !alreadyRunning {
6313 // Wait for the previous routine to stop running.
6314 o.stopMonitoring()
6315 if o.shouldStartMonitor() {
6316 started := s.startGoRoutine(
6317 func() { js.monitorConsumer(o, ca) },
6318 pprofLabels{
6319 "type": "consumer",
6320 "account": mset.accName(),
6321 "stream": mset.name(),
6322 "consumer": ca.Name,
6323 },
6324 )
6325 if !started {
6326 o.clearMonitorRunning()
6327 }
6328 }
6329 }
6330 // For existing consumer, only send response if not recovering.
6331 if wasExisting && !js.isMetaRecovering() {
6332 if o.IsLeader() || (!didCreate && needsLocalResponse) {
6333 // Process if existing as an update. Double check that this is not recovered.
6334 js.mu.RLock()
6335 client, subject, reply, recovering, sourcing := ca.Client, ca.Subject, ca.Reply, ca.recovering, ca.Config.Sourcing
6336 js.mu.RUnlock()
6337 if !recovering {
6338 // If it's a sourcing consumer, we need to respond after the consumer has been reset instead.
6339 if sourcing {
6340 var resp = JSApiConsumerResetResponse{ApiResponse: ApiResponse{Type: JSApiConsumerResetResponseType}}
6341 resetSeq, canRespond, err := o.resetStartingSeq(0, reply, true)
6342 if err != nil {
6343 resp.Error = NewJSConsumerInvalidResetError(err)
6344 s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
6345 } else if canRespond {
6346 resp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.info())
6347 resp.ResetSeq = resetSeq
6348 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
6349 }
6350 } else {
6351 var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
6352 resp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.info())
6353 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
6354 }
6355 }
6356 }
6357 }
6358 }
6359 }
6360 }
6361
6362 func (js *jetStream) processClusterDeleteConsumer(ca *consumerAssignment, wasLeader bool) {
6363 if ca == nil {
6364 return
6365 }
6366 js.mu.RLock()
6367 s := js.srv
6368 node := ca.Group.node
6369 offline := s.allPeersOffline(ca.Group) || ca.unsupported != nil
6370 var isMetaLeader bool
6371 if cc := js.cluster; cc != nil {
6372 isMetaLeader = cc.isLeader()
6373 }
6374 recovering := ca.recovering
6375 js.mu.RUnlock()
6376
6377 stopped := false
6378 var resp = JSApiConsumerDeleteResponse{ApiResponse: ApiResponse{Type: JSApiConsumerDeleteResponseType}}
6379 var err error
6380 var acc *Account
6381
6382 // Go ahead and delete the consumer if we have it and the account.
6383 if acc, _ = s.LookupAccount(ca.Client.serviceAccount()); acc != nil {
6384 if mset, _ := acc.lookupStream(ca.Stream); mset != nil {
6385 if o := mset.lookupConsumer(ca.Name); o != nil {
6386 err = o.stopWithFlags(true, false, true, wasLeader)
6387 stopped = true
6388 }
6389 }
6390 }
6391
6392 // Always delete the node if present.
6393 if node != nil {
6394 node.Delete()
6395 }
6396
6397 // This is a stop gap cleanup in case
6398 // 1) the account, mset, or consumer does not exist and/or
6399 // 2) node was nil (and couldn't be deleted)
6400 if !stopped || node == nil {
6401 if sacc := s.SystemAccount(); sacc != nil {
6402 os.RemoveAll(filepath.Join(js.config.StoreDir, sacc.GetName(), defaultStoreDirName, ca.Group.Name))
6403 }
6404 }
6405
6406 accDir := filepath.Join(js.config.StoreDir, ca.Client.serviceAccount())
6407 consumersDir := filepath.Join(accDir, streamsDir, ca.Stream, consumerDir)
6408 os.RemoveAll(filepath.Join(consumersDir, ca.Name))
6409
6410 if !wasLeader || ca.Reply == _EMPTY_ {
6411 if !(offline && isMetaLeader) {
6412 return
6413 }
6414 }
6415
6416 // Do not respond if the account does not exist any longer or this is during recovery.
6417 if acc == nil || recovering {
6418 return
6419 }
6420
6421 if err != nil {
6422 resp.Error = NewJSConsumerNotFoundError(Unless(err))
6423 s.sendAPIErrResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(resp))
6424 } else {
6425 resp.Success = true
6426 s.sendAPIResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(resp))
6427 }
6428 }
6429
6430 // Returns the consumer assignment, or nil if not present.
6431 // Lock should be held.
6432 func (js *jetStream) consumerAssignment(account, stream, consumer string) *consumerAssignment {
6433 if sa := js.streamAssignment(account, stream); sa != nil {
6434 return sa.consumers[consumer]
6435 }
6436 return nil
6437 }
6438
6439 // Will look up a consumer assignment, either an applied or inflight assignment.
6440 // Lock should be held.
6441 func (js *jetStream) consumerAssignmentOrInflight(account, stream, consumer string) *consumerAssignment {
6442 cc := js.cluster
6443 if cc == nil {
6444 return nil
6445 }
6446 if streams, ok := cc.inflightConsumers[account]; ok {
6447 if consumers, ok := streams[stream]; ok {
6448 if inflight, ok := consumers[consumer]; ok {
6449 if !inflight.deleted {
6450 return inflight.consumerAssignment
6451 } else {
6452 return nil
6453 }
6454 }
6455 }
6456 }
6457 if sa := js.streamAssignment(account, stream); sa != nil {
6458 return sa.consumers[consumer]
6459 }
6460 return nil
6461 }
6462
6463 // Will gather all consumer assignments for the specified account and stream, both applied and inflight assignments.
6464 // Lock should be held.
6465 func (js *jetStream) consumerAssignmentsOrInflightSeq(account, stream string) iter.Seq[*consumerAssignment] {
6466 return func(yield func(*consumerAssignment) bool) {
6467 cc := js.cluster
6468 if cc == nil {
6469 return
6470 }
6471
6472 var inflight map[string]*inflightConsumerInfo
6473 if streams, ok := cc.inflightConsumers[account]; ok {
6474 inflight = streams[stream]
6475 }
6476 for _, i := range inflight {
6477 if !i.deleted && !yield(i.consumerAssignment) {
6478 return
6479 }
6480 }
6481 sa := js.streamAssignment(account, stream)
6482 if sa == nil {
6483 return
6484 }
6485 for _, ca := range sa.consumers {
6486 // Skip if we already iterated over it as inflight.
6487 if _, ok := inflight[ca.Name]; ok {
6488 continue
6489 }
6490 if !yield(ca) {
6491 return
6492 }
6493 }
6494 }
6495 }
6496
6497 // consumerAssigned informs us if this server has this consumer assigned.
6498 func (jsa *jsAccount) consumerAssigned(stream, consumer string) bool {
6499 jsa.mu.RLock()
6500 js, acc := jsa.js, jsa.account
6501 jsa.mu.RUnlock()
6502
6503 if js == nil {
6504 return false
6505 }
6506 js.mu.RLock()
6507 defer js.mu.RUnlock()
6508 return js.cluster.isConsumerAssigned(acc, stream, consumer)
6509 }
6510
6511 // Read lock should be held.
6512 func (cc *jetStreamCluster) isConsumerAssigned(a *Account, stream, consumer string) bool {
6513 // Non-clustered mode always return true.
6514 if cc == nil {
6515 return true
6516 }
6517 if cc.meta == nil {
6518 return false
6519 }
6520 var sa *streamAssignment
6521 accStreams := cc.streams[a.Name]
6522 if accStreams != nil {
6523 sa = accStreams[stream]
6524 }
6525 if sa == nil {
6526 // TODO(dlc) - This should not happen.
6527 return false
6528 }
6529 ca := sa.consumers[consumer]
6530 if ca == nil {
6531 return false
6532 }
6533 return ca.Group.isMember(cc.meta.ID())
6534 }
6535
6536 // Returns our stream and underlying raft node.
6537 func (o *consumer) streamAndNode() (*stream, RaftNode) {
6538 if o == nil {
6539 return nil, nil
6540 }
6541 o.mu.RLock()
6542 defer o.mu.RUnlock()
6543 return o.mset, o.node
6544 }
6545
6546 // Return the replica count for this consumer. If the consumer has been
6547 // stopped, this will return an error.
6548 func (o *consumer) replica() (int, error) {
6549 o.mu.RLock()
6550 oCfg := o.cfg
6551 mset := o.mset
6552 o.mu.RUnlock()
6553 if mset == nil {
6554 return 0, errBadConsumer
6555 }
6556 sCfg := mset.config()
6557 return oCfg.replicas(&sCfg), nil
6558 }
6559
6560 func (o *consumer) raftGroup() *raftGroup {
6561 if o == nil {
6562 return nil
6563 }
6564 o.mu.RLock()
6565 defer o.mu.RUnlock()
6566 if o.ca == nil {
6567 return nil
6568 }
6569 return o.ca.Group
6570 }
6571
6572 func (o *consumer) raftNode() RaftNode {
6573 if o == nil {
6574 return nil
6575 }
6576 o.mu.RLock()
6577 defer o.mu.RUnlock()
6578 return o.node
6579 }
6580
6581 func (js *jetStream) monitorConsumer(o *consumer, ca *consumerAssignment) {
6582 s, n, meta := js.server(), o.raftNode(), js.getMetaGroup()
6583 defer s.grWG.Done()
6584
6585 defer o.clearMonitorRunning()
6586
6587 if n == nil || meta == nil {
6588 s.Warnf("No RAFT group for '%s > %s > %s'", o.acc.Name, ca.Stream, ca.Name)
6589 return
6590 }
6591
6592 // Make sure to stop the raft group on exit to prevent accidental memory bloat.
6593 // This should be below the checkInMonitor call though to avoid stopping it out
6594 // from underneath the one that is running since it will be the same raft node.
6595 defer n.Stop()
6596
6597 qch, mqch, lch, aq, uch := n.QuitC(), o.monitorQuitC(), n.LeadChangeC(), n.ApplyQ(), o.updateC()
6598
6599 s.Debugf("Starting consumer monitor for '%s > %s > %s' [%s]", o.acc.Name, ca.Stream, ca.Name, n.Group())
6600 defer s.Debugf("Exiting consumer monitor for '%s > %s > %s' [%s]", o.acc.Name, ca.Stream, ca.Name, n.Group())
6601
6602 const (
6603 compactInterval = 2 * time.Minute
6604 compactMinInterval = 15 * time.Second
6605 compactSizeMin = 64 * 1024 // What is stored here is always small for consumers.
6606 compactNumMin = 1024
6607 minSnapDelta = 10 * time.Second
6608 )
6609
6610 // Spread these out for large numbers on server restart.
6611 rci := time.Duration(rand.Int63n(int64(time.Minute)))
6612 t := time.NewTicker(compactInterval + rci)
6613 defer t.Stop()
6614
6615 // Highwayhash key for generating hashes.
6616 key := make([]byte, 32)
6617 crand.Read(key)
6618
6619 var lastSnapTime time.Time
6620
6621 // Don't allow the upper layer to install snapshots until we have
6622 // fully recovered from disk.
6623 recovering := true
6624
6625 var failedSnapshots int
6626 doSnapshot := func(force bool) {
6627 // Bail if trying too fast and not in a forced situation.
6628 // If snapshots have failed, and we're not forced to, we'll wait for the timer since it'll now be forced.
6629 if recovering || (!force && (time.Since(lastSnapTime) < minSnapDelta || failedSnapshots > 0)) {
6630 return
6631 }
6632
6633 if snap, err := o.store.EncodedState(); err == nil {
6634 // If we had a significant number of failed snapshots, start relaxing Raft-layer checks
6635 // to force it through. We might have been catching up a peer for a long period, and this
6636 // protects our log size from growing indefinitely.
6637 forceSnapshot := failedSnapshots > 4
6638 if err := n.InstallSnapshot(snap, forceSnapshot); err == nil {
6639 lastSnapTime = time.Now()
6640 // If there was a failed snapshot before, we reduced the timer's interval.
6641 // Reset it back to the original interval now.
6642 if failedSnapshots > 0 {
6643 t.Reset(compactInterval + rci)
6644 }
6645 failedSnapshots = 0
6646 } else if err != errNoSnapAvailable && err != errNodeClosed && err != errCatchupsRunning {
6647 s.RateLimitWarnf("Failed to install snapshot for '%s > %s > %s' [%s]: %v", o.acc.Name, ca.Stream, ca.Name, n.Group(), err)
6648 // If this is the first failure, reduce the interval of the snapshot timer.
6649 // This ensures we're not waiting too long for snapshotting to eventually become forced.
6650 if failedSnapshots == 0 {
6651 t.Reset(compactMinInterval)
6652 }
6653 failedSnapshots++
6654 }
6655 } else {
6656 s.RateLimitWarnf("Failed to install snapshot for '%s > %s > %s' [%s]: %v", o.acc.Name, ca.Stream, ca.Name, n.Group(), err)
6657 }
6658 }
6659
6660 // For migration tracking.
6661 mmtd := 500 * time.Millisecond
6662 var mmt *time.Ticker
6663 var mmtc <-chan time.Time
6664
6665 startMigrationMonitoring := func() {
6666 if mmt == nil {
6667 mmt = time.NewTicker(mmtd)
6668 mmtc = mmt.C
6669 }
6670 }
6671
6672 stopMigrationMonitoring := func() {
6673 if mmt != nil {
6674 mmt.Stop()
6675 mmt, mmtc = nil, nil
6676 }
6677 }
6678 defer stopMigrationMonitoring()
6679
6680 // Track if we are leader.
6681 var isLeader bool
6682
6683 for {
6684 select {
6685 case <-s.quitCh:
6686 // Server shutting down, but we might receive this before qch, so try to snapshot.
6687 doSnapshot(false)
6688 return
6689 case <-mqch:
6690 // Clean signal from shutdown routine so do best effort attempt to snapshot.
6691 // Don't snapshot if not shutting down, monitor goroutine could be going away
6692 // on a scale down or a remove for example.
6693 if s.isShuttingDown() {
6694 doSnapshot(false)
6695 }
6696 return
6697 case <-qch:
6698 // Raft node is closed, no use in trying to snapshot.
6699 return
6700 case <-aq.ch:
6701 ces := aq.pop()
6702 for _, ce := range ces {
6703 // No special processing needed for when we are caught up on restart.
6704 if ce == nil {
6705 if !recovering {
6706 continue
6707 }
6708 recovering = false
6709 if n.NeedSnapshot() {
6710 doSnapshot(true)
6711 }
6712 continue
6713 }
6714 if err := js.applyConsumerEntries(o, ce, isLeader); err == nil {
6715 var ne, nb uint64
6716 // We can't guarantee writes are flushed while we're shutting down. Just rely on replay during recovery.
6717 if !js.isShuttingDown() {
6718 ne, nb = n.Applied(ce.Index)
6719 }
6720 // If we have at least min entries to compact, go ahead and snapshot/compact.
6721 if nb > 0 && ne >= compactNumMin || nb > compactSizeMin {
6722 doSnapshot(false)
6723 }
6724 } else if err != errConsumerClosed {
6725 s.Warnf("Error applying consumer entries to '%s > %s'", ca.Client.serviceAccount(), ca.Name)
6726 }
6727 ce.ReturnToPool()
6728 }
6729 aq.recycle(&ces)
6730
6731 case lc := <-lch:
6732 isLeader = lc.isLeader
6733 if recovering && !isLeader {
6734 js.setConsumerAssignmentRecovering(ca)
6735 }
6736
6737 // Process the change.
6738 if err := js.processConsumerLeaderChange(o, isLeader, lc.term); err == nil {
6739 // Check our state if we are under an interest based stream.
6740 if mset := o.getStream(); mset != nil {
6741 var ss StreamState
6742 mset.store.FastState(&ss)
6743 o.checkStateForInterestStream(&ss)
6744 }
6745 }
6746
6747 // We may receive a leader change after the consumer assignment which would cancel us
6748 // monitoring for this closely. So re-assess our state here as well.
6749 // Or the old leader is no longer part of the set and transferred leadership
6750 // for this leader to resume with removal
6751 migrating := o.isMigrating()
6752 if isLeader && migrating {
6753 startMigrationMonitoring()
6754 } else {
6755 stopMigrationMonitoring()
6756 }
6757 case <-uch:
6758 // keep consumer assignment current
6759 ca = o.consumerAssignment()
6760 // We get this when we have a new consumer assignment caused by an update.
6761 // We want to know if we are migrating.
6762 migrating := o.isMigrating()
6763 if isLeader && migrating {
6764 startMigrationMonitoring()
6765 } else {
6766 stopMigrationMonitoring()
6767 }
6768 case <-mmtc:
6769 if !isLeader {
6770 // We are no longer leader, so not our job.
6771 stopMigrationMonitoring()
6772 continue
6773 }
6774 if done := js.runConsumerMigration(o, ca, n); done {
6775 stopMigrationMonitoring()
6776 continue
6777 }
6778
6779 case <-t.C:
6780 // Start forcing snapshots if they failed previously.
6781 forceIfFailed := failedSnapshots > 0
6782 doSnapshot(forceIfFailed)
6783 }
6784 }
6785 }
6786
6787 // Migrate a consumer from peer set A to peer set B. Returns true when migration is done.
6788 func (js *jetStream) runConsumerMigration(o *consumer, ca *consumerAssignment, n RaftNode) bool {
6789 ourPeerId, cc, s := n.ID(), js.cluster, js.srv
6790
6791 js.mu.RLock()
6792 // We are shutting down.
6793 if cc == nil || cc.meta == nil {
6794 js.mu.RUnlock()
6795 return true
6796 }
6797 meta := cc.meta
6798 accName, streamName, consumerName := ca.Client.serviceAccount(), ca.Stream, ca.Name
6799 js.mu.RUnlock()
6800
6801 rg := o.raftGroup()
6802 ci := js.clusterInfo(rg)
6803 replicas, err := o.replica()
6804 if err != nil {
6805 return true
6806 }
6807 if len(rg.Peers) <= replicas {
6808 // Migration no longer happening, so not our job anymore
6809 return true
6810 }
6811 newPeers, _, newPeerSet, _ := genPeerInfo(rg.Peers, len(rg.Peers)-replicas)
6812
6813 // If we are part of the new peerset and we have been passed the baton.
6814 // We will handle scale down.
6815 if newPeerSet[ourPeerId] {
6816 n.ProposeKnownPeers(newPeers)
6817 cca := ca.copyGroup()
6818 cca.Group.Peers = newPeers
6819 cca.Group.Cluster = s.cachedClusterName()
6820 meta.ForwardProposal(encodeAddConsumerAssignment(cca))
6821 s.Noticef("Scaling down '%s > %s > %s' to %+v", accName, streamName, consumerName, s.peerSetToNames(newPeers))
6822
6823 } else {
6824 var newLeaderPeer, newLeader, newCluster string
6825 neededCurrent, current := replicas/2+1, 0
6826 for _, r := range ci.Replicas {
6827 if r.Current && newPeerSet[r.Peer] {
6828 current++
6829 if newCluster == _EMPTY_ {
6830 newLeaderPeer, newLeader, newCluster = r.Peer, r.Name, r.cluster
6831 }
6832 }
6833 }
6834
6835 // Check if we have a quorom
6836 if current >= neededCurrent {
6837 s.Noticef("Transfer of consumer leader for '%s > %s > %s' to '%s'", accName, streamName, consumerName, newLeader)
6838 n.StepDown(newLeaderPeer)
6839 }
6840 }
6841 return false
6842 }
6843
6844 // Determine if we are migrating
6845 func (o *consumer) isMigrating() bool {
6846 if o == nil {
6847 return false
6848 }
6849
6850 replicas, err := o.replica()
6851 if err != nil {
6852 return false
6853 }
6854 o.mu.RLock()
6855 js, ca := o.js, o.ca
6856 o.mu.RUnlock()
6857
6858 js.mu.RLock()
6859 defer js.mu.RUnlock()
6860
6861 // During migration we will always be R>1, even when we start R1.
6862 // So if we do not have a group or node, we know we are not migrating.
6863 if ca == nil || ca.Group == nil || ca.Group.node == nil {
6864 return false
6865 }
6866 // The sign of migration is if our group peer count != configured replica count.
6867 if replicas != len(ca.Group.Peers) {
6868 return true
6869 }
6870 return false
6871 }
6872
6873 func (js *jetStream) applyConsumerEntries(o *consumer, ce *CommittedEntry, isLeader bool) error {
6874 for _, e := range ce.Entries {
6875 // Ignore if lower-level catchup is started.
6876 // We don't need to optimize during this, all entries are handled as normal.
6877 if e.Type == EntryCatchup {
6878 continue
6879 }
6880
6881 if e.Type == EntrySnapshot {
6882 if !isLeader {
6883 // No-op needed?
6884 state, err := decodeConsumerState(e.Data)
6885 if err != nil {
6886 if mset, node := o.streamAndNode(); mset != nil && node != nil {
6887 s := js.srv
6888 s.Errorf("JetStream cluster could not decode consumer snapshot for '%s > %s > %s' [%s]",
6889 mset.account(), mset.name(), o, node.Group())
6890 }
6891 panic(err.Error())
6892 }
6893
6894 if err = o.store.Update(state); err != nil && err != ErrStoreOldUpdate {
6895 o.mu.RLock()
6896 s, acc, mset, name := o.srv, o.acc, o.mset, o.name
6897 o.mu.RUnlock()
6898 if s != nil && mset != nil {
6899 s.Warnf("Consumer '%s > %s > %s' error on store update from snapshot entry: %v", acc, mset.name(), name, err)
6900 }
6901 }
6902 // Check our interest state if applicable.
6903 if mset := o.getStream(); mset != nil {
6904 var ss StreamState
6905 mset.store.FastState(&ss)
6906 // We used to register preacks here if our ack floor was higher than the last sequence.
6907 // Now when streams catch up they properly call checkInterestState() and periodically run this as well.
6908 // If our states drift this could have allocated lots of pre-acks.
6909 o.checkStateForInterestStream(&ss)
6910 }
6911 }
6912
6913 } else if e.Type == EntryRemovePeer {
6914 js.mu.RLock()
6915 var ourID string
6916 if js.cluster != nil && js.cluster.meta != nil {
6917 ourID = js.cluster.meta.ID()
6918 }
6919 js.mu.RUnlock()
6920 if peer := string(e.Data); peer == ourID {
6921 shouldRemove := true
6922 if mset := o.getStream(); mset != nil {
6923 if sa := mset.streamAssignment(); sa != nil && sa.Group != nil {
6924 js.mu.RLock()
6925 shouldRemove = !sa.Group.isMember(ourID)
6926 js.mu.RUnlock()
6927 }
6928 }
6929 if shouldRemove {
6930 o.stopWithFlags(true, false, false, false)
6931 }
6932 }
6933 } else if e.Type == EntryAddPeer {
6934 // Ignore for now.
6935 } else {
6936 buf := e.Data
6937 if len(buf) == 0 {
6938 return errBadEntryOp
6939 }
6940 switch entryOp(buf[0]) {
6941 case updateDeliveredOp:
6942 dseq, sseq, dc, ts, err := decodeDeliveredUpdate(buf[1:])
6943 if err != nil {
6944 if mset, node := o.streamAndNode(); mset != nil && node != nil {
6945 s := js.srv
6946 s.Errorf("JetStream cluster could not decode consumer delivered update for '%s > %s > %s' [%s]",
6947 mset.account(), mset.name(), o, node.Group())
6948 }
6949 panic(err.Error())
6950 }
6951 // Make sure to update delivered under the lock.
6952 o.mu.Lock()
6953 err = o.store.UpdateDelivered(dseq, sseq, dc, ts)
6954 o.ldt = time.Now()
6955 // Need to send message to the client, since we have quorum to do so now.
6956 if pmsg, ok := o.pendingDeliveries[sseq]; ok {
6957 // Copy delivery subject and sequence first, as the send returns it to the pool and clears it.
6958 dsubj, seq := pmsg.dsubj, pmsg.seq
6959 o.outq.send(pmsg)
6960 delete(o.pendingDeliveries, sseq)
6961
6962 // Might need to send a request timeout after sending the last replicated delivery.
6963 if wd, ok := o.waitingDeliveries[dsubj]; ok && wd.seq == seq {
6964 if wd.pn > 0 || wd.pb > 0 {
6965 hdr := fmt.Appendf(nil, "NATS/1.0 408 Request Timeout\r\n%s: %d\r\n%s: %d\r\n\r\n", JSPullRequestPendingMsgs, wd.pn, JSPullRequestPendingBytes, wd.pb)
6966 o.outq.send(newJSPubMsg(dsubj, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
6967 }
6968 wd.recycle()
6969 delete(o.waitingDeliveries, dsubj)
6970 }
6971 }
6972 o.mu.Unlock()
6973 if err != nil {
6974 panic(err.Error())
6975 }
6976 case updateAcksOp:
6977 dseq, sseq, err := decodeAckUpdate(buf[1:])
6978 if err != nil {
6979 if mset, node := o.streamAndNode(); mset != nil && node != nil {
6980 s := js.srv
6981 s.Errorf("JetStream cluster could not decode consumer ack update for '%s > %s > %s' [%s]",
6982 mset.account(), mset.name(), o, node.Group())
6983 }
6984 panic(err.Error())
6985 }
6986 if err := o.processReplicatedAck(dseq, sseq); err == errConsumerClosed {
6987 return err
6988 }
6989 case updateSkipOp:
6990 sseq, err := decodeSkipUpdate(buf[1:])
6991 if err != nil {
6992 return err
6993 }
6994 o.mu.Lock()
6995 if !o.isLeader() && sseq > o.sseq {
6996 o.sseq = sseq
6997 }
6998 if o.dseq == 0 {
6999 o.dseq = 1
7000 }
7001 if o.store != nil {
7002 o.store.UpdateStarting(sseq - 1)
7003 }
7004 o.mu.Unlock()
7005 case resetSeqOp:
7006 sseq, reply, err := decodeResetUpdate(buf[1:])
7007 if err != nil {
7008 return err
7009 }
7010 o.mu.Lock()
7011 o.resetLocalStartingSeq(sseq)
7012 if o.store != nil {
7013 o.store.Reset(sseq - 1)
7014 }
7015 // Cleanup messages that lost interest.
7016 if o.retention == InterestPolicy {
7017 if mset := o.mset; mset != nil {
7018 o.mu.Unlock()
7019 ss := mset.state()
7020 o.checkStateForInterestStream(&ss)
7021 o.mu.Lock()
7022 }
7023 }
7024 // Recalculate pending, and re-trigger message delivery.
7025 if !o.isLeader() {
7026 o.mu.Unlock()
7027 } else {
7028 o.streamNumPending()
7029 o.signalNewMessages()
7030 s, a := o.srv, o.acc
7031 if reply == _EMPTY_ {
7032 o.mu.Unlock()
7033 } else if internal, ok := o.rsm[reply]; !ok {
7034 o.mu.Unlock()
7035 } else {
7036 delete(o.rsm, reply)
7037 o.mu.Unlock()
7038
7039 // Check if the reset request needs to be answered on the system account.
7040 // This will happen for replicated sourcing consumers that get reset as part of a create/update.
7041 if internal {
7042 a = nil
7043 }
7044 var resp = JSApiConsumerResetResponse{ApiResponse: ApiResponse{Type: JSApiConsumerResetResponseType}}
7045 resp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.info())
7046 resp.ResetSeq = sseq
7047 s.sendInternalAccountMsg(a, reply, s.jsonResponse(&resp))
7048 }
7049 }
7050 case addPendingRequest:
7051 o.mu.Lock()
7052 if !o.isLeader() {
7053 if o.prm == nil {
7054 o.prm = make(map[string]struct{})
7055 }
7056 o.prm[string(buf[1:])] = struct{}{}
7057 }
7058 o.mu.Unlock()
7059 case removePendingRequest:
7060 o.mu.Lock()
7061 if !o.isLeader() {
7062 if o.prm != nil {
7063 delete(o.prm, string(buf[1:]))
7064 }
7065 }
7066 o.mu.Unlock()
7067 default:
7068 panic(fmt.Sprintf("JetStream Cluster Unknown group entry op type: %v", entryOp(buf[0])))
7069 }
7070 }
7071 }
7072 return nil
7073 }
7074
7075 var errConsumerClosed = errors.New("consumer closed")
7076
7077 func (o *consumer) processReplicatedAck(dseq, sseq uint64) error {
7078 o.mu.Lock()
7079 // Update activity.
7080 o.lat = time.Now()
7081
7082 var ackAllSeqs []uint64
7083 if o.retention != LimitsPolicy && (o.cfg.AckPolicy == AckAll || o.cfg.AckPolicy == AckFlowControl) {
7084 // Always use the store state, as o.asflr is skipped ahead already.
7085 // Capture before updating store, which clears the pending below.
7086 state, err := o.store.BorrowState()
7087 if err == nil {
7088 // Only need to collect if the ack covers more than the sequence itself.
7089 if sagap := sseq - state.AckFloor.Stream; sagap > 1 {
7090 // At most the pending entries below the ack, don't over-allocate.
7091 ackAllSeqs = make([]uint64, 0, min(uint64(len(state.Pending)), sagap-1))
7092 for seq := range state.Pending {
7093 if seq < sseq {
7094 ackAllSeqs = append(ackAllSeqs, seq)
7095 }
7096 }
7097 }
7098 }
7099 }
7100
7101 // Do actual ack update to store.
7102 // Always do this to have it recorded.
7103 o.store.UpdateAcks(dseq, sseq)
7104
7105 mset := o.mset
7106 if o.closed || mset == nil {
7107 o.mu.Unlock()
7108 return errConsumerClosed
7109 }
7110 if mset.closed.Load() {
7111 o.mu.Unlock()
7112 return errStreamClosed
7113 }
7114
7115 // Check if we have a reply that was requested.
7116 if reply := o.replies[sseq]; reply != _EMPTY_ {
7117 o.outq.sendMsg(reply, nil)
7118 delete(o.replies, sseq)
7119 }
7120
7121 if o.retention == LimitsPolicy {
7122 o.mu.Unlock()
7123 return nil
7124 }
7125 o.mu.Unlock()
7126
7127 mset.ackMsg(o, sseq)
7128 for _, seq := range ackAllSeqs {
7129 mset.ackMsg(o, seq)
7130 }
7131 return nil
7132 }
7133
7134 var errBadEntryOp = errors.New("jetstream cluster bad replicated entry")
7135 var errBadAckUpdate = errors.New("jetstream cluster bad replicated ack update")
7136 var errBadDeliveredUpdate = errors.New("jetstream cluster bad replicated delivered update")
7137 var errBadSkipUpdate = errors.New("jetstream cluster bad replicated skip update")
7138 var errBadResetUpdate = errors.New("jetstream cluster bad replicated reset update")
7139
7140 func decodeAckUpdate(buf []byte) (dseq, sseq uint64, err error) {
7141 var bi, n int
7142 if dseq, n = binary.Uvarint(buf); n <= 0 {
7143 return 0, 0, errBadAckUpdate
7144 }
7145 bi += n
7146 if sseq, n = binary.Uvarint(buf[bi:]); n <= 0 {
7147 return 0, 0, errBadAckUpdate
7148 }
7149 return dseq, sseq, nil
7150 }
7151
7152 func decodeDeliveredUpdate(buf []byte) (dseq, sseq, dc uint64, ts int64, err error) {
7153 var bi, n int
7154 if dseq, n = binary.Uvarint(buf); n <= 0 {
7155 return 0, 0, 0, 0, errBadDeliveredUpdate
7156 }
7157 bi += n
7158 if sseq, n = binary.Uvarint(buf[bi:]); n <= 0 {
7159 return 0, 0, 0, 0, errBadDeliveredUpdate
7160 }
7161 bi += n
7162 if dc, n = binary.Uvarint(buf[bi:]); n <= 0 {
7163 return 0, 0, 0, 0, errBadDeliveredUpdate
7164 }
7165 bi += n
7166 if ts, n = binary.Varint(buf[bi:]); n <= 0 {
7167 return 0, 0, 0, 0, errBadDeliveredUpdate
7168 }
7169 return dseq, sseq, dc, ts, nil
7170 }
7171
7172 func decodeSkipUpdate(buf []byte) (sseq uint64, err error) {
7173 if len(buf) < 8 {
7174 return 0, errBadSkipUpdate
7175 }
7176 return binary.LittleEndian.Uint64(buf), nil
7177 }
7178
7179 func decodeResetUpdate(buf []byte) (sseq uint64, reply string, err error) {
7180 if len(buf) < 8 {
7181 return 0, _EMPTY_, errBadResetUpdate
7182 }
7183 return binary.LittleEndian.Uint64(buf[:8]), string(buf[8:]), nil
7184 }
7185
7186 func (js *jetStream) processConsumerLeaderChange(o *consumer, isLeader bool, term uint64) error {
7187 return js.processConsumerLeaderChangeWithAssignment(o, nil, isLeader, term)
7188 }
7189
7190 func (js *jetStream) processConsumerLeaderChangeWithAssignment(o *consumer, ca *consumerAssignment, isLeader bool, term uint64) error {
7191 stepDownIfLeader := func() error {
7192 if node := o.raftNode(); node != nil && isLeader {
7193 node.StepDown()
7194 }
7195 return errors.New("failed to update consumer leader status")
7196 }
7197
7198 if o == nil || o.isClosed() {
7199 return stepDownIfLeader()
7200 }
7201
7202 if ca == nil {
7203 ca = o.consumerAssignment()
7204 }
7205 if ca == nil {
7206 return stepDownIfLeader()
7207 }
7208 js.mu.RLock()
7209 s, account, err := js.srv, ca.Client.serviceAccount(), ca.err
7210 client, subject, reply, streamName, consumerName, sourcing := ca.Client, ca.Subject, ca.Reply, ca.Stream, ca.Name, ca.Config.Sourcing
7211 hasResponded := ca.markResponded()
7212 js.mu.RUnlock()
7213
7214 acc, _ := s.LookupAccount(account)
7215 if acc == nil {
7216 return stepDownIfLeader()
7217 }
7218
7219 if isLeader {
7220 // Only log if the consumer is replicated and/or durable.
7221 // Logging about R1 ephemerals, like KV watchers, is mostly noise since the leader will always be known.
7222 o.mu.RLock()
7223 isReplicated, durable := o.node != nil, o.isDurable()
7224 o.mu.RUnlock()
7225 if isReplicated || durable {
7226 s.Noticef("JetStream cluster new consumer leader for '%s > %s > %s'", ca.Client.serviceAccount(), streamName, consumerName)
7227 }
7228 s.sendConsumerLeaderElectAdvisory(o)
7229 } else {
7230 // We are stepping down.
7231 // Make sure if we are doing so because we have lost quorum that we send the appropriate advisories.
7232 if node := o.raftNode(); node != nil && !node.Quorum() && time.Since(node.Created()) > 5*time.Second {
7233 s.sendConsumerLostQuorumAdvisory(o)
7234 }
7235 }
7236
7237 // Tell consumer to switch leader status.
7238 if lerr := o.setLeader(isLeader, term); lerr != nil && err == nil {
7239 err = lerr
7240 }
7241
7242 if !isLeader || hasResponded {
7243 if isLeader {
7244 o.clearInitialInfo()
7245 }
7246 return nil
7247 }
7248
7249 var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
7250 if err != nil {
7251 resp.Error = NewJSConsumerCreateError(err, Unless(err))
7252 s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
7253 } else {
7254 // If it's a sourcing consumer, we need to respond after the consumer has been reset instead.
7255 if sourcing {
7256 var rresp = JSApiConsumerResetResponse{ApiResponse: ApiResponse{Type: JSApiConsumerResetResponseType}}
7257 resetSeq, canRespond, err := o.resetStartingSeq(0, reply, true)
7258 if err != nil {
7259 rresp.Error = NewJSConsumerInvalidResetError(err)
7260 s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&rresp))
7261 } else if canRespond {
7262 rresp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.info())
7263 rresp.ResetSeq = resetSeq
7264 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&rresp))
7265 }
7266 } else {
7267 resp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.initialInfo())
7268 s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
7269 }
7270 o.sendCreateAdvisory()
7271 }
7272
7273 // Only send a pause advisory on consumer create if we're
7274 // actually paused. The timer would have been kicked by now
7275 // by the call to o.setLeader() above.
7276 o.mu.RLock()
7277 if isLeader && o.cfg.PauseUntil != nil && !o.cfg.PauseUntil.IsZero() && time.Now().Before(*o.cfg.PauseUntil) {
7278 o.sendPauseAdvisoryLocked(&o.cfg)
7279 }
7280 o.mu.RUnlock()
7281
7282 return nil
7283 }
7284
7285 // Determines if we should send lost quorum advisory. We throttle these after first one.
7286 func (o *consumer) shouldSendLostQuorum() bool {
7287 o.mu.Lock()
7288 defer o.mu.Unlock()
7289 if time.Since(o.lqsent) >= lostQuorumAdvInterval {
7290 o.lqsent = time.Now()
7291 return true
7292 }
7293 return false
7294 }
7295
7296 func (s *Server) sendConsumerLostQuorumAdvisory(o *consumer) {
7297 if o == nil {
7298 return
7299 }
7300 node, stream, consumer, acc := o.raftNode(), o.streamName(), o.String(), o.account()
7301 if node == nil {
7302 return
7303 }
7304 if !o.shouldSendLostQuorum() {
7305 return
7306 }
7307
7308 s.Warnf("JetStream cluster consumer '%s > %s > %s' has NO quorum, stalled.", acc.GetName(), stream, consumer)
7309
7310 subj := JSAdvisoryConsumerQuorumLostPre + "." + stream + "." + consumer
7311 adv := &JSConsumerQuorumLostAdvisory{
7312 TypedEvent: TypedEvent{
7313 Type: JSConsumerQuorumLostAdvisoryType,
7314 ID: nuid.Next(),
7315 Time: time.Now().UTC(),
7316 },
7317 Stream: stream,
7318 Consumer: consumer,
7319 Replicas: s.replicas(node),
7320 Domain: s.getOpts().JetStreamDomain,
7321 }
7322
7323 // Send to the user's account if not the system account.
7324 if acc != s.SystemAccount() {
7325 s.publishAdvisory(acc, subj, adv)
7326 }
7327 // Now do system level one. Place account info in adv, and nil account means system.
7328 adv.Account = acc.GetName()
7329 s.publishAdvisory(nil, subj, adv)
7330 }
7331
7332 func (s *Server) sendConsumerLeaderElectAdvisory(o *consumer) {
7333 if o == nil {
7334 return
7335 }
7336 node, stream, consumer, acc := o.raftNode(), o.streamName(), o.String(), o.account()
7337 if node == nil {
7338 return
7339 }
7340
7341 subj := JSAdvisoryConsumerLeaderElectedPre + "." + stream + "." + consumer
7342 adv := &JSConsumerLeaderElectedAdvisory{
7343 TypedEvent: TypedEvent{
7344 Type: JSConsumerLeaderElectedAdvisoryType,
7345 ID: nuid.Next(),
7346 Time: time.Now().UTC(),
7347 },
7348 Stream: stream,
7349 Consumer: consumer,
7350 Leader: s.serverNameForNode(node.GroupLeader()),
7351 Replicas: s.replicas(node),
7352 Domain: s.getOpts().JetStreamDomain,
7353 }
7354
7355 // Send to the user's account if not the system account.
7356 if acc != s.SystemAccount() {
7357 s.publishAdvisory(acc, subj, adv)
7358 }
7359 // Now do system level one. Place account info in adv, and nil account means system.
7360 adv.Account = acc.GetName()
7361 s.publishAdvisory(nil, subj, adv)
7362 }
7363
7364 type streamAssignmentResult struct {
7365 Account string `json:"account"`
7366 Stream string `json:"stream"`
7367 Response *JSApiStreamCreateResponse `json:"create_response,omitempty"`
7368 Restore *JSApiStreamRestoreResponse `json:"restore_response,omitempty"`
7369 Update bool `json:"is_update,omitempty"`
7370 }
7371
7372 // Determine if this is an insufficient resources' error type.
7373 func isInsufficientResourcesErr(resp *JSApiStreamCreateResponse) bool {
7374 return resp != nil && resp.Error != nil && IsNatsErr(resp.Error, JSInsufficientResourcesErr, JSMemoryResourcesExceededErr, JSStorageResourcesExceededErr)
7375 }
7376
7377 // Process error results of stream and consumer assignments.
7378 // Success will be handled by stream leader.
7379 func (js *jetStream) processStreamAssignmentResults(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
7380 var result streamAssignmentResult
7381 if err := json.Unmarshal(msg, &result); err != nil {
7382 // TODO(dlc) - log
7383 return
7384 }
7385 acc, _ := js.srv.LookupAccount(result.Account)
7386 if acc == nil {
7387 // TODO(dlc) - log
7388 return
7389 }
7390
7391 js.mu.Lock()
7392 defer js.mu.Unlock()
7393
7394 s, cc := js.srv, js.cluster
7395 if cc == nil || cc.meta == nil {
7396 return
7397 }
7398
7399 if sa := js.streamAssignmentOrInflight(result.Account, result.Stream); sa != nil && !sa.reassigning {
7400 canDelete := !result.Update && time.Since(sa.Created) < 5*time.Second
7401
7402 // See if we should retry in case this cluster is full but there are others.
7403 if cfg, ci := sa.Config, sa.Client; cfg != nil && ci != nil && isInsufficientResourcesErr(result.Response) && canDelete {
7404 // If cluster is defined we can not retry.
7405 if cfg.Placement == nil || cfg.Placement.Cluster == _EMPTY_ {
7406 // If we have additional clusters to try we can retry.
7407 // We have already verified that ci != nil.
7408 if len(ci.Alternates) > 0 {
7409 if rg, err := js.createGroupForStream(ci, cfg); err != nil {
7410 s.Warnf("Retrying cluster placement for stream '%s > %s' failed due to placement error: %+v", result.Account, result.Stream, err)
7411 } else {
7412 if org := sa.Group; org != nil && len(org.Peers) > 0 {
7413 s.Warnf("Retrying cluster placement for stream '%s > %s' due to insufficient resources in cluster %q",
7414 result.Account, result.Stream, s.clusterNameForNode(org.Peers[0]))
7415 } else {
7416 s.Warnf("Retrying cluster placement for stream '%s > %s' due to insufficient resources", result.Account, result.Stream)
7417 }
7418 // Pick a new preferred leader.
7419 rg.setPreferred(s)
7420 // Get rid of previous attempt.
7421 if err := cc.meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil {
7422 return
7423 }
7424 cc.trackInflightStreamProposal(result.Account, sa, true)
7425 // Propose new.
7426 nsa := sa.copyGroup()
7427 nsa.Group, nsa.err = rg, nil
7428 if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(nsa)); err != nil {
7429 return
7430 }
7431 cc.trackInflightStreamProposal(result.Account, nsa, false)
7432 // When the new stream assignment is processed, sa.reassigning will be
7433 // automatically set back to false. Until then, don't process any more
7434 // assignment results.
7435 nsa.reassigning = true
7436 return
7437 }
7438 }
7439 }
7440 }
7441
7442 // Respond to the user here.
7443 var resp string
7444 if result.Response != nil {
7445 resp = s.jsonResponse(result.Response)
7446 } else if result.Restore != nil {
7447 resp = s.jsonResponse(result.Restore)
7448 }
7449 if !sa.hasResponded() || result.Update {
7450 sa.markResponded()
7451 js.srv.sendAPIErrResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, resp)
7452 }
7453 // Remove this assignment if possible.
7454 if canDelete {
7455 var apiErr *ApiError
7456 if result.Response != nil {
7457 apiErr = result.Response.Error
7458 } else if result.Restore != nil {
7459 apiErr = result.Restore.Error
7460 }
7461 s.Warnf("Stream assignment for '%s > %s' rejected by assigned member: %v", sa.Client.serviceAccount(), sa.Config.Name, apiErr)
7462 sa.err = NewJSClusterNotAssignedError()
7463 if err := cc.meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil {
7464 return
7465 }
7466 cc.trackInflightStreamProposal(result.Account, sa, true)
7467 }
7468 }
7469 }
7470
7471 func (js *jetStream) processConsumerAssignmentResults(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
7472 var result consumerAssignmentResult
7473 if err := json.Unmarshal(msg, &result); err != nil {
7474 // TODO(dlc) - log
7475 return
7476 }
7477 acc, _ := js.srv.LookupAccount(result.Account)
7478 if acc == nil {
7479 // TODO(dlc) - log
7480 return
7481 }
7482
7483 js.mu.Lock()
7484 defer js.mu.Unlock()
7485
7486 s, cc := js.srv, js.cluster
7487 if cc == nil || cc.meta == nil {
7488 return
7489 }
7490
7491 if sa := js.streamAssignment(result.Account, result.Stream); sa != nil && sa.consumers != nil {
7492 if ca := sa.consumers[result.Consumer]; ca != nil && !ca.hasResponded() {
7493 js.srv.sendAPIErrResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(result.Response))
7494 ca.markResponded()
7495
7496 // Check if this failed.
7497 // TODO(dlc) - Could have mixed results, should track per peer.
7498 // Make sure this is recent response.
7499 if result.Response.Error != nil && result.Response.Error != NewJSConsumerNameExistError() && time.Since(ca.Created) < 2*time.Second {
7500 // Do not list in consumer names/lists.
7501 s.Warnf("Consumer assignment for '%s > %s > %s' rejected by assigned member: %v", ca.Client.serviceAccount(), ca.Stream, ca.Name, result.Response.Error)
7502 ca.err = NewJSClusterNotAssignedError()
7503 }
7504 }
7505 }
7506 }
7507
7508 const (
7509 streamAssignmentSubj = "$SYS.JSC.STREAM.ASSIGNMENT.RESULT"
7510 consumerAssignmentSubj = "$SYS.JSC.CONSUMER.ASSIGNMENT.RESULT"
7511 )
7512
7513 // Lock should be held.
7514 func (js *jetStream) startUpdatesSub() {
7515 cc, s, c := js.cluster, js.srv, js.cluster.c
7516 if cc.streamResults == nil {
7517 cc.streamResults, _ = s.systemSubscribe(streamAssignmentSubj, _EMPTY_, false, c, js.processStreamAssignmentResults)
7518 }
7519 if cc.consumerResults == nil {
7520 cc.consumerResults, _ = s.systemSubscribe(consumerAssignmentSubj, _EMPTY_, false, c, js.processConsumerAssignmentResults)
7521 }
7522 if cc.stepdown == nil {
7523 cc.stepdown, _ = s.systemSubscribe(JSApiLeaderStepDown, _EMPTY_, false, c, s.jsLeaderStepDownRequest)
7524 }
7525 if cc.peerRemove == nil {
7526 cc.peerRemove, _ = s.systemSubscribe(JSApiRemoveServer, _EMPTY_, false, c, s.jsLeaderServerRemoveRequest)
7527 }
7528 if cc.peerStreamMove == nil {
7529 cc.peerStreamMove, _ = s.systemSubscribe(JSApiServerStreamMove, _EMPTY_, false, c, s.jsLeaderServerStreamMoveRequest)
7530 }
7531 if cc.peerStreamCancelMove == nil {
7532 cc.peerStreamCancelMove, _ = s.systemSubscribe(JSApiServerStreamCancelMove, _EMPTY_, false, c, s.jsLeaderServerStreamCancelMoveRequest)
7533 }
7534 if js.accountPurge == nil {
7535 js.accountPurge, _ = s.systemSubscribe(JSApiAccountPurge, _EMPTY_, false, c, s.jsLeaderAccountPurgeRequest)
7536 }
7537 }
7538
7539 // Lock should be held.
7540 func (js *jetStream) stopUpdatesSub() {
7541 cc := js.cluster
7542 if cc.streamResults != nil {
7543 cc.s.sysUnsubscribe(cc.streamResults)
7544 cc.streamResults = nil
7545 }
7546 if cc.consumerResults != nil {
7547 cc.s.sysUnsubscribe(cc.consumerResults)
7548 cc.consumerResults = nil
7549 }
7550 if cc.stepdown != nil {
7551 cc.s.sysUnsubscribe(cc.stepdown)
7552 cc.stepdown = nil
7553 }
7554 if cc.peerRemove != nil {
7555 cc.s.sysUnsubscribe(cc.peerRemove)
7556 cc.peerRemove = nil
7557 }
7558 if cc.peerStreamMove != nil {
7559 cc.s.sysUnsubscribe(cc.peerStreamMove)
7560 cc.peerStreamMove = nil
7561 }
7562 if cc.peerStreamCancelMove != nil {
7563 cc.s.sysUnsubscribe(cc.peerStreamCancelMove)
7564 cc.peerStreamCancelMove = nil
7565 }
7566 if js.accountPurge != nil {
7567 cc.s.sysUnsubscribe(js.accountPurge)
7568 js.accountPurge = nil
7569 }
7570 }
7571
7572 func (s *Server) sendDomainLeaderElectAdvisory() {
7573 js, cc := s.getJetStreamCluster()
7574 if js == nil || cc == nil {
7575 return
7576 }
7577
7578 js.mu.RLock()
7579 node := cc.meta
7580 js.mu.RUnlock()
7581
7582 if node == nil {
7583 return
7584 }
7585
7586 adv := &JSDomainLeaderElectedAdvisory{
7587 TypedEvent: TypedEvent{
7588 Type: JSDomainLeaderElectedAdvisoryType,
7589 ID: nuid.Next(),
7590 Time: time.Now().UTC(),
7591 },
7592 Leader: node.GroupLeader(),
7593 Replicas: s.replicas(node),
7594 Cluster: s.cachedClusterName(),
7595 Domain: s.getOpts().JetStreamDomain,
7596 }
7597
7598 s.publishAdvisory(nil, JSAdvisoryDomainLeaderElected, adv)
7599 }
7600
7601 func (js *jetStream) processLeaderChange(isLeader bool, term uint64) {
7602 if js == nil {
7603 return
7604 }
7605 s := js.srv
7606 if s == nil {
7607 return
7608 }
7609
7610 if isLeader {
7611 s.Noticef("Self is new JetStream cluster metadata leader")
7612 s.sendDomainLeaderElectAdvisory()
7613 } else {
7614 var node string
7615 if meta := js.getMetaGroup(); meta != nil {
7616 node = meta.GroupLeader()
7617 }
7618 if node == _EMPTY_ {
7619 s.Noticef("JetStream cluster no metadata leader")
7620 } else if srv := js.srv.serverNameForNode(node); srv == _EMPTY_ {
7621 s.Noticef("JetStream cluster new remote metadata leader")
7622 } else if clst := js.srv.clusterNameForNode(node); clst == _EMPTY_ {
7623 s.Noticef("JetStream cluster new metadata leader: %s", srv)
7624 } else {
7625 s.Noticef("JetStream cluster new metadata leader: %s/%s", srv, clst)
7626 }
7627 }
7628
7629 js.mu.Lock()
7630 defer js.mu.Unlock()
7631
7632 // Update our server atomic, while holding the lock to not race with API requests.
7633 s.isMetaLeader.Store(isLeader)
7634 js.cluster.term = term
7635
7636 // Clear replies for peer-removes.
7637 js.cluster.peerRemoveReply = nil
7638
7639 // Clear inflight proposal tracking.
7640 js.cluster.inflightStreams = nil
7641 js.cluster.inflightConsumers = nil
7642
7643 if isLeader {
7644 if meta := js.cluster.meta; meta != nil && meta.IsObserver() {
7645 meta.StepDown()
7646 return
7647 }
7648 }
7649
7650 if isLeader {
7651 js.startUpdatesSub()
7652 } else {
7653 js.stopUpdatesSub()
7654 // TODO(dlc) - stepdown.
7655 }
7656
7657 // If we have been signaled to check the streams, this is for a bug that left stream
7658 // assignments with no sync subject after an update and no way to sync/catchup outside of the RAFT layer.
7659 if isLeader && js.cluster.streamsCheck {
7660 cc := js.cluster
7661 for acc, sa := range js.streamAssignmentsOrInflightSeqAllAccounts() {
7662 if sa.unsupported != nil {
7663 continue
7664 }
7665 if sa.Sync == _EMPTY_ {
7666 s.Warnf("Stream assignment corrupt for stream '%s > %s'", acc, sa.Config.Name)
7667 nsa := &streamAssignment{Group: sa.Group, Config: sa.Config, Subject: sa.Subject, Reply: sa.Reply, Client: sa.Client, Created: sa.Created}
7668 nsa.Sync = syncSubjForStream()
7669 if err := cc.meta.Propose(cc.term, encodeUpdateStreamAssignment(nsa)); err != nil {
7670 return
7671 }
7672 cc.trackInflightStreamProposal(acc, nsa, false)
7673 }
7674 }
7675 // Clear check.
7676 cc.streamsCheck = false
7677 }
7678 }
7679
7680 // Lock should be held.
7681 func (cc *jetStreamCluster) remapStreamAssignment(sa *streamAssignment, removePeer string) bool {
7682 // Invoke placement algo passing RG peers that stay (existing) and the peer that is being removed (ignore)
7683 var retain, ignore []string
7684 for _, v := range sa.Group.Peers {
7685 if v == removePeer {
7686 ignore = append(ignore, v)
7687 } else {
7688 retain = append(retain, v)
7689 }
7690 }
7691
7692 newPeers, placementError := cc.selectPeerGroup(len(sa.Group.Peers), sa.Group.Cluster, sa.Config, retain, 0, ignore)
7693
7694 if placementError == nil {
7695 sa.Group.Peers = newPeers
7696 // Don't influence preferred leader.
7697 sa.Group.Preferred = _EMPTY_
7698 return true
7699 }
7700
7701 // If R1 just return to avoid bricking the stream.
7702 if sa.Group.node == nil || len(sa.Group.Peers) == 1 {
7703 return false
7704 }
7705
7706 // If we are here let's remove the peer at least, as long as we are R>1
7707 for i, peer := range sa.Group.Peers {
7708 if peer == removePeer {
7709 sa.Group.Peers[i] = sa.Group.Peers[len(sa.Group.Peers)-1]
7710 sa.Group.Peers = sa.Group.Peers[:len(sa.Group.Peers)-1]
7711 break
7712 }
7713 }
7714 return false
7715 }
7716
7717 type selectPeerError struct {
7718 excludeTag bool
7719 offline bool
7720 noStorage bool
7721 uniqueTag bool
7722 misc bool
7723 noJsClust bool
7724 noMatchTags map[string]struct{}
7725 excludeTags map[string]struct{}
7726 }
7727
7728 func (e *selectPeerError) Error() string {
7729 b := strings.Builder{}
7730 writeBoolErrReason := func(hasErr bool, errMsg string) {
7731 if !hasErr {
7732 return
7733 }
7734 b.WriteString(", ")
7735 b.WriteString(errMsg)
7736 }
7737 b.WriteString("no suitable peers for placement")
7738 writeBoolErrReason(e.offline, "peer offline")
7739 writeBoolErrReason(e.excludeTag, "exclude tag set")
7740 writeBoolErrReason(e.noStorage, "insufficient storage")
7741 writeBoolErrReason(e.uniqueTag, "server tag not unique")
7742 writeBoolErrReason(e.misc, "miscellaneous issue")
7743 writeBoolErrReason(e.noJsClust, "jetstream not enabled in cluster")
7744 if len(e.noMatchTags) != 0 {
7745 b.WriteString(", tags not matched [")
7746 var firstTagWritten bool
7747 for tag := range e.noMatchTags {
7748 if firstTagWritten {
7749 b.WriteString(", ")
7750 }
7751 firstTagWritten = true
7752 b.WriteRune('\'')
7753 b.WriteString(tag)
7754 b.WriteRune('\'')
7755 }
7756 b.WriteString("]")
7757 }
7758 if len(e.excludeTags) != 0 {
7759 b.WriteString(", tags excluded [")
7760 var firstTagWritten bool
7761 for tag := range e.excludeTags {
7762 if firstTagWritten {
7763 b.WriteString(", ")
7764 }
7765 firstTagWritten = true
7766 b.WriteRune('\'')
7767 b.WriteString(tag)
7768 b.WriteRune('\'')
7769 }
7770 b.WriteString("]")
7771 }
7772
7773 return b.String()
7774 }
7775
7776 func (e *selectPeerError) addMissingTag(t string) {
7777 if e.noMatchTags == nil {
7778 e.noMatchTags = map[string]struct{}{}
7779 }
7780 e.noMatchTags[t] = struct{}{}
7781 }
7782
7783 func (e *selectPeerError) addExcludeTag(t string) {
7784 if e.excludeTags == nil {
7785 e.excludeTags = map[string]struct{}{}
7786 }
7787 e.excludeTags[t] = struct{}{}
7788 }
7789
7790 func (e *selectPeerError) accumulate(eAdd *selectPeerError) {
7791 if eAdd == nil {
7792 return
7793 }
7794 acc := func(val *bool, valAdd bool) {
7795 if valAdd {
7796 *val = valAdd
7797 }
7798 }
7799 acc(&e.offline, eAdd.offline)
7800 acc(&e.excludeTag, eAdd.excludeTag)
7801 acc(&e.noStorage, eAdd.noStorage)
7802 acc(&e.uniqueTag, eAdd.uniqueTag)
7803 acc(&e.misc, eAdd.misc)
7804 acc(&e.noJsClust, eAdd.noJsClust)
7805 for tag := range eAdd.noMatchTags {
7806 e.addMissingTag(tag)
7807 }
7808 for tag := range eAdd.excludeTags {
7809 e.addExcludeTag(tag)
7810 }
7811 }
7812
7813 // selectPeerGroup will select a group of peers to start a raft group.
7814 // when peers exist already the unique tag prefix check for the replaceFirstExisting will be skipped
7815 // js lock should be held.
7816 func (cc *jetStreamCluster) selectPeerGroup(r int, cluster string, cfg *StreamConfig, existing []string, replaceFirstExisting int, ignore []string) ([]string, *selectPeerError) {
7817 if cluster == _EMPTY_ || cfg == nil {
7818 return nil, &selectPeerError{misc: true}
7819 }
7820
7821 var maxBytes uint64
7822 if cfg.MaxBytes > 0 {
7823 maxBytes = uint64(cfg.MaxBytes)
7824 }
7825
7826 // Check for tags.
7827 type tagInfo struct {
7828 tag string
7829 exclude bool
7830 }
7831 var ti []tagInfo
7832 if cfg.Placement != nil {
7833 ti = make([]tagInfo, 0, len(cfg.Placement.Tags))
7834 for _, t := range cfg.Placement.Tags {
7835 ti = append(ti, tagInfo{
7836 tag: strings.TrimPrefix(t, "!"),
7837 exclude: strings.HasPrefix(t, "!"),
7838 })
7839 }
7840 }
7841
7842 // Used for weighted sorting based on availability.
7843 type wn struct {
7844 id string
7845 avail uint64
7846 off bool
7847 ha int
7848 ns int
7849 }
7850
7851 var nodes []wn
7852 // peers is a randomized list
7853 s, peers := cc.s, cc.meta.Peers()
7854
7855 uniqueTagPrefix := s.getOpts().JetStreamUniqueTag
7856 if uniqueTagPrefix != _EMPTY_ {
7857 for _, t := range ti {
7858 if strings.HasPrefix(t.tag, uniqueTagPrefix) {
7859 // disable uniqueness check if explicitly listed in tags
7860 uniqueTagPrefix = _EMPTY_
7861 break
7862 }
7863 }
7864 }
7865 var uniqueTags = make(map[string]*nodeInfo)
7866
7867 checkUniqueTag := func(ni *nodeInfo) (bool, *nodeInfo) {
7868 for _, t := range ni.tags {
7869 if strings.HasPrefix(t, uniqueTagPrefix) {
7870 if n, ok := uniqueTags[t]; !ok {
7871 uniqueTags[t] = ni
7872 return true, ni
7873 } else {
7874 return false, n
7875 }
7876 }
7877 }
7878 // default requires the unique prefix to be present
7879 return false, nil
7880 }
7881
7882 // Map existing.
7883 var ep map[string]struct{}
7884 if le := len(existing); le > 0 {
7885 if le >= r {
7886 return existing[:r], nil
7887 }
7888 ep = make(map[string]struct{})
7889 for i, p := range existing {
7890 ep[p] = struct{}{}
7891 if uniqueTagPrefix == _EMPTY_ {
7892 continue
7893 }
7894 si, ok := s.nodeToInfo.Load(p)
7895 if !ok || si == nil || i < replaceFirstExisting {
7896 continue
7897 }
7898 ni := si.(nodeInfo)
7899 // collect unique tags, but do not require them as this node is already part of the peerset
7900 checkUniqueTag(&ni)
7901 }
7902 }
7903
7904 // Map ignore
7905 var ip map[string]struct{}
7906 if li := len(ignore); li > 0 {
7907 ip = make(map[string]struct{})
7908 for _, p := range ignore {
7909 ip[p] = struct{}{}
7910 }
7911 }
7912
7913 // Grab the number of streams and HA assets currently assigned to each peer.
7914 // HAAssets under usage is async, so calculate here in realtime based on assignments.
7915 peerStreams := make(map[string]int, len(peers))
7916 peerHA := make(map[string]int, len(peers))
7917 for _, asa := range cc.streams {
7918 for _, sa := range asa {
7919 if sa.unsupported != nil {
7920 continue
7921 }
7922 isHA := len(sa.Group.Peers) > 1
7923 for _, peer := range sa.Group.Peers {
7924 peerStreams[peer]++
7925 if isHA {
7926 peerHA[peer]++
7927 }
7928 }
7929 }
7930 }
7931
7932 maxHaAssets := s.getOpts().JetStreamLimits.MaxHAAssets
7933
7934 // An error is a result of multiple individual placement decisions.
7935 // Which is why we keep taps on how often which one happened.
7936 err := selectPeerError{}
7937
7938 var onlinePeers int
7939
7940 // Shuffle them up.
7941 rand.Shuffle(len(peers), func(i, j int) { peers[i], peers[j] = peers[j], peers[i] })
7942 for _, p := range peers {
7943 si, ok := s.nodeToInfo.Load(p.ID)
7944 if !ok || si == nil {
7945 err.misc = true
7946 continue
7947 }
7948 ni := si.(nodeInfo)
7949 // Only select from the designated named cluster.
7950 if ni.cluster != cluster {
7951 s.Debugf("Peer selection: discard %s@%s reason: not target cluster %s", ni.name, ni.cluster, cluster)
7952 continue
7953 }
7954
7955 // If we've never heard from a server, don't consider.
7956 if ni.cfg == nil || ni.stats == nil {
7957 s.Debugf("Peer selection: discard %s@%s reason: offline", ni.name, ni.cluster)
7958 err.offline = true
7959 continue
7960 }
7961
7962 // If ignore skip
7963 if _, ok := ip[p.ID]; ok {
7964 continue
7965 }
7966
7967 // If existing also skip, we will add back in to front of the list when done.
7968 if _, ok := ep[p.ID]; ok {
7969 continue
7970 }
7971
7972 if ni.tags.Contains(jsExcludePlacement) {
7973 s.Debugf("Peer selection: discard %s@%s tags: %v reason: %s present",
7974 ni.name, ni.cluster, ni.tags, jsExcludePlacement)
7975 err.excludeTag = true
7976 continue
7977 }
7978
7979 if len(ti) > 0 {
7980 matched := true
7981 for _, t := range ti {
7982 contains := ni.tags.Contains(t.tag)
7983 if t.exclude && contains {
7984 matched = false
7985 s.Debugf("Peer selection: discard %s@%s tags: %v reason: excluded tag %s present",
7986 ni.name, ni.cluster, ni.tags, t)
7987 err.addExcludeTag(t.tag)
7988 break
7989 } else if !t.exclude && !contains {
7990 matched = false
7991 s.Debugf("Peer selection: discard %s@%s tags: %v reason: mandatory tag %s not present",
7992 ni.name, ni.cluster, ni.tags, t)
7993 err.addMissingTag(t.tag)
7994 break
7995 }
7996 }
7997 if !matched {
7998 continue
7999 }
8000 }
8001
8002 var available uint64
8003 if ni.stats != nil {
8004 switch cfg.Storage {
8005 case MemoryStorage:
8006 used := ni.stats.ReservedMemory
8007 if ni.stats.Memory > used {
8008 used = ni.stats.Memory
8009 }
8010 if ni.cfg.MaxMemory > int64(used) {
8011 available = uint64(ni.cfg.MaxMemory) - used
8012 }
8013 case FileStorage:
8014 used := ni.stats.ReservedStore
8015 if ni.stats.Store > used {
8016 used = ni.stats.Store
8017 }
8018 if ni.cfg.MaxStore > int64(used) {
8019 available = uint64(ni.cfg.MaxStore) - used
8020 }
8021 }
8022 }
8023
8024 // Otherwise check if we have enough room if maxBytes set.
8025 if maxBytes > 0 && maxBytes > available {
8026 s.Warnf("Peer selection: discard %s@%s (Max Bytes: %d) exceeds available %s storage of %d bytes",
8027 ni.name, ni.cluster, maxBytes, cfg.Storage.String(), available)
8028 err.noStorage = true
8029 continue
8030 }
8031 // HAAssets contain _meta_ which we want to ignore, hence > and not >=.
8032 if maxHaAssets > 0 && ni.stats != nil && ni.stats.HAAssets > maxHaAssets {
8033 s.Warnf("Peer selection: discard %s@%s (HA Asset Count: %d) exceeds max ha asset limit of %d for stream placement",
8034 ni.name, ni.cluster, ni.stats.HAAssets, maxHaAssets)
8035 err.misc = true
8036 continue
8037 }
8038
8039 if uniqueTagPrefix != _EMPTY_ {
8040 if unique, owner := checkUniqueTag(&ni); !unique {
8041 if owner != nil {
8042 s.Debugf("Peer selection: discard %s@%s tags:%v reason: unique prefix %s owned by %s@%s",
8043 ni.name, ni.cluster, ni.tags, owner.name, owner.cluster)
8044 } else {
8045 s.Debugf("Peer selection: discard %s@%s tags:%v reason: unique prefix %s not present",
8046 ni.name, ni.cluster, ni.tags)
8047 }
8048 err.uniqueTag = true
8049 continue
8050 }
8051 }
8052 // Add to our list of potential nodes.
8053 nodes = append(nodes, wn{p.ID, available, ni.offline, peerHA[p.ID], peerStreams[p.ID]})
8054 if !ni.offline {
8055 onlinePeers++
8056 }
8057 }
8058
8059 // If we could not select enough peers, fail.
8060 quorum := r/2 + 1
8061 missingQuorum := onlinePeers+len(existing) < quorum
8062 if missingNodes := len(nodes) < (r - len(existing)); missingNodes || missingQuorum {
8063 if len(peers) == 0 {
8064 err.noJsClust = true
8065 } else if !missingNodes && missingQuorum {
8066 err.offline = true
8067 }
8068 s.Debugf("Peer selection: required %d nodes but found %d (cluster: %s replica: %d existing: %v/%d peers: %d result-peers: %d err: %+v)",
8069 r-len(existing), len(nodes), cluster, r, existing, replaceFirstExisting, len(peers), len(nodes), err)
8070 return nil, &err
8071 }
8072 // Sort based on available from most to least, breaking ties by number of total streams assigned to the peer.
8073 slices.SortFunc(nodes, func(i, j wn) int {
8074 // Prefer online servers to offline ones.
8075 if i.off != j.off {
8076 if i.off {
8077 return 1
8078 } else {
8079 return -1
8080 }
8081 }
8082 if i.avail == j.avail {
8083 return cmp.Compare(i.ns, j.ns)
8084 }
8085 return -cmp.Compare(i.avail, j.avail) // reverse
8086 })
8087 // If we are placing a replicated stream, let's sort based on HAAssets, as that is more important to balance.
8088 if cfg.Replicas > 1 {
8089 slices.SortStableFunc(nodes, func(i, j wn) int {
8090 // Prefer online servers to offline ones.
8091 if i.off != j.off {
8092 if i.off {
8093 return 1
8094 } else {
8095 return -1
8096 }
8097 }
8098 return cmp.Compare(i.ha, j.ha)
8099 })
8100 }
8101
8102 var results []string
8103 if len(existing) > 0 {
8104 results = append(results, existing...)
8105 r -= len(existing)
8106 }
8107 for _, r := range nodes[:r] {
8108 results = append(results, r.id)
8109 }
8110 return results, nil
8111 }
8112
8113 func groupNameForStream(peers []string, storage StorageType) string {
8114 return groupName("S", peers, storage)
8115 }
8116
8117 func groupNameForConsumer(peers []string, storage StorageType) string {
8118 return groupName("C", peers, storage)
8119 }
8120
8121 func groupName(prefix string, peers []string, storage StorageType) string {
8122 gns := getHash(nuid.Next())
8123 return fmt.Sprintf("%s-R%d%s-%s", prefix, len(peers), storage.String()[:1], gns)
8124 }
8125
8126 // returns stream count for this tier as well as applicable reservation size (not including cfg)
8127 // jetStream read lock should be held
8128 func (js *jetStream) tieredStreamAndReservationCount(accName, tier string, cfg *StreamConfig) (int, int64) {
8129 var numStreams int
8130 var reservation int64
8131 for sa := range js.streamAssignmentsOrInflightSeq(accName) {
8132 // Don't count the stream toward the limit if it already exists.
8133 if sa.Config.Name == cfg.Name {
8134 continue
8135 }
8136 if tier == _EMPTY_ || isSameTier(sa.Config.Replicas, cfg.Replicas) {
8137 numStreams++
8138 if sa.Config.MaxBytes > 0 && sa.Config.Storage == cfg.Storage {
8139 reservation = addSaturate(reservation, accountReservation(tier, sa.Config.Replicas, sa.Config.MaxBytes))
8140 }
8141 }
8142 }
8143 return numStreams, reservation
8144 }
8145
8146 // createGroupForStream will create a group for assignment for the stream.
8147 // Lock should be held.
8148 func (js *jetStream) createGroupForStream(ci *ClientInfo, cfg *StreamConfig) (*raftGroup, *selectPeerError) {
8149 replicas := cfg.Replicas
8150 if replicas == 0 {
8151 replicas = 1
8152 }
8153
8154 // Default connected cluster from the request origin.
8155 cc, cluster := js.cluster, ci.Cluster
8156 // If specified, override the default.
8157 clusterDefined := cfg.Placement != nil && cfg.Placement.Cluster != _EMPTY_
8158 if clusterDefined {
8159 cluster = cfg.Placement.Cluster
8160 }
8161 clusters := []string{cluster}
8162 if !clusterDefined {
8163 clusters = append(clusters, ci.Alternates...)
8164 }
8165
8166 // Need to create a group here.
8167 errs := &selectPeerError{}
8168 for _, cn := range clusters {
8169 peers, err := cc.selectPeerGroup(replicas, cn, cfg, nil, 0, nil)
8170 if len(peers) < replicas {
8171 errs.accumulate(err)
8172 continue
8173 }
8174 return &raftGroup{Name: groupNameForStream(peers, cfg.Storage), Storage: cfg.Storage, Peers: peers, Cluster: cn}, nil
8175 }
8176 return nil, errs
8177 }
8178
8179 func (acc *Account) selectLimits(replicas int) (*JetStreamAccountLimits, string, *jsAccount, *ApiError) {
8180 // Grab our jetstream account info.
8181 acc.mu.RLock()
8182 jsa := acc.js
8183 acc.mu.RUnlock()
8184
8185 if jsa == nil {
8186 return nil, _EMPTY_, nil, NewJSNotEnabledForAccountError()
8187 }
8188
8189 jsa.usageMu.RLock()
8190 selectedLimits, tierName, ok := jsa.selectLimits(replicas)
8191 jsa.usageMu.RUnlock()
8192
8193 if !ok {
8194 return nil, _EMPTY_, nil, NewJSNoLimitsError()
8195 }
8196 return &selectedLimits, tierName, jsa, nil
8197 }
8198
8199 // Read lock needs to be held
8200 func (js *jetStream) jsClusteredStreamLimitsCheck(acc *Account, cfg *StreamConfig) *ApiError {
8201 var replicas int
8202 if cfg != nil {
8203 replicas = cfg.Replicas
8204 }
8205 selectedLimits, tier, _, apiErr := acc.selectLimits(replicas)
8206 if apiErr != nil {
8207 return apiErr
8208 }
8209
8210 numStreams, reservations := js.tieredStreamAndReservationCount(acc.Name, tier, cfg)
8211 if selectedLimits.MaxStreams > 0 && numStreams >= selectedLimits.MaxStreams {
8212 return NewJSMaximumStreamsLimitError()
8213 }
8214 // Check for account limits here before proposing.
8215 if err := js.checkAccountLimits(selectedLimits, tier, cfg, reservations); err != nil {
8216 return NewJSStreamLimitsError(err, Unless(err))
8217 }
8218 return nil
8219 }
8220
8221 func (s *Server) jsClusteredStreamRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, config *StreamConfigRequest) {
8222 js, cc := s.getJetStreamCluster()
8223 if js == nil || cc == nil {
8224 return
8225 }
8226
8227 var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}}
8228
8229 ccfg, apiErr := s.checkStreamCfg(&config.StreamConfig, acc, config.Pedantic)
8230 if apiErr != nil {
8231 resp.Error = apiErr
8232 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8233 return
8234 }
8235 cfg := &ccfg
8236
8237 // Now process the request and proposal.
8238 js.mu.Lock()
8239 defer js.mu.Unlock()
8240
8241 var self *streamAssignment
8242 var rg *raftGroup
8243 var syncSubject string
8244
8245 // Capture if we have existing/inflight assignment first.
8246 if osa := js.streamAssignmentOrInflight(acc.Name, cfg.Name); osa != nil {
8247 copyStreamMetadata(cfg, osa.Config)
8248 // Set the index name on both to ensure the DeepEqual works
8249 currentIName := make(map[string]struct{})
8250 for _, s := range osa.Config.Sources {
8251 currentIName[s.iname] = struct{}{}
8252 }
8253 for _, s := range cfg.Sources {
8254 s.setIndexName()
8255 if _, ok := currentIName[s.iname]; !ok {
8256 s.iname = _EMPTY_
8257 }
8258 }
8259 if !reflect.DeepEqual(osa.Config, cfg) {
8260 resp.Error = NewJSStreamNameExistError()
8261 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8262 return
8263 }
8264 // This is an equal assignment.
8265 self, rg, syncSubject = osa, osa.Group, osa.Sync
8266 }
8267
8268 if cfg.Sealed {
8269 resp.Error = NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration for create can not be sealed"))
8270 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8271 return
8272 }
8273
8274 // Check for subject collisions here.
8275 if js.subjectsOverlap(acc.Name, cfg.Subjects, self) {
8276 resp.Error = NewJSStreamSubjectOverlapError()
8277 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8278 return
8279 }
8280
8281 apiErr = js.jsClusteredStreamLimitsCheck(acc, cfg)
8282 // Check for stream limits here before proposing. These need to be tracked from meta layer, not jsa.
8283 if apiErr != nil {
8284 resp.Error = apiErr
8285 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8286 return
8287 }
8288
8289 // Create a new one here if needed.
8290 if rg == nil {
8291 nrg, err := js.createGroupForStream(ci, cfg)
8292 if err != nil {
8293 resp.Error = NewJSClusterNoPeersError(err)
8294 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8295 return
8296 }
8297 rg = nrg
8298 // Pick a preferred leader.
8299 rg.setPreferred(s)
8300 }
8301
8302 if syncSubject == _EMPTY_ {
8303 syncSubject = syncSubjForStream()
8304 }
8305 // Preserve the original creation time on an idempotent create retry.
8306 created := time.Now().UTC()
8307 if self != nil {
8308 created = self.Created
8309 }
8310 // Sync subject for post snapshot sync.
8311 sa := &streamAssignment{Group: rg, Sync: syncSubject, Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: created}
8312 if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(sa)); err != nil {
8313 return
8314 }
8315 // On success, add this as an inflight proposal so we can apply limits
8316 // on concurrent create requests while this stream assignment has
8317 // possibly not been processed yet.
8318 cc.trackInflightStreamProposal(acc.Name, sa, false)
8319 }
8320
8321 var (
8322 errReqTimeout = errors.New("timeout while waiting for response")
8323 errReqSrvExit = errors.New("server shutdown while waiting for response")
8324 )
8325
8326 // blocking utility call to perform requests on the system account
8327 // returns (synchronized) v or error
8328 func sysRequest[T any](s *Server, subjFormat string, args ...any) (*T, error) {
8329 isubj := fmt.Sprintf(subjFormat, args...)
8330
8331 s.mu.Lock()
8332 if s.sys == nil {
8333 s.mu.Unlock()
8334 return nil, ErrNoSysAccount
8335 }
8336 inbox := s.newRespInbox()
8337 results := make(chan *T, 1)
8338 s.sys.replies[inbox] = func(_ *subscription, _ *client, _ *Account, _, _ string, msg []byte) {
8339 var v T
8340 if err := json.Unmarshal(msg, &v); err != nil {
8341 s.Warnf("Error unmarshalling response for request '%s':%v", isubj, err)
8342 return
8343 }
8344 select {
8345 case results <- &v:
8346 default:
8347 s.Warnf("Failed placing request response on internal channel")
8348 }
8349 }
8350 s.mu.Unlock()
8351
8352 s.sendInternalMsgLocked(isubj, inbox, nil, nil)
8353
8354 defer func() {
8355 s.mu.Lock()
8356 defer s.mu.Unlock()
8357 if s.sys != nil && s.sys.replies != nil {
8358 delete(s.sys.replies, inbox)
8359 }
8360 }()
8361
8362 ttl := time.NewTimer(2 * time.Second)
8363 defer ttl.Stop()
8364
8365 select {
8366 case <-s.quitCh:
8367 return nil, errReqSrvExit
8368 case <-ttl.C:
8369 return nil, errReqTimeout
8370 case data := <-results:
8371 return data, nil
8372 }
8373 }
8374
8375 func (s *Server) jsClusteredStreamUpdateRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, cfg *StreamConfig, peerSet []string, pedantic bool) {
8376 js, cc := s.getJetStreamCluster()
8377 if js == nil || cc == nil {
8378 return
8379 }
8380
8381 // Now process the request and proposal.
8382 js.mu.Lock()
8383 defer js.mu.Unlock()
8384 meta := cc.meta
8385 if meta == nil {
8386 return
8387 }
8388
8389 var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}}
8390
8391 osa := js.streamAssignmentOrInflight(acc.Name, cfg.Name)
8392 if osa == nil {
8393 resp.Error = NewJSStreamNotFoundError()
8394 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8395 return
8396 }
8397
8398 // Don't allow updating if all peers are offline.
8399 if s.allPeersOffline(osa.Group) {
8400 resp.Error = NewJSStreamOfflineError()
8401 s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp), nil, errRespDelay)
8402 return
8403 }
8404
8405 // Update asset version metadata.
8406 setStaticStreamMetadata(cfg)
8407
8408 var newCfg *StreamConfig
8409 if jsa := js.accounts[acc.Name]; jsa != nil {
8410 js.mu.Unlock()
8411 ncfg, err := jsa.configUpdateCheck(osa.Config, cfg, s, pedantic)
8412 js.mu.Lock()
8413 if err != nil {
8414 resp.Error = NewJSStreamUpdateError(err, Unless(err))
8415 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8416 return
8417 } else {
8418 newCfg = ncfg
8419 }
8420 } else {
8421 resp.Error = NewJSNotEnabledForAccountError()
8422 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8423 return
8424 }
8425 // Check for mirror changes which are not allowed.
8426 // We will allow removing the mirror config to "promote" the mirror to a normal stream.
8427 if newCfg.Mirror != nil && !reflect.DeepEqual(newCfg.Mirror, osa.Config.Mirror) {
8428 resp.Error = NewJSStreamMirrorNotUpdatableError()
8429 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8430 return
8431 }
8432
8433 // Check for subject collisions here.
8434 if js.subjectsOverlap(acc.Name, cfg.Subjects, osa) {
8435 resp.Error = NewJSStreamSubjectOverlapError()
8436 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8437 return
8438 }
8439
8440 // In the event that some of the stream-level limits have changed, yell appropriately
8441 // if any of the consumers exceed that limit.
8442 oldInactiveThreshold, newInactiveThreshold := osa.Config.ConsumerLimits.InactiveThreshold, newCfg.ConsumerLimits.InactiveThreshold
8443 oldMaxAckPending, newMaxAckPending := osa.Config.ConsumerLimits.MaxAckPending, newCfg.ConsumerLimits.MaxAckPending
8444 updateLimits := (newInactiveThreshold > 0 && oldInactiveThreshold != newInactiveThreshold) ||
8445 (newMaxAckPending > 0 && oldMaxAckPending != newMaxAckPending)
8446 if updateLimits {
8447 var errorConsumers []string
8448 for ca := range js.consumerAssignmentsOrInflightSeq(acc.Name, cfg.Name) {
8449 if ca.Config == nil {
8450 continue
8451 }
8452 if (newInactiveThreshold > 0 && ca.Config.InactiveThreshold > newInactiveThreshold) ||
8453 (newMaxAckPending > 0 && ca.Config.MaxAckPending > newMaxAckPending) {
8454 errorConsumers = append(errorConsumers, ca.Name)
8455 }
8456 }
8457 if len(errorConsumers) > 0 {
8458 err := fmt.Errorf("change to limits violates consumers: %s", strings.Join(errorConsumers, ", "))
8459 resp.Error = NewJSStreamUpdateError(err)
8460 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8461 return
8462 }
8463 }
8464
8465 // Make copy so to not change original.
8466 rg := osa.copyGroup().Group
8467
8468 // Check for a move request.
8469 var isMoveRequest, isMoveCancel bool
8470 if lPeerSet := len(peerSet); lPeerSet > 0 {
8471 isMoveRequest = true
8472 // check if this is a cancellation
8473 if lPeerSet == osa.Config.Replicas && lPeerSet <= len(rg.Peers) {
8474 isMoveCancel = true
8475 // can only be a cancellation if the peer sets overlap as expected
8476 for i := 0; i < lPeerSet; i++ {
8477 if peerSet[i] != rg.Peers[i] {
8478 isMoveCancel = false
8479 break
8480 }
8481 }
8482 }
8483 } else {
8484 isMoveRequest = newCfg.Placement != nil && !reflect.DeepEqual(osa.Config.Placement, newCfg.Placement)
8485 }
8486
8487 // Check for replica changes.
8488 isReplicaChange := newCfg.Replicas != osa.Config.Replicas
8489
8490 // We stage consumer updates and do them after the stream update.
8491 var consumers []*consumerAssignment
8492
8493 // Check if this is a move request, but no cancellation, and we are already moving this stream.
8494 if isMoveRequest && !isMoveCancel && osa.Config.Replicas != len(rg.Peers) {
8495 // obtain stats to include in error message
8496 msg := _EMPTY_
8497 if s.allPeersOffline(rg) {
8498 msg = fmt.Sprintf("all %d peers offline", len(rg.Peers))
8499 } else {
8500 // Need to release js lock.
8501 js.mu.Unlock()
8502 if si, err := sysRequest[StreamInfo](s, clusterStreamInfoT, ci.serviceAccount(), cfg.Name); err != nil {
8503 msg = fmt.Sprintf("error retrieving info: %s", err.Error())
8504 } else if si != nil {
8505 currentCount := 0
8506 if si.Cluster.Leader != _EMPTY_ {
8507 currentCount++
8508 }
8509 combinedLag := uint64(0)
8510 for _, r := range si.Cluster.Replicas {
8511 if r.Current {
8512 currentCount++
8513 }
8514 combinedLag += r.Lag
8515 }
8516 msg = fmt.Sprintf("total peers: %d, current peers: %d, combined lag: %d",
8517 len(rg.Peers), currentCount, combinedLag)
8518 }
8519 // Re-acquire here.
8520 js.mu.Lock()
8521 }
8522 resp.Error = NewJSStreamMoveInProgressError(msg)
8523 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8524 return
8525 }
8526
8527 // Can not move and scale at same time.
8528 if isMoveRequest && isReplicaChange {
8529 resp.Error = NewJSStreamMoveAndScaleError()
8530 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8531 return
8532 }
8533
8534 // Reset notion of scaling up, if this was done in a previous update.
8535 rg.ScaleUp = false
8536 if isReplicaChange {
8537 isScaleUp := newCfg.Replicas > len(rg.Peers)
8538 // We are adding new peers here.
8539 if isScaleUp {
8540 // Check that we have the allocation available.
8541 if err := js.jsClusteredStreamLimitsCheck(acc, newCfg); err != nil {
8542 resp.Error = err
8543 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8544 return
8545 }
8546 // Check if we do not have a cluster assigned, and if we do not make sure we
8547 // try to pick one. This could happen with older streams that were assigned by
8548 // previous servers.
8549 if rg.Cluster == _EMPTY_ {
8550 // Prefer placement directives if we have them.
8551 if newCfg.Placement != nil && newCfg.Placement.Cluster != _EMPTY_ {
8552 rg.Cluster = newCfg.Placement.Cluster
8553 } else {
8554 // Fall back to the cluster assignment from the client.
8555 rg.Cluster = ci.Cluster
8556 }
8557 }
8558 peers, err := cc.selectPeerGroup(newCfg.Replicas, rg.Cluster, newCfg, rg.Peers, 0, nil)
8559 if err != nil {
8560 resp.Error = NewJSClusterNoPeersError(err)
8561 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8562 return
8563 }
8564 // Single nodes are not recorded by the NRG layer so we can rename.
8565 if len(peers) == 1 || osa.Config.Replicas == 1 {
8566 rg.Name = groupNameForStream(peers, rg.Storage)
8567 }
8568 if len(rg.Peers) == 1 {
8569 // This is scale up from being a singleton, set preferred to that singleton.
8570 rg.Preferred = rg.Peers[0]
8571 }
8572 rg.ScaleUp = true
8573 rg.Peers = peers
8574 } else {
8575 // We are deleting nodes here. We want to do our best to preserve the current leader.
8576 // We have support now from above that guarantees we are in our own Go routine, so can
8577 // ask for stream info from the stream leader to make sure we keep the leader in the new list.
8578 var curLeader string
8579 if !s.allPeersOffline(rg) {
8580 // Need to release js lock.
8581 js.mu.Unlock()
8582 if si, err := sysRequest[StreamInfo](s, clusterStreamInfoT, ci.serviceAccount(), cfg.Name); err != nil {
8583 s.Warnf("Did not receive stream info results for '%s > %s' due to: %s", acc, cfg.Name, err)
8584 } else if si != nil {
8585 if cl := si.Cluster; cl != nil && cl.Leader != _EMPTY_ {
8586 curLeader = getHash(cl.Leader)
8587 }
8588 }
8589 // Re-acquire here.
8590 js.mu.Lock()
8591 }
8592 // If we identified a leader make sure its part of the new group.
8593 rg.Peers = s.selectScaleDownPeers(rg.Peers, curLeader, newCfg.Replicas)
8594 // Single nodes are not recorded by the NRG layer so we can rename.
8595 // MUST do this, otherwise a scaleup afterward could potentially lead to inconsistencies.
8596 if len(rg.Peers) == 1 {
8597 rg.Name = groupNameForStream(rg.Peers, rg.Storage)
8598 }
8599 }
8600
8601 // Need to remap any consumers.
8602 for ca := range js.consumerAssignmentsOrInflightSeq(acc.Name, osa.Config.Name) {
8603 // Legacy ephemerals are R=1 but present as R=0, so only auto-remap named consumers, or if we are downsizing the consumer peers.
8604 // If stream is interest or workqueue policy always remaps since they require peer parity with stream.
8605 numPeers := len(ca.Group.Peers)
8606 isAutoScale := ca.Config.Replicas == 0 && (ca.Config.Durable != _EMPTY_ || ca.Config.Name != _EMPTY_)
8607 if isAutoScale || numPeers > len(rg.Peers) || cfg.Retention != LimitsPolicy {
8608 cca := ca.copyGroup()
8609 // Adjust preferred as needed.
8610 if numPeers == 1 && isScaleUp {
8611 cca.Group.Preferred = ca.Group.Peers[0]
8612 } else {
8613 cca.Group.Preferred = _EMPTY_
8614 }
8615 // Assign new peers.
8616 cca.Group.Peers = rg.Peers
8617 // Single nodes are not recorded by the NRG layer so we can rename.
8618 if len(cca.Group.Peers) == 1 || numPeers == 1 {
8619 cca.Group.Name = groupNameForConsumer(cca.Group.Peers, cca.Group.Storage)
8620 }
8621 // If the replicas was not 0 make sure it matches here.
8622 if cca.Config.Replicas != 0 {
8623 cca.Config.Replicas = len(rg.Peers)
8624 }
8625 // We can not propose here before the stream itself so we collect them.
8626 consumers = append(consumers, cca)
8627
8628 } else if !isScaleUp {
8629 // We decided to leave this consumer's peer group alone but we are also scaling down.
8630 // We need to make sure we do not have any peers that are no longer part of the stream.
8631 // Note we handle down scaling of a consumer above if its number of peers were > new stream peers.
8632 var needReplace []string
8633 for _, rp := range ca.Group.Peers {
8634 // Check if we have an orphaned peer now for this consumer.
8635 if !rg.isMember(rp) {
8636 needReplace = append(needReplace, rp)
8637 }
8638 }
8639 if len(needReplace) > 0 {
8640 newPeers := copyStrings(rg.Peers)
8641 rand.Shuffle(len(newPeers), func(i, j int) { newPeers[i], newPeers[j] = newPeers[j], newPeers[i] })
8642 // If we had a small size then the peer set, restrict to the same number.
8643 if lp := len(ca.Group.Peers); lp < len(newPeers) {
8644 newPeers = newPeers[:lp]
8645 }
8646 cca := ca.copyGroup()
8647 // Assign new peers.
8648 cca.Group.Peers = newPeers
8649 // Single nodes are not recorded by the NRG layer so we can rename.
8650 if len(cca.Group.Peers) == 1 || numPeers == 1 {
8651 cca.Group.Name = groupNameForConsumer(cca.Group.Peers, cca.Group.Storage)
8652 }
8653 // If the replicas was not 0 make sure it matches here.
8654 if cca.Config.Replicas != 0 {
8655 cca.Config.Replicas = len(newPeers)
8656 }
8657 // Check if all peers are invalid. This can happen with R1 under replicated streams that are being scaled down.
8658 if len(needReplace) == len(ca.Group.Peers) {
8659 // We have to transfer state to new peers.
8660 // we will grab our state and attach to the new assignment.
8661 // TODO(dlc) - In practice we would want to make sure the consumer is paused.
8662 // Need to release js lock.
8663 js.mu.Unlock()
8664 if ci, err := sysRequest[ConsumerInfo](s, clusterConsumerInfoT, acc, osa.Config.Name, ca.Name); err != nil {
8665 s.Warnf("Did not receive consumer info results for '%s > %s > %s' due to: %s", acc, osa.Config.Name, ca.Name, err)
8666 } else if ci != nil {
8667 cca.State = &ConsumerState{
8668 Delivered: SequencePair{
8669 Consumer: ci.Delivered.Consumer,
8670 Stream: ci.Delivered.Stream,
8671 },
8672 AckFloor: SequencePair{
8673 Consumer: ci.AckFloor.Consumer,
8674 Stream: ci.AckFloor.Stream,
8675 },
8676 }
8677 }
8678 // Re-acquire here.
8679 js.mu.Lock()
8680 }
8681 // We can not propose here before the stream itself so we collect them.
8682 consumers = append(consumers, cca)
8683 }
8684 }
8685 }
8686
8687 } else if isMoveRequest {
8688 if len(peerSet) == 0 {
8689 nrg, err := js.createGroupForStream(ci, newCfg)
8690 if err != nil {
8691 resp.Error = NewJSClusterNoPeersError(err)
8692 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8693 return
8694 }
8695 // filter peers present in both sets
8696 for _, peer := range rg.Peers {
8697 if !slices.Contains(nrg.Peers, peer) {
8698 peerSet = append(peerSet, peer)
8699 }
8700 }
8701 peerSet = append(peerSet, nrg.Peers...)
8702 }
8703 if len(rg.Peers) == 1 {
8704 rg.Preferred = peerSet[0]
8705 }
8706 rg.Peers = peerSet
8707
8708 for ca := range js.consumerAssignmentsOrInflightSeq(acc.Name, osa.Config.Name) {
8709 cca := ca.copyGroup()
8710 r := cca.Config.replicas(osa.Config)
8711 // shuffle part of cluster peer set we will be keeping
8712 randPeerSet := copyStrings(peerSet[len(peerSet)-newCfg.Replicas:])
8713 rand.Shuffle(newCfg.Replicas, func(i, j int) { randPeerSet[i], randPeerSet[j] = randPeerSet[j], randPeerSet[i] })
8714 // move overlapping peers at the end of randPeerSet and keep a tally of non overlapping peers
8715 dropPeerSet := make([]string, 0, len(cca.Group.Peers))
8716 for _, p := range cca.Group.Peers {
8717 found := false
8718 for i, rp := range randPeerSet {
8719 if p == rp {
8720 randPeerSet[i] = randPeerSet[newCfg.Replicas-1]
8721 randPeerSet[newCfg.Replicas-1] = p
8722 found = true
8723 break
8724 }
8725 }
8726 if !found {
8727 dropPeerSet = append(dropPeerSet, p)
8728 }
8729 }
8730 cPeerSet := randPeerSet[newCfg.Replicas-r:]
8731 // In case of a set or cancel simply assign
8732 if len(peerSet) == newCfg.Replicas {
8733 cca.Group.Peers = cPeerSet
8734 } else {
8735 cca.Group.Peers = append(dropPeerSet, cPeerSet...)
8736 }
8737 // make sure it overlaps with peers and remove if not
8738 if cca.Group.Preferred != _EMPTY_ {
8739 if !slices.Contains(cca.Group.Peers, cca.Group.Preferred) {
8740 cca.Group.Preferred = _EMPTY_
8741 }
8742 }
8743 // We can not propose here before the stream itself so we collect them.
8744 consumers = append(consumers, cca)
8745 }
8746 } else {
8747 // All other updates make sure no preferred is set.
8748 rg.Preferred = _EMPTY_
8749 }
8750
8751 syncSubject := osa.Sync
8752 if syncSubject == _EMPTY_ {
8753 syncSubject = syncSubjForStream()
8754 }
8755 sa := &streamAssignment{Group: rg, Sync: syncSubject, Created: osa.Created, Config: newCfg, Subject: subject, Reply: reply, Client: ci}
8756 if err := meta.Propose(cc.term, encodeUpdateStreamAssignment(sa)); err != nil {
8757 return
8758 }
8759 cc.trackInflightStreamProposal(acc.Name, sa, false)
8760
8761 // Process any staged consumers.
8762 for _, ca := range consumers {
8763 if err := meta.Propose(cc.term, encodeAddConsumerAssignment(ca)); err != nil {
8764 return
8765 }
8766 cc.trackInflightConsumerProposal(acc.Name, sa.Config.Name, ca, false)
8767 }
8768 }
8769
8770 func (s *Server) jsClusteredStreamDeleteRequest(ci *ClientInfo, acc *Account, stream, subject, reply string, rmsg []byte) {
8771 js, cc := s.getJetStreamCluster()
8772 if js == nil || cc == nil {
8773 return
8774 }
8775
8776 js.mu.Lock()
8777 defer js.mu.Unlock()
8778
8779 if cc.meta == nil {
8780 return
8781 }
8782
8783 osa := js.streamAssignmentOrInflight(acc.Name, stream)
8784 if osa == nil {
8785 var resp = JSApiStreamDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamDeleteResponseType}}
8786 resp.Error = NewJSStreamNotFoundError()
8787 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8788 return
8789 }
8790
8791 sa := &streamAssignment{Group: osa.Group, Config: osa.Config, Subject: subject, Reply: reply, Client: ci, Created: osa.Created}
8792 if err := cc.meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil {
8793 return
8794 }
8795 cc.trackInflightStreamProposal(acc.Name, sa, true)
8796 }
8797
8798 // Process a clustered purge request.
8799 func (s *Server) jsClusteredStreamPurgeRequest(
8800 ci *ClientInfo,
8801 acc *Account,
8802 mset *stream,
8803 stream, subject, reply string,
8804 rmsg []byte,
8805 preq *JSApiStreamPurgeRequest,
8806 ) {
8807 js, cc := s.getJetStreamCluster()
8808 if js == nil || cc == nil || mset == nil {
8809 return
8810 }
8811
8812 js.mu.Lock()
8813 sa := js.streamAssignment(acc.Name, stream)
8814 if sa == nil {
8815 resp := JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
8816 resp.Error = NewJSStreamNotFoundError()
8817 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8818 js.mu.Unlock()
8819 return
8820 }
8821
8822 if n := sa.Group.node; n != nil {
8823 sp := encodeStreamPurge(&streamPurge{Stream: stream, LastSeq: mset.state().LastSeq, Subject: subject, Reply: reply, Client: ci, Request: preq})
8824 js.mu.Unlock()
8825 mset.mu.RLock()
8826 term := mset.term
8827 mset.mu.RUnlock()
8828 n.Propose(term, sp)
8829 return
8830 }
8831 js.mu.Unlock()
8832
8833 var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
8834 purged, err := mset.purge(preq)
8835 if err != nil {
8836 resp.Error = NewJSStreamGeneralError(err, Unless(err))
8837 } else {
8838 resp.Purged = purged
8839 resp.Success = true
8840 }
8841 s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
8842 }
8843
8844 func (s *Server) jsClusteredStreamRestoreRequest(
8845 ci *ClientInfo,
8846 acc *Account,
8847 req *JSApiStreamRestoreRequest,
8848 subject, reply string, rmsg []byte) {
8849
8850 js, cc := s.getJetStreamCluster()
8851 if js == nil || cc == nil {
8852 return
8853 }
8854
8855 resp := JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}}
8856
8857 // check stream config at the start of the restore process, not at the end
8858 cfg, apiErr := s.checkStreamCfg(&req.Config, acc, false)
8859 if apiErr != nil {
8860 resp.Error = apiErr
8861 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8862 return
8863 }
8864
8865 js.mu.Lock()
8866 defer js.mu.Unlock()
8867
8868 if cc.meta == nil {
8869 return
8870 }
8871
8872 if err := js.jsClusteredStreamLimitsCheck(acc, &cfg); err != nil {
8873 resp.Error = err
8874 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8875 return
8876 }
8877
8878 if sa := js.streamAssignmentOrInflight(ci.serviceAccount(), cfg.Name); sa != nil {
8879 resp.Error = NewJSStreamNameExistRestoreFailedError()
8880 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8881 return
8882 }
8883
8884 // Raft group selection and placement.
8885 rg, err := js.createGroupForStream(ci, &cfg)
8886 if err != nil {
8887 resp.Error = NewJSClusterNoPeersError(err)
8888 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
8889 return
8890 }
8891 // Pick a preferred leader.
8892 rg.setPreferred(s)
8893 sa := &streamAssignment{Group: rg, Sync: syncSubjForStream(), Config: &cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
8894 // Now add in our restore state and pre-select a peer to handle the actual receipt of the snapshot.
8895 sa.Restore = &req.State
8896 if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(sa)); err != nil {
8897 return
8898 }
8899 cc.trackInflightStreamProposal(ci.serviceAccount(), sa, false)
8900 }
8901
8902 // Determine if all peers for this group are offline.
8903 func (s *Server) allPeersOffline(rg *raftGroup) bool {
8904 if rg == nil {
8905 return false
8906 }
8907 // Check to see if this stream has any servers online to respond.
8908 for _, peer := range rg.Peers {
8909 if si, ok := s.nodeToInfo.Load(peer); ok && si != nil {
8910 if !si.(nodeInfo).offline {
8911 return false
8912 }
8913 }
8914 }
8915 return true
8916 }
8917
8918 // Select the peers to keep when scaling a raft group down to replicas.
8919 // The current leader, if known and in peer set, is kept. Online peers are preferred,
8920 // but we will fall back to offline peers to honor the requested replica count.
8921 func (s *Server) selectScaleDownPeers(peers []string, curLeader string, replicas int) []string {
8922 selected := make([]string, 0, replicas)
8923 if curLeader != _EMPTY_ && slices.Contains(peers, curLeader) {
8924 selected = append(selected, curLeader)
8925 if len(selected) == replicas {
8926 return selected
8927 }
8928 }
8929 // Prefer online peers.
8930 for _, peer := range peers {
8931 if peer == curLeader {
8932 continue
8933 }
8934 if si, ok := s.nodeToInfo.Load(peer); ok && si != nil && !si.(nodeInfo).offline {
8935 selected = append(selected, peer)
8936 if len(selected) == replicas {
8937 return selected
8938 }
8939 }
8940 }
8941
8942 // Fall back to offline peers for the remainder.
8943 for _, peer := range peers {
8944 if slices.Contains(selected, peer) {
8945 continue
8946 }
8947 selected = append(selected, peer)
8948 if len(selected) == replicas {
8949 break
8950 }
8951 }
8952 return selected
8953 }
8954
8955 // This will do a scatter and gather operation for all streams for this account. This is only called from metadata leader.
8956 // This will be running in a separate Go routine.
8957 func (s *Server) jsClusteredStreamListRequest(acc *Account, ci *ClientInfo, filter string, offset int, subject, reply string, rmsg []byte) {
8958 defer s.grWG.Done()
8959
8960 js, cc := s.getJetStreamCluster()
8961 if js == nil || cc == nil {
8962 return
8963 }
8964
8965 js.mu.RLock()
8966
8967 var streams []*streamAssignment
8968 for _, sa := range cc.streams[acc.Name] {
8969 if IsNatsErr(sa.err, JSClusterNotAssignedErr) {
8970 continue
8971 }
8972
8973 if filter != _EMPTY_ {
8974 // These could not have subjects auto-filled in since they are raw and unprocessed.
8975 if len(sa.Config.Subjects) == 0 {
8976 if SubjectsCollide(filter, sa.Config.Name) {
8977 streams = append(streams, sa)
8978 }
8979 } else {
8980 for _, subj := range sa.Config.Subjects {
8981 if SubjectsCollide(filter, subj) {
8982 streams = append(streams, sa)
8983 break
8984 }
8985 }
8986 }
8987 } else {
8988 streams = append(streams, sa)
8989 }
8990 }
8991
8992 // Needs to be sorted for offsets etc.
8993 if len(streams) > 1 {
8994 slices.SortFunc(streams, func(i, j *streamAssignment) int { return cmp.Compare(i.Config.Name, j.Config.Name) })
8995 }
8996
8997 scnt := len(streams)
8998 if offset < 0 {
8999 offset = 0
9000 }
9001 if offset > scnt {
9002 offset = scnt
9003 }
9004 if offset > 0 {
9005 streams = streams[offset:]
9006 }
9007 if len(streams) > JSApiListLimit {
9008 streams = streams[:JSApiListLimit]
9009 }
9010
9011 var resp = JSApiStreamListResponse{
9012 ApiResponse: ApiResponse{Type: JSApiStreamListResponseType},
9013 Streams: make([]*StreamInfo, 0, len(streams)),
9014 }
9015
9016 js.mu.RUnlock()
9017
9018 if len(streams) == 0 {
9019 resp.Limit = JSApiListLimit
9020 resp.Offset = offset
9021 s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
9022 return
9023 }
9024
9025 // Create an inbox for our responses and send out our requests.
9026 s.mu.Lock()
9027 inbox := s.newRespInbox()
9028 rc := make(chan *streamInfoClusterResponse, len(streams))
9029
9030 // Store our handler.
9031 s.sys.replies[inbox] = func(sub *subscription, _ *client, _ *Account, subject, _ string, msg []byte) {
9032 var si streamInfoClusterResponse
9033 if err := json.Unmarshal(msg, &si); err != nil {
9034 s.Warnf("Error unmarshalling clustered stream info response:%v", err)
9035 return
9036 }
9037 select {
9038 case rc <- &si:
9039 default:
9040 s.Warnf("Failed placing remote stream info result on internal channel")
9041 }
9042 }
9043 s.mu.Unlock()
9044
9045 // Cleanup after.
9046 defer func() {
9047 s.mu.Lock()
9048 if s.sys != nil && s.sys.replies != nil {
9049 delete(s.sys.replies, inbox)
9050 }
9051 s.mu.Unlock()
9052 }()
9053
9054 var missingNames []string
9055 sent := map[string]int{}
9056
9057 // Send out our requests here.
9058 js.mu.RLock()
9059 for _, sa := range streams {
9060 if s.allPeersOffline(sa.Group) {
9061 // Place offline onto our results by hand here.
9062 si := &StreamInfo{
9063 Config: *sa.Config,
9064 Created: sa.Created,
9065 Cluster: js.offlineClusterInfo(sa.Group),
9066 TimeStamp: time.Now().UTC(),
9067 }
9068 resp.Streams = append(resp.Streams, si)
9069 missingNames = append(missingNames, sa.Config.Name)
9070 } else {
9071 isubj := fmt.Sprintf(clusterStreamInfoT, sa.Client.serviceAccount(), sa.Config.Name)
9072 s.sendInternalMsgLocked(isubj, inbox, nil, nil)
9073 sent[sa.Config.Name] = len(sa.consumers)
9074 }
9075 }
9076 // Don't hold lock.
9077 js.mu.RUnlock()
9078
9079 const timeout = 4 * time.Second
9080 notActive := time.NewTimer(timeout)
9081 defer notActive.Stop()
9082
9083 LOOP:
9084 for len(sent) > 0 {
9085 select {
9086 case <-s.quitCh:
9087 return
9088 case <-notActive.C:
9089 s.Warnf("Did not receive all stream info results for %q", acc)
9090 for sName := range sent {
9091 missingNames = append(missingNames, sName)
9092 }
9093 break LOOP
9094 case si := <-rc:
9095 consCount := sent[si.Config.Name]
9096 if consCount > 0 {
9097 si.State.Consumers = consCount
9098 }
9099 delete(sent, si.Config.Name)
9100 if si.OfflineReason == _EMPTY_ {
9101 resp.Streams = append(resp.Streams, &si.StreamInfo)
9102 } else if _, ok := resp.Offline[si.Config.Name]; !ok {
9103 if resp.Offline == nil {
9104 resp.Offline = make(map[string]string, 1)
9105 }
9106 resp.Offline[si.Config.Name] = si.OfflineReason
9107 missingNames = append(missingNames, si.Config.Name)
9108 }
9109 }
9110 }
9111
9112 // Needs to be sorted as well.
9113 if len(resp.Streams) > 1 {
9114 slices.SortFunc(resp.Streams, func(i, j *StreamInfo) int { return cmp.Compare(i.Config.Name, j.Config.Name) })
9115 }
9116
9117 resp.Total = scnt
9118 resp.Limit = JSApiListLimit
9119 resp.Offset = offset
9120 resp.Missing = missingNames
9121 s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
9122 }
9123
9124 // This will do a scatter and gather operation for all consumers for this stream and account.
9125 // This will be running in a separate Go routine.
9126 func (s *Server) jsClusteredConsumerListRequest(acc *Account, ci *ClientInfo, offset int, stream, subject, reply string, rmsg []byte) {
9127 defer s.grWG.Done()
9128
9129 js, cc := s.getJetStreamCluster()
9130 if js == nil || cc == nil {
9131 return
9132 }
9133
9134 js.mu.RLock()
9135
9136 var consumers []*consumerAssignment
9137 if sas := cc.streams[acc.Name]; sas != nil {
9138 if sa := sas[stream]; sa != nil {
9139 // Copy over since we need to sort etc.
9140 for _, ca := range sa.consumers {
9141 consumers = append(consumers, ca)
9142 }
9143 }
9144 }
9145 // Needs to be sorted.
9146 if len(consumers) > 1 {
9147 slices.SortFunc(consumers, func(i, j *consumerAssignment) int { return cmp.Compare(i.Config.Name, j.Config.Name) })
9148 }
9149
9150 ocnt := len(consumers)
9151 if offset < 0 {
9152 offset = 0
9153 }
9154 if offset > ocnt {
9155 offset = ocnt
9156 }
9157 if offset > 0 {
9158 consumers = consumers[offset:]
9159 }
9160 if len(consumers) > JSApiListLimit {
9161 consumers = consumers[:JSApiListLimit]
9162 }
9163
9164 // Send out our requests here.
9165 var resp = JSApiConsumerListResponse{
9166 ApiResponse: ApiResponse{Type: JSApiConsumerListResponseType},
9167 Consumers: []*ConsumerInfo{},
9168 }
9169
9170 js.mu.RUnlock()
9171
9172 if len(consumers) == 0 {
9173 resp.Limit = JSApiListLimit
9174 resp.Offset = offset
9175 s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
9176 return
9177 }
9178
9179 // Create an inbox for our responses and send out requests.
9180 s.mu.Lock()
9181 inbox := s.newRespInbox()
9182 rc := make(chan *consumerInfoClusterResponse, len(consumers))
9183
9184 // Store our handler.
9185 s.sys.replies[inbox] = func(sub *subscription, _ *client, _ *Account, subject, _ string, msg []byte) {
9186 var ci consumerInfoClusterResponse
9187 if err := json.Unmarshal(msg, &ci); err != nil {
9188 s.Warnf("Error unmarshaling clustered consumer info response:%v", err)
9189 return
9190 }
9191 select {
9192 case rc <- &ci:
9193 default:
9194 s.Warnf("Failed placing consumer info result on internal chan")
9195 }
9196 }
9197 s.mu.Unlock()
9198
9199 // Cleanup after.
9200 defer func() {
9201 s.mu.Lock()
9202 if s.sys != nil && s.sys.replies != nil {
9203 delete(s.sys.replies, inbox)
9204 }
9205 s.mu.Unlock()
9206 }()
9207
9208 var missingNames []string
9209 sent := map[string]struct{}{}
9210
9211 // Send out our requests here.
9212 js.mu.RLock()
9213 for _, ca := range consumers {
9214 if s.allPeersOffline(ca.Group) {
9215 // Place offline onto our results by hand here.
9216 ci := &ConsumerInfo{
9217 Config: ca.Config,
9218 Created: ca.Created,
9219 Cluster: js.offlineClusterInfo(ca.Group),
9220 TimeStamp: time.Now().UTC(),
9221 }
9222 resp.Consumers = append(resp.Consumers, ci)
9223 missingNames = append(missingNames, ca.Name)
9224 } else {
9225 isubj := fmt.Sprintf(clusterConsumerInfoT, ca.Client.serviceAccount(), stream, ca.Name)
9226 s.sendInternalMsgLocked(isubj, inbox, nil, nil)
9227 sent[ca.Name] = struct{}{}
9228 }
9229 }
9230 // Don't hold lock.
9231 js.mu.RUnlock()
9232
9233 const timeout = 4 * time.Second
9234 notActive := time.NewTimer(timeout)
9235 defer notActive.Stop()
9236
9237 LOOP:
9238 for len(sent) > 0 {
9239 select {
9240 case <-s.quitCh:
9241 return
9242 case <-notActive.C:
9243 s.Warnf("Did not receive all consumer info results for '%s > %s'", acc, stream)
9244 for cName := range sent {
9245 missingNames = append(missingNames, cName)
9246 }
9247 break LOOP
9248 case ci := <-rc:
9249 delete(sent, ci.Name)
9250 if ci.OfflineReason == _EMPTY_ {
9251 resp.Consumers = append(resp.Consumers, &ci.ConsumerInfo)
9252 } else if _, ok := resp.Offline[ci.Name]; !ok {
9253 if resp.Offline == nil {
9254 resp.Offline = make(map[string]string, 1)
9255 }
9256 resp.Offline[ci.Name] = ci.OfflineReason
9257 missingNames = append(missingNames, ci.Name)
9258 }
9259 }
9260 }
9261
9262 // Needs to be sorted as well.
9263 if len(resp.Consumers) > 1 {
9264 slices.SortFunc(resp.Consumers, func(i, j *ConsumerInfo) int { return cmp.Compare(i.Name, j.Name) })
9265 }
9266
9267 resp.Total = ocnt
9268 resp.Limit = JSApiListLimit
9269 resp.Offset = offset
9270 resp.Missing = missingNames
9271 s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
9272 }
9273
9274 func encodeStreamPurge(sp *streamPurge) []byte {
9275 var bb bytes.Buffer
9276 bb.WriteByte(byte(purgeStreamOp))
9277 json.NewEncoder(&bb).Encode(sp)
9278 return bb.Bytes()
9279 }
9280
9281 func decodeStreamPurge(buf []byte) (*streamPurge, error) {
9282 var sp streamPurge
9283 err := json.Unmarshal(buf, &sp)
9284 return &sp, err
9285 }
9286
9287 func (s *Server) jsClusteredConsumerDeleteRequest(ci *ClientInfo, acc *Account, stream, consumer, subject, reply string, rmsg []byte) {
9288 js, cc := s.getJetStreamCluster()
9289 if js == nil || cc == nil {
9290 return
9291 }
9292
9293 js.mu.Lock()
9294 defer js.mu.Unlock()
9295
9296 if cc.meta == nil {
9297 return
9298 }
9299
9300 var resp = JSApiConsumerDeleteResponse{ApiResponse: ApiResponse{Type: JSApiConsumerDeleteResponseType}}
9301
9302 sa := js.streamAssignment(acc.Name, stream)
9303 if sa == nil {
9304 resp.Error = NewJSStreamNotFoundError()
9305 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9306 return
9307
9308 }
9309 if sa.consumers == nil {
9310 resp.Error = NewJSConsumerNotFoundError()
9311 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9312 return
9313 }
9314 oca := sa.consumers[consumer]
9315 if oca == nil {
9316 resp.Error = NewJSConsumerNotFoundError()
9317 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9318 return
9319 }
9320 ca := &consumerAssignment{Group: oca.Group, Stream: stream, Name: consumer, Config: oca.Config, Subject: subject, Reply: reply, Client: ci, Created: oca.Created}
9321 if err := cc.meta.Propose(cc.term, encodeDeleteConsumerAssignment(ca)); err != nil {
9322 return
9323 }
9324 cc.trackInflightConsumerProposal(acc.Name, stream, ca, true)
9325 }
9326
9327 func encodeMsgDelete(md *streamMsgDelete) []byte {
9328 var bb bytes.Buffer
9329 bb.WriteByte(byte(deleteMsgOp))
9330 json.NewEncoder(&bb).Encode(md)
9331 return bb.Bytes()
9332 }
9333
9334 func decodeMsgDelete(buf []byte) (*streamMsgDelete, error) {
9335 var md streamMsgDelete
9336 err := json.Unmarshal(buf, &md)
9337 return &md, err
9338 }
9339
9340 func (s *Server) jsClusteredMsgDeleteRequest(ci *ClientInfo, acc *Account, mset *stream, stream, subject, reply string, req *JSApiMsgDeleteRequest, rmsg []byte) {
9341 js, cc := s.getJetStreamCluster()
9342 if js == nil || cc == nil {
9343 return
9344 }
9345
9346 js.mu.Lock()
9347 sa := js.streamAssignment(acc.Name, stream)
9348 if sa == nil {
9349 s.Debugf("Message delete failed, could not locate stream '%s > %s'", acc.Name, stream)
9350 js.mu.Unlock()
9351 return
9352 }
9353
9354 // Check for single replica items.
9355 if n := sa.Group.node; n != nil {
9356 md := encodeMsgDelete(&streamMsgDelete{Seq: req.Seq, NoErase: req.NoErase, Stream: stream, Subject: subject, Reply: reply, Client: ci})
9357 js.mu.Unlock()
9358 mset.mu.RLock()
9359 term := mset.term
9360 mset.mu.RUnlock()
9361 n.Propose(term, md)
9362 return
9363 }
9364 js.mu.Unlock()
9365
9366 if mset == nil {
9367 return
9368 }
9369
9370 var err error
9371 var removed bool
9372 if req.NoErase {
9373 removed, err = mset.removeMsg(req.Seq)
9374 } else {
9375 removed, err = mset.eraseMsg(req.Seq)
9376 }
9377 var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
9378 if err != nil {
9379 resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err))
9380 } else if !removed {
9381 resp.Error = NewJSSequenceNotFoundError(req.Seq)
9382 } else {
9383 resp.Success = true
9384 }
9385 s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
9386 }
9387
9388 func encodeAddStreamAssignment(sa *streamAssignment) []byte {
9389 csa := sa.clone()
9390 csa.Client = csa.Client.forProposal()
9391 csa.ConfigJSON, _ = json.Marshal(sa.Config)
9392 var bb bytes.Buffer
9393 bb.WriteByte(byte(assignStreamOp))
9394 json.NewEncoder(&bb).Encode(csa)
9395 return bb.Bytes()
9396 }
9397
9398 func encodeUpdateStreamAssignment(sa *streamAssignment) []byte {
9399 csa := sa.clone()
9400 csa.Client = csa.Client.forProposal()
9401 csa.ConfigJSON, _ = json.Marshal(sa.Config)
9402 var bb bytes.Buffer
9403 bb.WriteByte(byte(updateStreamOp))
9404 json.NewEncoder(&bb).Encode(csa)
9405 return bb.Bytes()
9406 }
9407
9408 func encodeDeleteStreamAssignment(sa *streamAssignment) []byte {
9409 csa := sa.clone()
9410 csa.Client = csa.Client.forProposal()
9411 csa.ConfigJSON, _ = json.Marshal(sa.Config)
9412 var bb bytes.Buffer
9413 bb.WriteByte(byte(removeStreamOp))
9414 json.NewEncoder(&bb).Encode(csa)
9415 return bb.Bytes()
9416 }
9417
9418 func decodeStreamAssignment(s *Server, buf []byte) (*streamAssignment, error) {
9419 var sa streamAssignment
9420 if err := json.Unmarshal(buf, &sa); err != nil {
9421 return nil, err
9422 }
9423 if err := decodeStreamAssignmentConfig(s, &sa); err != nil {
9424 return nil, err
9425 }
9426 return &sa, nil
9427 }
9428
9429 func decodeStreamAssignmentConfig(s *Server, sa *streamAssignment) error {
9430 var unsupported bool
9431 var cfg StreamConfig
9432 var err error
9433 decoder := json.NewDecoder(bytes.NewReader(sa.ConfigJSON))
9434 decoder.DisallowUnknownFields()
9435 if err = decoder.Decode(&cfg); err != nil {
9436 unsupported = true
9437 cfg = StreamConfig{}
9438 if err2 := json.Unmarshal(sa.ConfigJSON, &cfg); err2 != nil {
9439 return err2
9440 }
9441 }
9442 sa.Config = &cfg
9443 fixCfgMirrorWithDedupWindow(sa.Config)
9444
9445 if unsupported || (sa.Config != nil && !supportsRequiredApiLevel(sa.Config.Metadata)) {
9446 sa.unsupported = newUnsupportedStreamAssignment(s, sa, err)
9447 }
9448 return nil
9449 }
9450
9451 func encodeDeleteRange(dr *DeleteRange) []byte {
9452 var bb bytes.Buffer
9453 bb.WriteByte(byte(deleteRangeOp))
9454 json.NewEncoder(&bb).Encode(dr)
9455 return bb.Bytes()
9456 }
9457
9458 func decodeDeleteRange(buf []byte) (*DeleteRange, error) {
9459 var dr DeleteRange
9460 err := json.Unmarshal(buf, &dr)
9461 if err != nil {
9462 return nil, err
9463 }
9464 return &dr, err
9465 }
9466
9467 // createGroupForConsumer will create a new group from same peer set as the stream.
9468 func (cc *jetStreamCluster) createGroupForConsumer(cfg *ConsumerConfig, sa *streamAssignment) (*raftGroup, *selectPeerError) {
9469 if len(sa.Group.Peers) == 0 || cfg.Replicas > len(sa.Group.Peers) {
9470 return nil, &selectPeerError{misc: true}
9471 }
9472
9473 replicas := cfg.replicas(sa.Config)
9474 peers := copyStrings(sa.Group.Peers)
9475 var _ss [5]string
9476 active := _ss[:0]
9477
9478 // Calculate all active peers.
9479 for _, peer := range peers {
9480 if sir, ok := cc.s.nodeToInfo.Load(peer); ok && sir != nil {
9481 if !sir.(nodeInfo).offline {
9482 active = append(active, peer)
9483 }
9484 }
9485 }
9486 if quorum := replicas/2 + 1; quorum > len(active) {
9487 // Not enough active to satisfy the request.
9488 return nil, &selectPeerError{offline: true}
9489 }
9490
9491 // If we want less then our parent stream, select from active.
9492 if replicas > 0 && replicas < len(peers) {
9493 // Pedantic in case stream is say R5 and consumer is R3 and 3 or more offline, etc.
9494 if len(active) < replicas {
9495 return nil, &selectPeerError{offline: true}
9496 }
9497 // First shuffle the active peers and then select to account for replica = 1.
9498 rand.Shuffle(len(active), func(i, j int) { active[i], active[j] = active[j], active[i] })
9499 peers = active[:replicas]
9500 }
9501 storage := sa.Config.Storage
9502 if cfg.MemoryStorage {
9503 storage = MemoryStorage
9504 }
9505 return &raftGroup{Name: groupNameForConsumer(peers, storage), Storage: storage, Peers: peers}, nil
9506 }
9507
9508 // jsClusteredConsumerRequest is first point of entry to create a consumer in clustered mode.
9509 func (s *Server) jsClusteredConsumerRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, stream string, cfg *ConsumerConfig, action ConsumerAction, pedantic bool) {
9510 js, cc := s.getJetStreamCluster()
9511 if js == nil || cc == nil {
9512 return
9513 }
9514
9515 // If the consumer is a direct sourcing consumer, we need to "upgrade" it to be durable without AckNone.
9516 // We only get here if the stream is not Limits-based.
9517 if cfg.Direct && cfg.Sourcing && cfg.Name != _EMPTY_ {
9518 cfg.Direct = false
9519 cfg.Durable = cfg.Name
9520 cfg.AckPolicy = AckFlowControl
9521 cfg.AckWait = 0
9522 cfg.MaxDeliver = 0
9523 cfg.InactiveThreshold = 0
9524 }
9525
9526 var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
9527
9528 streamCfg, ok := js.clusterStreamConfig(acc.Name, stream)
9529 if !ok {
9530 resp.Error = NewJSStreamNotFoundError()
9531 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9532 return
9533 }
9534 selectedReplicas := cfg.replicas(&streamCfg)
9535 selectedLimits, selectedTier, _, apiErr := acc.selectLimits(selectedReplicas)
9536 if apiErr != nil {
9537 resp.Error = apiErr
9538 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9539 return
9540 }
9541 srvLim := &s.getOpts().JetStreamLimits
9542 // Make sure we have sane defaults
9543 if err := setConsumerConfigDefaults(cfg, &streamCfg, srvLim, selectedLimits, pedantic); err != nil {
9544 resp.Error = err
9545 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9546 return
9547 }
9548
9549 if err := checkConsumerCfg(cfg, srvLim, &streamCfg, acc, selectedLimits, false); err != nil {
9550 resp.Error = err
9551 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9552 return
9553 }
9554
9555 js.mu.Lock()
9556 defer js.mu.Unlock()
9557
9558 if cc.meta == nil {
9559 return
9560 }
9561
9562 // Lookup the stream assignment.
9563 sa := js.streamAssignmentOrInflight(acc.Name, stream)
9564 if sa == nil {
9565 resp.Error = NewJSStreamNotFoundError()
9566 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9567 return
9568 }
9569
9570 // Was a consumer name provided?
9571 var oname string
9572 if isDurableConsumer(cfg) || cfg.Name != _EMPTY_ {
9573 if cfg.Name != _EMPTY_ {
9574 oname = cfg.Name
9575 } else {
9576 oname = cfg.Durable
9577 }
9578 }
9579
9580 // Check for max consumers here to short circuit if possible.
9581 // Start with limit on a stream, but if one is defined at the level of the account
9582 // and is lower, use that limit.
9583 if action == ActionCreate || action == ActionCreateOrUpdate {
9584 // The stream limit caps every consumer of the stream. The account limit
9585 // caps only the consumers of the selected tier, so the two need separate
9586 // counts.
9587 streamMaxc := sa.Config.MaxConsumers
9588 tierMaxc := selectedLimits.MaxConsumers
9589 if streamMaxc > 0 || tierMaxc > 0 {
9590 // If the consumer name is specified and we think it already exists, then
9591 // we're likely updating an existing consumer, so don't count it. Otherwise
9592 // we will incorrectly return NewJSMaximumConsumersLimitError for an update.
9593 if oname == _EMPTY_ || js.consumerAssignmentOrInflight(acc.Name, stream, oname) == nil {
9594 // Don't count direct/sourcing consumers.
9595 var total, tierTotal int
9596 for ca := range js.consumerAssignmentsOrInflightSeq(acc.Name, stream) {
9597 if ca.unsupported != nil {
9598 continue
9599 }
9600 if ca.Config != nil && !ca.Config.Direct && !ca.Config.Sourcing {
9601 total++
9602 if selectedTier == _EMPTY_ || isSameTier(ca.Config.replicas(&streamCfg), selectedReplicas) {
9603 tierTotal++
9604 }
9605 }
9606 }
9607 if (streamMaxc > 0 && total >= streamMaxc) || (tierMaxc > 0 && tierTotal >= tierMaxc) {
9608 resp.Error = NewJSMaximumConsumersLimitError()
9609 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9610 return
9611 }
9612 }
9613 }
9614 }
9615
9616 // Also short circuit if DeliverLastPerSubject is set with no FilterSubject.
9617 if cfg.DeliverPolicy == DeliverLastPerSubject {
9618 if cfg.FilterSubject == _EMPTY_ && len(cfg.FilterSubjects) == 0 {
9619 resp.Error = NewJSConsumerInvalidPolicyError(fmt.Errorf("consumer delivery policy is deliver last per subject, but FilterSubject is not set"))
9620 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9621 return
9622 }
9623 }
9624
9625 // Setup proper default for ack wait if we are in explicit ack mode.
9626 if cfg.AckWait == 0 && (cfg.AckPolicy == AckExplicit || cfg.AckPolicy == AckAll) {
9627 cfg.AckWait = JsAckWaitDefault
9628 }
9629 // Setup default of -1, meaning no limit for MaxDeliver.
9630 if cfg.MaxDeliver == 0 {
9631 cfg.MaxDeliver = -1
9632 }
9633 // Set proper default for max ack pending if we are ack explicit and none has been set.
9634 if cfg.AckPolicy == AckExplicit && cfg.MaxAckPending == 0 {
9635 cfg.MaxAckPending = JsDefaultMaxAckPending
9636 }
9637
9638 if cfg.PriorityPolicy == PriorityPinnedClient && cfg.PinnedTTL == 0 {
9639 cfg.PinnedTTL = JsDefaultPinnedTTL
9640 }
9641
9642 var ca *consumerAssignment
9643 // See if we have an existing one already under same durable name or
9644 // if name was set by the user.
9645 if oname != _EMPTY_ {
9646 if ca = js.consumerAssignmentOrInflight(acc.Name, stream, oname); ca != nil {
9647 // Provided config might miss metadata, copy from existing config.
9648 copyConsumerMetadata(cfg, ca.Config)
9649
9650 // If a durable sourcing consumer is used, we need to reset the deliver policy.
9651 if cfg.Sourcing && cfg.Durable != _EMPTY_ {
9652 cfg.DeliverPolicy = ca.Config.DeliverPolicy
9653 cfg.OptStartSeq = ca.Config.OptStartSeq
9654 cfg.OptStartTime = ca.Config.OptStartTime
9655 }
9656
9657 if action == ActionCreate && !reflect.DeepEqual(cfg, ca.Config) {
9658 resp.Error = NewJSConsumerAlreadyExistsError()
9659 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9660 return
9661 }
9662 // Do quick sanity check on new cfg to prevent here if possible.
9663 if err := acc.checkNewConsumerConfig(ca.Config, cfg); err != nil {
9664 resp.Error = NewJSConsumerCreateError(err, Unless(err))
9665 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9666 return
9667 }
9668 // Don't allow updating if all peers are offline.
9669 if s.allPeersOffline(ca.Group) {
9670 resp.Error = NewJSConsumerOfflineError()
9671 s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp), nil, errRespDelay)
9672 return
9673 }
9674 } else {
9675 // Initialize/update asset version metadata.
9676 // First time creating this consumer, or updating.
9677 setStaticConsumerMetadata(cfg)
9678 }
9679 }
9680
9681 // Initialize/update asset version metadata.
9682 // But only if we're not creating, should only update it the first time
9683 // to be idempotent with versions where there's no versioning metadata.
9684 if action != ActionCreate {
9685 setStaticConsumerMetadata(cfg)
9686 }
9687
9688 // If this is new consumer.
9689 if ca == nil {
9690 if action == ActionUpdate {
9691 resp.Error = NewJSConsumerDoesNotExistError()
9692 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9693 return
9694 }
9695 rg, err := cc.createGroupForConsumer(cfg, sa)
9696 if err != nil {
9697 resp.Error = NewJSInsufficientResourcesError()
9698 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9699 return
9700 }
9701 // Pick a preferred leader.
9702 rg.setPreferred(s)
9703
9704 // Inherit cluster from stream.
9705 rg.Cluster = sa.Group.Cluster
9706
9707 // We need to set the ephemeral here before replicating.
9708 if !isDurableConsumer(cfg) {
9709 if cfg.Name != _EMPTY_ {
9710 oname = cfg.Name
9711 } else {
9712 // Make sure name is unique.
9713 for {
9714 oname = createConsumerName()
9715 if js.consumerAssignmentOrInflight(acc.Name, stream, oname) != nil {
9716 continue
9717 }
9718 break
9719 }
9720 }
9721 }
9722 if len(rg.Peers) > 1 {
9723 if maxHaAssets := s.getOpts().JetStreamLimits.MaxHAAssets; maxHaAssets != 0 {
9724 for _, peer := range rg.Peers {
9725 if ni, ok := s.nodeToInfo.Load(peer); ok {
9726 ni := ni.(nodeInfo)
9727 if stats := ni.stats; stats != nil && stats.HAAssets > maxHaAssets {
9728 resp.Error = NewJSInsufficientResourcesError()
9729 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9730 s.Warnf("%s@%s (HA Asset Count: %d) exceeds max ha asset limit of %d"+
9731 " for (durable) consumer %s placement on stream %s",
9732 ni.name, ni.cluster, ni.stats.HAAssets, maxHaAssets, oname, stream)
9733 return
9734 }
9735 }
9736 }
9737 }
9738 }
9739
9740 // Check if we are work queue policy.
9741 // We will do pre-checks here to avoid thrashing meta layer.
9742 if sa.Config.Retention == WorkQueuePolicy && !cfg.Direct && !cfg.Sourcing {
9743 if cfg.AckPolicy != AckExplicit && cfg.AckPolicy != AckFlowControl {
9744 resp.Error = NewJSConsumerWQRequiresExplicitAckError()
9745 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9746 return
9747 }
9748 if cfg.DeliverPolicy != DeliverAll {
9749 resp.Error = NewJSConsumerWQConsumerNotDeliverAllError()
9750 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9751 return
9752 }
9753 subjects := gatherSubjectFilters(cfg.FilterSubject, cfg.FilterSubjects)
9754 for oca := range js.consumerAssignmentsOrInflightSeq(acc.Name, stream) {
9755 if oca.Name == oname || oca.Config.Direct || oca.Config.Sourcing {
9756 continue
9757 }
9758 if len(subjects) == 0 {
9759 resp.Error = NewJSConsumerWQMultipleUnfilteredError()
9760 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9761 return
9762 }
9763 for _, psubj := range gatherSubjectFilters(oca.Config.FilterSubject, oca.Config.FilterSubjects) {
9764 for _, subj := range subjects {
9765 if SubjectsCollide(subj, psubj) {
9766 resp.Error = NewJSConsumerWQConsumerNotUniqueError()
9767 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9768 return
9769 }
9770 }
9771 }
9772 }
9773 }
9774
9775 ca = &consumerAssignment{
9776 Group: rg,
9777 Stream: stream,
9778 Name: oname,
9779 Config: cfg,
9780 Subject: subject,
9781 Reply: reply,
9782 Client: ci,
9783 Created: time.Now().UTC(),
9784 }
9785 } else {
9786 // If the consumer already exists then don't allow updating the PauseUntil, just set
9787 // it back to whatever the current configured value is.
9788 cfg.PauseUntil = ca.Config.PauseUntil
9789
9790 nca := ca.copyGroup()
9791
9792 // Reset notion of scaling up, if this was done in a previous update.
9793 nca.Group.ScaleUp = false
9794
9795 rBefore := nca.Config.replicas(sa.Config)
9796 rAfter := cfg.replicas(sa.Config)
9797
9798 var curLeader string
9799 if rBefore != rAfter {
9800 // We are modifying nodes here. We want to do our best to preserve the current leader.
9801 // We have support now from above that guarantees we are in our own Go routine, so can
9802 // ask for stream info from the stream leader to make sure we keep the leader in the new list.
9803 if !s.allPeersOffline(ca.Group) {
9804 // Need to release js lock.
9805 js.mu.Unlock()
9806 if ci, err := sysRequest[ConsumerInfo](s, clusterConsumerInfoT, ci.serviceAccount(), sa.Config.Name, oname); err != nil {
9807 s.Warnf("Did not receive consumer info results for '%s > %s > %s' due to: %s", acc, sa.Config.Name, oname, err)
9808 } else if ci != nil {
9809 if cl := ci.Cluster; cl != nil && cl.Leader != _EMPTY_ {
9810 curLeader = getHash(cl.Leader)
9811 }
9812 }
9813 // Re-acquire here.
9814 js.mu.Lock()
9815 }
9816 }
9817
9818 if rBefore < rAfter {
9819 newPeerSet := nca.Group.Peers
9820 // Scale up by adding new members from the stream peer set that are not yet in the consumer peer set.
9821 streamPeerSet := copyStrings(sa.Group.Peers)
9822
9823 // Respond with error when there is a config mismatch between the intended config and expected peer size.
9824 if len(streamPeerSet) < rAfter {
9825 resp.Error = NewJSConsumerReplicasExceedsStreamError()
9826 s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
9827 return
9828 }
9829 rand.Shuffle(rAfter, func(i, j int) { streamPeerSet[i], streamPeerSet[j] = streamPeerSet[j], streamPeerSet[i] })
9830 for _, p := range streamPeerSet {
9831 found := false
9832 for _, sp := range newPeerSet {
9833 if sp == p {
9834 found = true
9835 break
9836 }
9837 }
9838 if !found {
9839 newPeerSet = append(newPeerSet, p)
9840 if len(newPeerSet) == rAfter {
9841 break
9842 }
9843 }
9844 }
9845 // Single nodes are not recorded by the NRG layer so we can rename.
9846 if rBefore == 1 {
9847 nca.Group.Name = groupNameForConsumer(newPeerSet, nca.Group.Storage)
9848 }
9849 nca.Group.Peers = newPeerSet
9850 nca.Group.Preferred = curLeader
9851 nca.Group.ScaleUp = true
9852 } else if rBefore > rAfter {
9853 // Mark the current leader as preferred, it will be kept in the new peer set.
9854 nca.Group.Preferred = curLeader
9855 nca.Group.Peers = s.selectScaleDownPeers(nca.Group.Peers, curLeader, rAfter)
9856 // Single nodes are not recorded by the NRG layer so we can rename.
9857 // MUST do this, otherwise a scaleup afterward could potentially lead to inconsistencies.
9858 if len(nca.Group.Peers) == 1 {
9859 nca.Group.Name = groupNameForConsumer(nca.Group.Peers, nca.Group.Storage)
9860 }
9861 }
9862
9863 // Update config and client info on copy of existing.
9864 nca.Config = cfg
9865 nca.Client = ci
9866 nca.Subject = subject
9867 nca.Reply = reply
9868 ca = nca
9869 }
9870
9871 // Do formal proposal.
9872 if err := cc.meta.Propose(cc.term, encodeAddConsumerAssignment(ca)); err != nil {
9873 return
9874 }
9875 cc.trackInflightConsumerProposal(acc.Name, stream, ca, false)
9876 }
9877
9878 func encodeAddConsumerAssignment(ca *consumerAssignment) []byte {
9879 cca := ca.clone()
9880 cca.Client = cca.Client.forProposal()
9881 cca.ConfigJSON, _ = json.Marshal(ca.Config)
9882 var bb bytes.Buffer
9883 bb.WriteByte(byte(assignConsumerOp))
9884 json.NewEncoder(&bb).Encode(cca)
9885 return bb.Bytes()
9886 }
9887
9888 func encodeDeleteConsumerAssignment(ca *consumerAssignment) []byte {
9889 cca := ca.clone()
9890 cca.Client = cca.Client.forProposal()
9891 cca.ConfigJSON, _ = json.Marshal(ca.Config)
9892 var bb bytes.Buffer
9893 bb.WriteByte(byte(removeConsumerOp))
9894 json.NewEncoder(&bb).Encode(cca)
9895 return bb.Bytes()
9896 }
9897
9898 func decodeConsumerAssignment(buf []byte) (*consumerAssignment, error) {
9899 var ca consumerAssignment
9900 if err := json.Unmarshal(buf, &ca); err != nil {
9901 return nil, err
9902 }
9903 if err := decodeConsumerAssignmentConfig(&ca); err != nil {
9904 return nil, err
9905 }
9906 return &ca, nil
9907 }
9908
9909 func decodeConsumerAssignmentConfig(ca *consumerAssignment) error {
9910 var unsupported bool
9911 var cfg ConsumerConfig
9912 var err error
9913 decoder := json.NewDecoder(bytes.NewReader(ca.ConfigJSON))
9914 decoder.DisallowUnknownFields()
9915 if err = decoder.Decode(&cfg); err != nil {
9916 unsupported = true
9917 cfg = ConsumerConfig{}
9918 if err2 := json.Unmarshal(ca.ConfigJSON, &cfg); err2 != nil {
9919 return err2
9920 }
9921 }
9922 ca.Config = &cfg
9923 if unsupported || (ca.Config != nil && !supportsRequiredApiLevel(ca.Config.Metadata)) {
9924 ca.unsupported = newUnsupportedConsumerAssignment(ca, err)
9925 }
9926 return nil
9927 }
9928
9929 func encodeAddConsumerAssignmentCompressed(ca *consumerAssignment) []byte {
9930 cca := ca.clone()
9931 cca.Client = cca.Client.forProposal()
9932 cca.ConfigJSON, _ = json.Marshal(ca.Config)
9933 var bb bytes.Buffer
9934 bb.WriteByte(byte(assignCompressedConsumerOp))
9935 s2e := s2.NewWriter(&bb)
9936 json.NewEncoder(s2e).Encode(cca)
9937 s2e.Close()
9938 return bb.Bytes()
9939 }
9940
9941 func decodeConsumerAssignmentCompressed(buf []byte) (*consumerAssignment, error) {
9942 var ca consumerAssignment
9943 bb := bytes.NewBuffer(buf)
9944 s2d := s2.NewReader(bb)
9945 decoder := json.NewDecoder(s2d)
9946 if err := decoder.Decode(&ca); err != nil {
9947 return nil, err
9948 }
9949 if err := decodeConsumerAssignmentConfig(&ca); err != nil {
9950 return nil, err
9951 }
9952 return &ca, nil
9953 }
9954
9955 var errBadStreamMsg = errors.New("jetstream cluster bad replicated stream msg")
9956
9957 func decodeStreamMsg(buf []byte) (subject, reply string, hdr, msg []byte, lseq uint64, ts int64, sourced bool, err error) {
9958 var le = binary.LittleEndian
9959 if len(buf) < 26 {
9960 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
9961 }
9962 lseq = le.Uint64(buf)
9963 buf = buf[8:]
9964 ts = int64(le.Uint64(buf))
9965 buf = buf[8:]
9966 sl := int(le.Uint16(buf))
9967 buf = buf[2:]
9968 if len(buf) < sl {
9969 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
9970 }
9971 subject = string(buf[:sl])
9972 buf = buf[sl:]
9973 if len(buf) < 2 {
9974 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
9975 }
9976 rl := int(le.Uint16(buf))
9977 buf = buf[2:]
9978 if len(buf) < rl {
9979 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
9980 }
9981 reply = string(buf[:rl])
9982 buf = buf[rl:]
9983 if len(buf) < 2 {
9984 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
9985 }
9986 hl := int(le.Uint16(buf))
9987 buf = buf[2:]
9988 if len(buf) < hl {
9989 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
9990 }
9991 if hdr = buf[:hl]; len(hdr) == 0 {
9992 hdr = nil
9993 }
9994 buf = buf[hl:]
9995 if len(buf) < 4 {
9996 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
9997 }
9998 ml := int(le.Uint32(buf))
9999 buf = buf[4:]
10000 // ml is read as a uint32 but held in an int; on 32-bit builds a length with
10001 // the high bit set becomes negative, which slips past len(buf) < ml and then
10002 // panics on buf[:ml]. Reject a negative length so the bound holds everywhere.
10003 if ml < 0 || len(buf) < ml {
10004 return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
10005 }
10006 if msg = buf[:ml]; len(msg) == 0 {
10007 msg = nil
10008 }
10009 buf = buf[ml:]
10010 if len(buf) > 0 {
10011 flags, _ := binary.Uvarint(buf)
10012 sourced = flags&msgFlagFromSourceOrMirror != 0
10013 }
10014 return subject, reply, hdr, msg, lseq, ts, sourced, nil
10015 }
10016
10017 func decodeBatchMsg(buf []byte) (batchId string, batchSeq uint64, op entryOp, mbuf []byte, err error) {
10018 var le = binary.LittleEndian
10019 if len(buf) < 2 {
10020 return _EMPTY_, 0, 0, nil, errBadStreamMsg
10021 }
10022 bl := int(le.Uint16(buf))
10023 buf = buf[2:]
10024 if len(buf) < bl {
10025 return _EMPTY_, 0, 0, nil, errBadStreamMsg
10026 }
10027 batchId = string(buf[:bl])
10028 buf = buf[bl:]
10029 var n int
10030 batchSeq, n = binary.Uvarint(buf)
10031 if n <= 0 {
10032 return _EMPTY_, 0, 0, nil, errBadStreamMsg
10033 }
10034 buf = buf[n:]
10035 if len(buf) < 1 {
10036 return _EMPTY_, 0, 0, nil, errBadStreamMsg
10037 }
10038 op = entryOp(buf[0])
10039 mbuf = buf[1:]
10040 return batchId, batchSeq, op, mbuf, nil
10041 }
10042
10043 // Flags for encodeStreamMsg/decodeStreamMsg.
10044 const (
10045 msgFlagFromSourceOrMirror uint64 = 1 << iota
10046 )
10047
10048 func encodeStreamMsg(subject, reply string, hdr, msg []byte, lseq uint64, ts int64, sourced bool) []byte {
10049 return encodeStreamMsgAllowCompress(subject, reply, hdr, msg, lseq, ts, sourced)
10050 }
10051
10052 func encodeStreamMsgAllowCompress(subject, reply string, hdr, msg []byte, lseq uint64, ts int64, sourced bool) []byte {
10053 return encodeStreamMsgAllowCompressAndBatch(subject, reply, hdr, msg, lseq, ts, sourced, _EMPTY_, 0, false)
10054 }
10055
10056 // Threshold for compression.
10057 // TODO(dlc) - Eventually make configurable.
10058 const compressThreshold = 8192 // 8k
10059
10060 // If allowed and contents over the threshold we will compress.
10061 func encodeStreamMsgAllowCompressAndBatch(subject, reply string, hdr, msg []byte, lseq uint64, ts int64, sourced bool, batchId string, batchSeq uint64, batchCommit bool) []byte {
10062 // Clip the subject, reply, header and msgs down. Operate on
10063 // uint64 lengths to avoid overflowing.
10064 slen := min(uint64(len(subject)), math.MaxUint16)
10065 rlen := min(uint64(len(reply)), math.MaxUint16)
10066 hlen := min(uint64(len(hdr)), math.MaxUint16)
10067 mlen := min(uint64(len(msg)), math.MaxUint32)
10068 total := slen + rlen + hlen + mlen
10069
10070 shouldCompress := total > compressThreshold
10071 elen := int(1 + 8 + 8 + total)
10072 elen += (2 + 2 + 2 + 4 + 8) // Encoded lengths, 4bytes, flags are up to 8 bytes
10073
10074 blen := min(uint64(len(batchId)), math.MaxUint16)
10075 if batchId != _EMPTY_ {
10076 elen += int(2 + blen + 8) // length of batchId, batchId itself, batchSeq (up to 8 bytes)
10077 }
10078
10079 var flags uint64
10080 if sourced {
10081 flags |= msgFlagFromSourceOrMirror
10082 }
10083
10084 var le = binary.LittleEndian
10085 var opIndex int
10086 buf := make([]byte, 1, elen)
10087 if batchId != _EMPTY_ {
10088 if batchCommit {
10089 buf[0] = byte(batchCommitMsgOp)
10090 } else {
10091 buf[0] = byte(batchMsgOp)
10092 }
10093 buf = le.AppendUint16(buf, uint16(blen))
10094 buf = append(buf, batchId[:blen]...)
10095 buf = binary.AppendUvarint(buf, batchSeq)
10096 opIndex = len(buf)
10097 buf = append(buf, byte(streamMsgOp))
10098 } else {
10099 buf[opIndex] = byte(streamMsgOp)
10100 }
10101
10102 buf = le.AppendUint64(buf, lseq)
10103 buf = le.AppendUint64(buf, uint64(ts))
10104 buf = le.AppendUint16(buf, uint16(slen))
10105 buf = append(buf, subject[:slen]...)
10106 buf = le.AppendUint16(buf, uint16(rlen))
10107 buf = append(buf, reply[:rlen]...)
10108 buf = le.AppendUint16(buf, uint16(hlen))
10109 buf = append(buf, hdr[:hlen]...)
10110 buf = le.AppendUint32(buf, uint32(mlen))
10111 buf = append(buf, msg[:mlen]...)
10112 buf = binary.AppendUvarint(buf, flags)
10113
10114 // Check if we should compress.
10115 if shouldCompress {
10116 nbuf := make([]byte, s2.MaxEncodedLen(elen))
10117 if opIndex > 0 {
10118 copy(nbuf[:opIndex], buf[:opIndex])
10119 }
10120 nbuf[opIndex] = byte(compressedStreamMsgOp)
10121 ebuf := s2.Encode(nbuf[opIndex+1:], buf[opIndex+1:])
10122 // Only pay the cost of decode on the other side if we compressed.
10123 // S2 will allow us to try without major penalty for non-compressable data.
10124 if len(ebuf) < len(buf) {
10125 buf = nbuf[:len(ebuf)+opIndex+1]
10126 }
10127 }
10128
10129 return buf
10130 }
10131
10132 // Determine if all peers in our set support the binary snapshot.
10133 func (mset *stream) supportsBinarySnapshot() bool {
10134 mset.mu.RLock()
10135 defer mset.mu.RUnlock()
10136 return mset.supportsBinarySnapshotLocked()
10137 }
10138
10139 // Determine if all peers in our set support the binary snapshot.
10140 // Lock should be held.
10141 func (mset *stream) supportsBinarySnapshotLocked() bool {
10142 s, n := mset.srv, mset.node
10143 if s == nil || n == nil {
10144 return false
10145 }
10146 // Grab our peers and walk them to make sure we can all support binary stream snapshots.
10147 id, peers := n.ID(), n.Peers()
10148 for _, p := range peers {
10149 if p.ID == id {
10150 // We know we support ourselves.
10151 continue
10152 }
10153 // Since release 2.10.16 only deny if we know the other node does not support.
10154 if sir, ok := s.nodeToInfo.Load(p.ID); ok && sir != nil && !sir.(nodeInfo).binarySnapshots {
10155 return false
10156 }
10157 }
10158 return true
10159 }
10160
10161 // StreamSnapshot is used for snapshotting and out of band catch up in clustered mode.
10162 // Legacy, replace with binary stream snapshots.
10163 type streamSnapshot struct {
10164 Msgs uint64 `json:"messages"`
10165 Bytes uint64 `json:"bytes"`
10166 FirstSeq uint64 `json:"first_seq"`
10167 LastSeq uint64 `json:"last_seq"`
10168 Failed uint64 `json:"clfs"`
10169 Deleted []uint64 `json:"deleted,omitempty"`
10170 }
10171
10172 // Grab a snapshot of a stream for clustered mode.
10173 func (mset *stream) stateSnapshot() []byte {
10174 mset.mu.RLock()
10175 defer mset.mu.RUnlock()
10176 return mset.stateSnapshotLocked()
10177 }
10178
10179 // Grab a snapshot of a stream for clustered mode.
10180 // Lock should be held.
10181 func (mset *stream) stateSnapshotLocked() []byte {
10182 // Decide if we can support the new style of stream snapshots.
10183 if mset.supportsBinarySnapshotLocked() {
10184 snap, err := mset.store.EncodedStreamState(mset.getCLFS())
10185 if err != nil {
10186 return nil
10187 }
10188 return snap
10189 }
10190
10191 // Older v1 version with deleted as a sorted []uint64.
10192 // For a stream with millions or billions of interior deletes, this will be huge.
10193 // Now that all server versions 2.10.+ support binary snapshots, we should never fall back.
10194 assert.Unreachable("Legacy JSON stream snapshot used", map[string]any{
10195 "stream": mset.cfg.Name,
10196 "account": mset.acc.Name,
10197 })
10198
10199 state := mset.store.State()
10200 snap := &streamSnapshot{
10201 Msgs: state.Msgs,
10202 Bytes: state.Bytes,
10203 FirstSeq: state.FirstSeq,
10204 LastSeq: state.LastSeq,
10205 Failed: mset.getCLFS(),
10206 Deleted: state.Deleted,
10207 }
10208 b, _ := json.Marshal(snap)
10209 return b
10210 }
10211
10212 // To warn when we are getting too far behind from what has been proposed vs what has been committed.
10213 const streamLagWarnThreshold = 10_000
10214
10215 // processClusteredInboundMsg will propose the inbound message to the underlying raft group.
10216 func (mset *stream) processClusteredInboundMsg(subject, reply string, hdr, msg []byte, mt *msgTrace, sourced bool) (retErr error) {
10217 // For possible error response.
10218 var response []byte
10219
10220 mset.mu.RLock()
10221 canRespond := !mset.cfg.NoAck && len(reply) > 0
10222 name, stype := mset.cfg.Name, mset.cfg.Storage
10223 discard, discardNewPer, maxMsgs, maxMsgsPer, maxBytes := mset.cfg.Discard, mset.cfg.DiscardNewPer, mset.cfg.MaxMsgs, mset.cfg.MaxMsgsPer, mset.cfg.MaxBytes
10224 s, js, jsa, st, r, tierName, outq, node, term := mset.srv, mset.js, mset.jsa, mset.cfg.Storage, mset.cfg.Replicas, mset.tier, mset.outq, mset.node, mset.term
10225 maxMsgSize, lseq := int(mset.cfg.MaxMsgSize), mset.lseq
10226 isLeader, isSealed, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules := mset.isLeader(), mset.cfg.Sealed, mset.cfg.AllowRollup, mset.cfg.DenyPurge, mset.cfg.AllowMsgTTL, mset.cfg.AllowMsgCounter, mset.cfg.AllowMsgSchedules
10227
10228 // Apply the input subject transform if any
10229 csubject := subject
10230 if mset.itr != nil {
10231 ts, err := mset.itr.Match(csubject)
10232 if err == nil {
10233 // no filtering: if the subject doesn't map the source of the transform, don't change it
10234 csubject = ts
10235 }
10236 }
10237 mset.mu.RUnlock()
10238
10239 // This should not happen but possible now that we allow scale up, and scale down where this could trigger.
10240 //
10241 // We also invoke this in clustering mode for message tracing when not
10242 // performing message delivery.
10243 if node == nil || mt.traceOnly() {
10244 return mset.processJetStreamMsg(subject, reply, hdr, msg, 0, 0, mt, sourced, true)
10245 }
10246
10247 // If message tracing (with message delivery), we will need to send the
10248 // event on exit in case there was an error (if message was not proposed).
10249 // Otherwise, the event will be sent from processJetStreamMsg when
10250 // invoked by the leader (from applyStreamEntries).
10251 if mt != nil {
10252 defer func() {
10253 if retErr != nil {
10254 mt.sendEventFromJetStream(retErr)
10255 }
10256 }()
10257 }
10258
10259 // Check that we are the leader. This can be false if we have scaled up from an R1 that had inbound queued messages.
10260 if !isLeader {
10261 return NewJSClusterNotLeaderError()
10262 }
10263
10264 // Bail here if sealed.
10265 if isSealed {
10266 var resp = JSPubAckResponse{PubAck: &PubAck{Stream: mset.name()}, Error: NewJSStreamSealedError()}
10267 b, _ := json.Marshal(resp)
10268 mset.outq.sendMsg(reply, b)
10269 return NewJSStreamSealedError()
10270 }
10271
10272 // Check here pre-emptively if we have exceeded this server limits.
10273 if js.limitsExceeded(stype) {
10274 s.resourcesExceededError(stype)
10275 if canRespond {
10276 b, _ := json.Marshal(&JSPubAckResponse{PubAck: &PubAck{Stream: name}, Error: NewJSInsufficientResourcesError()})
10277 outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, nil, b, nil, 0))
10278 }
10279 // Stepdown regardless.
10280 if node := mset.raftNode(); node != nil {
10281 node.StepDown()
10282 }
10283 return NewJSInsufficientResourcesError()
10284 }
10285
10286 // Check here pre-emptively if we have exceeded our account limits.
10287 if exceeded, err := jsa.wouldExceedLimits(st, tierName, r, csubject, hdr, msg); exceeded {
10288 if err == nil {
10289 err = NewJSAccountResourcesExceededError()
10290 }
10291 s.RateLimitWarnf("JetStream account limits exceeded for '%s': %s", jsa.acc().GetName(), err.Error())
10292 if canRespond {
10293 var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: name}}
10294 resp.Error = err
10295 response, _ = json.Marshal(resp)
10296 outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, nil, response, nil, 0))
10297 }
10298 return err
10299 }
10300
10301 // Check msgSize if we have a limit set there. Again this works if it goes through but better to be pre-emptive.
10302 // Subtract to prevent against overflows.
10303 if maxMsgSize >= 0 && (len(hdr) > maxMsgSize || len(msg) > maxMsgSize-len(hdr)) {
10304 err := fmt.Errorf("JetStream message size exceeds limits for '%s > %s'", jsa.acc().Name, name)
10305 s.RateLimitWarnf("%s", err.Error())
10306 if canRespond {
10307 var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: name}}
10308 resp.Error = NewJSStreamMessageExceedsMaximumError()
10309 response, _ = json.Marshal(resp)
10310 outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, nil, response, nil, 0))
10311 }
10312 return err
10313 }
10314
10315 // Proceed with proposing this message.
10316
10317 // We only use mset.clseq for clustering and in case we run ahead of actual commits.
10318 // Check if we need to set initial value here
10319 mset.clMu.Lock()
10320 if mset.clseq == 0 || mset.clseq < lseq+mset.clfs {
10321 lseq = recalculateClusteredSeq(mset, true)
10322 }
10323
10324 var (
10325 dseq uint64
10326 apiErr *ApiError
10327 err error
10328 )
10329 diff := &batchStagedDiff{}
10330 if hdr, msg, dseq, apiErr, err = checkMsgHeadersPreClusteredProposal(diff, mset, csubject, subject, hdr, msg, sourced, name, jsa, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules, discard, discardNewPer, maxMsgSize, maxMsgs, maxMsgsPer, maxBytes); err != nil {
10331 mset.clMu.Unlock()
10332 if err == errMsgIdDuplicate && dseq > 0 {
10333 var buf [256]byte
10334 pubAck := append(buf[:0], mset.pubAck...)
10335 response = append(pubAck, strconv.FormatUint(dseq, 10)...)
10336 response = append(response, ",\"duplicate\": true}"...)
10337 outq.sendMsg(reply, response)
10338 return err
10339 }
10340 if canRespond {
10341 var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: name}}
10342 resp.Error = apiErr
10343 response, _ = json.Marshal(resp)
10344 outq.sendMsg(reply, response)
10345 }
10346 return err
10347 }
10348
10349 err = commitSingleMsg(diff, mset, subject, reply, hdr, msg, name, jsa, mt, node, term, r, lseq)
10350 mset.clMu.Unlock()
10351 return err
10352 }
10353
10354 func (mset *stream) getAndDeleteMsgTrace(lseq uint64) *msgTrace {
10355 if mset == nil {
10356 return nil
10357 }
10358 mset.clMu.Lock()
10359 mt, ok := mset.mt[lseq]
10360 if ok {
10361 delete(mset.mt, lseq)
10362 }
10363 mset.clMu.Unlock()
10364 return mt
10365 }
10366
10367 // For requesting messages post raft snapshot to catch up streams post server restart.
10368 // Any deleted msgs etc will be handled inline on catchup.
10369 type streamSyncRequest struct {
10370 Peer string `json:"peer,omitempty"`
10371 FirstSeq uint64 `json:"first_seq"`
10372 LastSeq uint64 `json:"last_seq"`
10373 DeleteRangesOk bool `json:"delete_ranges"`
10374 MinApplied uint64 `json:"min_applied"`
10375 }
10376
10377 // Given a stream state that represents a snapshot, calculate the sync request based on our current state.
10378 // Stream lock must be held.
10379 func (mset *stream) calculateSyncRequest(state *StreamState, snap *StreamReplicatedState, index uint64) *streamSyncRequest {
10380 // Shouldn't happen, but consequences are pretty bad if we have the lock held and
10381 // our caller tries to take the lock again on panic defer, as in processSnapshot.
10382 if state == nil || snap == nil || mset.node == nil {
10383 return nil
10384 }
10385 // Quick check if we are already caught up.
10386 if state.LastSeq >= snap.LastSeq {
10387 return nil
10388 }
10389 return &streamSyncRequest{FirstSeq: state.LastSeq + 1, LastSeq: snap.LastSeq, Peer: mset.node.ID(), DeleteRangesOk: true, MinApplied: index}
10390 }
10391
10392 // processSnapshotDeletes will update our current store based on the snapshot
10393 // but only processing deletes and new FirstSeq / purges.
10394 func (mset *stream) processSnapshotDeletes(snap *StreamReplicatedState) error {
10395 mset.mu.Lock()
10396 var state StreamState
10397 mset.store.FastState(&state)
10398 // Always adjust if FirstSeq has moved beyond our state.
10399 var didReset bool
10400 if snap.FirstSeq > state.FirstSeq {
10401 if _, err := mset.store.Compact(snap.FirstSeq); err != nil {
10402 mset.mu.Unlock()
10403 return err
10404 }
10405 mset.store.FastState(&state)
10406 mset.lseq = state.LastSeq
10407 mset.clearAllPreAcksBelowFloor(state.FirstSeq)
10408 didReset = true
10409 }
10410 s := mset.srv
10411 mset.mu.Unlock()
10412
10413 if didReset {
10414 s.Warnf("Catchup for stream '%s > %s' resetting first sequence: %d on catchup request",
10415 mset.account(), mset.name(), snap.FirstSeq)
10416 }
10417
10418 if len(snap.Deleted) > 0 {
10419 return mset.store.SyncDeleted(snap.Deleted)
10420 }
10421 return nil
10422 }
10423
10424 func (mset *stream) setCatchupPeer(peer string, lag uint64) {
10425 if peer == _EMPTY_ {
10426 return
10427 }
10428 mset.mu.Lock()
10429 if mset.catchups == nil {
10430 mset.catchups = make(map[string]uint64)
10431 }
10432 mset.catchups[peer] = lag
10433 mset.mu.Unlock()
10434 }
10435
10436 // Will decrement by one.
10437 func (mset *stream) updateCatchupPeer(peer string) {
10438 if peer == _EMPTY_ {
10439 return
10440 }
10441 mset.mu.Lock()
10442 if lag := mset.catchups[peer]; lag > 0 {
10443 mset.catchups[peer] = lag - 1
10444 }
10445 mset.mu.Unlock()
10446 }
10447
10448 func (mset *stream) decrementCatchupPeer(peer string, num uint64) {
10449 if peer == _EMPTY_ {
10450 return
10451 }
10452 mset.mu.Lock()
10453 if lag := mset.catchups[peer]; lag > 0 {
10454 if lag >= num {
10455 lag -= num
10456 } else {
10457 lag = 0
10458 }
10459 mset.catchups[peer] = lag
10460 }
10461 mset.mu.Unlock()
10462 }
10463
10464 func (mset *stream) clearCatchupPeer(peer string) {
10465 mset.mu.Lock()
10466 if mset.catchups != nil {
10467 delete(mset.catchups, peer)
10468 }
10469 mset.mu.Unlock()
10470 }
10471
10472 // Lock should be held.
10473 func (mset *stream) clearAllCatchupPeers() {
10474 if mset.catchups != nil {
10475 mset.catchups = nil
10476 }
10477 }
10478
10479 func (mset *stream) lagForCatchupPeer(peer string) uint64 {
10480 mset.mu.RLock()
10481 defer mset.mu.RUnlock()
10482 if mset.catchups == nil {
10483 return 0
10484 }
10485 return mset.catchups[peer]
10486 }
10487
10488 func (mset *stream) hasCatchupPeers() bool {
10489 mset.mu.RLock()
10490 defer mset.mu.RUnlock()
10491 return len(mset.catchups) > 0
10492 }
10493
10494 func (mset *stream) setCatchingUp() {
10495 mset.catchup.Store(true)
10496 }
10497
10498 func (mset *stream) clearCatchingUp() {
10499 mset.catchup.Store(false)
10500 }
10501
10502 func (mset *stream) isCatchingUp() bool {
10503 return mset.catchup.Load()
10504 }
10505
10506 // Determine if a non-leader is current.
10507 // Lock should be held.
10508 func (mset *stream) isCurrent() bool {
10509 if mset.node == nil {
10510 return true
10511 }
10512 return mset.node.Current() && !mset.catchup.Load()
10513 }
10514
10515 // Maximum requests for the whole server that can be in flight at the same time.
10516 const maxConcurrentSyncRequests = 32
10517
10518 var (
10519 errCatchupCorruptSnapshot = errors.New("corrupt stream snapshot detected")
10520 errCatchupStalled = errors.New("catchup stalled")
10521 errCatchupStreamStopped = errors.New("stream has been stopped") // when a catchup is terminated due to the stream going away.
10522 errCatchupBadMsg = errors.New("bad catchup msg")
10523 errCatchupWrongSeqForSkip = errors.New("wrong sequence for skipped msg")
10524 errCatchupAbortedNoLeader = errors.New("catchup aborted, no leader")
10525 errCatchupTooManyRetries = errors.New("catchup failed, too many retries")
10526 )
10527
10528 // Catchup inactivity timers.
10529 const (
10530 defaultStreamCatchupStartInterval = 5 * time.Second
10531 defaultStreamCatchupActivityInterval = 30 * time.Second
10532 )
10533
10534 var (
10535 streamCatchupStartInterval = defaultStreamCatchupStartInterval
10536 streamCatchupActivityInterval = defaultStreamCatchupActivityInterval
10537 )
10538
10539 // Process a stream snapshot.
10540 func (mset *stream) processSnapshot(snap *StreamReplicatedState, index uint64) (e error) {
10541 // Update any deletes, etc.
10542 if err := mset.processSnapshotDeletes(snap); err != nil {
10543 return err
10544 }
10545 mset.setCLFS(snap.Failed)
10546
10547 mset.mu.Lock()
10548 var state StreamState
10549 mset.store.FastState(&state)
10550 sreq := mset.calculateSyncRequest(&state, snap, index)
10551
10552 if mset.sa == nil || mset.node == nil {
10553 mset.mu.Unlock()
10554 return errCatchupStreamStopped
10555 }
10556 s, js, subject, n, st := mset.srv, mset.js, mset.sa.Sync, mset.node, mset.cfg.Storage
10557 qname := fmt.Sprintf("[ACC:%s] stream '%s' snapshot", mset.acc.Name, mset.cfg.Name)
10558 mset.mu.Unlock()
10559
10560 // Always try to resume applies, we might be paused already if we timed out of processing the snapshot previously.
10561 defer func() {
10562 // Don't bother resuming if server or stream is gone.
10563 if e != errCatchupStreamStopped && e != ErrServerNotRunning {
10564 n.ResumeApply()
10565 }
10566 }()
10567
10568 // Bug that would cause this to be empty on stream update.
10569 if subject == _EMPTY_ {
10570 return errCatchupCorruptSnapshot
10571 }
10572
10573 // Just return if up to date.
10574 if sreq == nil {
10575 return nil
10576 }
10577
10578 // We need to catch up, but are already exceeding limits.
10579 if js.limitsExceeded(st) {
10580 s.resourcesExceededError(st)
10581 return NewJSInsufficientResourcesError()
10582 }
10583
10584 // Pause the apply channel for our raft group while we catch up.
10585 if err := n.PauseApply(); err != nil {
10586 // The only reason PauseApply can fail is due to errAlreadyLeader.
10587 // We step down to get someone else to become the leader that can catch us up.
10588 // Ignore the error since we could have already stepped down before us doing so here.
10589 _ = n.StepDown()
10590 // Now try pausing again and continue to catchup.
10591 if err = n.PauseApply(); err != nil {
10592 return err
10593 }
10594 }
10595
10596 // Set our catchup state.
10597 mset.setCatchingUp()
10598 defer mset.clearCatchingUp()
10599
10600 var sub *subscription
10601 var err error
10602
10603 startInterval := streamCatchupStartInterval
10604 activityInterval := streamCatchupActivityInterval
10605 notActive := time.NewTimer(startInterval)
10606 defer notActive.Stop()
10607
10608 defer func() {
10609 if sub != nil {
10610 s.sysUnsubscribe(sub)
10611 }
10612 // Make sure any consumers are updated for the pending amounts.
10613 mset.mu.Lock()
10614 for _, o := range mset.consumers {
10615 o.mu.Lock()
10616 o.streamNumPending()
10617 o.mu.Unlock()
10618 }
10619 mset.mu.Unlock()
10620
10621 // If we are interest based make sure to check our ack floor state.
10622 // We will delay a bit to allow consumer states to also catchup.
10623 if mset.isInterestRetention() {
10624 fire := time.Duration(rand.Intn(10)+5) * time.Second
10625 time.AfterFunc(fire, mset.checkInterestState)
10626 }
10627 }()
10628
10629 var releaseSem bool
10630 releaseSyncOutSem := func() {
10631 if !releaseSem {
10632 return
10633 }
10634 // Need to use select for the server shutdown case.
10635 select {
10636 case s.syncOutSem <- struct{}{}:
10637 default:
10638 }
10639 releaseSem = false
10640 }
10641 // On exit, we will release our semaphore if we acquired it.
10642 defer releaseSyncOutSem()
10643
10644 // Do not let this go on forever.
10645 start := time.Now()
10646 const maxRetries = 3
10647 var numRetries int
10648
10649 RETRY:
10650 // On retry, we need to release the semaphore we got. Call will be no-op
10651 // if releaseSem boolean has not been set to true on successfully getting
10652 // the semaphore.
10653 releaseSyncOutSem()
10654
10655 if n.Leaderless() {
10656 // Prevent us from spinning if we've installed a snapshot from a leader but there's no leader online.
10657 // We wait a bit to check if a leader has come online in the meantime, if so we can continue.
10658 var canContinue bool
10659 if numRetries == 0 {
10660 time.Sleep(startInterval)
10661 canContinue = !n.Leaderless()
10662 }
10663 if !canContinue {
10664 return fmt.Errorf("%w for stream '%s > %s'", errCatchupAbortedNoLeader, mset.account(), mset.name())
10665 }
10666 }
10667
10668 // If we have a sub clear that here.
10669 if sub != nil {
10670 s.sysUnsubscribe(sub)
10671 sub = nil
10672 }
10673
10674 if !s.isRunning() {
10675 return ErrServerNotRunning
10676 }
10677
10678 numRetries++
10679 if numRetries > maxRetries {
10680 // Force a hard reset here.
10681 return errCatchupTooManyRetries
10682 }
10683
10684 // Block here if we have too many requests in flight.
10685 <-s.syncOutSem
10686 releaseSem = true
10687
10688 // We may have been blocked for a bit, so the reset needs to ensure that we
10689 // consume the already fired timer.
10690 if !notActive.Stop() {
10691 select {
10692 case <-notActive.C:
10693 default:
10694 }
10695 }
10696 notActive.Reset(startInterval)
10697
10698 // Grab sync request again on failures.
10699 if sreq == nil {
10700 mset.mu.RLock()
10701 var state StreamState
10702 mset.store.FastState(&state)
10703 sreq = mset.calculateSyncRequest(&state, snap, index)
10704 mset.mu.RUnlock()
10705 if sreq == nil {
10706 return nil
10707 }
10708 }
10709
10710 // Used to transfer message from the wire to another Go routine internally.
10711 type im struct {
10712 msg []byte
10713 reply string
10714 }
10715 // This is used to notify the leader that it should stop the runCatchup
10716 // because we are either bailing out or going to retry due to an error.
10717 notifyLeaderStopCatchup := func(mrec *im, err error) {
10718 if mrec.reply == _EMPTY_ {
10719 return
10720 }
10721 s.sendInternalMsgLocked(mrec.reply, _EMPTY_, nil, err.Error())
10722 }
10723
10724 msgsQ := newIPQueue[*im](s, qname)
10725 defer msgsQ.unregister()
10726
10727 // Send our catchup request here.
10728 reply := syncReplySubject()
10729 sub, err = s.sysSubscribe(reply, func(_ *subscription, _ *client, _ *Account, _, reply string, msg []byte) {
10730 // Make copy since we are using a buffer from the inbound client/route.
10731 msgsQ.push(&im{copyBytes(msg), reply})
10732 })
10733 if err != nil {
10734 s.Errorf("Could not subscribe to stream catchup: %v", err)
10735 goto RETRY
10736 }
10737
10738 // Send our sync request.
10739 b, _ := json.Marshal(sreq)
10740 s.sendInternalMsgLocked(subject, reply, nil, b)
10741
10742 // Remember when we sent this out to avoid loop spins on errors below.
10743 reqSendTime := time.Now()
10744
10745 // Clear our sync request.
10746 sreq = nil
10747
10748 // Run our own select loop here.
10749 for qch := n.QuitC(); ; {
10750 select {
10751 case <-msgsQ.ch:
10752 notActive.Reset(activityInterval)
10753
10754 mrecs := msgsQ.pop()
10755 for _, mrec := range mrecs {
10756 msg := mrec.msg
10757 // Check for eof signaling.
10758 if len(msg) == 0 {
10759 msgsQ.recycle(&mrecs)
10760
10761 // Sanity check that we've received all data expected by the snapshot.
10762 mset.mu.RLock()
10763 lseq := mset.lseq
10764 mset.mu.RUnlock()
10765 if lseq >= snap.LastSeq {
10766 // We MUST ensure all data is flushed up to this point, if the store hadn't already.
10767 // Because the snapshot needs to represent what has been persisted.
10768 err = mset.flushAllPending()
10769 if err == nil {
10770 s.Noticef("Catchup for stream '%s > %s' complete (took %v)", mset.account(), mset.name(), time.Since(start).Round(time.Millisecond))
10771 } else {
10772 s.Noticef("Catchup for stream '%s > %s' errored: %v (took %v)", mset.account(), mset.name(), err, time.Since(start).Round(time.Millisecond))
10773 }
10774 return err
10775 }
10776
10777 // Make sure we do not spin and make things worse.
10778 const minRetryWait = 2 * time.Second
10779 elapsed := time.Since(reqSendTime)
10780 if elapsed < minRetryWait {
10781 select {
10782 case <-s.quitCh:
10783 return ErrServerNotRunning
10784 case <-qch:
10785 return errCatchupStreamStopped
10786 case <-time.After(minRetryWait - elapsed):
10787 }
10788 }
10789 goto RETRY
10790 }
10791 if _, err := mset.processCatchupMsg(msg); err == nil {
10792 if mrec.reply != _EMPTY_ {
10793 s.sendInternalMsgLocked(mrec.reply, _EMPTY_, nil, nil)
10794 }
10795 } else if isOutOfSpaceErr(err) {
10796 notifyLeaderStopCatchup(mrec, err)
10797 msgsQ.recycle(&mrecs)
10798 return err
10799 } else if err == NewJSInsufficientResourcesError() {
10800 notifyLeaderStopCatchup(mrec, err)
10801 if mset.js.limitsExceeded(st) {
10802 s.resourcesExceededError(st)
10803 } else {
10804 s.Warnf("Catchup for stream '%s > %s' errored, account resources exceeded: %v", mset.account(), mset.name(), err)
10805 }
10806 msgsQ.recycle(&mrecs)
10807 return err
10808 } else {
10809 notifyLeaderStopCatchup(mrec, err)
10810 s.Warnf("Catchup for stream '%s > %s' errored, will retry: %v", mset.account(), mset.name(), err)
10811 msgsQ.recycle(&mrecs)
10812
10813 // Make sure we do not spin and make things worse.
10814 const minRetryWait = 2 * time.Second
10815 elapsed := time.Since(reqSendTime)
10816 if elapsed < minRetryWait {
10817 select {
10818 case <-s.quitCh:
10819 return ErrServerNotRunning
10820 case <-qch:
10821 return errCatchupStreamStopped
10822 case <-time.After(minRetryWait - elapsed):
10823 }
10824 }
10825 goto RETRY
10826 }
10827 }
10828 notActive.Reset(activityInterval)
10829 msgsQ.recycle(&mrecs)
10830 case <-notActive.C:
10831 if mrecs := msgsQ.pop(); len(mrecs) > 0 {
10832 mrec := mrecs[0]
10833 notifyLeaderStopCatchup(mrec, errCatchupStalled)
10834 msgsQ.recycle(&mrecs)
10835 }
10836 s.Warnf("Catchup for stream '%s > %s' stalled", mset.account(), mset.name())
10837 // Sanity check that we've not become leader. Shouldn't be possible
10838 // since we haven't applied the snapshot yet.
10839 if n.State() == Leader {
10840 n.StepDown()
10841 }
10842 goto RETRY
10843 case <-s.quitCh:
10844 return ErrServerNotRunning
10845 case <-qch:
10846 return errCatchupStreamStopped
10847 }
10848 }
10849 }
10850
10851 // processCatchupMsg will be called to process out of band catchup msgs from a sync request.
10852 func (mset *stream) processCatchupMsg(msg []byte) (uint64, error) {
10853 if len(msg) == 0 {
10854 return 0, errCatchupBadMsg
10855 }
10856 op := entryOp(msg[0])
10857 if op != streamMsgOp && op != compressedStreamMsgOp && op != deleteRangeOp {
10858 return 0, errCatchupBadMsg
10859 }
10860
10861 mbuf := msg[1:]
10862 if op == deleteRangeOp {
10863 dr, err := decodeDeleteRange(mbuf)
10864 if err != nil {
10865 return 0, errCatchupBadMsg
10866 }
10867 // Handle the delete range.
10868 // Make sure the sequences match up properly.
10869 mset.mu.Lock()
10870 lseq := dr.First + dr.Num - 1
10871 if err = mset.store.SkipMsgs(dr.First, dr.Num); err != nil {
10872 mset.mu.Unlock()
10873 return 0, errCatchupWrongSeqForSkip
10874 }
10875 mset.clearAllPreAcksInRange(dr.First, lseq)
10876 mset.lseq = lseq
10877 mset.mu.Unlock()
10878 return lseq, nil
10879 }
10880
10881 if op == compressedStreamMsgOp {
10882 var err error
10883 mbuf, err = s2.Decode(nil, mbuf)
10884 if err != nil {
10885 panic(err.Error())
10886 }
10887 }
10888
10889 subj, _, hdr, msg, seq, ts, _, err := decodeStreamMsg(mbuf)
10890 if err != nil {
10891 return 0, errCatchupBadMsg
10892 }
10893
10894 mset.mu.Lock()
10895 st := mset.cfg.Storage
10896 if mset.hasAllPreAcks(seq, subj) {
10897 mset.clearAllPreAcks(seq)
10898 // Mark this to be skipped
10899 subj, ts = _EMPTY_, 0
10900 }
10901 mset.mu.Unlock()
10902
10903 // Since we're clustered we do not want to check limits based on tier here and possibly introduce skew.
10904 if mset.js.limitsExceeded(st) {
10905 return 0, NewJSInsufficientResourcesError()
10906 }
10907
10908 // Find the message TTL if any.
10909 // TODO(nat): If the TTL isn't valid by this stage then there isn't really a
10910 // lot we can do about it, as we'd break the catchup if we reject the message.
10911 ttl, _ := getMessageTTL(hdr)
10912
10913 // Put into our store
10914 // Messages to be skipped have no subject or timestamp.
10915 // TODO(dlc) - formalize with skipMsgOp
10916 if subj == _EMPTY_ && ts == 0 {
10917 if _, err = mset.store.SkipMsg(seq); err != nil {
10918 return 0, errCatchupWrongSeqForSkip
10919 }
10920 } else if err := mset.store.StoreRawMsg(subj, hdr, msg, seq, ts, ttl, false); err != nil {
10921 return 0, err
10922 }
10923
10924 mset.mu.Lock()
10925 defer mset.mu.Unlock()
10926 // Update our lseq.
10927 mset.lseq = seq
10928
10929 // Check for MsgId and if we have one here make sure to update our internal map.
10930 if len(hdr) > 0 {
10931 if msgId := getMsgId(hdr); msgId != _EMPTY_ {
10932 mset.ddMu.Lock()
10933 mset.storeMsgIdLocked(&ddentry{msgId, seq, ts})
10934 mset.ddMu.Unlock()
10935 }
10936 }
10937
10938 return seq, nil
10939 }
10940
10941 // flushAllPending will flush any pending writes as a result of installing a snapshot or performing catchup.
10942 func (mset *stream) flushAllPending() error {
10943 return mset.store.FlushAllPending()
10944 }
10945
10946 func (mset *stream) handleClusterSyncRequest(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
10947 var sreq streamSyncRequest
10948 if err := json.Unmarshal(msg, &sreq); err != nil {
10949 // Log error.
10950 return
10951 }
10952 mset.srv.startGoRoutine(func() { mset.runCatchup(reply, &sreq) })
10953 }
10954
10955 // Lock should be held.
10956 func (js *jetStream) offlineClusterInfo(rg *raftGroup) *ClusterInfo {
10957 s := js.srv
10958
10959 ci := &ClusterInfo{Name: s.ClusterName(), RaftGroup: rg.Name}
10960 for _, peer := range rg.Peers {
10961 if sir, ok := s.nodeToInfo.Load(peer); ok && sir != nil {
10962 si := sir.(nodeInfo)
10963 pi := &PeerInfo{Peer: peer, Name: si.name, Current: false, Offline: true}
10964 ci.Replicas = append(ci.Replicas, pi)
10965 }
10966 }
10967 return ci
10968 }
10969
10970 // clusterInfo will report on the status of the raft group.
10971 func (js *jetStream) clusterInfo(rg *raftGroup) *ClusterInfo {
10972 if js == nil {
10973 return nil
10974 }
10975 js.mu.RLock()
10976 s := js.srv
10977 if rg == nil || rg.node == nil {
10978 js.mu.RUnlock()
10979 return &ClusterInfo{
10980 Name: s.cachedClusterName(),
10981 Leader: s.Name(),
10982 }
10983 }
10984
10985 // Capture what we need and let go of the lock to ensure that
10986 // contention on Raft locks can't happen while holding JS lock.
10987 n := rg.node
10988 rgName := rg.Name
10989 rgPeers := slices.Clone(rg.Peers)
10990 js.mu.RUnlock()
10991
10992 ci := &ClusterInfo{
10993 Name: s.cachedClusterName(),
10994 Leader: s.serverNameForNode(n.GroupLeader()),
10995 LeaderSince: n.LeaderSince(),
10996 SystemAcc: n.IsSystemAccount(),
10997 TrafficAcc: n.GetTrafficAccountName(),
10998 RaftGroup: rgName,
10999 }
11000
11001 now := time.Now()
11002 id, peers := n.ID(), n.Peers()
11003
11004 // If we are leaderless, do not suppress putting us in the peer list.
11005 if ci.Leader == _EMPTY_ {
11006 id = _EMPTY_
11007 }
11008
11009 for _, rp := range peers {
11010 if rp.ID != id && slices.Contains(rgPeers, rp.ID) {
11011 var lastSeen time.Duration
11012 if now.After(rp.Last) && !rp.Last.IsZero() {
11013 lastSeen = now.Sub(rp.Last)
11014 }
11015 current := rp.Current
11016 if current && lastSeen > lostQuorumInterval {
11017 current = false
11018 }
11019 // Create a peer info with common settings if the peer has not been seen
11020 // yet (which can happen after the whole cluster is stopped and only some
11021 // of the nodes are restarted).
11022 pi := &PeerInfo{
11023 Current: current,
11024 Offline: true,
11025 Active: lastSeen,
11026 Lag: rp.Lag,
11027 Peer: rp.ID,
11028 }
11029 // If node is found, complete/update the settings.
11030 if sir, ok := s.nodeToInfo.Load(rp.ID); ok && sir != nil {
11031 si := sir.(nodeInfo)
11032 pi.Name, pi.Offline, pi.cluster = si.name, si.offline, si.cluster
11033 } else {
11034 // If not, then add a name that indicates that the server name
11035 // is unknown at this time, and clear the lag since it is misleading
11036 // (the node may not have that much lag).
11037 // Note: We return now the Peer ID in PeerInfo, so the "(peerID: %s)"
11038 // would technically not be required, but keeping it for now.
11039 pi.Name, pi.Lag = fmt.Sprintf("Server name unknown at this time (peerID: %s)", rp.ID), 0
11040 }
11041 ci.Replicas = append(ci.Replicas, pi)
11042 }
11043 }
11044 // Order the result based on the name so that we get something consistent
11045 // when doing repeated stream info in the CLI, etc...
11046 slices.SortFunc(ci.Replicas, func(i, j *PeerInfo) int { return cmp.Compare(i.Name, j.Name) })
11047 return ci
11048 }
11049
11050 func (mset *stream) checkClusterInfo(ci *ClusterInfo) {
11051 for _, r := range ci.Replicas {
11052 peer := getHash(r.Name)
11053 if lag := mset.lagForCatchupPeer(peer); lag > 0 {
11054 r.Current = false
11055 r.Lag = lag
11056 }
11057 }
11058 }
11059
11060 // Return a list of alternates, ranked by preference order to the request, of stream mirrors.
11061 // This allows clients to select or get more information about read replicas that could be a
11062 // better option to connect to versus the original source.
11063 func (js *jetStream) streamAlternates(ci *ClientInfo, stream string) []StreamAlternate {
11064 if js == nil {
11065 return nil
11066 }
11067
11068 js.mu.RLock()
11069 defer js.mu.RUnlock()
11070
11071 s, cc := js.srv, js.cluster
11072 // Track our domain.
11073 domain := s.getOpts().JetStreamDomain
11074
11075 // No clustering just return nil.
11076 if cc == nil {
11077 return nil
11078 }
11079 acc, _ := s.LookupAccount(ci.serviceAccount())
11080 if acc == nil {
11081 return nil
11082 }
11083
11084 // Collect our ordering first for clusters.
11085 weights := make(map[string]int)
11086 all := []string{ci.Cluster}
11087 all = append(all, ci.Alternates...)
11088
11089 for i := 0; i < len(all); i++ {
11090 weights[all[i]] = len(all) - i
11091 }
11092
11093 var alts []StreamAlternate
11094 for _, sa := range cc.streams[acc.Name] {
11095 if sa.unsupported != nil {
11096 continue
11097 }
11098 // Add in ourselves and any mirrors.
11099 if sa.Config.Name == stream || (sa.Config.Mirror != nil && sa.Config.Mirror.Name == stream) {
11100 alts = append(alts, StreamAlternate{Name: sa.Config.Name, Domain: domain, Cluster: sa.Group.Cluster})
11101 }
11102 }
11103 // If just us don't fill in.
11104 if len(alts) == 1 {
11105 return nil
11106 }
11107
11108 // Sort based on our weights that originate from the request itself.
11109 // reverse sort
11110 slices.SortFunc(alts, func(i, j StreamAlternate) int { return -cmp.Compare(weights[i.Cluster], weights[j.Cluster]) })
11111
11112 return alts
11113 }
11114
11115 // Internal request for stream info, this is coming on the wire so do not block here.
11116 func (mset *stream) handleClusterStreamInfoRequest(_ *subscription, c *client, _ *Account, subject, reply string, _ []byte) {
11117 go mset.processClusterStreamInfoRequest(reply)
11118 }
11119
11120 func (mset *stream) processClusterStreamInfoRequest(reply string) {
11121 mset.mu.RLock()
11122 sysc, js, sa, config := mset.sysc, mset.srv.js.Load(), mset.sa, mset.cfg
11123 isLeader := mset.isLeader()
11124 mset.mu.RUnlock()
11125
11126 // By design all members will receive this. Normally we only want the leader answering.
11127 // But if we have stalled and lost quorom all can respond.
11128 if sa != nil && !js.isGroupLeaderless(sa.Group) && !isLeader {
11129 return
11130 }
11131
11132 // If we are not the leader let someone else possibly respond first.
11133 if !isLeader {
11134 time.Sleep(500 * time.Millisecond)
11135 }
11136
11137 si := &StreamInfo{
11138 Created: mset.createdTime(),
11139 State: mset.state(),
11140 Config: config,
11141 Cluster: js.clusterInfo(mset.raftGroup()),
11142 Sources: mset.sourcesInfo(),
11143 Mirror: mset.mirrorInfo(),
11144 TimeStamp: time.Now().UTC(),
11145 }
11146
11147 // Check for out of band catchups.
11148 if mset.hasCatchupPeers() {
11149 mset.checkClusterInfo(si.Cluster)
11150 }
11151
11152 sysc.sendInternalMsg(reply, _EMPTY_, nil, si)
11153 }
11154
11155 // 64MB for now, for the total server. This is max we will blast out if asked to
11156 // do so to another server for purposes of catchups.
11157 // This number should be ok on 1Gbit interface.
11158 const defaultMaxTotalCatchupOutBytes = int64(64 * 1024 * 1024)
11159
11160 // Current total outstanding catchup bytes.
11161 func (s *Server) gcbTotal() int64 {
11162 s.gcbMu.RLock()
11163 defer s.gcbMu.RUnlock()
11164 return s.gcbOut
11165 }
11166
11167 // Returns true if Current total outstanding catchup bytes is below
11168 // the maximum configured.
11169 func (s *Server) gcbBelowMax() bool {
11170 s.gcbMu.RLock()
11171 defer s.gcbMu.RUnlock()
11172 return s.gcbOut <= s.gcbOutMax
11173 }
11174
11175 // Adds `sz` to the server's total outstanding catchup bytes and to `localsz`
11176 // under the gcbMu lock. The `localsz` points to the local outstanding catchup
11177 // bytes of the runCatchup go routine of a given stream.
11178 func (s *Server) gcbAdd(localsz *int64, sz int64) {
11179 s.gcbMu.Lock()
11180 atomic.AddInt64(localsz, sz)
11181 s.gcbOut += sz
11182 if s.gcbOut >= s.gcbOutMax && s.gcbKick == nil {
11183 s.gcbKick = make(chan struct{})
11184 }
11185 s.gcbMu.Unlock()
11186 }
11187
11188 // Removes `sz` from the server's total outstanding catchup bytes and from
11189 // `localsz`, but only if `localsz` is non 0, which would signal that gcSubLast
11190 // has already been invoked. See that function for details.
11191 // Must be invoked under the gcbMu lock.
11192 func (s *Server) gcbSubLocked(localsz *int64, sz int64) {
11193 if atomic.LoadInt64(localsz) == 0 {
11194 return
11195 }
11196 atomic.AddInt64(localsz, -sz)
11197 s.gcbOut -= sz
11198 if s.gcbKick != nil && s.gcbOut < s.gcbOutMax {
11199 close(s.gcbKick)
11200 s.gcbKick = nil
11201 }
11202 }
11203
11204 // Locked version of gcbSubLocked()
11205 func (s *Server) gcbSub(localsz *int64, sz int64) {
11206 s.gcbMu.Lock()
11207 s.gcbSubLocked(localsz, sz)
11208 s.gcbMu.Unlock()
11209 }
11210
11211 // Similar to gcbSub() but reset `localsz` to 0 at the end under the gcbMu lock.
11212 // This will signal further calls to gcbSub() for this `localsz` pointer that
11213 // nothing should be done because runCatchup() has exited and any remaining
11214 // outstanding bytes value has already been decremented.
11215 func (s *Server) gcbSubLast(localsz *int64) {
11216 s.gcbMu.Lock()
11217 s.gcbSubLocked(localsz, *localsz)
11218 *localsz = 0
11219 s.gcbMu.Unlock()
11220 }
11221
11222 // Returns our kick chan, or nil if it does not exist.
11223 func (s *Server) cbKickChan() <-chan struct{} {
11224 s.gcbMu.RLock()
11225 defer s.gcbMu.RUnlock()
11226 return s.gcbKick
11227 }
11228
11229 func (mset *stream) runCatchup(sendSubject string, sreq *streamSyncRequest) {
11230 s := mset.srv
11231 defer s.grWG.Done()
11232
11233 const maxOutBytes = int64(64 * 1024 * 1024) // 64MB for now, these are all internal, from server to server
11234 const maxOutMsgs = int32(256 * 1024) // 256k in case we have lots of small messages or skip msgs.
11235 outb := int64(0)
11236 outm := int32(0)
11237
11238 // On abnormal exit make sure to update global total.
11239 defer s.gcbSubLast(&outb)
11240
11241 // Flow control processing.
11242 ackReplySize := func(subj string) int64 {
11243 if li := strings.LastIndexByte(subj, btsep); li > 0 && li < len(subj) {
11244 return parseAckReplyNum(subj[li+1:])
11245 }
11246 return 0
11247 }
11248
11249 nextBatchC := make(chan struct{}, 4)
11250 nextBatchC <- struct{}{}
11251 remoteQuitCh := make(chan struct{})
11252
11253 activityInterval := streamCatchupActivityInterval
11254 notActive := time.NewTimer(activityInterval)
11255 defer notActive.Stop()
11256
11257 // Setup ackReply for flow control.
11258 ackReply := syncAckSubject()
11259 ackSub, _ := s.sysSubscribe(ackReply, func(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
11260 if len(msg) > 0 {
11261 s.Warnf("Catchup for stream '%s > %s' was aborted on the remote due to: %q",
11262 mset.account(), mset.name(), msg)
11263 s.sysUnsubscribe(sub)
11264 close(remoteQuitCh)
11265 return
11266 }
11267 sz := ackReplySize(subject)
11268 s.gcbSub(&outb, sz)
11269 atomic.AddInt32(&outm, -1)
11270 mset.updateCatchupPeer(sreq.Peer)
11271 // Kick ourselves and anyone else who might have stalled on global state.
11272 select {
11273 case nextBatchC <- struct{}{}:
11274 default:
11275 }
11276 // Reset our activity
11277 notActive.Reset(activityInterval)
11278 })
11279 defer s.sysUnsubscribe(ackSub)
11280 ackReplyT := strings.ReplaceAll(ackReply, ".*", ".%d")
11281
11282 // Grab our state.
11283 var state StreamState
11284 // mset.store never changes after being set, don't need lock.
11285 mset.store.FastState(&state)
11286
11287 // Setup sequences to walk through.
11288 seq, last := sreq.FirstSeq, sreq.LastSeq
11289
11290 // The follower received a snapshot from another leader, and we've become leader since.
11291 // We have an up-to-date log but could be behind on applies. We must wait until we've reached the minimum required.
11292 // The follower will automatically retry after a timeout, so we can safely return here.
11293 if node := mset.raftNode(); node != nil {
11294 index, _, applied := node.Progress()
11295 // Only skip if our log has enough entries, and they could be applied in the future.
11296 if index >= sreq.MinApplied && applied < sreq.MinApplied {
11297 return
11298 }
11299 // We know here we've either applied enough entries, or our log doesn't have enough entries.
11300 // In the latter case the request expects us to have more. Just continue and value availability here.
11301 // This should only be possible if the logs have already desynced, and we shouldn't have become leader
11302 // in the first place. Not much we can do here in this (hypothetical) scenario.
11303
11304 // Do another quick sanity check that we actually have enough data to satisfy the request.
11305 // If not, let's step down and hope a new leader can correct this.
11306 if state.LastSeq < last {
11307 s.Warnf("Catchup for stream '%s > %s' skipped, requested sequence %d was larger than current state: %+v",
11308 mset.account(), mset.name(), seq, state)
11309 node.StepDown()
11310 return
11311 }
11312 }
11313
11314 start := time.Now()
11315 mset.setCatchupPeer(sreq.Peer, last-seq)
11316
11317 var spb int
11318 const minWait = 5 * time.Second
11319
11320 sendNextBatchAndContinue := func(qch chan struct{}) bool {
11321 // Check if we know we will not enter the loop because we are done.
11322 if seq > last {
11323 s.Noticef("Catchup for stream '%s > %s' complete (took %v)", mset.account(), mset.name(), time.Since(start).Round(time.Millisecond))
11324 // EOF
11325 s.sendInternalMsgLocked(sendSubject, _EMPTY_, nil, nil)
11326 return false
11327 }
11328
11329 // If we already sent a batch, we will try to make sure we can at least send a minimum
11330 // batch before sending the next batch.
11331 if spb > 0 {
11332 // Wait til we can send at least 4k
11333 const minBatchWait = int32(4 * 1024)
11334 mw := time.NewTimer(minWait)
11335 for done := maxOutMsgs-atomic.LoadInt32(&outm) > minBatchWait; !done; {
11336 select {
11337 case <-nextBatchC:
11338 done = maxOutMsgs-atomic.LoadInt32(&outm) > minBatchWait
11339 if !done {
11340 // Wait for a small bit.
11341 time.Sleep(100 * time.Millisecond)
11342 } else {
11343 // GC friendly.
11344 mw.Stop()
11345 }
11346 case <-mw.C:
11347 done = true
11348 case <-s.quitCh:
11349 return false
11350 case <-qch:
11351 return false
11352 case <-remoteQuitCh:
11353 return false
11354 }
11355 }
11356 spb = 0
11357 }
11358
11359 // Send an encoded msg.
11360 sendEM := func(em []byte) {
11361 // Place size in reply subject for flow control.
11362 l := int64(len(em))
11363 reply := fmt.Sprintf(ackReplyT, l)
11364 s.gcbAdd(&outb, l)
11365 atomic.AddInt32(&outm, 1)
11366 s.sendInternalMsgLocked(sendSubject, reply, nil, em)
11367 spb++
11368 }
11369
11370 // If we support gap markers.
11371 var dr DeleteRange
11372 drOk := sreq.DeleteRangesOk
11373
11374 // Will send our delete range.
11375 // Should already be checked for being valid.
11376 sendDR := func() {
11377 if dr.Num == 1 {
11378 // Send like a normal skip msg.
11379 sendEM(encodeStreamMsg(_EMPTY_, _EMPTY_, nil, nil, dr.First, 0, false))
11380 } else {
11381 // We have a run, send a gap record. We send these without reply or tracking.
11382 s.sendInternalMsgLocked(sendSubject, _EMPTY_, nil, encodeDeleteRange(&dr))
11383 // Clear out the pending for catchup.
11384 mset.decrementCatchupPeer(sreq.Peer, dr.Num)
11385 }
11386 // Reset always.
11387 dr.First, dr.Num = 0, 0
11388 }
11389
11390 // See if we should use LoadNextMsg instead of walking sequence by sequence if we have an order magnitude more interior deletes.
11391 // Only makes sense with delete range capabilities.
11392 useLoadNext := drOk && (uint64(state.NumDeleted) > 2*state.Msgs || state.NumDeleted > 1_000_000)
11393
11394 var smv StoreMsg
11395 for ; seq <= last && atomic.LoadInt64(&outb) <= maxOutBytes && atomic.LoadInt32(&outm) <= maxOutMsgs && s.gcbBelowMax(); seq++ {
11396 var sm *StoreMsg
11397 var err error
11398 // If we should use load next do so here.
11399 if useLoadNext {
11400 var nseq uint64
11401 sm, nseq, err = mset.store.LoadNextMsg(fwcs, true, seq, &smv)
11402 if err == nil && nseq > seq {
11403 // If we jumped over the requested last sequence, clamp it down.
11404 // Otherwise, we would send too much to the follower.
11405 if nseq > last {
11406 nseq = last
11407 sm = nil
11408 }
11409 dr.First, dr.Num = seq, nseq-seq
11410 // Jump ahead
11411 seq = nseq
11412 } else if err == ErrStoreEOF {
11413 dr.First, dr.Num = seq, last-seq
11414 // Clear EOF here for normal processing.
11415 err = nil
11416 // Jump ahead
11417 seq = last
11418 }
11419 } else {
11420 sm, err = mset.store.LoadMsg(seq, &smv)
11421 }
11422
11423 // if this is not a deleted msg, bail out.
11424 if err != nil && err != ErrStoreMsgNotFound && err != errDeletedMsg {
11425 if err == ErrStoreEOF {
11426 var state StreamState
11427 mset.store.FastState(&state)
11428 if seq > state.LastSeq {
11429 // The snapshot has a larger last sequence then we have. This could be due to a truncation
11430 // when trying to recover after corruption, still not 100% sure. Could be off by 1 too somehow,
11431 // but tested a ton of those with no success.
11432 s.Warnf("Catchup for stream '%s > %s' completed (took %v), but requested sequence %d was larger than current state: %+v",
11433 mset.account(), mset.name(), time.Since(start).Round(time.Millisecond), seq, state)
11434 // Try our best to redo our invalidated snapshot as well.
11435 if n := mset.raftNode(); n != nil {
11436 if snap := mset.stateSnapshot(); snap != nil {
11437 n.InstallSnapshot(snap, true)
11438 }
11439 }
11440 // If we allow gap markers check if we have one pending.
11441 if drOk && dr.First > 0 {
11442 sendDR()
11443 }
11444 // Signal EOF
11445 s.sendInternalMsgLocked(sendSubject, _EMPTY_, nil, nil)
11446 return false
11447 }
11448 }
11449 s.Warnf("Error loading message for catchup '%s > %s': %v", mset.account(), mset.name(), err)
11450 return false
11451 }
11452
11453 if sm != nil {
11454 // If we allow gap markers check if we have one pending.
11455 if drOk && dr.First > 0 {
11456 sendDR()
11457 }
11458 // Send the normal message now.
11459 sendEM(encodeStreamMsgAllowCompress(sm.subj, _EMPTY_, sm.hdr, sm.msg, sm.seq, sm.ts, false))
11460 } else {
11461 if drOk {
11462 if dr.First == 0 {
11463 dr.First, dr.Num = seq, 1
11464 } else {
11465 dr.Num++
11466 }
11467 } else {
11468 // Skip record for deleted msg.
11469 sendEM(encodeStreamMsg(_EMPTY_, _EMPTY_, nil, nil, seq, 0, false))
11470 }
11471 }
11472
11473 // Check if we are done.
11474 if seq == last {
11475 // Need to see if we have a pending delete range.
11476 if drOk && dr.First > 0 {
11477 sendDR()
11478 }
11479 s.Noticef("Catchup for stream '%s > %s' complete (took %v)", mset.account(), mset.name(), time.Since(start).Round(time.Millisecond))
11480 // EOF
11481 s.sendInternalMsgLocked(sendSubject, _EMPTY_, nil, nil)
11482 return false
11483 }
11484 select {
11485 case <-remoteQuitCh:
11486 return false
11487 default:
11488 }
11489 }
11490 if drOk && dr.First > 0 {
11491 sendDR()
11492 }
11493 return true
11494 }
11495
11496 // Check is this stream got closed.
11497 mset.mu.RLock()
11498 qch := mset.qch
11499 mset.mu.RUnlock()
11500 if qch == nil {
11501 return
11502 }
11503
11504 // Run as long as we are still active and need catchup.
11505 // FIXME(dlc) - Purge event? Stream delete?
11506 retryTimer := time.NewTimer(500 * time.Millisecond)
11507 defer stopAndClearTimer(&retryTimer)
11508 for {
11509 // Get this each time, will be non-nil if globally blocked and we will close to wake everyone up.
11510 cbKick := s.cbKickChan()
11511
11512 select {
11513 case <-s.quitCh:
11514 return
11515 case <-qch:
11516 return
11517 case <-remoteQuitCh:
11518 mset.clearCatchupPeer(sreq.Peer)
11519 return
11520 case <-notActive.C:
11521 s.Warnf("Catchup for stream '%s > %s' stalled", mset.account(), mset.name())
11522 // Do NOT clear the catchup peer on a transient inactivity stall, this allows the
11523 // follower to retry without us losing track of it requiring catchup.
11524 return
11525 case <-nextBatchC:
11526 if !sendNextBatchAndContinue(qch) {
11527 mset.clearCatchupPeer(sreq.Peer)
11528 return
11529 }
11530 case <-cbKick:
11531 if !sendNextBatchAndContinue(qch) {
11532 mset.clearCatchupPeer(sreq.Peer)
11533 return
11534 }
11535 case <-retryTimer.C:
11536 if !sendNextBatchAndContinue(qch) {
11537 mset.clearCatchupPeer(sreq.Peer)
11538 return
11539 }
11540 }
11541 retryTimer.Reset(500 * time.Millisecond)
11542 }
11543 }
11544
11545 const jscAllSubj = "$JSC.>"
11546
11547 func syncSubjForStream() string {
11548 return syncSubject("$JSC.SYNC")
11549 }
11550
11551 func syncReplySubject() string {
11552 return syncSubject("$JSC.R")
11553 }
11554
11555 func infoReplySubject() string {
11556 return syncSubject("$JSC.R")
11557 }
11558
11559 func syncAckSubject() string {
11560 return syncSubject("$JSC.ACK") + ".*"
11561 }
11562
11563 func syncSubject(pre string) string {
11564 var sb strings.Builder
11565 sb.WriteString(pre)
11566 sb.WriteByte(btsep)
11567
11568 var b [replySuffixLen]byte
11569 rn := rand.Int63()
11570 for i, l := 0, rn; i < len(b); i++ {
11571 b[i] = digits[l%base]
11572 l /= base
11573 }
11574
11575 sb.Write(b[:])
11576 return sb.String()
11577 }
11578
11579 const (
11580 clusterStreamInfoT = "$JSC.SI.%s.%s"
11581 clusterConsumerInfoT = "$JSC.CI.%s.%s.%s"
11582 jsaUpdatesSubT = "$JSC.ARU.%s.*"
11583 jsaUpdatesPubT = "$JSC.ARU.%s.%s"
11584 )