-
Notifications
You must be signed in to change notification settings - Fork 94
/
consumer_command.go
1872 lines (1550 loc) · 53.6 KB
/
consumer_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 2019 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"
"math"
"math/rand"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/choria-io/fisk"
"github.com/dustin/go-humanize"
"github.com/google/go-cmp/cmp"
"github.com/nats-io/jsm.go/api"
"github.com/nats-io/nats.go"
"github.com/nats-io/jsm.go"
)
type consumerCmd struct {
consumer string
stream string
json bool
listNames bool
force bool
ack bool
ackSetByUser bool
term bool
raw bool
destination string
inputFile string
outFile string
showAll bool
acceptDefaults bool
selectedConsumer *jsm.Consumer
ackPolicy string
ackWait time.Duration
bpsRateLimit uint64
delivery string
ephemeral bool
filterSubjects []string
idleHeartbeat string
maxAckPending int
maxDeliver int
maxWaiting int
deliveryGroup string
pull bool
pullCount int
replayPolicy string
reportLeaderDistrib bool
samplePct int
startPolicy string
validateOnly bool
description string
inactiveThreshold time.Duration
maxPullExpire time.Duration
maxPullBytes int
maxPullBatch int
backoffMode string
backoffSteps uint
backoffMin time.Duration
backoffMax time.Duration
replicas int
memory bool
hdrsOnly bool
hdrsOnlySet bool
fc bool
fcSet bool
metadataIsSet bool
metadata map[string]string
pauseUntil string
dryRun bool
mgr *jsm.Manager
nc *nats.Conn
nak bool
}
func configureConsumerCommand(app commandHost) {
c := &consumerCmd{metadata: map[string]string{}}
addCreateFlags := func(f *fisk.CmdClause, edit bool) {
if !edit {
f.Flag("ack", "Acknowledgment policy (none, all, explicit)").StringVar(&c.ackPolicy)
f.Flag("bps", "Restrict message delivery to a certain bit per second").Default("0").Uint64Var(&c.bpsRateLimit)
}
f.Flag("backoff", "Creates a consumer backoff policy using a specific pre-written algorithm (none, linear)").PlaceHolder("MODE").EnumVar(&c.backoffMode, "linear", "none")
f.Flag("backoff-steps", "Number of steps to use when creating the backoff policy").PlaceHolder("STEPS").Default("10").UintVar(&c.backoffSteps)
f.Flag("backoff-min", "The shortest backoff period that will be generated").PlaceHolder("MIN").Default("1m").DurationVar(&c.backoffMin)
f.Flag("backoff-max", "The longest backoff period that will be generated").PlaceHolder("MAX").Default("20m").DurationVar(&c.backoffMax)
if !edit {
f.Flag("deliver", "Start policy (all, new, last, subject, 1h, msg sequence)").PlaceHolder("POLICY").StringVar(&c.startPolicy)
f.Flag("deliver-group", "Delivers push messages only to subscriptions matching this group").Default("_unset_").PlaceHolder("GROUP").StringVar(&c.deliveryGroup)
}
f.Flag("description", "Sets a contextual description for the consumer").StringVar(&c.description)
if !edit {
f.Flag("ephemeral", "Create an ephemeral Consumer").UnNegatableBoolVar(&c.ephemeral)
}
f.Flag("filter", "Filter Stream by subjects").PlaceHolder("SUBJECTS").StringsVar(&c.filterSubjects)
if !edit {
f.Flag("flow-control", "Enable Push consumer flow control").IsSetByUser(&c.fcSet).UnNegatableBoolVar(&c.fc)
f.Flag("heartbeat", "Enable idle Push consumer heartbeats (-1 disable)").StringVar(&c.idleHeartbeat)
}
f.Flag("headers-only", "Deliver only headers and no bodies").IsSetByUser(&c.hdrsOnlySet).BoolVar(&c.hdrsOnly)
f.Flag("max-deliver", "Maximum amount of times a message will be delivered").PlaceHolder("TRIES").IntVar(&c.maxDeliver)
f.Flag("max-outstanding", "Maximum pending Acks before consumers are paused").Hidden().Default("-1").IntVar(&c.maxAckPending)
f.Flag("max-pending", "Maximum pending Acks before consumers are paused").Default("-1").IntVar(&c.maxAckPending)
f.Flag("max-waiting", "Maximum number of outstanding pulls allowed").PlaceHolder("PULLS").IntVar(&c.maxWaiting)
f.Flag("max-pull-batch", "Maximum size batch size for a pull request to accept").PlaceHolder("BATCH_SIZE").IntVar(&c.maxPullBatch)
f.Flag("max-pull-expire", "Maximum expire duration for a pull request to accept").PlaceHolder("EXPIRES").DurationVar(&c.maxPullExpire)
f.Flag("max-pull-bytes", "Maximum max bytes for a pull request to accept").PlaceHolder("BYTES").IntVar(&c.maxPullBytes)
if !edit {
f.Flag("pull", "Deliver messages in 'pull' mode").UnNegatableBoolVar(&c.pull)
f.Flag("replay", "Replay Policy (instant, original)").PlaceHolder("POLICY").EnumVar(&c.replayPolicy, "instant", "original")
}
f.Flag("sample", "Percentage of requests to sample for monitoring purposes").Default("-1").IntVar(&c.samplePct)
f.Flag("target", "Push based delivery target subject").PlaceHolder("SUBJECT").StringVar(&c.delivery)
f.Flag("wait", "Acknowledgment waiting time").Default("-1s").DurationVar(&c.ackWait)
if !edit {
f.Flag("inactive-threshold", "How long to allow an ephemeral consumer to be idle before removing it").PlaceHolder("THRESHOLD").DurationVar(&c.inactiveThreshold)
f.Flag("memory", "Force the consumer state to be stored in memory rather than inherit from the stream").UnNegatableBoolVar(&c.memory)
}
f.Flag("replicas", "Sets a custom replica count rather than inherit from the stream").IntVar(&c.replicas)
f.Flag("metadata", "Adds metadata to the stream").PlaceHolder("META").IsSetByUser(&c.metadataIsSet).StringMapVar(&c.metadata)
if !edit {
f.Flag("pause", fmt.Sprintf("Pause the consumer for a duration after start or until a specific timestamp (eg %s)", time.Now().Format(time.DateTime))).StringVar(&c.pauseUntil)
}
}
cons := app.Command("consumer", "JetStream Consumer management").Alias("con").Alias("obs").Alias("c")
addCheat("consumer", cons)
cons.Flag("all", "Operate on all streams including system ones").Short('a').UnNegatableBoolVar(&c.showAll)
consAdd := cons.Command("add", "Creates a new Consumer").Alias("create").Alias("new").Action(c.createAction)
consAdd.Arg("stream", "Stream name").StringVar(&c.stream)
consAdd.Arg("consumer", "Consumer name").StringVar(&c.consumer)
consAdd.Flag("config", "JSON file to read configuration from").ExistingFileVar(&c.inputFile)
consAdd.Flag("validate", "Only validates the configuration against the official Schema").UnNegatableBoolVar(&c.validateOnly)
consAdd.Flag("output", "Save configuration instead of creating").PlaceHolder("FILE").StringVar(&c.outFile)
addCreateFlags(consAdd, false)
consAdd.Flag("defaults", "Accept default values for all prompts").UnNegatableBoolVar(&c.acceptDefaults)
edit := cons.Command("edit", "Edits the configuration of a consumer").Alias("update").Action(c.editAction)
edit.Arg("stream", "Stream name").StringVar(&c.stream)
edit.Arg("consumer", "Consumer name").StringVar(&c.consumer)
edit.Flag("config", "JSON file to read configuration from").ExistingFileVar(&c.inputFile)
edit.Flag("force", "Force removal without prompting").Short('f').UnNegatableBoolVar(&c.force)
edit.Flag("dry-run", "Only shows differences, do not edit the stream").UnNegatableBoolVar(&c.dryRun)
addCreateFlags(edit, true)
consLs := cons.Command("ls", "List known Consumers").Alias("list").Action(c.lsAction)
consLs.Arg("stream", "Stream name").StringVar(&c.stream)
consLs.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
consLs.Flag("names", "Show just the consumer names").Short('n').UnNegatableBoolVar(&c.listNames)
consLs.Flag("no-select", "Do not select consumers from a list").Default("false").UnNegatableBoolVar(&c.force)
consInfo := cons.Command("info", "Consumer information").Alias("nfo").Action(c.infoAction)
consInfo.Arg("stream", "Stream name").StringVar(&c.stream)
consInfo.Arg("consumer", "Consumer name").StringVar(&c.consumer)
consInfo.Flag("json", "Produce JSON output").Short('j').UnNegatableBoolVar(&c.json)
consInfo.Flag("no-select", "Do not select consumers from a list").Default("false").UnNegatableBoolVar(&c.force)
consRm := cons.Command("rm", "Removes a Consumer").Alias("delete").Alias("del").Action(c.rmAction)
consRm.Arg("stream", "Stream name").StringVar(&c.stream)
consRm.Arg("consumer", "Consumer name").StringVar(&c.consumer)
consRm.Flag("force", "Force removal without prompting").Short('f').UnNegatableBoolVar(&c.force)
consCp := cons.Command("copy", "Creates a new Consumer based on the configuration of another").Alias("cp").Action(c.cpAction)
consCp.Arg("stream", "Stream name").Required().StringVar(&c.stream)
consCp.Arg("source", "Source Consumer name").Required().StringVar(&c.consumer)
consCp.Arg("destination", "Destination Consumer name").Required().StringVar(&c.destination)
addCreateFlags(consCp, false)
consNext := cons.Command("next", "Retrieves messages from Pull Consumers without interactive prompts").Action(c.nextAction)
consNext.Arg("stream", "Stream name").Required().StringVar(&c.stream)
consNext.Arg("consumer", "Consumer name").Required().StringVar(&c.consumer)
consNext.Flag("ack", "Acknowledge received message").Default("true").IsSetByUser(&c.ackSetByUser).BoolVar(&c.ack)
consNext.Flag("nak", "Perform a Negative Acknowledgement on the message").UnNegatableBoolVar(&c.nak)
consNext.Flag("term", "Terms the message").Default("false").UnNegatableBoolVar(&c.term)
consNext.Flag("raw", "Show only the message").Short('r').UnNegatableBoolVar(&c.raw)
consNext.Flag("wait", "Wait up to this period to acknowledge messages").DurationVar(&c.ackWait)
consNext.Flag("count", "Number of messages to try to fetch from the pull consumer").Default("1").IntVar(&c.pullCount)
consSub := cons.Command("sub", "Retrieves messages from Consumers").Action(c.subAction)
consSub.Arg("stream", "Stream name").StringVar(&c.stream)
consSub.Arg("consumer", "Consumer name").StringVar(&c.consumer)
consSub.Flag("ack", "Acknowledge received message").Default("true").BoolVar(&c.ack)
consSub.Flag("raw", "Show only the message").Short('r').UnNegatableBoolVar(&c.raw)
consSub.Flag("deliver-group", "Deliver group of the consumer").StringVar(&c.deliveryGroup)
conPause := cons.Command("pause", "Pause a consumer until a later time").Action(c.pauseAction)
conPause.Arg("stream", "Stream name").StringVar(&c.stream)
conPause.Arg("consumer", "Consumer name").StringVar(&c.consumer)
conPause.Arg("until", fmt.Sprintf("Pause until a specific time (eg %s)", time.Now().UTC().Format(time.DateTime))).PlaceHolder("TIME").StringVar(&c.pauseUntil)
conPause.Flag("force", "Force pause without prompting").Short('f').UnNegatableBoolVar(&c.force)
conResume := cons.Command("resume", "Resume a paused consumer").Action(c.resumeAction)
conResume.Arg("stream", "Stream name").StringVar(&c.stream)
conResume.Arg("consumer", "Consumer name").StringVar(&c.consumer)
conResume.Flag("force", "Force resume without prompting").Short('f').UnNegatableBoolVar(&c.force)
conReport := cons.Command("report", "Reports on Consumer statistics").Action(c.reportAction)
conReport.Arg("stream", "Stream name").StringVar(&c.stream)
conReport.Flag("raw", "Show un-formatted numbers").Short('r').UnNegatableBoolVar(&c.raw)
conReport.Flag("leaders", "Show details about the leaders").Short('l').UnNegatableBoolVar(&c.reportLeaderDistrib)
conCluster := cons.Command("cluster", "Manages a clustered Consumer").Alias("c")
conClusterDown := conCluster.Command("step-down", "Force a new leader election by standing down the current leader").Alias("elect").Alias("down").Alias("d").Action(c.leaderStandDown)
conClusterDown.Arg("stream", "Stream to act on").StringVar(&c.stream)
conClusterDown.Arg("consumer", "Consumer to act on").StringVar(&c.consumer)
}
func init() {
registerCommand("consumer", 4, configureConsumerCommand)
}
func (c *consumerCmd) leaderStandDown(_ *fisk.ParseContext) error {
c.connectAndSetup(true, true)
consumer, err := c.mgr.LoadConsumer(c.stream, c.consumer)
if err != nil {
return err
}
info, err := consumer.LatestState()
if err != nil {
return err
}
if info.Cluster == nil {
return fmt.Errorf("consumer %q > %q is not clustered", consumer.StreamName(), consumer.Name())
}
leader := info.Cluster.Leader
if leader == "" {
return fmt.Errorf("consumer has no current leader")
}
log.Printf("Requesting leader step down of %q in a %d peer RAFT group", leader, len(info.Cluster.Replicas)+1)
err = consumer.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("consumer did not elect a new leader in time")
}
ctr++
info, err = consumer.State()
if err != nil {
log.Printf("Failed to retrieve Consumer State: %s", err)
continue
}
if info.Cluster == nil {
log.Printf("Failed to retrieve Consumer State: no cluster information received")
continue
}
if info.Cluster.Leader != leader {
log.Printf("New leader elected %q", info.Cluster.Leader)
break
}
}
switch {
case info.Cluster == nil:
log.Printf("Consumer did not elect a leader after %s", time.Since(start).Round(time.Millisecond))
case info.Cluster.Leader == leader:
log.Printf("Leader did not change after %s", time.Since(start).Round(time.Millisecond))
}
fmt.Println()
c.showConsumer(consumer)
return nil
}
func (c *consumerCmd) editAction(pc *fisk.ParseContext) error {
c.connectAndSetup(true, true)
var err error
if c.selectedConsumer == nil {
c.selectedConsumer, err = c.mgr.LoadConsumer(c.stream, c.consumer)
fisk.FatalIfError(err, "could not load Consumer")
}
if !c.selectedConsumer.IsDurable() {
return fmt.Errorf("only durable consumers can be edited")
}
// lazy deep copy
t := c.selectedConsumer.Configuration()
tj, err := json.Marshal(t)
if err != nil {
return err
}
var ncfg api.ConsumerConfig
if c.inputFile != "" {
cf, err := os.ReadFile(c.inputFile)
if err != nil {
return err
}
err = json.Unmarshal(cf, &ncfg)
if err != nil {
return err
}
} else {
err = json.Unmarshal(tj, &ncfg)
if err != nil {
return err
}
if c.description != "" {
ncfg.Description = c.description
}
if c.maxDeliver != 0 {
ncfg.MaxDeliver = c.maxDeliver
}
if c.maxAckPending != -1 {
ncfg.MaxAckPending = c.maxAckPending
}
if c.ackWait != -1*time.Second {
ncfg.AckWait = c.ackWait
}
if c.maxWaiting != 0 {
ncfg.MaxWaiting = c.maxWaiting
}
if c.samplePct != -1 {
ncfg.SampleFrequency = c.sampleFreqFromInt(c.samplePct)
}
if c.maxPullBatch > 0 {
ncfg.MaxRequestBatch = c.maxPullBatch
}
if c.maxPullExpire > 0 {
ncfg.MaxRequestExpires = c.maxPullExpire
}
if c.maxPullBytes > 0 {
ncfg.MaxRequestMaxBytes = c.maxPullBytes
}
if c.backoffMode != "" {
ncfg.BackOff, err = c.backoffPolicy()
if err != nil {
return fmt.Errorf("could not determine backoff policy: %v", err)
}
}
if c.delivery != "" {
ncfg.DeliverSubject = c.delivery
}
if c.hdrsOnlySet {
ncfg.HeadersOnly = c.hdrsOnly
}
if len(c.filterSubjects) == 1 {
ncfg.FilterSubject = c.filterSubjects[0]
ncfg.FilterSubjects = nil
} else if len(c.filterSubjects) > 1 {
ncfg.FilterSubjects = c.filterSubjects
ncfg.FilterSubject = ""
}
if c.replicas > 0 {
ncfg.Replicas = c.replicas
}
if c.metadataIsSet {
ncfg.Metadata = c.metadata
}
}
if len(ncfg.BackOff) > 0 && ncfg.AckWait != t.AckWait {
return fmt.Errorf("consumers with backoff policies do not support editing Ack Wait")
}
// sort strings to subject lists that only differ in ordering is considered equal
sorter := cmp.Transformer("Sort", func(in []string) []string {
out := append([]string(nil), in...)
sort.Strings(out)
return out
})
diff := cmp.Diff(c.selectedConsumer.Configuration(), ncfg, sorter)
if diff == "" {
if !c.dryRun {
fmt.Println("No difference in configuration")
}
return nil
}
fmt.Printf("Differences (-old +new):\n%s", diff)
if c.dryRun {
os.Exit(1)
}
if !c.force {
ok, err := askConfirmation(fmt.Sprintf("Really edit Consumer %s > %s", c.stream, c.consumer), false)
fisk.FatalIfError(err, "could not obtain confirmation")
if !ok {
return nil
}
}
cons, err := c.mgr.NewConsumerFromDefault(c.stream, ncfg)
if err != nil {
return err
}
c.showConsumer(cons)
return nil
}
func (c *consumerCmd) backoffPolicy() ([]time.Duration, error) {
if c.backoffMode == "none" {
return nil, nil
}
if c.backoffMode == "" || c.backoffSteps == 0 || c.backoffMin == 0 || c.backoffMax == 0 {
return nil, fmt.Errorf("required policy properties not supplied")
}
switch c.backoffMode {
case "linear":
return jsm.LinearBackoffPeriods(c.backoffSteps, c.backoffMin, c.backoffMax)
default:
return nil, fmt.Errorf("invalid backoff mode %q", c.backoffMode)
}
}
func (c *consumerCmd) rmAction(_ *fisk.ParseContext) error {
var err error
if c.force {
if c.stream == "" || c.consumer == "" {
return fmt.Errorf("--force requires a stream and consumer name")
}
c.nc, c.mgr, err = prepareHelper("", natsOpts()...)
fisk.FatalIfError(err, "setup failed")
err = c.mgr.DeleteConsumer(c.stream, c.consumer)
if err != nil {
if err == context.DeadlineExceeded {
fmt.Println("Delete failed due to timeout, the stream or consumer might not exist or be in an unmanageable state")
}
}
return err
}
c.connectAndSetup(true, true)
ok, err := askConfirmation(fmt.Sprintf("Really delete Consumer %s > %s", c.stream, c.consumer), false)
fisk.FatalIfError(err, "could not obtain confirmation")
if !ok {
return nil
}
if c.selectedConsumer == nil {
c.selectedConsumer, err = c.mgr.LoadConsumer(c.stream, c.consumer)
fisk.FatalIfError(err, "could not load Consumer")
}
return c.selectedConsumer.Delete()
}
func (c *consumerCmd) lsAction(pc *fisk.ParseContext) error {
c.connectAndSetup(true, false)
stream, err := c.mgr.LoadStream(c.stream)
fisk.FatalIfError(err, "could not load Consumers")
consumers, err := stream.ConsumerNames()
fisk.FatalIfError(err, "could not load Consumers")
if c.json {
err = printJSON(consumers)
fisk.FatalIfError(err, "could not display Consumers")
return nil
}
if c.listNames {
for _, sc := range consumers {
fmt.Println(sc)
}
return nil
}
if len(consumers) == 0 {
fmt.Println("No Consumers defined")
return nil
}
fmt.Printf("Consumers for Stream %s:\n", c.stream)
fmt.Println()
for _, sc := range consumers {
fmt.Printf("\t%s\n", sc)
}
fmt.Println()
return nil
}
func (c *consumerCmd) showConsumer(consumer *jsm.Consumer) {
config := consumer.Configuration()
state, err := consumer.LatestState()
fisk.FatalIfError(err, "could not load Consumer %s > %s", c.stream, c.consumer)
c.showInfo(config, state)
}
func (c *consumerCmd) renderBackoff(bo []time.Duration) string {
if len(bo) == 0 {
return "unset"
}
var times []string
if len(bo) > 15 {
for _, d := range bo[:5] {
times = append(times, d.String())
}
times = append(times, "...")
for _, d := range bo[len(bo)-5:] {
times = append(times, d.String())
}
return fmt.Sprintf("%s (%d total)", f(times), len(bo))
} else {
for _, p := range bo {
times = append(times, p.String())
}
return f(times)
}
}
func (c *consumerCmd) showInfo(config api.ConsumerConfig, state api.ConsumerInfo) {
if c.json {
printJSON(state)
return
}
cols := newColumns(fmt.Sprintf("Information for Consumer %s > %s created %s", state.Stream, state.Name, state.Created.Local().Format(time.RFC3339)))
cols.AddSectionTitle("Configuration")
cols.AddRowIfNotEmpty("Name", config.Name)
cols.AddRowIf("Durable Name", config.Durable, config.Durable != "" && config.Durable != config.Name)
cols.AddRowIfNotEmpty("Description", config.Description)
if config.DeliverSubject != "" {
cols.AddRow("Delivery Subject", config.DeliverSubject)
} else {
cols.AddRow("Pull Mode", true)
}
if config.FilterSubject != "" {
cols.AddRow("Filter Subject", config.FilterSubject)
} else if len(config.FilterSubjects) > 0 {
cols.AddRow("Filter Subjects", config.FilterSubjects)
}
switch config.DeliverPolicy {
case api.DeliverAll:
cols.AddRow("Deliver Policy", "All")
case api.DeliverLast:
cols.AddRow("Deliver Policy", "Last")
case api.DeliverNew:
cols.AddRow("Deliver Policy", "New")
case api.DeliverLastPerSubject:
cols.AddRow("Deliver Policy", "Last Per Subject")
case api.DeliverByStartTime:
cols.AddRowf("Deliver Policy", "Since %s", config.OptStartTime)
case api.DeliverByStartSequence:
cols.AddRowf("Deliver Policy", "From Sequence %d", config.OptStartSeq)
}
cols.AddRowIf("Deliver Queue Group", config.DeliverGroup, config.DeliverGroup != "" && config.DeliverSubject != "")
cols.AddRow("Ack Policy", config.AckPolicy.String())
cols.AddRowIf("Ack Wait", config.AckWait, config.AckPolicy != api.AckNone)
cols.AddRow("Replay Policy", config.ReplayPolicy.String())
cols.AddRowIf("Maximum Deliveries", config.MaxDeliver, config.MaxDeliver != -1)
cols.AddRowIfNotEmpty("Sampling Rate", config.SampleFrequency)
cols.AddRowIf("Rate Limit", fmt.Sprintf("%s / second", humanize.IBytes(config.RateLimit/8)), config.RateLimit > 0)
cols.AddRowIf("Max Ack Pending", config.MaxAckPending, config.MaxAckPending > 0)
cols.AddRowIf("Max Waiting Pulls", int64(config.MaxWaiting), config.MaxWaiting > 0)
cols.AddRowIf("Idle Heartbeat", config.Heartbeat, config.Heartbeat > 0)
cols.AddRowIf("Flow Control", config.FlowControl, config.DeliverSubject != "")
cols.AddRowIf("Headers Only", true, config.HeadersOnly)
cols.AddRowIf("Inactive Threshold", config.InactiveThreshold, config.InactiveThreshold > 0 && config.DeliverSubject == "")
cols.AddRowIf("Max Pull Expire", config.MaxRequestExpires, config.MaxRequestExpires > 0)
cols.AddRowIf("Max Pull Batch", config.MaxRequestBatch, config.MaxRequestBatch > 0)
cols.AddRowIf("Max Pull MaxBytes", config.MaxRequestMaxBytes, config.MaxRequestMaxBytes > 0)
cols.AddRowIf("Backoff", c.renderBackoff(config.BackOff), len(config.BackOff) > 0)
cols.AddRowIf("Replicas", config.Replicas, config.Replicas > 0)
cols.AddRowIf("Memory Storage", true, config.MemoryStorage)
if state.Paused {
cols.AddRowf("Paused Until Deadline", "%s (%s remaining)", f(config.PauseUntil), state.PauseRemaining.Round(time.Second))
} else {
cols.AddRowIf("Paused Until Deadline", fmt.Sprintf("%s (passed)", f(config.PauseUntil)), !config.PauseUntil.IsZero())
}
if len(config.Metadata) > 0 {
cols.AddSectionTitle("Metadata")
maxLen := progressWidth()
for k, v := range config.Metadata {
if len(v) > maxLen && maxLen > 20 {
w := maxLen/2 - 10
v = fmt.Sprintf("%v ... %v", v[0:w], v[len(v)-w:])
}
cols.AddRow(k, v)
}
}
if state.Cluster != nil && state.Cluster.Name != "" {
cols.AddSectionTitle("Cluster Information")
cols.AddRow("Name", state.Cluster.Name)
cols.AddRowIfNotEmpty("Raft Group", state.Cluster.RaftGroup)
cols.AddRow("Leader", state.Cluster.Leader)
for _, r := range state.Cluster.Replicas {
since := fmt.Sprintf("seen %s ago", f(r.Active))
if r.Active == 0 || r.Active == math.MaxInt64 {
since = "not seen"
}
if r.Current {
cols.AddRowf("Replica", "%s, current, %s", r.Name, since)
} else {
cols.AddRowf("Replica", "%s, outdated, %s", r.Name, since)
}
}
}
cols.AddSectionTitle("State")
if state.Delivered.Last == nil {
cols.AddRowf("Last Delivered Message", "Consumer sequence: %s Stream sequence: %s", f(state.Delivered.Consumer), f(state.Delivered.Stream))
} else {
cols.AddRowf("Last Delivered Message", "Consumer sequence: %s Stream sequence: %s Last delivery: %s ago", f(state.Delivered.Consumer), f(state.Delivered.Stream), f(sinceRefOrNow(state.TimeStamp, *state.Delivered.Last)))
}
if config.AckPolicy != api.AckNone {
if state.AckFloor.Last == nil {
cols.AddRowf("Acknowledgment Floor", "Consumer sequence: %s Stream sequence: %s", f(state.AckFloor.Consumer), f(state.AckFloor.Stream))
} else {
cols.AddRowf("Acknowledgment Floor", "Consumer sequence: %s Stream sequence: %s Last Ack: %s ago", f(state.AckFloor.Consumer), f(state.AckFloor.Stream), f(sinceRefOrNow(state.TimeStamp, *state.AckFloor.Last)))
}
if config.MaxAckPending > 0 {
cols.AddRowf("Outstanding Acks", "%s out of maximum %s", f(state.NumAckPending), f(config.MaxAckPending))
} else {
cols.AddRow("Outstanding Acks", state.NumAckPending)
}
cols.AddRow("Redelivered Messages", state.NumRedelivered)
}
cols.AddRow("Unprocessed Messages", state.NumPending)
if config.DeliverSubject == "" {
if config.MaxWaiting > 0 {
cols.AddRowf("Waiting Pulls", "%s of maximum %s", f(state.NumWaiting), f(config.MaxWaiting))
} else {
cols.AddRowf("Waiting Pulls", "%s of unlimited", f(state.NumWaiting))
}
} else {
if state.PushBound {
if config.DeliverGroup != "" {
cols.AddRowf("Active Interest", "Active using Queue Group %s", config.DeliverGroup)
} else {
cols.AddRow("Active Interest", "Active")
}
} else {
cols.AddRow("Active Interest", "No interest")
}
}
if state.Paused {
cols.AddRowf("Paused Until", "%s (%s remaining)", f(state.TimeStamp.Add(state.PauseRemaining)), state.PauseRemaining.Round(time.Second))
}
cols.Frender(os.Stdout)
}
func (c *consumerCmd) infoAction(_ *fisk.ParseContext) error {
c.connectAndSetup(true, true)
var err error
consumer := c.selectedConsumer
if consumer == nil {
consumer, err = c.mgr.LoadConsumer(c.stream, c.consumer)
fisk.FatalIfError(err, "could not load Consumer %s > %s", c.stream, c.consumer)
}
c.showConsumer(consumer)
return nil
}
func (c *consumerCmd) replayPolicyFromString(p string) api.ReplayPolicy {
switch strings.ToLower(p) {
case "instant":
return api.ReplayInstant
case "original":
return api.ReplayOriginal
default:
fisk.Fatalf("invalid replay policy '%s'", p)
return api.ReplayInstant
}
}
func (c *consumerCmd) ackPolicyFromString(p string) api.AckPolicy {
switch strings.ToLower(p) {
case "none":
return api.AckNone
case "all":
return api.AckAll
case "explicit":
return api.AckExplicit
default:
fisk.Fatalf("invalid ack policy '%s'", p)
// unreachable
return api.AckExplicit
}
}
func (c *consumerCmd) sampleFreqFromInt(s int) string {
if s > 100 || s < 0 {
fisk.Fatalf("sample percent is not between 0 and 100")
}
if s > 0 {
return strconv.Itoa(c.samplePct)
}
return ""
}
func (c *consumerCmd) defaultConsumer() *api.ConsumerConfig {
return &api.ConsumerConfig{
AckPolicy: api.AckExplicit,
ReplayPolicy: api.ReplayInstant,
}
}
func (c *consumerCmd) setStartPolicy(cfg *api.ConsumerConfig, policy string) {
if policy == "" {
return
}
if policy == "all" {
cfg.DeliverPolicy = api.DeliverAll
} else if policy == "last" {
cfg.DeliverPolicy = api.DeliverLast
} else if policy == "new" || policy == "next" {
cfg.DeliverPolicy = api.DeliverNew
} else if policy == "subject" || policy == "last_per_subject" {
cfg.DeliverPolicy = api.DeliverLastPerSubject
} else if ok, _ := regexp.MatchString("^\\d+$", policy); ok {
seq, _ := strconv.Atoi(policy)
cfg.DeliverPolicy = api.DeliverByStartSequence
cfg.OptStartSeq = uint64(seq)
} else {
d, err := parseDurationString(policy)
fisk.FatalIfError(err, "could not parse starting delta")
t := time.Now().UTC().Add(-d)
cfg.DeliverPolicy = api.DeliverByStartTime
cfg.OptStartTime = &t
}
}
func (c *consumerCmd) cpAction(pc *fisk.ParseContext) (err error) {
c.connectAndSetup(true, false)
source, err := c.mgr.LoadConsumer(c.stream, c.consumer)
fisk.FatalIfError(err, "could not load source Consumer")
cfg := source.Configuration()
if c.ackWait > 0 {
cfg.AckWait = c.ackWait
}
if c.samplePct != -1 {
cfg.SampleFrequency = c.sampleFreqFromInt(c.samplePct)
}
if c.startPolicy != "" {
c.setStartPolicy(&cfg, c.startPolicy)
}
if c.ephemeral {
cfg.Durable = ""
} else {
cfg.Durable = c.destination
}
if c.delivery != "" {
cfg.DeliverSubject = c.delivery
}
if c.pull {
cfg.DeliverSubject = ""
cfg.MaxWaiting = c.maxWaiting
}
if c.ackPolicy != "" {
cfg.AckPolicy = c.ackPolicyFromString(c.ackPolicy)
}
if len(c.filterSubjects) == 1 {
cfg.FilterSubject = c.filterSubjects[0]
} else if len(c.filterSubjects) > 1 {
cfg.FilterSubjects = c.filterSubjects
}
if c.replayPolicy != "" {
cfg.ReplayPolicy = c.replayPolicyFromString(c.replayPolicy)
}
if c.maxDeliver != 0 {
cfg.MaxDeliver = c.maxDeliver
}
if c.bpsRateLimit != 0 {
cfg.RateLimit = c.bpsRateLimit
}
if c.maxAckPending != -1 {
cfg.MaxAckPending = c.maxAckPending
}
if c.idleHeartbeat != "" && c.idleHeartbeat != "-1" {
hb, err := parseDurationString(c.idleHeartbeat)
fisk.FatalIfError(err, "Invalid heartbeat duration")
cfg.Heartbeat = hb
}
if c.description != "" {
cfg.Description = c.description
}
if c.fcSet {
cfg.FlowControl = c.fc
}
if cfg.DeliverSubject == "" {
cfg.Heartbeat = 0
cfg.FlowControl = false
}
if c.deliveryGroup != "_unset_" {
cfg.DeliverGroup = c.deliveryGroup
}
if c.delivery == "" {
cfg.DeliverGroup = ""
}
if c.deliveryGroup == "_unset_" {
cfg.DeliverGroup = ""
}
if c.inactiveThreshold > 0 {
cfg.InactiveThreshold = c.inactiveThreshold
}
if c.maxPullExpire > 0 {
cfg.MaxRequestExpires = c.maxPullExpire
}
if c.maxPullBatch > 0 {
cfg.MaxRequestBatch = c.maxPullBatch
}
if c.maxPullBytes > 0 {
cfg.MaxRequestMaxBytes = c.maxPullBytes
}
if c.backoffMode != "" {
cfg.BackOff, err = c.backoffPolicy()
if err != nil {
return fmt.Errorf("could not determine backoff policy: %v", err)
}
}
if c.hdrsOnlySet {
cfg.HeadersOnly = c.hdrsOnly
}
consumer, err := c.mgr.NewConsumerFromDefault(c.stream, cfg)
fisk.FatalIfError(err, "Consumer creation failed")
if cfg.Durable == "" {
return nil
}
c.consumer = cfg.Durable
c.showConsumer(consumer)
return nil
}
func (c *consumerCmd) loadConfigFile(file string) (*api.ConsumerConfig, error) {
f, err := os.ReadFile(file)
if err != nil {
return nil, err
}
var cfg api.ConsumerConfig
// there is a chance that this is a `nats c info --json` output
// which is a ConsumerInfo, so we detect if this is one of those
// by checking if there's a config key then extract that, else
// we try loading it as a StreamConfig
var nfo map[string]any
err = json.Unmarshal(f, &nfo)
if err != nil {
return nil, err
}
_, ok := nfo["config"]
if ok {
var nfo api.ConsumerInfo
err = json.Unmarshal(f, &nfo)
if err != nil {
return nil, err
}
cfg = nfo.Config
} else {
err = json.Unmarshal(f, &cfg)
if err != nil {
return nil, err
}
}
return &cfg, nil
}
func (c *consumerCmd) prepareConfig(pc *fisk.ParseContext) (cfg *api.ConsumerConfig, err error) {
cfg = c.defaultConsumer()
cfg.Description = c.description
if c.inputFile != "" {
cfg, err = c.loadConfigFile(c.inputFile)
if err != nil {
return nil, err
}
if cfg.Durable != "" && c.consumer != "" && cfg.Durable != c.consumer {
if c.consumer != "" {
cfg.Durable = c.consumer
} else {
return cfg, fmt.Errorf("durable consumer name in %s does not match CLI consumer name %s", c.inputFile, c.consumer)
}
}