-
Notifications
You must be signed in to change notification settings - Fork 48
/
kafka-topics.go
93 lines (74 loc) · 2.24 KB
/
kafka-topics.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
package main
import (
"bytes"
"flag"
"fmt"
"os"
"sort"
"sync"
"time"
"github.com/wvanbergen/kazoo-go"
)
var (
zookeeper = flag.String("zookeeper", os.Getenv("ZOOKEEPER_PEERS"), "Zookeeper connection string. It can include a chroot.")
zookeeperTimeout = flag.Int("zookeeper-timeout", 1000, "Zookeeper timeout in milliseconds.")
)
func main() {
flag.Parse()
if *zookeeper == "" {
printUsageErrorAndExit("You have to provide a zookeeper connection string using -zookeeper, or the ZOOKEEPER_PEERS environment variable")
}
conf := kazoo.NewConfig()
conf.Timeout = time.Duration(*zookeeperTimeout) * time.Millisecond
kz, err := kazoo.NewKazooFromConnectionString(*zookeeper, conf)
if err != nil {
printErrorAndExit(69, "Failed to connect to Zookeeper: %v", err)
}
defer func() { _ = kz.Close() }()
topics, err := kz.Topics()
if err != nil {
printErrorAndExit(69, "Failed to get Kafka topics from Zookeeper: %v", err)
}
sort.Sort(topics)
var (
wg sync.WaitGroup
l sync.Mutex
stdout = make([]string, len(topics))
)
for i, topic := range topics {
wg.Add(1)
go func(i int, topic *kazoo.Topic) {
defer wg.Done()
buffer := bytes.NewBuffer(make([]byte, 0))
partitions, err := topic.Partitions()
if err != nil {
printErrorAndExit(69, "Failed to get Kafka topic partitions from Zookeeper: %v", err)
}
fmt.Fprintf(buffer, "Topic: %s\tPartitions: %d\n", topic.Name, len(partitions))
for _, partition := range partitions {
leader, _ := partition.Leader()
isr, _ := partition.ISR()
fmt.Fprintf(buffer, "\tPartition: %d\tReplicas: %v\tLeader: %d\tISR: %v\n", partition.ID, partition.Replicas, leader, isr)
}
l.Lock()
stdout[i] = buffer.String()
l.Unlock()
}(i, topic)
}
wg.Wait()
for _, msg := range stdout {
fmt.Print(msg)
}
}
func printUsageErrorAndExit(format string, values ...interface{}) {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", fmt.Sprintf(format, values...))
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Available command line options:")
flag.PrintDefaults()
os.Exit(64)
}
func printErrorAndExit(code int, format string, values ...interface{}) {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", fmt.Sprintf(format, values...))
fmt.Fprintln(os.Stderr)
os.Exit(code)
}