This repository has been archived by the owner on Feb 18, 2021. It is now read-only.
/
lib.go
2257 lines (1856 loc) · 69.4 KB
/
lib.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 (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package common
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"math"
"math/rand"
"os"
"regexp"
"runtime/debug"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/apache/thrift/lib/go/thrift"
"github.com/codegangsta/cli"
ccli "github.com/uber/cherami-client-go/client/cherami"
"github.com/uber/cherami-server/clients/inputhost"
mcli "github.com/uber/cherami-server/clients/metadata"
"github.com/uber/cherami-server/clients/outputhost"
"github.com/uber/cherami-server/clients/storehost"
"github.com/uber/cherami-server/common"
"github.com/uber/cherami-thrift/.generated/go/admin"
"github.com/uber/cherami-thrift/.generated/go/cherami"
"github.com/uber/cherami-thrift/.generated/go/metadata"
"github.com/uber/cherami-thrift/.generated/go/shared"
"github.com/uber/cherami-thrift/.generated/go/store"
)
// GlobalOptions are options shared by most command line
type GlobalOptions struct {
hyperbahn bool
hyperbahnBootstrapFile string
env string
frontendHost string
frontendPort int
timeoutSecs int
}
const (
// DefaultPageSize is the default page size for data base access for command line
DefaultPageSize = 1000
// UnknownUUID is the suffix added to a host when the host uuid does not exist in cassandra
UnknownUUID = " UNKNOWN_HOST_UUID"
// DestinationType is the name for entity type for destination in listEntityOps
DestinationType = "DST"
// ConsumerGroupType is the name for entity type for consumer group in listEntityOps
ConsumerGroupType = "CG"
// DefaultUnconsumedMessagesRetention is the default value for unconsumed messages retention
DefaultUnconsumedMessagesRetention = 3 * 24 * 3600 // 3 days
// DefaultConsumedMessagesRetention is the default value for consumed messages retention
DefaultConsumedMessagesRetention = 1 * 24 * 3600 // 1 day
// MinUnconsumedMessagesRetentionForMultiZoneDest is the minimum unconsumed retention allowed
MinUnconsumedMessagesRetentionForMultiZoneDest = 3 * 24 * 3600
// MinConsumedMessagesRetention is the minimum consumed retention
MinConsumedMessagesRetention = 180
// MaxConsumedMessagesRetention is the maximum consumed retention
MaxConsumedMessagesRetention = 7 * 24 * 3600
// MinUnconsumedMessagesRetention is the minimum unconsumed retention
MinUnconsumedMessagesRetention = 180
// MaxUnconsumedMessagesRetention is the maximum unconsumed retention
MaxUnconsumedMessagesRetention = 7 * 24 * 3600
// DefaultLockTimeoutSeconds is the default value for lock timeout seconds
DefaultLockTimeoutSeconds = 60
// MinLockTimeoutSeconds is the minimum lock timeout seconds
MinLockTimeoutSeconds = 10
// MaxLockTimeoutSeconds is the maximum lock timeout seconds
MaxLockTimeoutSeconds = 3600
// DefaultMaxDeliveryCount is the default value for max delivery count
DefaultMaxDeliveryCount = 10
// MinMaxDeliveryCount is the minimum value for max delivery count
MinMaxDeliveryCount = 1
// MaxMaxDeliveryCount is the maximum value for max delivery count
MaxMaxDeliveryCount = 1000
// DefaultSkipOlderMessageSeconds is the default value for skipping older message
DefaultSkipOlderMessageSeconds = 0
// MinSkipOlderMessageSeconds is the minimum value for skipping older message
MinSkipOlderMessageSeconds = 1800
// MaxSkipOlderMessageSeconds is the maximum value for skipping older message
MaxSkipOlderMessageSeconds = 2 * 24 * 3600
// DefaultDelayMessageSeconds is the default value for delaying message
DefaultDelayMessageSeconds = 0
// MinDelayMessageSeconds is the minimum value for delaying message
MinDelayMessageSeconds = 0
// MaxDelayMessageSeconds is the maximum value for delaying message
MaxDelayMessageSeconds = 2 * 24 * 3600
// Kafka prefix is a required prefix for all Kafka type destinations and consumer groups
kafkaPrefix = `/kafka_`
)
const (
strNotEnoughArgs = "Not enough arguments. Try \"-help\""
strTooManyArgs = "Too many arguments. Try \"-help\""
strNoChange = "Update must update something. Try \"-help\""
strCGSpecIncorrectArgs = "Incorrect consumer group specification. Use \"<cg_uuid>\" or \"<dest_path> <cg_name>\""
strDestStatus = "Destination status must be \"enabled\", \"disabled\", \"sendonly\", or \"recvonly\""
strCGStatus = "Consumer group status must be \"enabled\", or \"disabled\""
strWrongDestZoneConfig = "Format of destination zone config is wrong, should be \"ZoneName,AllowPublish,AllowConsume,ReplicaCount\". For example: \"zone1,true,true,3\""
strWrongReplicaCount = "Replica count must be within 1 to 3"
strWrongZoneConfigCount = "Multi zone destination or consumer group must have at least 2 zone configs"
strWrongCgZoneConfig = "Format of consumer group zone config is wrong, should be \"ZoneName,PreferedActiveZone\". For example: \"zone1,false\""
strMultiZoneCgWithSingleZoneDest = "Multi zone consumer group must be created with a multi zone destination"
strMultiplePreferedActiveZone = "At most one zone can be prefered active zone"
strUnconsumedRetentionTooSmall = "Unconsumed retention period for multi zone destination should be at least 3 days"
strKafkaNaming = "Kafka destinations and consumer groups must begin with \"" + kafkaPrefix + "\""
strKafkaNotEnoughArgs = "Kafka destinations must specify the Kafka cluster and at least one topic"
strInvalidConsumedRetention = "Invalid consumed message retention %v (must be between %v and %v), please contact cherami team"
strInvalidUnconsumedRetention = "Invalid unconsumed message retention %v (must be between %v and %v), please contact cherami team"
strInvalidLockTimeoutSeconds = "Invalid lock timeout seconds %v (must be between %v and %v), please contact cherami team"
strInvalidMaxDeliveryCount = "Invalid max delivery count %v (must be between %v and %v), please contact cherami team"
strInvalidSkipOlderMessageSeconds = "Invalid skip older message seconds %v (must be zero or between %v and %v), please contact cherami team"
strInvalidDelayMessageSeconds = "Invalid delay message seconds %v (must be between %v and %v), please contact cherami team"
)
var uuidRegex, _ = regexp.Compile(`^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$`)
// ExitIfError exit while err is not nil and print the calling stack also
func ExitIfError(err error) {
const stacksEnv = `CHERAMI_SHOW_STACKS`
envReminder := "\n-env=staging is now the default. Did you mean '-env=prod' ?\n"
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
fmt.Fprintln(os.Stderr, envReminder)
if os.Getenv(stacksEnv) != `` {
debug.PrintStack()
} else {
fmt.Fprintf(os.Stderr, "('export %s=1' to see stack traces)\n", stacksEnv)
}
os.Exit(1)
}
}
// newGlobalOptionsFromCLIContext return GlobalOptions based on the cli.Context
func newGlobalOptionsFromCLIContext(c *cli.Context) *GlobalOptions {
host, port, err := common.SplitHostPort(c.GlobalString("hostport"))
ExitIfError(err)
environment := c.GlobalString("env")
if strings.HasPrefix(environment, `prod`) {
environment = ``
}
return &GlobalOptions{
hyperbahn: c.GlobalBool("hyperbahn"),
hyperbahnBootstrapFile: c.GlobalString("hyperbahn_bootstrap_file"),
env: environment,
frontendHost: host,
frontendPort: port,
timeoutSecs: c.GlobalInt("timeout"),
}
}
// GetCClient return a cherami.Client
func GetCClient(c *cli.Context, serviceName string) ccli.Client {
return GetCClientSecure(c, serviceName, nil)
}
// GetCClientSecure return a cherami.Client with security enabled
func GetCClientSecure(c *cli.Context, serviceName string, authProvider ccli.AuthProvider) ccli.Client {
gOpts := newGlobalOptionsFromCLIContext(c)
var cClient ccli.Client
var err error
cOpts := ccli.ClientOptions{
Timeout: time.Duration(gOpts.timeoutSecs) * time.Second,
DeploymentStr: gOpts.env,
AuthProvider: authProvider,
}
if !(len(gOpts.frontendHost) > 0 || gOpts.frontendPort > 0) && gOpts.hyperbahn {
cClient, err = ccli.NewHyperbahnClient(serviceName, gOpts.hyperbahnBootstrapFile, &cOpts)
} else {
cClient, err = ccli.NewClient(serviceName, gOpts.frontendHost, gOpts.frontendPort, &cOpts)
}
ExitIfError(err)
return cClient
}
// GetMClient return a metadata.Client
func GetMClient(c *cli.Context, serviceName string) mcli.Client {
gOpts := newGlobalOptionsFromCLIContext(c)
var mClient mcli.Client
var err error
cOpts := ccli.ClientOptions{
Timeout: time.Duration(gOpts.timeoutSecs) * time.Second,
DeploymentStr: gOpts.env,
}
if !(len(gOpts.frontendHost) > 0 || gOpts.frontendPort > 0) && gOpts.hyperbahn {
mClient, err = mcli.NewHyperbahnClient(serviceName, gOpts.hyperbahnBootstrapFile, &cOpts)
} else {
mClient, err = mcli.NewClient(serviceName, gOpts.frontendHost, gOpts.frontendPort, &cOpts)
}
ExitIfError(err)
return mClient
}
// Jsonify return the json string based on the obj
func Jsonify(obj thrift.TStruct) string {
transport := thrift.NewTMemoryBufferLen(1024)
protocol := thrift.NewTSimpleJSONProtocol(transport)
obj.Write(protocol)
protocol.Flush()
transport.Flush()
return transport.String()
}
func getChecksumOptionParam(optionStr string) cherami.ChecksumOption {
checksumstr := strings.ToLower(optionStr)
if checksumstr == "md5" {
return cherami.ChecksumOption_MD5
}
return cherami.ChecksumOption_CRC32IEEE
}
// CreateDestination creates destination
func CreateDestination(c *cli.Context, cliHelper common.CliHelper, serviceName string) {
CreateDestinationSecure(c, cliHelper, serviceName, nil)
}
// CreateDestinationSecure creates destination with security enabled
func CreateDestinationSecure(
c *cli.Context,
cliHelper common.CliHelper,
serviceName string,
authProvider ccli.AuthProvider,
) {
cClient := GetCClientSecure(c, serviceName, authProvider)
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
adminMode := c.GlobalBool("admin_mode")
path := c.Args().First()
kafkaCluster := c.String("kafka_cluster")
kafkaTopics := c.StringSlice("kafka_topics")
dType := cherami.DestinationType_PLAIN
if c.String("type") == "timer" {
dType = cherami.DestinationType_TIMER
}
if c.String("type") == "kafka" { // Kafka type, check Kafka params
dType = cherami.DestinationType_KAFKA
if !strings.HasPrefix(path, kafkaPrefix) {
ExitIfError(errors.New(strKafkaNaming))
}
if kafkaCluster == `` || common.ContainsEmpty(kafkaTopics) || len(kafkaTopics) == 0 { // Server will also check this
ExitIfError(errors.New(strKafkaNotEnoughArgs))
}
}
consumedMessagesRetention := int32(c.Int("consumed_messages_retention"))
if !adminMode && (consumedMessagesRetention < MinConsumedMessagesRetention || consumedMessagesRetention > MaxConsumedMessagesRetention) {
ExitIfError(fmt.Errorf(strInvalidConsumedRetention, consumedMessagesRetention, MinConsumedMessagesRetention, MaxConsumedMessagesRetention))
}
unconsumedMessagesRetention := int32(c.Int("unconsumed_messages_retention"))
if !adminMode && (unconsumedMessagesRetention < MinUnconsumedMessagesRetention || unconsumedMessagesRetention > MaxUnconsumedMessagesRetention) {
ExitIfError(fmt.Errorf(strInvalidUnconsumedRetention, unconsumedMessagesRetention, MinUnconsumedMessagesRetention, MaxUnconsumedMessagesRetention))
}
checksumOption := getChecksumOptionParam(string(c.String("checksum_option")))
ownerEmail := string(c.String("owner_email"))
if len(ownerEmail) == 0 {
cliHelper.GetDefaultOwnerEmail()
}
zoneConfigs := getDestZoneConfigs(c, cliHelper)
// don't allow short unconsumed message retention for multi_zone destination
// this is a prevention mechanism to prevent messages from being deleted in source zone in case there's some
// issue with cross zone replication(for example, network down between zones)
if len(zoneConfigs.Configs) > 1 && unconsumedMessagesRetention < MinUnconsumedMessagesRetentionForMultiZoneDest {
ExitIfError(errors.New(strUnconsumedRetentionTooSmall))
}
desc, err := cClient.CreateDestination(&cherami.CreateDestinationRequest{
Path: &path,
Type: &dType,
ConsumedMessagesRetention: &consumedMessagesRetention,
UnconsumedMessagesRetention: &unconsumedMessagesRetention,
ChecksumOption: checksumOption,
OwnerEmail: &ownerEmail,
IsMultiZone: common.BoolPtr(len(zoneConfigs.Configs) > 0),
ZoneConfigs: &zoneConfigs,
KafkaCluster: &kafkaCluster,
KafkaTopics: kafkaTopics,
})
ExitIfError(err)
fmt.Printf("%v\n", Jsonify(desc))
}
func getDestZoneConfigs(c *cli.Context, cliHelper common.CliHelper) cherami.DestinationZoneConfigs {
var zoneConfigs cherami.DestinationZoneConfigs
configs := c.StringSlice("zone_config")
for _, config := range configs {
parts := strings.Split(config, `,`)
if len(parts) != 4 {
ExitIfError(errors.New(strWrongDestZoneConfig))
}
zone, err := cliHelper.GetCanonicalZone(parts[0])
ExitIfError(err)
allowPublish, err := strconv.ParseBool(parts[1])
ExitIfError(err)
allowConsume, err := strconv.ParseBool(parts[2])
ExitIfError(err)
replicaCount, err := strconv.ParseInt(parts[3], 10, 0)
ExitIfError(err)
if replicaCount < 1 || replicaCount > 3 {
ExitIfError(errors.New(strWrongReplicaCount))
}
zoneConfigs.Configs = append(zoneConfigs.Configs, &cherami.DestinationZoneConfig{
Zone: common.StringPtr(zone),
AllowPublish: common.BoolPtr(allowPublish),
AllowConsume: common.BoolPtr(allowConsume),
RemoteExtentReplicaNum: common.Int32Ptr(int32(replicaCount)),
})
}
if len(zoneConfigs.Configs) == 1 {
ExitIfError(errors.New(strWrongZoneConfigCount))
}
return zoneConfigs
}
// UpdateDestination updates destination
func UpdateDestination(c *cli.Context, cliHelper common.CliHelper, serviceName string) {
UpdateDestinationSecure(c, cliHelper, serviceName, nil)
}
// UpdateDestinationSecure updates destination with security enabled
func UpdateDestinationSecure(
c *cli.Context,
cliHelper common.CliHelper,
serviceName string,
authProvider ccli.AuthProvider,
) {
mClient := GetMClient(c, serviceName)
cClient := GetCClientSecure(c, serviceName, authProvider)
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
path := c.Args().First()
status := cherami.DestinationStatus_ENABLED
switch c.String("status") {
case "disabled":
status = cherami.DestinationStatus_DISABLED
case "sendonly":
status = cherami.DestinationStatus_SENDONLY
case "recvonly:":
status = cherami.DestinationStatus_RECEIVEONLY
case "enabled":
default:
if c.IsSet(`status`) {
ExitIfError(errors.New(strDestStatus))
}
}
setCount := 0
request := &cherami.UpdateDestinationRequest{
Path: &path,
ConsumedMessagesRetention: getIfSetInt32(c, `consumed_messages_retention`, &setCount),
UnconsumedMessagesRetention: getIfSetInt32(c, `unconsumed_messages_retention`, &setCount),
ZoneConfigs: getIfSetDestZoneConfig(c, &setCount, cliHelper),
}
// don't allow short unconsumed message retention for multi_zone destination
// this is a prevention mechanism to prevent messages from being deleted in source zone in case there's some
// issue with cross zone replication(for example, network down between zones)
existingDesc, err := readDestinationFromMetadata(mClient, path)
ExitIfError(err)
if existingDesc.GetIsMultiZone() || (request.IsSetZoneConfigs() && len(request.GetZoneConfigs().GetConfigs()) > 0) {
if c.IsSet(`unconsumed_messages_retention`) && int32(c.Int(`unconsumed_messages_retention`)) < MinUnconsumedMessagesRetentionForMultiZoneDest {
ExitIfError(errors.New(strUnconsumedRetentionTooSmall))
}
if !c.IsSet(`unconsumed_messages_retention`) && existingDesc.GetUnconsumedMessagesRetention() < MinUnconsumedMessagesRetentionForMultiZoneDest {
ExitIfError(errors.New(strUnconsumedRetentionTooSmall))
}
}
if c.IsSet(`status`) {
setCount++
request.Status = &status
}
if c.IsSet(`checksum_option`) {
checksumOption := getChecksumOptionParam(string(c.String("checksum_option")))
request.ChecksumOption = &checksumOption
setCount++
}
if setCount == 0 {
ExitIfError(errors.New(strNoChange))
}
desc, err := cClient.UpdateDestination(request)
ExitIfError(err)
fmt.Printf("%v\n", Jsonify(desc))
}
// CreateConsumerGroup creates consumer group based on cli.Context
func CreateConsumerGroup(c *cli.Context, cliHelper common.CliHelper, serviceName string) {
CreateConsumerGroupSecure(c, cliHelper, serviceName, nil)
}
// CreateConsumerGroupSecure creates consumer group based on cli.Context
func CreateConsumerGroupSecure(
c *cli.Context,
cliHelper common.CliHelper,
serviceName string,
authProvider ccli.AuthProvider,
) {
mClient := GetMClient(c, serviceName)
cClient := GetCClientSecure(c, serviceName, authProvider)
if len(c.Args()) < 2 {
ExitIfError(errors.New(strNotEnoughArgs))
}
adminMode := c.GlobalBool("admin_mode")
path := c.Args()[0]
name := c.Args()[1]
// For Kafka-type destinations, verify that the consumer group has the prefix, too
if strings.HasPrefix(path, kafkaPrefix) && !strings.HasPrefix(name, kafkaPrefix) {
ExitIfError(errors.New(strKafkaNaming))
}
// StartFrom is a 64-bit value with nano-second precision
startTime := int64(c.Int("start_time")) * 1e9
lockTimeout := int32(c.Int("lock_timeout_seconds"))
if !adminMode && (lockTimeout < MinLockTimeoutSeconds || lockTimeout > MaxLockTimeoutSeconds) {
ExitIfError(fmt.Errorf(strInvalidLockTimeoutSeconds, lockTimeout, MinLockTimeoutSeconds, MaxLockTimeoutSeconds))
}
maxDelivery := int32(c.Int("max_delivery_count"))
if !adminMode && (maxDelivery < MinMaxDeliveryCount || maxDelivery > MaxMaxDeliveryCount) {
ExitIfError(fmt.Errorf(strInvalidMaxDeliveryCount, maxDelivery, MinMaxDeliveryCount, MaxMaxDeliveryCount))
}
skipOlder := int32(c.Int("skip_older_messages_in_seconds"))
if !adminMode && skipOlder != 0 && (skipOlder < MinSkipOlderMessageSeconds || skipOlder > MaxSkipOlderMessageSeconds) {
ExitIfError(fmt.Errorf(strInvalidSkipOlderMessageSeconds, skipOlder, MinSkipOlderMessageSeconds, MaxSkipOlderMessageSeconds))
}
delay := int32(c.Int("delay_seconds"))
if !adminMode && (delay < MinDelayMessageSeconds || delay > MaxDelayMessageSeconds) {
ExitIfError(fmt.Errorf(strInvalidDelayMessageSeconds, delay, MinDelayMessageSeconds, MaxDelayMessageSeconds))
}
ownerEmail := string(c.String("owner_email"))
// Override default startFrom for DLQ consumer groups
if common.UUIDRegex.MatchString(path) && int64(c.Int("start_time")) > time.Now().Unix()-60 {
fmt.Printf(`Start_time defaulted to zero, while creating DLQ consumer group`)
startTime = 0
}
if len(ownerEmail) == 0 {
ownerEmail = cliHelper.GetDefaultOwnerEmail()
}
zoneConfigs := getCgZoneConfigs(c, mClient, cliHelper, path)
isMultiZone := len(zoneConfigs.GetConfigs()) > 0
options := make(map[string]string)
if c.Bool(common.FlagDisableNackThrottling) {
options[common.FlagDisableNackThrottling] = "true"
}
if c.Bool(common.FlagEnableSmartRetry) {
options[common.FlagEnableSmartRetry] = "true"
}
if c.Bool(common.FlagEnableQueueDepthTabulation) {
options[common.FlagEnableQueueDepthTabulation] = "true"
}
desc, err := cClient.CreateConsumerGroup(&cherami.CreateConsumerGroupRequest{
DestinationPath: &path,
ConsumerGroupName: &name,
StartFrom: &startTime,
LockTimeoutInSeconds: &lockTimeout,
MaxDeliveryCount: &maxDelivery,
SkipOlderMessagesInSeconds: &skipOlder,
DelaySeconds: &delay,
OwnerEmail: &ownerEmail,
IsMultiZone: &isMultiZone,
ZoneConfigs: &zoneConfigs,
Options: options,
})
ExitIfError(err)
fmt.Printf("%v\n", Jsonify(desc))
}
func getCgZoneConfigs(c *cli.Context, mClient mcli.Client, cliHelper common.CliHelper, destinationPath string) cherami.ConsumerGroupZoneConfigs {
var zoneConfigs cherami.ConsumerGroupZoneConfigs
configs := c.StringSlice("zone_config")
var preferedActiveZone string
for _, config := range configs {
parts := strings.Split(config, `,`)
if len(parts) != 2 {
ExitIfError(errors.New(strWrongCgZoneConfig))
}
zone, err := cliHelper.GetCanonicalZone(parts[0])
ExitIfError(err)
isPreferedActiveZone, err := strconv.ParseBool(parts[1])
ExitIfError(err)
if isPreferedActiveZone {
if len(preferedActiveZone) > 0 {
ExitIfError(errors.New(strMultiplePreferedActiveZone))
} else {
preferedActiveZone = zone
}
}
zoneConfigs.Configs = append(zoneConfigs.Configs, &cherami.ConsumerGroupZoneConfig{
Zone: common.StringPtr(zone),
Visible: common.BoolPtr(true),
})
}
if len(zoneConfigs.Configs) == 1 {
ExitIfError(errors.New(strWrongZoneConfigCount))
}
if len(zoneConfigs.Configs) > 1 {
dest, err := readDestinationFromMetadata(mClient, destinationPath)
ExitIfError(err)
if !dest.GetIsMultiZone() {
ExitIfError(errors.New(strMultiZoneCgWithSingleZoneDest))
}
zoneConfigs.ActiveZone = common.StringPtr(preferedActiveZone)
}
return zoneConfigs
}
func getCgFromMedatada(mClient mcli.Client, path string, name string) *shared.ConsumerGroupDescription {
cg, err := mClient.ReadConsumerGroup(&shared.ReadConsumerGroupRequest{
DestinationPath: common.StringPtr(path),
ConsumerGroupName: common.StringPtr(name),
})
ExitIfError(err)
return cg
}
// UpdateConsumerGroup updates the consumer group
func UpdateConsumerGroup(c *cli.Context, cliHelper common.CliHelper, serviceName string) {
UpdateConsumerGroupSecure(c, cliHelper, serviceName, nil)
}
// UpdateConsumerGroupSecure updates the consumer group with security enabled
func UpdateConsumerGroupSecure(
c *cli.Context,
cliHelper common.CliHelper,
serviceName string,
authProvider ccli.AuthProvider,
) {
mClient := GetMClient(c, serviceName)
cClient := GetCClientSecure(c, serviceName, authProvider)
var path, name string
switch {
case len(c.Args()) < 1:
ExitIfError(errors.New(strNotEnoughArgs))
case len(c.Args()) == 1: // assume the arg is a uuid
respCG, err := mClient.ReadConsumerGroupByUUID(&shared.ReadConsumerGroupRequest{
ConsumerGroupUUID: &c.Args()[0],
})
ExitIfError(err)
respDest, err := mClient.ReadDestination(&shared.ReadDestinationRequest{
DestinationUUID: respCG.DestinationUUID,
})
ExitIfError(err)
path, name = respDest.GetPath(), respCG.GetConsumerGroupName()
default:
path, name = c.Args()[0], c.Args()[1]
}
status := cherami.ConsumerGroupStatus_ENABLED
if c.String("status") == "disabled" {
status = cherami.ConsumerGroupStatus_DISABLED
} else if c.String("status") != "enabled" {
if c.IsSet(`status`) {
ExitIfError(errors.New(strCGStatus))
}
}
setCount := 0
uReq := &cherami.UpdateConsumerGroupRequest{
DestinationPath: &path,
ConsumerGroupName: &name,
LockTimeoutInSeconds: getIfSetInt32(c, `lock_timeout_seconds`, &setCount),
MaxDeliveryCount: getIfSetInt32(c, `max_delivery_count`, &setCount),
SkipOlderMessagesInSeconds: getIfSetInt32(c, `skip_older_messages_in_seconds`, &setCount),
DelaySeconds: getIfSetInt32(c, `delay_seconds`, &setCount),
OwnerEmail: getIfSetString(c, `owner_email`, &setCount),
ActiveZone: getIfSetString(c, `active_zone`, &setCount),
ZoneConfigs: getIfSetCgZoneConfig(c, mClient, cliHelper, path, &setCount),
Options: getIfSetOptions(c, mClient, path, name, &setCount),
}
if c.IsSet(`status`) {
setCount++
uReq.Status = &status
}
if setCount == 0 {
ExitIfError(errors.New(strNoChange))
}
desc, err := cClient.UpdateConsumerGroup(uReq)
ExitIfError(err)
fmt.Printf("%v\n", Jsonify(desc))
}
// UnloadConsumerGroup unloads the CG based on cli.Context
func UnloadConsumerGroup(c *cli.Context, mClient mcli.Client) {
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
hostPort := c.Args()[0]
cgUUID := c.String("cg_uuid")
if !uuidRegex.MatchString(cgUUID) {
ExitIfError(errors.New("specify a valid cg UUID"))
}
// generate a random instance id to be used to create a client tchannel
instanceID := rand.Intn(50000)
outputClient, err := outputhost.NewClient(instanceID, hostPort)
ExitIfError(err)
defer outputClient.Close()
cgUnloadReq := admin.NewUnloadConsumerGroupsRequest()
cgUnloadReq.CgUUIDs = []string{cgUUID}
err = outputClient.UnloadConsumerGroups(cgUnloadReq)
ExitIfError(err)
}
// ListAllConsumerGroups lists all loaded CGs in memory of the outputhost
func ListAllConsumerGroups(c *cli.Context) {
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
hostPort := c.Args()[0]
// generate a random instance id to be used to create a client tchannel
instanceID := rand.Intn(50000)
outputClient, err := outputhost.NewClient(instanceID, hostPort)
ExitIfError(err)
defer outputClient.Close()
listCgResult, err := outputClient.ListLoadedConsumerGroups()
ExitIfError(err)
if listCgResult != nil {
for _, cg := range listCgResult.Cgs {
fmt.Printf("%v\n", Jsonify(cg))
}
}
}
// GetConsumerGroupState unloads the CG based on cli.Context
func GetConsumerGroupState(c *cli.Context) {
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
hostPort := c.Args()[0]
cgUUID := c.String("cg_uuid")
if !uuidRegex.MatchString(cgUUID) {
ExitIfError(errors.New("specify a valid cg UUID"))
}
// generate a random instance id to be used to create a client tchannel
instanceID := rand.Intn(50000)
outputClient, err := outputhost.NewClient(instanceID, hostPort)
ExitIfError(err)
defer outputClient.Close()
cgStateReq := admin.NewReadConsumerGroupStateRequest()
cgStateReq.CgUUIDs = []string{cgUUID}
readcgStateRes, err1 := outputClient.ReadCgState(cgStateReq)
ExitIfError(err1)
fmt.Printf("sessionID: %v\n", readcgStateRes.GetSessionID())
for _, cg := range readcgStateRes.CgState {
printCgState(cg)
for _, ext := range cg.CgExtents {
fmt.Printf("\t%v\n", Jsonify(ext))
}
}
}
type cgStateJSONOutput struct {
CgUUID string `json:"cgUUID"`
NumOutstandingMsgs int32 `json:"numOutstandingMsgs"`
MsgChSize int64 `json:"msgChSize"`
MsgCacheChSize int64 `json:"msgCacheChSize"`
NumConnections int64 `json:"numConnections"`
}
func printCgState(cgState *admin.ConsumerGroupState) {
output := &cgStateJSONOutput{
CgUUID: cgState.GetCgUUID(),
NumOutstandingMsgs: cgState.GetNumOutstandingMsgs(),
MsgChSize: cgState.GetMsgChSize(),
MsgCacheChSize: cgState.GetMsgCacheChSize(),
NumConnections: cgState.GetNumConnections(),
}
outputStr, _ := json.Marshal(output)
fmt.Fprintln(os.Stdout, string(outputStr))
}
// UnloadDestination unloads the Destination based on cli.Context
func UnloadDestination(c *cli.Context, mClient mcli.Client) {
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
hostPort := c.Args()[0]
destUUID := c.String("dest_uuid")
if !uuidRegex.MatchString(destUUID) {
ExitIfError(errors.New("specify a valid dest UUID"))
}
// generate a random instance id to be used to create a client tchannel
instanceID := rand.Intn(50000)
inputClient, err := inputhost.NewClient(instanceID, hostPort)
ExitIfError(err)
defer inputClient.Close()
destUnloadReq := admin.NewUnloadDestinationsRequest()
destUnloadReq.DestUUIDs = []string{destUUID}
err = inputClient.UnloadDestinations(destUnloadReq)
ExitIfError(err)
}
// ListAllLoadedDestinations lists all loaded Destinations in memory of the inputhost
func ListAllLoadedDestinations(c *cli.Context) {
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
hostPort := c.Args()[0]
// generate a random instance id to be used to create a client tchannel
instanceID := rand.Intn(50000)
inputClient, err := inputhost.NewClient(instanceID, hostPort)
ExitIfError(err)
defer inputClient.Close()
listDestResult, err := inputClient.ListLoadedDestinations()
ExitIfError(err)
if listDestResult != nil {
for _, dest := range listDestResult.Dests {
fmt.Printf("%v\n", Jsonify(dest))
}
}
}
// GetDestinationState unloads the Destination based on cli.Context
func GetDestinationState(c *cli.Context) {
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
hostPort := c.Args()[0]
destUUID := c.String("dest_uuid")
if !uuidRegex.MatchString(destUUID) {
ExitIfError(errors.New("specify a valid dest UUID"))
}
// generate a random instance id to be used to create a client tchannel
instanceID := rand.Intn(50000)
inputClient, err := inputhost.NewClient(instanceID, hostPort)
ExitIfError(err)
defer inputClient.Close()
destStateReq := admin.NewReadDestinationStateRequest()
destStateReq.DestUUIDs = []string{destUUID}
readdestStateRes, err1 := inputClient.ReadDestState(destStateReq)
ExitIfError(err1)
fmt.Printf("inputhostUUID: %v\n", readdestStateRes.GetInputHostUUID())
for _, dest := range readdestStateRes.DestState {
printDestState(dest)
for _, ext := range dest.DestExtents {
fmt.Printf("\t%v\n", Jsonify(ext))
}
}
}
type destStateJSONOutput struct {
DestUUID string `json:"destUUID"`
MsgsChSize int64 `json:"msgsChSize"`
NumConnections int64 `json:"numConnections"`
NumMsgsIn int64 `json:"numMsgsIn"`
NumSentAcks int64 `json:"numSentAcks"`
NumSentNacks int64 `json:"numSentNacks"`
NumThrottled int64 `json:"numThrottled"`
NumFailed int64 `json:"numFailed"`
}
func printDestState(destState *admin.DestinationState) {
input := &destStateJSONOutput{
DestUUID: destState.GetDestUUID(),
MsgsChSize: destState.GetMsgsChSize(),
NumConnections: destState.GetNumConnections(),
NumMsgsIn: destState.GetNumMsgsIn(),
NumSentAcks: destState.GetNumSentAcks(),
NumSentNacks: destState.GetNumSentNacks(),
NumThrottled: destState.GetNumThrottled(),
NumFailed: destState.GetNumFailed(),
}
inputStr, _ := json.Marshal(input)
fmt.Fprintln(os.Stdout, string(inputStr))
}
type destDescJSONOutputFields struct {
Path string `json:"path"`
UUID string `json:"uuid"`
Status shared.DestinationStatus `json:"status"`
Type shared.DestinationType `json:"type"`
ChecksumOption string `json:"checksum_option"`
OwnerEmail string `json:"owner_email"`
ConsumedMessagesRetention int32 `json:"consumed_messages_retention"`
UnconsumedMessagesRetention int32 `json:"unconsumed_messages_retention"`
DLQCGUUID string `json:"dlq_cg_uuid"`
DLQPurgeBefore int64 `json:"dlq_purge_before"`
DLQMergeBefore int64 `json:"dlq_merge_before"`
IsMultiZone bool `json:"is_multi_zone"`
ZoneConfigs []*shared.DestinationZoneConfig `json:"zone_configs"`
KafkaCluster string `json:"kafka_cluster"`
KafkaTopics []string `json:"kafka_topics"`
}
func printDest(dest *shared.DestinationDescription) {
output := &destDescJSONOutputFields{
Path: dest.GetPath(),
UUID: dest.GetDestinationUUID(),
Status: dest.GetStatus(),
Type: dest.GetType(),
OwnerEmail: dest.GetOwnerEmail(),
ConsumedMessagesRetention: dest.GetConsumedMessagesRetention(),
UnconsumedMessagesRetention: dest.GetUnconsumedMessagesRetention(),
DLQCGUUID: dest.GetDLQConsumerGroupUUID(),
DLQPurgeBefore: dest.GetDLQPurgeBefore(),
DLQMergeBefore: dest.GetDLQMergeBefore(),
IsMultiZone: dest.GetIsMultiZone(),
ZoneConfigs: dest.GetZoneConfigs(),
KafkaCluster: dest.GetKafkaCluster(),
KafkaTopics: dest.GetKafkaTopics(),
}
switch dest.GetChecksumOption() {
case shared.ChecksumOption_CRC32IEEE:
output.ChecksumOption = "CRC32_IEEE"
case shared.ChecksumOption_MD5:
output.ChecksumOption = "MD5"
}
outputStr, _ := json.Marshal(output)
fmt.Fprintln(os.Stdout, string(outputStr))
}
// ReadDestination return the detail for dest, and also consumer group for this dest
func ReadDestination(c *cli.Context, serviceName string) {
mClient := GetMClient(c, serviceName)
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
path := c.Args().First()
showCG := c.Bool("showcg")
desc, err := readDestinationFromMetadata(mClient, path)
ExitIfError(err)
printDest(desc)
// only show cg info if showCG flag is true
if showCG {
// read all the consumer group for this destination, including deleted ones
destUUID := desc.GetDestinationUUID()
req := &shared.ListConsumerGroupRequest{
Limit: common.Int64Ptr(DefaultPageSize),
}
var cgsInfo = make([]*shared.ConsumerGroupDescription, 0)
for {
resp, err1 := mClient.ListAllConsumerGroups(req)
ExitIfError(err1)
for _, cg := range resp.GetConsumerGroups() {
if destUUID == cg.GetDestinationUUID() {
cgsInfo = append(cgsInfo, cg)
}
}
if len(resp.GetConsumerGroups()) < DefaultPageSize {
break
} else {
req.PageToken = resp.NextPageToken
}
}
// print out all the consumer groups for this destination
for _, cg := range cgsInfo {
printCG(cg)
}
}
}
// path passed from tools might contain a password for some hacky security check, however the ReadDestination
// metadata call doesn't handle that. This helper function strips the password if there's any.
// TODO: we should remove this once the hacky security check is removed
func readDestinationFromMetadata(mClient mcli.Client, path string) (*shared.DestinationDescription, error) {
return mClient.ReadDestination(&shared.ReadDestinationRequest{
Path: common.StringPtr(strings.Split(path, `+`)[0]),
})
}
// ReadDlq return the info for dlq dest and related consumer group
func ReadDlq(c *cli.Context, serviceName string) {
mClient := GetMClient(c, serviceName)
if len(c.Args()) < 1 {
ExitIfError(errors.New(strNotEnoughArgs))
}
dlqUUID := c.Args().First()
desc, err0 := readDestinationFromMetadata(mClient, dlqUUID)
ExitIfError(err0)
printDest(desc)