forked from xstevens/k
/
commands.go
245 lines (208 loc) · 5.7 KB
/
commands.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
package main
import (
"bufio"
"fmt"
"github.com/shopify/sarama"
"os"
"os/signal"
"strings"
"sync"
)
func brokers() []string {
s := os.Getenv("KAFKA_BROKERS")
if s == "" {
s = "127.0.0.1:9092"
}
return strings.Split(s, ",")
}
func offsets(client sarama.Client, topic string, partition int32) (oldest int64, newest int64) {
oldest, err := client.GetOffset(topic, partition, sarama.OffsetOldest)
must(err)
newest, err = client.GetOffset(topic, partition, sarama.OffsetNewest)
must(err)
return oldest, newest
}
var (
topic string
partition int32
offset int64
n int
)
var cmdProduce = &Command{
Usage: "produce --topic <topic>",
Short: "produce messages to given topic",
Long: `
Produces a message to the given topic with the data given by
reading stdin (newline delimited).
Example:
$ echo content | k produce --topic foo`,
Run: runProduce,
}
func runProduce(cmd *Command, args []string) {
brokers := brokers()
config := sarama.NewConfig()
config.ClientID = "k produce"
config.Producer.Return.Successes = true
client, err := sarama.NewClient(brokers, config)
must(err)
defer client.Close()
producer, err := sarama.NewAsyncProducerFromClient(client)
must(err)
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
defer close(signals)
var wg sync.WaitGroup
var enqueued, successes, errors int
wg.Add(1)
go func() {
defer wg.Done()
for _ = range producer.Successes() {
successes++
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for err := range producer.Errors() {
fmt.Fprintf(os.Stderr, "Failed to produce message: %s\n", err)
errors++
}
}()
scanner := bufio.NewScanner(os.Stdin)
producerLoop:
for scanner.Scan() {
line := scanner.Text()
idx := strings.Index(line, "\t")
var msg *sarama.ProducerMessage
if idx > 0 {
msg = &sarama.ProducerMessage{Topic: topic, Key: sarama.ByteEncoder(line[0:idx]), Value: sarama.ByteEncoder(line[idx+1:])}
} else {
msg = &sarama.ProducerMessage{Topic: topic, Key: nil, Value: sarama.ByteEncoder(line)}
}
select {
case producer.Input() <- msg:
enqueued++
case <-signals:
break producerLoop
}
}
producer.AsyncClose()
wg.Wait()
fmt.Fprintf(os.Stderr, "messages produced: %d, errors: %d\n", successes, errors)
}
var cmdConsume = &Command{
Usage: "consume --topic <topic> [--partition <partition>] [--offset <offset>] [-n <n_messages>]",
Short: "consume messages from given topic",
Long: `
Consumes messages from the given topic and writes them to stdout.
Example:
$ k consume --topic foo`,
Run: runConsume,
}
func runConsume(cmd *Command, args []string) {
brokers := brokers()
config := sarama.NewConfig()
config.ClientID = "k consume"
config.Consumer.Return.Errors = true
client, err := sarama.NewClient(brokers, config)
must(err)
defer client.Close()
consumer, err := sarama.NewConsumerFromClient(client)
must(err)
defer consumer.Close()
signals := make(chan os.Signal, 1)
defer close(signals)
signal.Notify(signals, os.Interrupt)
// calculate a starting offset
_, newestOffset := offsets(client, topic, partition)
must(err)
startingOffset := newestOffset
if offset < 0 {
startingOffset = newestOffset + offset
} else if offset > 0 {
startingOffset = offset
}
// TODO: support consuming all partitions
fmt.Fprintf(os.Stderr, "Using starting offset: %d\n", startingOffset)
partConsumer, err := consumer.ConsumePartition(topic, partition, startingOffset)
must(err)
defer partConsumer.Close()
var received, errors int
consumerLoop:
for {
select {
case msg := <-partConsumer.Messages():
if msg.Key != nil {
fmt.Printf("%s\t", string(msg.Key))
}
fmt.Println(string(msg.Value))
received++
if n > 0 && received >= n {
break consumerLoop
}
case err := <-partConsumer.Errors():
fmt.Fprintf(os.Stderr, "Failed to receive message: %s\n", err)
errors++
case <-signals:
break consumerLoop
}
}
fmt.Fprintf(os.Stderr, "Messages received: %d, errors: %d\n", received, errors)
}
var cmdOffsets = &Command{
Usage: "offsets --topic <topic>",
Short: "show the oldest and newest offset for a given topic and partition",
Long: `
Prints oldest and newest offsets for the given topic to stdout.
Example:
$ k offsets --topic foo`,
Run: runOffsets,
}
func runOffsets(cmd *Command, args []string) {
brokers := brokers()
config := sarama.NewConfig()
config.ClientID = "k offsets"
client, err := sarama.NewClient(brokers, config)
must(err)
defer client.Close()
// get partitions for topic
parts, err := client.Partitions(topic)
must(err)
// print offsets for each partition
for _, part := range parts {
oldestOffset, newestOffset := offsets(client, topic, 0)
must(err)
fmt.Printf("partition=%d oldest=%d newest=%d\n", part, oldestOffset, newestOffset)
}
}
var cmdTopics = &Command{
Usage: "topics",
Short: "show the list of topics",
Long: `
Prints the list of topics to stdout.
Example:
$ k topics`,
Run: runTopics,
}
func runTopics(cmd *Command, args []string) {
brokers := brokers()
config := sarama.NewConfig()
config.ClientID = "k topics"
client, err := sarama.NewClient(brokers, config)
must(err)
defer client.Close()
// get list of topics
topics, err := client.Topics()
must(err)
for _, topic := range topics {
fmt.Println(topic)
}
}
func init() {
cmdProduce.Flag.StringVarP(&topic, "topic", "t", "k", "produce to topic")
cmdConsume.Flag.StringVarP(&topic, "topic", "t", "k", "topic to consume")
cmdConsume.Flag.Int32VarP(&partition, "partition", "p", 0, "partition to consume")
cmdConsume.Flag.Int64VarP(&offset, "offset", "o", 0, "starting offset for consumer")
cmdConsume.Flag.IntVarP(&n, "n", "n", -1, "number of messages to consume")
cmdOffsets.Flag.StringVarP(&topic, "topic", "t", "k", "get offsets for topic")
}