-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreplicator.go
99 lines (89 loc) · 2.33 KB
/
replicator.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
package main
import (
"context"
"os"
"os/signal"
"sync"
"syscall"
"github.com/Shopify/sarama"
log "github.com/sirupsen/logrus"
)
/*
Simple replicator functionality
Useful to easily copy topic A to topic B (since Kafka does not support renaming)
*/
// Replicator object also implemented the sarama ConsumerGroupHandler interface
type Replicator struct {
consumer *Consumer
producer *Producer
fromTopic string
toTopic string
ready chan bool
ctx context.Context // tell the consumer to stop
cancel context.CancelFunc
}
func (r *Replicator) Setup(session sarama.ConsumerGroupSession) error {
close(r.ready)
return nil
}
func (r *Replicator) Cleanup(session sarama.ConsumerGroupSession) error {
return nil
}
func (r *Replicator) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
for {
select {
case message := <-claim.Messages():
err := r.producer.SendByteMsg(r.toTopic, message.Key, message.Value)
if err != nil {
return err
}
session.MarkMessage(message, "")
case <-session.Context().Done():
return nil
}
}
}
func NewReplicator(consumer *Consumer, producer *Producer, fromTopic, toTopic string) (*Replicator, error) {
var newReplicator Replicator
newReplicator.consumer = consumer
newReplicator.producer = producer
newReplicator.fromTopic = fromTopic
newReplicator.toTopic = toTopic
return &newReplicator, nil
}
// Copy from source to destination.
func (r *Replicator) Copy() {
r.ready = make(chan bool)
ctx, cancel := context.WithCancel(context.Background())
r.cancel = cancel
r.ctx = ctx
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
if err := r.consumer.ConsumerGroup.Consume(ctx, []string{r.fromTopic}, r); err != nil {
log.Panicf("Error from consumer: %v", err)
}
// check if context was cancelled, signaling that the consumer should stop
if ctx.Err() != nil {
return
}
r.ready = make(chan bool)
}
}()
<-r.ready // Await till the consumer has been set up
sigterm := make(chan os.Signal, 1)
signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM)
select {
case <-ctx.Done():
log.Println("terminating..")
case <-sigterm:
log.Println("terminating (received signal)")
}
cancel()
wg.Wait()
if err := r.consumer.ConsumerGroup.Close(); err != nil {
log.Panicf("Error closing client: %v", err)
}
}