-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.go
95 lines (81 loc) · 2.1 KB
/
producer.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
package main
import (
"context"
"os"
"os/signal"
exporter "producer/metrics"
"strconv"
"time"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
"github.com/Shopify/sarama"
)
func init() {
log.SetLevel(logLevel())
}
func main() {
topic := "input"
if value, ok := os.LookupEnv("TOPIC"); ok {
topic = value
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background())
go exporter.Exporter()
go func() {
oscall := <-c
log.Debug("system call: ", oscall)
cancel()
}()
producer, err := newProducer()
if err != nil {
log.Error("Could not create producer: ", err)
os.Exit(1)
}
if err := sendEpochMessage(ctx, producer, topic); err != nil {
log.Error("failed to produce: ", err)
}
}
func sendEpochMessage(ctx context.Context, producer sarama.SyncProducer, topic string) error {
log.Info("Server Start Producing")
var partitionProduced = cmap.New()
go func() {
for {
time.Sleep(time.Millisecond)
epochTime := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
msg := prepareMessage(topic, epochTime)
partition, offset, err := producer.SendMessage(msg)
if err != nil {
log.Info(err)
time.Sleep(1 * time.Second)
}
counter, _ := partitionProduced.Get(string(partition))
if counter == nil {
partitionProduced.Set(string(partition), 1)
} else {
counted := counter.(int)
counted++
partitionProduced.Set(string(partition), counted)
log.Trace("Counter: ", " Message: ", epochTime, " topic: ", topic, " partition: ", partition, " offset: ", offset)
M := exporter.ProducedMessageCounter.WithLabelValues(strconv.Itoa(int(partition)), topic)
M.Inc()
}
}
}()
<-ctx.Done()
log.Info("Server Stopped")
_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
log.Info("Server Exited Properly")
return nil
}
func prepareMessage(topic, message string) *sarama.ProducerMessage {
msg := &sarama.ProducerMessage{
Topic: topic,
Partition: -1,
Value: sarama.StringEncoder(message),
}
return msg
}