diff --git a/consume.go b/consume.go index 7d8ac7c..d5a9d6e 100644 --- a/consume.go +++ b/consume.go @@ -1,20 +1,31 @@ package main import ( + "context" + "errors" "fmt" + "github.com/IBM/sarama" + cli "github.com/jawher/mow.cli" + "github.com/mouminoux/kafkacli/filter" + uuid "github.com/satori/go.uuid" "log" "os" "os/signal" "strings" - - "github.com/Shopify/sarama" - cluster "github.com/bsm/sarama-cluster" - cli "github.com/jawher/mow.cli" - "github.com/mouminoux/kafkacli/filter" - "github.com/pkg/errors" - uuid "github.com/satori/go.uuid" + "sync" + "syscall" ) +type stack []uintptr +type consumeError struct { + message string + cause error +} + +func (f *consumeError) Error() string { return f.message } + +var messageCount int + func consumeCmd(c *cli.Cmd) { var ( prettyPrint = c.BoolOpt("p pretty-print", false, "pretty print the messages") @@ -37,11 +48,11 @@ The currently supported filters: cfg := config(*useSSL, *sslCAFile, *sslCertFile, *sslKeyFile) f, err := parseFilters(*filters) die(err) - consume(*cfg, splitFlatten(*bootstrapServers), splitFlatten(*topics), *prettyPrint, *fromBeginning, *consumerGroupId, *existOnLastMessage, f) + consume(cfg, splitFlatten(*bootstrapServers), splitFlatten(*topics), *prettyPrint, *fromBeginning, *consumerGroupId, *existOnLastMessage, f) } } -func consume(config cluster.Config, +func consume(config *sarama.Config, bootstrapServers []string, topics []string, prettyPrint bool, @@ -59,76 +70,84 @@ func consume(config cluster.Config, uuidString := uuid.NewV4().String() consumerGroupId = uuidString } - consumer, err := cluster.NewConsumer(bootstrapServers, consumerGroupId, topics, &config) - die(err) - defer func() { - if err := consumer.Close(); err != nil { - log.Printf("error while closing consumer: %+v\n", err) - } - }() - - // trap SIGINT to trigger a shutdown. - signals := make(chan os.Signal, 1) - signal.Notify(signals, os.Interrupt) - - // consume errors - go func() { - for err := range consumer.Errors() { - fmt.Printf("Error: %v\n", err) - } - }() + /** + * Setup a new Sarama consumer group + */ + consumer := Consumer{ + ready: make(chan bool), + filter: f, + prettyPrint: prettyPrint, + } - startConsuming := make(chan struct{}) - var partitionToRead int + ctx, cancel := context.WithCancel(context.Background()) + consumerGroup, err := sarama.NewConsumerGroup(bootstrapServers, consumerGroupId, config) + die(err) - // consume notifications + consumptionIsPaused := false + wg := &sync.WaitGroup{} + wg.Add(1) go func() { - for ntf := range consumer.Notifications() { - fmt.Printf("Rebalanced: %+v\n", ntf) - if len(ntf.Claimed) != 0 { - for _, topic := range ntf.Claimed { - partitionToRead += len(topic) + defer wg.Done() + for { + // `Consume` should be called inside an infinite loop, when a + // server-side rebalance happens, the consumer session will need to be + // recreated to get the new claims + if err := consumerGroup.Consume(ctx, topics, &consumer); err != nil { + if errors.Is(err, sarama.ErrClosedConsumerGroup) { + return } - startConsuming <- struct{}{} + log.Panicf("Error from consumer: %v", err) } + // check if context was cancelled, signaling that the consumer should stop + if ctx.Err() != nil { + return + } + consumer.ready = make(chan bool) } }() + <-consumer.ready // Await till the consumer has been set up + log.Println("Sarama consumer up and running!...") - // consume messages, watch signals - <-startConsuming + sigusr1 := make(chan os.Signal, 1) + signal.Notify(sigusr1, syscall.SIGUSR1) - var messageCount int + sigterm := make(chan os.Signal, 1) + signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM) - for { + keepRunning := true + for keepRunning { select { - case msg, ok := <-consumer.Messages(): - if !ok { - continue - } - if !f(msg) { - continue - } - if prettyPrint { - displayMessagePretty(msg) - } else { - displayMessageUgly(msg) - } - messageCount++ - marks := consumer.HighWaterMarks() - if existOnLastMessage && msg.Offset+1 == marks[msg.Topic][msg.Partition] { - partitionToRead -= 1 - } - - case <-signals: - partitionToRead = 0 - } - - if partitionToRead == 0 { - break + case <-ctx.Done(): + log.Println("terminating: context cancelled") + keepRunning = false + case <-sigterm: + log.Println("terminating: via signal") + keepRunning = false + case <-sigusr1: + toggleConsumptionFlow(consumerGroup, &consumptionIsPaused) } } + log.Printf("%d messages received\n", messageCount) + + cancel() + wg.Wait() + if err = consumerGroup.Close(); err != nil { + log.Panicf("Error closing client: %v", err) + } +} + +func toggleConsumptionFlow(client sarama.ConsumerGroup, isPaused *bool) { + if *isPaused { + client.ResumeAll() + log.Println("Resuming consumption") + } else { + client.PauseAll() + log.Println("Pausing consumption") + } + + *isPaused = !*isPaused } func displayMessagePretty(msg *sarama.ConsumerMessage) { @@ -162,17 +181,24 @@ func parseFilters(ffs []string) (filter.Filter, error) { for i, fs := range ffs { parts := strings.SplitN(fs, ":", 2) if len(parts) != 2 { - return nil, errors.Errorf("Invalid filter %q. must be in : format", fs) + return nil, &consumeError{ + message: fmt.Sprintf("Invalid filter %q. must be in : format", fs), + } } switch parts[0] { case "header", "h": k, v, err := parseKEqV(parts[1]) if err != nil { - return nil, errors.Wrapf(err, "Invalid filter %q", fs) + return nil, &consumeError{ + message: fmt.Sprintf("Invalid filter %q", fs), + cause: err, + } } ff[i] = filter.Header(k, v) default: - return nil, errors.Errorf("Unknown filter type %q in filter %q", parts[0], fs) + return nil, &consumeError{ + message: fmt.Sprintf("Unknown filter type %q in filter %q", parts[0], fs), + } } } @@ -182,7 +208,53 @@ func parseFilters(ffs []string) (filter.Filter, error) { func parseKEqV(s string) (string, string, error) { parts := strings.SplitN(s, "=", 2) if len(parts) != 2 { - return "", "", errors.Errorf("Invalid filter condition %q. must be in = format", s) + return "", "", &consumeError{ + message: fmt.Sprintf("Invalid filter condition %q. must be in = format", s), + } } return parts[0], parts[1], nil } + +// Consumer represents a Sarama consumer group consumer +type Consumer struct { + ready chan bool + filter filter.Filter + prettyPrint bool +} + +// Setup is run at the beginning of a new session, before ConsumeClaim +func (consumer *Consumer) Setup(session sarama.ConsumerGroupSession) error { + // Mark the consumer as ready + close(consumer.ready) + return nil +} + +// Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exited +func (consumer *Consumer) Cleanup(sarama.ConsumerGroupSession) error { + return nil +} + +// ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages(). +// Once the Messages() channel is closed, the Handler must finish its processing +// loop and exit. +func (consumer *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { + for { + select { + case msg, ok := <-claim.Messages(): + if !ok { + continue + } + if !consumer.filter(msg) { + continue + } + if consumer.prettyPrint { + displayMessagePretty(msg) + } else { + displayMessageUgly(msg) + } + messageCount++ + case <-session.Context().Done(): + return nil + } + } +} diff --git a/consumer_groups.go b/consumer_groups.go index f10990f..1aa82f1 100644 --- a/consumer_groups.go +++ b/consumer_groups.go @@ -2,8 +2,7 @@ package main import ( "fmt" - "github.com/Shopify/sarama" - cluster "github.com/bsm/sarama-cluster" + "github.com/IBM/sarama" cli "github.com/jawher/mow.cli" "log" "sort" @@ -18,14 +17,14 @@ func consumerGroupsCmd(c *cli.Cmd) { c.Action = func() { cfg := config(*useSSL, *sslCAFile, *sslCertFile, *sslKeyFile) - consumerGroups(*cfg, splitFlatten(*bootstrapServers), sorted) + consumerGroups(cfg, splitFlatten(*bootstrapServers), sorted) } } -func consumerGroups(config cluster.Config, bootstrapServers []string, sorted *bool) { +func consumerGroups(config *sarama.Config, bootstrapServers []string, sorted *bool) { fmt.Printf("Listing consumer groups for all topics on broker(s) %q\n", strings.Join(bootstrapServers, ", ")) - newAdmin, err := sarama.NewClusterAdmin(bootstrapServers, &config.Config) + newAdmin, err := sarama.NewClusterAdmin(bootstrapServers, config) die(err) defer func() { diff --git a/filter/filter.go b/filter/filter.go index 45c43f5..5c26d25 100644 --- a/filter/filter.go +++ b/filter/filter.go @@ -1,7 +1,7 @@ package filter import ( - "github.com/Shopify/sarama" + "github.com/IBM/sarama" ) type Filter func(message *sarama.ConsumerMessage) bool diff --git a/filter/header.go b/filter/header.go index 3ab83b8..b96b705 100644 --- a/filter/header.go +++ b/filter/header.go @@ -1,7 +1,7 @@ package filter import ( - "github.com/Shopify/sarama" + "github.com/IBM/sarama" ) func Header(key, value string) Filter { diff --git a/go.mod b/go.mod index 7721a56..91ae2bc 100644 --- a/go.mod +++ b/go.mod @@ -3,18 +3,10 @@ module github.com/mouminoux/kafkacli go 1.12 require ( - github.com/DataDog/zstd v1.3.5 - github.com/Shopify/sarama v1.21.0 - github.com/bsm/sarama-cluster v2.1.15+incompatible - github.com/davecgh/go-spew v1.1.1 - github.com/eapache/go-resiliency v1.1.0 - github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 - github.com/eapache/queue v1.1.0 - github.com/golang/snappy v0.0.1 + github.com/IBM/sarama v1.43.2 + github.com/docker/go-units v0.5.0 github.com/jawher/mow.cli v1.1.0 - github.com/pierrec/lz4 v2.0.5+incompatible github.com/pkg/errors v0.8.1 - github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a github.com/satori/go.uuid v1.2.0 - github.com/sirupsen/logrus v1.4.1 // indirect + github.com/xdg-go/scram v1.1.2 // indirect ) diff --git a/go.sum b/go.sum index d208a66..8cb07fe 100644 --- a/go.sum +++ b/go.sum @@ -1,42 +1,177 @@ github.com/DataDog/zstd v1.3.5 h1:DtpNbljikUepEPD16hD4LvIcmhnhdLTiW/5pHgbmp14= github.com/DataDog/zstd v1.3.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/IBM/sarama v1.42.1 h1:wugyWa15TDEHh2kvq2gAy1IHLjEjuYOYgXz/ruC/OSQ= +github.com/IBM/sarama v1.42.1/go.mod h1:Xxho9HkHd4K/MDUo/T/sOqwtX/17D33++E9Wib6hUdQ= +github.com/IBM/sarama v1.43.2 h1:HABeEqRUh32z8yzY2hGB/j8mHSzC/HA9zlEjqFNCzSw= +github.com/IBM/sarama v1.43.2/go.mod h1:Kyo4WkF24Z+1nz7xeVUFWIuKVV8RS3wM8mkvPKMdXFQ= github.com/Shopify/sarama v1.21.0 h1:0GKs+e8mn1RRUzfg9oUXv3v7ZieQLmOZF/bfnmmGhM8= github.com/Shopify/sarama v1.21.0/go.mod h1:yuqtN/pe8cXRWG5zPaO7hCfNJp5MwmkoJEoLjkm5tCQ= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/bsm/sarama-cluster v2.1.15+incompatible h1:RkV6WiNRnqEEbp81druK8zYhmnIgdOjqSVi0+9Cnl2A= github.com/bsm/sarama-cluster v2.1.15+incompatible/go.mod h1:r7ao+4tTNXvWm+VRpRJchr2kQhqxgmAp2iEX5W96gMM= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/eapache/go-resiliency v1.1.0 h1:1NtRmCAqadE2FN4ZcN6g90TP3uk8cg9rn9eNK2197aU= github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-resiliency v1.4.0 h1:3OK9bWpPk5q6pbFAaYSEwD9CLUSHG8bnZuqX2yMt3B0= +github.com/eapache/go-resiliency v1.4.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= +github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30= +github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3/go.mod h1:YvSRo5mw33fLEx1+DlK6L2VV43tJt5Eyel9n9XBcR+0= github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/jawher/mow.cli v1.0.5 h1:MEWYfyzcJXp8yvqtJYBMa8GLW073pM7RXN1zRDayMU8= github.com/jawher/mow.cli v1.0.5/go.mod h1:rZZcz2ygDSemQyV66jOaCszjT/zAL3FcEGNj5ReUpkQ= github.com/jawher/mow.cli v1.1.0 h1:NdtHXRc0CwZQ507wMvQ/IS+Q3W3x2fycn973/b8Zuk8= github.com/jawher/mow.cli v1.1.0/go.mod h1:aNaQlc7ozF3vw6IJ2dHjp2ZFiA4ozMIYY6PyuRJwlUg= +github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= +github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= +github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= +github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= +github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= +github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= +github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= +github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8= +github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= +github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= +github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= +github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= +github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= +github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/pierrec/lz4 v0.0.0-20190222153722-062282ea0dcf/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pierrec/lz4/v4 v4.1.18 h1:xaKrnTkyoqfh1YItXl56+6KJNVYWlEEPuAQW9xsplYQ= +github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= +github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/kafkacli.go b/kafkacli.go index 3ea14ae..3a3f1cb 100644 --- a/kafkacli.go +++ b/kafkacli.go @@ -4,12 +4,10 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "os" "strings" - "github.com/Shopify/sarama" - cluster "github.com/bsm/sarama-cluster" + "github.com/IBM/sarama" "github.com/pkg/errors" cli "github.com/jawher/mow.cli" @@ -51,14 +49,16 @@ func main() { app.Command("consume", "consume and display messages from 1 or more topics", consumeCmd) app.Command("produce", "produce a message into 1 or more topics", produceCmd) app.Command("consumer-groups", "list consumer groups", consumerGroupsCmd) + app.Command("topics", "list topics", topicsCmd) die(app.Run(os.Args)) } -func config(useSSL bool, sslCAFile string, sslCertFile string, sslKeyFile string) *cluster.Config { - config := cluster.NewConfig() +func config(useSSL bool, sslCAFile string, sslCertFile string, sslKeyFile string) *sarama.Config { + config := sarama.NewConfig() config.Version = sarama.V1_0_0_0 - config.Group.Return.Notifications = true + // can't find what is corresponding in new version of sarama + //config.Group.Return.Notifications = true config.Consumer.Return.Errors = true config.Consumer.Offsets.Initial = sarama.OffsetNewest @@ -85,7 +85,7 @@ func config(useSSL bool, sslCAFile string, sslCertFile string, sslKeyFile string } if sslCAFile != "" { - caCert, err := ioutil.ReadFile(sslCAFile) + caCert, err := os.ReadFile(sslCAFile) die(err) caCertPool := x509.NewCertPool() diff --git a/produce.go b/produce.go index 912c660..95f5272 100644 --- a/produce.go +++ b/produce.go @@ -8,8 +8,7 @@ import ( "os" "strings" - "github.com/Shopify/sarama" - cluster "github.com/bsm/sarama-cluster" + "github.com/IBM/sarama" cli "github.com/jawher/mow.cli" "github.com/pkg/errors" ) @@ -34,12 +33,12 @@ func produceCmd(c *cli.Cmd) { if *message == "" || *message == "-" { *message = readStdin() } - produce(*cfg, splitFlatten(*bootstrapServers), splitFlatten(*topics), *headers, *message, *key) + produce(cfg, splitFlatten(*bootstrapServers), splitFlatten(*topics), *headers, *message, *key) } } -func produce(config cluster.Config, bootstrapServers []string, topics []string, headers []string, message string, key string) { - producer, err := sarama.NewSyncProducer(bootstrapServers, &config.Config) +func produce(cfg *sarama.Config, bootstrapServers []string, topics []string, headers []string, message string, key string) { + producer, err := sarama.NewSyncProducer(bootstrapServers, cfg) die(err) defer func() { diff --git a/topics.go b/topics.go new file mode 100644 index 0000000..b862cc3 --- /dev/null +++ b/topics.go @@ -0,0 +1,118 @@ +package main + +import ( + "fmt" + "github.com/IBM/sarama" + "github.com/docker/go-units" + cli "github.com/jawher/mow.cli" + "sort" + "strings" +) + +func topicsCmd(c *cli.Cmd) { + c.Command("list", "list topics", listCmd) +} + +func listCmd(cmd *cli.Cmd) { + var ( + details = cmd.BoolOpt("d details", false, "print topics details") + topic = cmd.StringOpt("t topic", "", "topic to list") + sorted = cmd.BoolOpt("s sorted", false, "sort the topics by size (descending)") + ) + + cmd.Action = func() { + cfg := config(*useSSL, *sslCAFile, *sslCertFile, *sslKeyFile) + list(cfg, splitFlatten(*bootstrapServers), details, topic, sorted) + } +} + +func list(cfg *sarama.Config, bootstrapServers []string, details *bool, queriedTopic *string, sorted *bool) { + fmt.Printf("Listing consumer groups for all topics on broker(s) %q\n", strings.Join(bootstrapServers, ", ")) + + clusterAdmin, err := sarama.NewClusterAdmin(bootstrapServers, cfg) + die(err) + + topicsDetails, err := clusterAdmin.ListTopics() + die(err) + + topics := getTopics(topicsDetails) + + brokers, _, _ := clusterAdmin.DescribeCluster() + for _, broker := range brokers { + die(broker.Open(cfg)) + } + + totalSizes := map[string]int64{} + + fmt.Printf("Topics:\n") + for _, topic := range topics { + if queriedTopic != nil && *queriedTopic != "" && topic != *queriedTopic { + continue + } + if *details { + + metadata, err := clusterAdmin.DescribeTopics([]string{topic}) + die(err) + + partitions := make([]int32, len(metadata[0].Partitions)) + for i, p := range metadata[0].Partitions { + partitions[i] = p.ID + } + + request := &sarama.DescribeLogDirsRequest{ + Version: 0, + DescribeTopics: []sarama.DescribeLogDirsRequestTopic{ + { + Topic: topic, + PartitionIDs: partitions, + }, + }, + } + + sizeByPartition := make(map[int32]int64) + for _, broker := range brokers { + resp, err := broker.DescribeLogDirs(request) + die(err) + + for _, t := range resp.LogDirs[0].Topics { + if t.Topic != topic { + continue + } + + for _, partition := range t.Partitions { + if _, ok := sizeByPartition[partition.PartitionID]; ok { + continue + } + sizeByPartition[partition.PartitionID] = partition.Size + } + } + } + + totalSizes[topic] = 0 + + for _, size := range sizeByPartition { + totalSizes[topic] += size + } + } + } + + if *sorted { + sort.SliceStable(topics, func(i, j int) bool { + return totalSizes[topics[i]] > totalSizes[topics[j]] + }) + } + + for _, topic := range topics { + totalSize := totalSizes[topic] + fmt.Printf(" %s: %v\n", topic, units.HumanSize(float64(totalSize))) + } +} + +func getTopics(topicsDetail map[string]sarama.TopicDetail) []string { + var keys []string + for topicDetail, _ := range topicsDetail { + keys = append(keys, topicDetail) + } + + return keys +}