| 1 |
package main |
| 2 |
|
| 3 |
// SIGUSR1 toggle the pause/resume consumption |
| 4 |
import ( |
| 5 |
"context" |
| 6 |
"flag" |
| 7 |
"fmt" |
| 8 |
"log" |
| 9 |
"os" |
| 10 |
"os/signal" |
| 11 |
"strings" |
| 12 |
"sync" |
| 13 |
"syscall" |
| 14 |
"time" |
| 15 |
|
| 16 |
_ "net/http/pprof" |
| 17 |
|
| 18 |
"github.com/rcrowley/go-metrics" |
| 19 |
|
| 20 |
"github.com/IBM/sarama" |
| 21 |
) |
| 22 |
|
| 23 |
// Sarama configuration options |
| 24 |
var ( |
| 25 |
brokers = "" |
| 26 |
version = "" |
| 27 |
topic = "" |
| 28 |
producers = 1 |
| 29 |
verbose = false |
| 30 |
|
| 31 |
recordsNumber int64 = 1 |
| 32 |
|
| 33 |
recordsRate = metrics.GetOrRegisterMeter("records.rate", nil) |
| 34 |
) |
| 35 |
|
| 36 |
func init() { |
| 37 |
flag.StringVar(&brokers, "brokers", "", "Kafka bootstrap brokers to connect to, as a comma separated list") |
| 38 |
flag.StringVar(&version, "version", sarama.DefaultVersion.String(), "Kafka cluster version") |
| 39 |
flag.StringVar(&topic, "topic", "", "Kafka topics where records will be copied from topics.") |
| 40 |
flag.IntVar(&producers, "producers", 10, "Number of concurrent producers") |
| 41 |
flag.Int64Var(&recordsNumber, "records-number", 10000, "Number of records sent per loop") |
| 42 |
flag.BoolVar(&verbose, "verbose", false, "Sarama logging") |
| 43 |
flag.Parse() |
| 44 |
|
| 45 |
if len(brokers) == 0 { |
| 46 |
panic("no Kafka bootstrap brokers defined, please set the -brokers flag") |
| 47 |
} |
| 48 |
|
| 49 |
if len(topic) == 0 { |
| 50 |
panic("no topic given to be consumed, please set the -topic flag") |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
func main() { |
| 55 |
keepRunning := true |
| 56 |
log.Println("Starting a new Sarama producer") |
| 57 |
|
| 58 |
if verbose { |
| 59 |
sarama.Logger = log.New(os.Stdout, "[sarama] ", log.LstdFlags) |
| 60 |
} |
| 61 |
|
| 62 |
version, err := sarama.ParseKafkaVersion(version) |
| 63 |
if err != nil { |
| 64 |
log.Panicf("Error parsing Kafka version: %v", err) |
| 65 |
} |
| 66 |
|
| 67 |
producerProvider := newProducerProvider(strings.Split(brokers, ","), func() *sarama.Config { |
| 68 |
config := sarama.NewConfig() |
| 69 |
config.Version = version |
| 70 |
config.Producer.Idempotent = true |
| 71 |
config.Producer.Return.Errors = false |
| 72 |
config.Producer.RequiredAcks = sarama.WaitForAll |
| 73 |
config.Producer.Partitioner = sarama.NewRoundRobinPartitioner |
| 74 |
config.Producer.Transaction.Retry.Backoff = 10 |
| 75 |
config.Producer.Transaction.ID = "txn_producer" |
| 76 |
config.Net.MaxOpenRequests = 1 |
| 77 |
return config |
| 78 |
}) |
| 79 |
|
| 80 |
go metrics.Log(metrics.DefaultRegistry, 5*time.Second, log.New(os.Stderr, "metrics: ", log.LstdFlags)) |
| 81 |
|
| 82 |
ctx, cancel := context.WithCancel(context.Background()) |
| 83 |
|
| 84 |
var wg sync.WaitGroup |
| 85 |
for i := 0; i < producers; i++ { |
| 86 |
wg.Add(1) |
| 87 |
go func() { |
| 88 |
defer wg.Done() |
| 89 |
|
| 90 |
for { |
| 91 |
select { |
| 92 |
case <-ctx.Done(): |
| 93 |
return |
| 94 |
default: |
| 95 |
produceTestRecord(producerProvider) |
| 96 |
} |
| 97 |
} |
| 98 |
}() |
| 99 |
} |
| 100 |
|
| 101 |
sigterm := make(chan os.Signal, 1) |
| 102 |
signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM) |
| 103 |
|
| 104 |
for keepRunning { |
| 105 |
<-sigterm |
| 106 |
log.Println("terminating: via signal") |
| 107 |
keepRunning = false |
| 108 |
} |
| 109 |
cancel() |
| 110 |
wg.Wait() |
| 111 |
|
| 112 |
producerProvider.clear() |
| 113 |
} |
| 114 |
|
| 115 |
func produceTestRecord(producerProvider *producerProvider) { |
| 116 |
producer := producerProvider.borrow() |
| 117 |
defer producerProvider.release(producer) |
| 118 |
|
| 119 |
// Start kafka transaction |
| 120 |
err := producer.BeginTxn() |
| 121 |
if err != nil { |
| 122 |
log.Printf("unable to start txn %s\n", err) |
| 123 |
return |
| 124 |
} |
| 125 |
|
| 126 |
// Produce some records in transaction |
| 127 |
var i int64 |
| 128 |
for i = 0; i < recordsNumber; i++ { |
| 129 |
producer.Input() <- &sarama.ProducerMessage{Topic: topic, Key: nil, Value: sarama.StringEncoder("test")} |
| 130 |
} |
| 131 |
|
| 132 |
// commit transaction |
| 133 |
err = producer.CommitTxn() |
| 134 |
if err != nil { |
| 135 |
log.Printf("Producer: unable to commit txn %s\n", err) |
| 136 |
for { |
| 137 |
if producer.TxnStatus()&sarama.ProducerTxnFlagFatalError != 0 { |
| 138 |
// fatal error. need to recreate producer. |
| 139 |
log.Printf("Producer: producer is in a fatal state, need to recreate it") |
| 140 |
break |
| 141 |
} |
| 142 |
// If producer is in abortable state, try to abort current transaction. |
| 143 |
if producer.TxnStatus()&sarama.ProducerTxnFlagAbortableError != 0 { |
| 144 |
err = producer.AbortTxn() |
| 145 |
if err != nil { |
| 146 |
// If an error occured just retry it. |
| 147 |
log.Printf("Producer: unable to abort transaction: %+v", err) |
| 148 |
continue |
| 149 |
} |
| 150 |
break |
| 151 |
} |
| 152 |
// if not you can retry |
| 153 |
err = producer.CommitTxn() |
| 154 |
if err != nil { |
| 155 |
log.Printf("Producer: unable to commit txn %s\n", err) |
| 156 |
continue |
| 157 |
} |
| 158 |
} |
| 159 |
return |
| 160 |
} |
| 161 |
recordsRate.Mark(recordsNumber) |
| 162 |
} |
| 163 |
|
| 164 |
// pool of producers that ensure transactional-id is unique. |
| 165 |
type producerProvider struct { |
| 166 |
transactionIdGenerator int32 |
| 167 |
|
| 168 |
producersLock sync.Mutex |
| 169 |
producers []sarama.AsyncProducer |
| 170 |
|
| 171 |
producerProvider func() sarama.AsyncProducer |
| 172 |
} |
| 173 |
|
| 174 |
func newProducerProvider(brokers []string, producerConfigurationProvider func() *sarama.Config) *producerProvider { |
| 175 |
provider := &producerProvider{} |
| 176 |
provider.producerProvider = func() sarama.AsyncProducer { |
| 177 |
config := producerConfigurationProvider() |
| 178 |
suffix := provider.transactionIdGenerator |
| 179 |
// Append transactionIdGenerator to current config.Producer.Transaction.ID to ensure transaction-id uniqueness. |
| 180 |
if config.Producer.Transaction.ID != "" { |
| 181 |
provider.transactionIdGenerator++ |
| 182 |
config.Producer.Transaction.ID = config.Producer.Transaction.ID + "-" + fmt.Sprint(suffix) |
| 183 |
} |
| 184 |
producer, err := sarama.NewAsyncProducer(brokers, config) |
| 185 |
if err != nil { |
| 186 |
return nil |
| 187 |
} |
| 188 |
return producer |
| 189 |
} |
| 190 |
return provider |
| 191 |
} |
| 192 |
|
| 193 |
func (p *producerProvider) borrow() (producer sarama.AsyncProducer) { |
| 194 |
p.producersLock.Lock() |
| 195 |
defer p.producersLock.Unlock() |
| 196 |
|
| 197 |
if len(p.producers) == 0 { |
| 198 |
for { |
| 199 |
producer = p.producerProvider() |
| 200 |
if producer != nil { |
| 201 |
return |
| 202 |
} |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
index := len(p.producers) - 1 |
| 207 |
producer = p.producers[index] |
| 208 |
p.producers = p.producers[:index] |
| 209 |
return |
| 210 |
} |
| 211 |
|
| 212 |
func (p *producerProvider) release(producer sarama.AsyncProducer) { |
| 213 |
p.producersLock.Lock() |
| 214 |
defer p.producersLock.Unlock() |
| 215 |
|
| 216 |
// If released producer is erroneous close it and don't return it to the producer pool. |
| 217 |
if producer.TxnStatus()&sarama.ProducerTxnFlagInError != 0 { |
| 218 |
// Try to close it |
| 219 |
_ = producer.Close() |
| 220 |
return |
| 221 |
} |
| 222 |
p.producers = append(p.producers, producer) |
| 223 |
} |
| 224 |
|
| 225 |
func (p *producerProvider) clear() { |
| 226 |
p.producersLock.Lock() |
| 227 |
defer p.producersLock.Unlock() |
| 228 |
|
| 229 |
for _, producer := range p.producers { |
| 230 |
producer.Close() |
| 231 |
} |
| 232 |
p.producers = p.producers[:0] |
| 233 |
} |