-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathstream_command.go
2574 lines (2127 loc) · 74.5 KB
/
stream_command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cli
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/choria-io/fisk"
"github.com/dustin/go-humanize"
"github.com/emicklei/dot"
"github.com/google/go-cmp/cmp"
"github.com/gosuri/uiprogress"
"github.com/nats-io/jsm.go"
"github.com/nats-io/jsm.go/api"
"github.com/nats-io/nats.go"
"github.com/xlab/tablewriter"
)
type streamCmd struct {
stream string
force bool
json bool
msgID int64
retentionPolicyS string
inputFile string
outFile string
filterSubject string
showAll bool
destination string
subjects []string
ack bool
storage string
maxMsgLimit int64
maxMsgPerSubjectLimit int64
maxBytesLimitString string
maxBytesLimit int64
maxAgeLimit string
maxMsgSizeString string
maxMsgSize int64
maxConsumers int
reportSortConsumers bool
reportSortMsgs bool
reportSortName bool
reportSortStorage bool
reportRaw bool
reportLimitCluster string
reportLeaderDistrib bool
maxStreams int
discardPolicy string
validateOnly bool
backupDirectory string
showProgress bool
healthCheck bool
snapShotConsumers bool
dupeWindow string
replicas int64
placementCluster string
placementTags []string
peerName string
sources []string
mirror string
interactive bool
purgeKeep uint64
purgeSubject string
purgeSequence uint64
description string
repubSource string
repubDest string
repubHeadersOnly bool
allowRollup bool
allowRollupSet bool
denyDelete bool
denyDeleteSet bool
denyPurge bool
denyPurgeSet bool
allowDirect bool
allowDirectSet bool
fServer string
fCluster string
fEmpty bool
fIdle time.Duration
fCreated time.Duration
fConsumers int
fInvert bool
listNames bool
vwStartId int
vwStartDelta time.Duration
vwPageSize int
vwRaw bool
vwSubject string
dryRun bool
selectedStream *jsm.Stream
nc *nats.Conn
mgr *jsm.Manager
}
type streamStat struct {
Name string
Consumers int
Msgs int64
Bytes uint64
Storage string
Template string
Cluster *api.ClusterInfo
LostBytes uint64
LostMsgs int
Deleted int
Mirror *api.StreamSourceInfo
Sources []*api.StreamSourceInfo
Placement *api.Placement
}
func configureStreamCommand(app commandHost) {
c := &streamCmd{msgID: -1}
addCreateFlags := func(f *fisk.CmdClause, edit bool) {
f.Flag("subjects", "Subjects that are consumed by the Stream").Default().StringsVar(&c.subjects)
f.Flag("description", "Sets a contextual description for the stream").StringVar(&c.description)
if !edit {
f.Flag("storage", "Storage backend to use (file, memory)").EnumVar(&c.storage, "file", "f", "memory", "m")
}
f.Flag("replicas", "When clustered, how many replicas of the data to create").Int64Var(&c.replicas)
f.Flag("tag", "Place the stream on servers that has specific tags (pass multiple times)").StringsVar(&c.placementTags)
f.Flag("tags", "Backward compatibility only, use --tag").Hidden().StringsVar(&c.placementTags)
f.Flag("cluster", "Place the stream on a specific cluster").StringVar(&c.placementCluster)
f.Flag("ack", "Acknowledge publishes").Default("true").BoolVar(&c.ack)
f.Flag("retention", "Defines a retention policy (limits, interest, work)").EnumVar(&c.retentionPolicyS, "limits", "interest", "workq", "work")
f.Flag("discard", "Defines the discard policy (new, old)").EnumVar(&c.discardPolicy, "new", "old")
f.Flag("max-age", "Maximum age of messages to keep").Default("").StringVar(&c.maxAgeLimit)
f.Flag("max-bytes", "Maximum bytes to keep").StringVar(&c.maxBytesLimitString)
f.Flag("max-consumers", "Maximum number of consumers to allow").Default("-1").IntVar(&c.maxConsumers)
f.Flag("max-msg-size", "Maximum size any 1 message may be").StringVar(&c.maxMsgSizeString)
f.Flag("max-msgs", "Maximum amount of messages to keep").Default("0").Int64Var(&c.maxMsgLimit)
f.Flag("max-msgs-per-subject", "Maximum amount of messages to keep per subject").Default("0").Int64Var(&c.maxMsgPerSubjectLimit)
f.Flag("dupe-window", "Duration of the duplicate message tracking window").Default("").StringVar(&c.dupeWindow)
f.Flag("mirror", "Completely mirror another stream").StringVar(&c.mirror)
f.Flag("source", "Source data from other Streams, merging into this one").PlaceHolder("STREAM").StringsVar(&c.sources)
f.Flag("allow-rollup", "Allows roll-ups to be done by publishing messages with special headers").IsSetByUser(&c.allowRollupSet).BoolVar(&c.allowRollup)
f.Flag("deny-delete", "Deny messages from being deleted via the API").IsSetByUser(&c.denyDeleteSet).BoolVar(&c.denyDelete)
f.Flag("deny-purge", "Deny entire stream or subject purges via the API").IsSetByUser(&c.denyPurgeSet).BoolVar(&c.denyPurge)
f.Flag("allow-direct", "Allows fast, direct, access to stream data via the direct get API").IsSetByUser(&c.allowDirectSet).BoolVar(&c.allowDirect)
f.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
f.PreAction(c.parseLimitStrings)
}
str := app.Command("stream", "JetStream Stream management").Alias("str").Alias("st").Alias("ms").Alias("s")
str.Flag("all", "When listing or selecting streams show all streams including system ones").Short('a').UnNegatableBoolVar(&c.showAll)
addCheat("stream", str)
strAdd := str.Command("add", "Create a new Stream").Alias("create").Alias("new").Action(c.addAction)
strAdd.Arg("stream", "Stream name").StringVar(&c.stream)
strAdd.Flag("config", "JSON file to read configuration from").ExistingFileVar(&c.inputFile)
strAdd.Flag("validate", "Only validates the configuration against the official Schema").UnNegatableBoolVar(&c.validateOnly)
strAdd.Flag("output", "Save configuration instead of creating").PlaceHolder("FILE").StringVar(&c.outFile)
addCreateFlags(strAdd, false)
strAdd.Flag("republish-source", "Republish messages to --republish-destination").StringVar(&c.repubSource)
strAdd.Flag("republish-destination", "Republish destination for messages in --republish-source").StringVar(&c.repubDest)
strAdd.Flag("republish-headers", "Republish only message headers, no bodies").UnNegatableBoolVar(&c.repubHeadersOnly)
strLs := str.Command("ls", "List all known Streams").Alias("list").Alias("l").Action(c.lsAction)
strLs.Flag("names", "Show just the stream names").Short('n').UnNegatableBoolVar(&c.listNames)
strLs.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
strReport := str.Command("report", "Reports on Stream statistics").Action(c.reportAction)
strReport.Flag("cluster", "Limit report to streams within a specific cluster").StringVar(&c.reportLimitCluster)
strReport.Flag("consumers", "Sort by number of Consumers").Short('o').UnNegatableBoolVar(&c.reportSortConsumers)
strReport.Flag("messages", "Sort by number of Messages").Short('m').UnNegatableBoolVar(&c.reportSortMsgs)
strReport.Flag("name", "Sort by Stream name").Short('n').UnNegatableBoolVar(&c.reportSortName)
strReport.Flag("storage", "Sort by Storage type").Short('t').UnNegatableBoolVar(&c.reportSortStorage)
strReport.Flag("raw", "Show un-formatted numbers").Short('r').UnNegatableBoolVar(&c.reportRaw)
strReport.Flag("dot", "Produce a GraphViz graph of replication topology").StringVar(&c.outFile)
strReport.Flag("leaders", "Show details about RAFT leaders").Short('l').UnNegatableBoolVar(&c.reportLeaderDistrib)
strFind := str.Command("find", "Finds streams matching certain criteria").Alias("query").Action(c.findAction)
strFind.Flag("server-name", "Display streams present on a regular expression matched server").StringVar(&c.fServer)
strFind.Flag("cluster", "Display streams present on a regular expression matched cluster").StringVar(&c.fCluster)
strFind.Flag("empty", "Display streams with no messages").UnNegatableBoolVar(&c.fEmpty)
strFind.Flag("idle", "Display streams with no new messages or consumer deliveries for a period").PlaceHolder("DURATION").DurationVar(&c.fIdle)
strFind.Flag("created", "Display streams created longer ago than duration").PlaceHolder("DURATION").DurationVar(&c.fCreated)
strFind.Flag("consumers", "Display streams with fewer consumers than threshold").PlaceHolder("THRESHOLD").Default("-1").IntVar(&c.fConsumers)
strFind.Flag("subject", "Filters Streams by those with interest matching a subject or wildcard").StringVar(&c.filterSubject)
strFind.Flag("names", "Show just the stream names").Short('n').UnNegatableBoolVar(&c.listNames)
strFind.Flag("invert", "Invert the check - before becomes after, with becomes without").BoolVar(&c.fInvert)
strInfo := str.Command("info", "Stream information").Alias("nfo").Alias("i").Action(c.infoAction)
strInfo.Arg("stream", "Stream to retrieve information for").StringVar(&c.stream)
strInfo.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
strSubs := str.Command("subjects", "Query subjects held in a stream").Alias("subj").Action(c.subjectsAction)
strSubs.Arg("stream", "Stream name").StringVar(&c.stream)
strSubs.Arg("filter", "Limit the subjects to those matching a filter").Default(">").StringVar(&c.filterSubject)
strSubs.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
strEdit := str.Command("edit", "Edits an existing stream").Alias("update").Action(c.editAction)
strEdit.Arg("stream", "Stream to retrieve edit").StringVar(&c.stream)
strEdit.Flag("config", "JSON file to read configuration from").ExistingFileVar(&c.inputFile)
strEdit.Flag("force", "Force edit without prompting").Short('f').UnNegatableBoolVar(&c.force)
strEdit.Flag("interactive", "Edit the configuring using your editor").Short('i').BoolVar(&c.interactive)
strEdit.Flag("dry-run", "Only shows differences, do not edit the stream").UnNegatableBoolVar(&c.dryRun)
addCreateFlags(strEdit, true)
strRm := str.Command("rm", "Removes a Stream").Alias("delete").Alias("del").Action(c.rmAction)
strRm.Arg("stream", "Stream name").StringVar(&c.stream)
strRm.Flag("force", "Force removal without prompting").Short('f').UnNegatableBoolVar(&c.force)
strPurge := str.Command("purge", "Purge a Stream without deleting it").Action(c.purgeAction)
strPurge.Arg("stream", "Stream name").StringVar(&c.stream)
strPurge.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
strPurge.Flag("force", "Force removal without prompting").Short('f').UnNegatableBoolVar(&c.force)
strPurge.Flag("subject", "Limits the purge to a specific subject").PlaceHolder("SUBJECT").StringVar(&c.purgeSubject)
strPurge.Flag("seq", "Purge up to but not including a specific message sequence").PlaceHolder("SEQUENCE").Uint64Var(&c.purgeSequence)
strPurge.Flag("keep", "Keeps a certain number of messages after the purge").PlaceHolder("MESSAGES").Uint64Var(&c.purgeKeep)
strCopy := str.Command("copy", "Creates a new Stream based on the configuration of another").Alias("cp").Action(c.cpAction)
strCopy.Arg("source", "Source Stream to copy").Required().StringVar(&c.stream)
strCopy.Arg("destination", "New Stream to create").Required().StringVar(&c.destination)
addCreateFlags(strCopy, false)
strRmMsg := str.Command("rmm", "Securely removes an individual message from a Stream").Action(c.rmMsgAction)
strRmMsg.Arg("stream", "Stream name").StringVar(&c.stream)
strRmMsg.Arg("id", "Message Sequence to remove").Int64Var(&c.msgID)
strRmMsg.Flag("force", "Force removal without prompting").Short('f').UnNegatableBoolVar(&c.force)
strView := str.Command("view", "View messages in a stream").Action(c.viewAction)
strView.Arg("stream", "Stream name").StringVar(&c.stream)
strView.Arg("size", "Page size").Default("10").IntVar(&c.vwPageSize)
strView.Flag("id", "Start at a specific message Sequence").IntVar(&c.vwStartId)
strView.Flag("since", "Start at a time delta").DurationVar(&c.vwStartDelta)
strView.Flag("raw", "Show the raw data received").UnNegatableBoolVar(&c.vwRaw)
strView.Flag("subject", "Filter the stream using a subject").StringVar(&c.vwSubject)
strGet := str.Command("get", "Retrieves a specific message from a Stream").Action(c.getAction)
strGet.Arg("stream", "Stream name").StringVar(&c.stream)
strGet.Arg("id", "Message Sequence to retrieve").Int64Var(&c.msgID)
strGet.Flag("last-for", "Retrieves the message for a specific subject").Short('S').PlaceHolder("SUBJECT").StringVar(&c.filterSubject)
strGet.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
strBackup := str.Command("backup", "Creates a backup of a Stream over the NATS network").Alias("snapshot").Action(c.backupAction)
strBackup.Arg("stream", "Stream to backup").Required().StringVar(&c.stream)
strBackup.Arg("target", "Directory to create the backup in").Required().StringVar(&c.backupDirectory)
strBackup.Flag("progress", "Enables or disables progress reporting using a progress bar").Default("true").BoolVar(&c.showProgress)
strBackup.Flag("check", "Checks the Stream for health prior to backup").UnNegatableBoolVar(&c.healthCheck)
strBackup.Flag("consumers", "Enable or disable consumer backups").Default("true").BoolVar(&c.snapShotConsumers)
strRestore := str.Command("restore", "Restore a Stream over the NATS network").Action(c.restoreAction)
strRestore.Arg("file", "The directory holding the backup to restore").Required().ExistingDirVar(&c.backupDirectory)
strRestore.Flag("progress", "Enables or disables progress reporting using a progress bar").Default("true").BoolVar(&c.showProgress)
strRestore.Flag("config", "Load a different configuration when restoring the stream").ExistingFileVar(&c.inputFile)
strRestore.Flag("cluster", "Place the stream in a specific cluster").StringVar(&c.placementCluster)
strRestore.Flag("tag", "Place the stream on servers that has specific tags (pass multiple times)").StringsVar(&c.placementTags)
strSeal := str.Command("seal", "Seals a stream preventing further updates").Action(c.sealAction)
strSeal.Arg("stream", "The name of the Stream to seal").Required().StringVar(&c.stream)
strSeal.Flag("force", "Force sealing without prompting").Short('f').UnNegatableBoolVar(&c.force)
strCluster := str.Command("cluster", "Manages a clustered Stream").Alias("c")
strClusterDown := strCluster.Command("step-down", "Force a new leader election by standing down the current leader").Alias("stepdown").Alias("sd").Alias("elect").Alias("down").Alias("d").Action(c.leaderStandDown)
strClusterDown.Arg("stream", "Stream to act on").StringVar(&c.stream)
strClusterRemovePeer := strCluster.Command("peer-remove", "Removes a peer from the Stream cluster").Alias("pr").Action(c.removePeer)
strClusterRemovePeer.Arg("stream", "The stream to act on").StringVar(&c.stream)
strClusterRemovePeer.Arg("peer", "The name of the peer to remove").StringVar(&c.peerName)
strTemplate := str.Command("template", "Manages Stream Templates").Alias("templ").Alias("t")
strTAdd := strTemplate.Command("create", "Creates a new Stream Template").Alias("add").Alias("new").Action(c.streamTemplateAdd)
strTAdd.Arg("stream", "Template name").StringVar(&c.stream)
strTAdd.Flag("max-streams", "Maximum amount of streams that this template can generate").Default("-1").IntVar(&c.maxStreams)
addCreateFlags(strTAdd, false)
strTInfo := strTemplate.Command("info", "Stream Template information").Alias("nfo").Alias("i").Action(c.streamTemplateInfo)
strTInfo.Arg("template", "Stream Template to retrieve information for").StringVar(&c.stream)
strTInfo.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
strTLs := strTemplate.Command("ls", "List all known Stream Templates").Alias("list").Alias("l").Action(c.streamTemplateLs)
strTLs.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
strTRm := strTemplate.Command("rm", "Removes a Stream Template").Alias("delete").Alias("del").Action(c.streamTemplateRm)
strTRm.Arg("template", "Stream Template name").StringVar(&c.stream)
strTRm.Flag("force", "Force removal without prompting").Short('f').UnNegatableBoolVar(&c.force)
}
func init() {
registerCommand("stream", 16, configureStreamCommand)
}
func (c *streamCmd) subjectsAction(_ *fisk.ParseContext) (err error) {
asked := c.connectAndAskStream()
subs, err := c.mgr.StreamContainedSubjects(c.stream, c.filterSubject)
if err != nil {
return err
}
if c.json {
printJSON(subs)
return nil
}
if asked {
fmt.Println()
}
if len(subs) == 0 {
fmt.Printf("No subjects found matching %s\n", c.filterSubject)
return nil
}
longest := 0
for _, v := range subs {
if len(v) > longest {
longest = len(v)
}
}
cols := 1
format := " %s\n"
switch {
case longest < 20:
cols = 3
format = " %-20s %-20s %-20s\n"
case longest < 30:
cols = 2
format = " %-30s %-30s\n"
}
sliceGroups(subs, cols, func(g []string) {
if cols == 1 {
fmt.Printf(format, g[0])
} else if cols == 2 {
fmt.Printf(format, g[0], g[1])
} else {
fmt.Printf(format, g[0], g[1], g[2])
}
})
return nil
}
func (c *streamCmd) parseLimitStrings(_ *fisk.ParseContext) (err error) {
if c.maxBytesLimitString != "" {
c.maxBytesLimit, err = parseStringAsBytes(c.maxBytesLimitString)
if err != nil {
return err
}
}
if c.maxMsgSizeString != "" {
c.maxMsgSize, err = parseStringAsBytes(c.maxMsgSizeString)
if err != nil {
return err
}
}
return nil
}
func (c *streamCmd) findAction(_ *fisk.ParseContext) (err error) {
c.nc, c.mgr, err = prepareHelper("", natsOpts()...)
if err != nil {
return fmt.Errorf("setup failed: %v", err)
}
opts := []jsm.StreamQueryOpt{}
if c.fServer != "" {
opts = append(opts, jsm.StreamQueryServerName(c.fServer))
}
if c.fCluster != "" {
opts = append(opts, jsm.StreamQueryClusterName(c.fCluster))
}
if c.fEmpty {
opts = append(opts, jsm.StreamQueryWithoutMessages())
}
if c.fIdle > 0 {
opts = append(opts, jsm.StreamQueryIdleLongerThan(c.fIdle))
}
if c.fCreated > 0 {
opts = append(opts, jsm.StreamQueryOlderThan(c.fCreated))
}
if c.fConsumers >= 0 {
opts = append(opts, jsm.StreamQueryFewerConsumersThan(uint(c.fConsumers)))
}
if c.fInvert {
opts = append(opts, jsm.StreamQueryInvert())
}
if c.filterSubject != "" {
opts = append(opts, jsm.StreamQuerySubjectWildcard(c.filterSubject))
}
found, err := c.mgr.QueryStreams(opts...)
if err != nil {
return err
}
out := ""
switch {
case c.json:
out, err = toJSON(found)
case c.listNames:
out = c.renderStreamsAsList(found)
default:
out, err = c.renderStreamsAsTable(found)
}
if err != nil {
return err
}
fmt.Println(out)
return nil
}
func (c *streamCmd) loadStream(stream string) (*jsm.Stream, error) {
if c.selectedStream != nil && c.selectedStream.Name() == stream {
return c.selectedStream, nil
}
return c.mgr.LoadStream(stream)
}
func (c *streamCmd) leaderStandDown(_ *fisk.ParseContext) error {
c.connectAndAskStream()
stream, err := c.loadStream(c.stream)
if err != nil {
return err
}
info, err := stream.LatestInformation()
if err != nil {
return err
}
if info.Cluster == nil {
return fmt.Errorf("stream %q is not clustered", stream.Name())
}
leader := info.Cluster.Leader
log.Printf("Requesting leader step down of %q in a %d peer RAFT group", leader, len(info.Cluster.Replicas)+1)
err = stream.LeaderStepDown()
if err != nil {
return err
}
ctr := 0
start := time.Now()
for range time.NewTimer(500 * time.Millisecond).C {
if ctr == 5 {
return fmt.Errorf("stream did not elect a new leader in time")
}
ctr++
info, err = stream.Information()
if err != nil {
log.Printf("Failed to retrieve Stream State: %s", err)
continue
}
if info.Cluster.Leader != leader {
log.Printf("New leader elected %q", info.Cluster.Leader)
break
}
}
if info.Cluster.Leader == leader {
log.Printf("Leader did not change after %s", time.Since(start).Round(time.Millisecond))
}
fmt.Println()
return c.showStream(stream)
}
func (c *streamCmd) removePeer(_ *fisk.ParseContext) error {
c.connectAndAskStream()
stream, err := c.loadStream(c.stream)
if err != nil {
return err
}
info, err := stream.Information()
if err != nil {
return err
}
if info.Cluster == nil {
return fmt.Errorf("stream %q is not clustered", stream.Name())
}
if c.peerName == "" {
peerNames := []string{info.Cluster.Leader}
for _, r := range info.Cluster.Replicas {
peerNames = append(peerNames, r.Name)
}
err = askOne(&survey.Select{
Message: "Select a Peer",
Options: peerNames,
}, &c.peerName)
if err != nil {
return err
}
}
log.Printf("Removing peer %q", c.peerName)
err = stream.RemoveRAFTPeer(c.peerName)
if err != nil {
return err
}
log.Printf("Requested removal of peer %q", c.peerName)
return nil
}
func (c *streamCmd) viewAction(_ *fisk.ParseContext) error {
if c.vwPageSize > 25 {
c.vwPageSize = 25
}
c.connectAndAskStream()
str, err := c.loadStream(c.stream)
if err != nil {
return err
}
if str.Retention() == api.WorkQueuePolicy {
return fmt.Errorf("work queue stream contents can not be viewed")
}
pops := []jsm.PagerOption{
jsm.PagerSize(c.vwPageSize),
}
switch {
case c.vwStartDelta > 0:
pops = append(pops, jsm.PagerStartDelta(c.vwStartDelta))
case c.vwStartId > 0:
pops = append(pops, jsm.PagerStartId(c.vwStartId))
}
if c.vwSubject != "" {
pops = append(pops, jsm.PagerFilterSubject(c.vwSubject))
}
pgr, err := str.PageContents(pops...)
if err != nil {
return err
}
defer pgr.Close()
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
select {
case <-ctx.Done():
return
case <-sigs:
cancel()
}
}()
for {
msg, last, err := pgr.NextMsg(ctx)
if err != nil && last {
log.Println("Reached apparent end of data")
return nil
}
if err != nil {
return err
}
switch {
case c.vwRaw:
fmt.Println(string(msg.Data))
default:
meta, err := jsm.ParseJSMsgMetadata(msg)
if err == nil {
fmt.Printf("[%d] Subject: %s Received: %s\n", meta.StreamSequence(), msg.Subject, meta.TimeStamp().Format(time.RFC3339))
} else {
fmt.Printf("Subject: %s Reply: %s\n", msg.Subject, msg.Reply)
}
if len(msg.Header) > 0 {
fmt.Println()
for k, vs := range msg.Header {
for _, v := range vs {
fmt.Printf(" %s: %s\n", k, v)
}
}
}
fmt.Println()
if len(msg.Data) == 0 {
fmt.Println("nil body")
} else {
fmt.Println(string(msg.Data))
if !strings.HasSuffix(string(msg.Data), "\n") {
fmt.Println()
}
}
}
if last {
next := false
askOne(&survey.Confirm{Message: "Next Page?", Default: true}, &next)
if !next {
return nil
}
}
}
}
func (c *streamCmd) sealAction(_ *fisk.ParseContext) error {
c.connectAndAskStream()
if !c.force {
ok, err := askConfirmation(fmt.Sprintf("Really seal Stream %s, sealed streams can not be unsealed or modified", c.stream), false)
fisk.FatalIfError(err, "could not obtain confirmation")
if !ok {
return nil
}
}
stream, err := c.loadStream(c.stream)
fisk.FatalIfError(err, "could not seal Stream")
stream.Seal()
fisk.FatalIfError(err, "could not seal Stream")
return c.showStream(stream)
}
func (c *streamCmd) restoreAction(_ *fisk.ParseContext) error {
_, mgr, err := prepareHelper("", natsOpts()...)
fisk.FatalIfError(err, "setup failed")
var bm api.JSApiStreamRestoreRequest
bmj, err := os.ReadFile(filepath.Join(c.backupDirectory, "backup.json"))
fisk.FatalIfError(err, "restore failed")
err = json.Unmarshal(bmj, &bm)
fisk.FatalIfError(err, "restore failed")
var cfg *api.StreamConfig
known, err := mgr.IsKnownStream(bm.Config.Name)
fisk.FatalIfError(err, "Could not check if the stream already exist")
if known {
fisk.Fatalf("Stream %q already exist", bm.Config.Name)
}
var progress *uiprogress.Bar
var bps uint64
cb := func(p jsm.RestoreProgress) {
bps = p.BytesPerSecond()
if progress == nil {
progress = uiprogress.AddBar(p.ChunksToSend()).AppendCompleted().PrependFunc(func(b *uiprogress.Bar) string {
return humanize.IBytes(bps) + "/s"
})
progress.Width = progressWidth()
}
progress.Set(int(p.ChunksSent()))
}
var opts []jsm.SnapshotOption
if c.showProgress {
uiprogress.Start()
opts = append(opts, jsm.RestoreNotify(cb))
} else {
opts = append(opts, jsm.SnapshotDebug())
}
if c.inputFile != "" {
cfg, err := c.loadConfigFile(c.inputFile)
if err != nil {
return err
}
// we need to confirm this new config has the same stream
// name as the snapshot else the server state can get confused
// see https://github.com/nats-io/nats-server/issues/2850
if bm.Config.Name != cfg.Name {
return fmt.Errorf("stream names may not be changed during restore")
}
} else {
cfg = &bm.Config
}
if c.placementCluster != "" || len(c.placementTags) > 0 {
cfg.Placement = &api.Placement{
Cluster: c.placementCluster,
Tags: c.placementTags,
}
}
opts = append(opts, jsm.RestoreConfiguration(*cfg))
fmt.Printf("Starting restore of Stream %q from file %q\n\n", bm.Config.Name, c.backupDirectory)
fp, _, err := mgr.RestoreSnapshotFromDirectory(ctx, bm.Config.Name, c.backupDirectory, opts...)
fisk.FatalIfError(err, "restore failed")
if c.showProgress {
progress.Set(int(fp.ChunksSent()))
uiprogress.Stop()
}
fmt.Println()
fmt.Printf("Restored stream %q in %v\n", bm.Config.Name, fp.EndTime().Sub(fp.StartTime()).Round(time.Second))
fmt.Println()
stream, err := mgr.LoadStream(bm.Config.Name)
fisk.FatalIfError(err, "could not request Stream info")
err = c.showStream(stream)
fisk.FatalIfError(err, "could not show stream")
return nil
}
func backupStream(stream *jsm.Stream, showProgress bool, consumers bool, check bool, target string) error {
first := true
inprogress := true
pmu := sync.Mutex{}
var bar *uiprogress.Bar
var bps uint64
var progress *uiprogress.Progress
expected := 1
timedOut := false
ctx, cancel := context.WithCancel(ctx)
defer cancel()
timeout := time.AfterFunc(5*time.Second, func() {
cancel()
timedOut = true
})
var received uint32
cb := func(p jsm.SnapshotProgress) {
if bar == nil && showProgress {
if p.BytesExpected() > 0 {
expected = int(p.BytesExpected())
}
bar = progress.AddBar(expected).AppendCompleted().PrependFunc(func(b *uiprogress.Bar) string {
return humanize.IBytes(bps) + "/s"
})
bar.Width = progressWidth()
}
if first {
fmt.Printf("Starting backup of Stream %q with %s\n", stream.Name(), humanize.IBytes(p.BytesExpected()))
if showProgress {
fmt.Println()
}
if p.HealthCheck() {
fmt.Printf("Health Check was requested, this can take a long time without progress reports\n\n")
}
first = false
}
if p.ChunksReceived() != received {
timeout.Reset(5 * time.Second)
received = p.ChunksReceived()
}
bps = p.BytesPerSecond()
if showProgress {
bar.Set(int(p.BytesReceived()))
}
if p.Finished() {
pmu.Lock()
if inprogress {
if showProgress {
progress.Stop()
}
inprogress = false
}
pmu.Unlock()
}
}
var opts []jsm.SnapshotOption
if consumers {
opts = append(opts, jsm.SnapshotConsumers())
}
if showProgress {
progress = uiprogress.New()
progress.Start()
}
opts = append(opts, jsm.SnapshotNotify(cb))
if check {
opts = append(opts, jsm.SnapshotHealthCheck())
}
fp, err := stream.SnapshotToDirectory(ctx, target, opts...)
if err != nil {
return err
}
pmu.Lock()
if showProgress && inprogress {
bar.Set(int(fp.BytesReceived()))
uiprogress.Stop()
inprogress = false
}
pmu.Unlock()
fmt.Println()
if timedOut {
return fmt.Errorf("backup timed out after receiving no data for a long period")
}
fmt.Printf("Received %s compressed data in %d chunks for stream %q in %v, %s uncompressed \n", humanize.IBytes(fp.BytesReceived()), fp.ChunksReceived(), stream.Name(), fp.EndTime().Sub(fp.StartTime()).Round(time.Millisecond), humanize.IBytes(fp.UncompressedBytesReceived()))
return nil
}
func (c *streamCmd) backupAction(_ *fisk.ParseContext) error {
var err error
c.nc, c.mgr, err = prepareHelper("", natsOpts()...)
fisk.FatalIfError(err, "setup failed")
stream, err := c.loadStream(c.stream)
if err != nil {
return err
}
err = backupStream(stream, c.showProgress, c.snapShotConsumers, c.healthCheck, c.backupDirectory)
fisk.FatalIfError(err, "snapshot failed")
return nil
}
func (c *streamCmd) streamTemplateRm(_ *fisk.ParseContext) error {
_, mgr, err := prepareHelper("", natsOpts()...)
fisk.FatalIfError(err, "setup failed")
c.stream, err = selectStreamTemplate(mgr, c.stream, c.force)
fisk.FatalIfError(err, "could not pick a Stream Template to operate on")
template, err := mgr.LoadStreamTemplate(c.stream)
fisk.FatalIfError(err, "could not load Stream Template")
if !c.force {
ok, err := askConfirmation(fmt.Sprintf("Really delete Stream Template %q, this will remove all managed Streams this template created as well", c.stream), false)
fisk.FatalIfError(err, "could not obtain confirmation")
if !ok {
return nil
}
}
err = template.Delete()
fisk.FatalIfError(err, "could not delete Stream Template")
return nil
}
func (c *streamCmd) streamTemplateAdd(pc *fisk.ParseContext) (err error) {
cfg := c.prepareConfig(pc, false)
if c.maxStreams == -1 {
err = askOne(&survey.Input{
Message: "Maximum Streams",
}, &c.maxStreams, survey.WithValidator(survey.Required))
fisk.FatalIfError(err, "invalid input")
}
if c.maxStreams < 0 {
fisk.Fatalf("Maximum Streams can not be negative")
}
cfg.Name = ""
_, mgr, err := prepareHelper("", natsOpts()...)
fisk.FatalIfError(err, "could not create Stream")
_, err = mgr.NewStreamTemplate(c.stream, uint32(c.maxStreams), cfg)
fisk.FatalIfError(err, "could not create Stream Template")
fmt.Printf("Stream Template %s was created\n\n", c.stream)
return c.streamTemplateInfo(pc)
}
func (c *streamCmd) streamTemplateInfo(_ *fisk.ParseContext) error {
_, mgr, err := prepareHelper("", natsOpts()...)
fisk.FatalIfError(err, "setup failed")
c.stream, err = selectStreamTemplate(mgr, c.stream, c.force)
fisk.FatalIfError(err, "could not pick a Stream Template to operate on")
info, err := mgr.LoadStreamTemplate(c.stream)
fisk.FatalIfError(err, "could not load Stream Template %q", c.stream)
if c.json {
err = printJSON(info.Configuration())
fisk.FatalIfError(err, "could not display info")
return nil
}
fmt.Printf("Information for Stream Template %s\n", c.stream)
fmt.Println()
c.showStreamConfig(info.StreamConfiguration())
fmt.Printf(" Maximum Streams: %d\n", info.MaxStreams())
fmt.Println()
fmt.Println("Managed Streams:")
fmt.Println()
if len(info.Streams()) == 0 {
fmt.Println(" No Streams have been defined by this template")
} else {
managed := info.Streams()
sort.Strings(managed)
for _, n := range managed {
fmt.Printf(" %s\n", n)
}
}
fmt.Println()
return nil
}
func (c *streamCmd) streamTemplateLs(_ *fisk.ParseContext) error {
_, mgr, err := prepareHelper("", natsOpts()...)
fisk.FatalIfError(err, "setup failed")
names, err := mgr.StreamTemplateNames()
fisk.FatalIfError(err, "could not list Stream Templates")
if c.json {
err = printJSON(names)
fisk.FatalIfError(err, "could not display Stream Templates")
return nil
}
if len(names) == 0 {
fmt.Println("No Streams Templates defined")
return nil
}
fmt.Println("Stream Templates:")
fmt.Println()
for _, t := range names {
fmt.Printf("\t%s\n", t)
}
fmt.Println()