github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/orderer/kafka/producer.go (about) 1 /* 2 Copyright IBM Corp. 2016 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package kafka 18 19 import ( 20 "time" 21 22 "github.com/Shopify/sarama" 23 "github.com/hyperledger/fabric/orderer/localconfig" 24 ) 25 26 // Producer allows the caller to post blobs to a chain partition on the Kafka cluster. 27 type Producer interface { 28 Send(cp ChainPartition, payload []byte) error 29 Closeable 30 } 31 32 type producerImpl struct { 33 producer sarama.SyncProducer 34 } 35 36 func newProducer(brokers []string, kafkaVersion sarama.KafkaVersion, retryOptions config.Retry, tls config.TLS) Producer { 37 var p sarama.SyncProducer 38 var err error 39 brokerConfig := newBrokerConfig(kafkaVersion, rawPartition, tls) 40 41 repeatTick := time.NewTicker(retryOptions.Period) 42 panicTick := time.NewTicker(retryOptions.Stop) 43 defer repeatTick.Stop() 44 defer panicTick.Stop() 45 46 loop: 47 for { 48 select { 49 case <-panicTick.C: 50 logger.Panicf("Failed to create Kafka producer: %v", err) 51 case <-repeatTick.C: 52 logger.Debug("Connecting to Kafka cluster:", brokers) 53 p, err = sarama.NewSyncProducer(brokers, brokerConfig) 54 if err == nil { 55 break loop 56 } 57 } 58 } 59 60 logger.Debug("Connected to the Kafka cluster") 61 return &producerImpl{producer: p} 62 } 63 64 // Close shuts down the Producer component of the orderer. 65 func (p *producerImpl) Close() error { 66 return p.producer.Close() 67 } 68 69 // Send posts a blob to a chain partition on the Kafka cluster. 70 func (p *producerImpl) Send(cp ChainPartition, payload []byte) error { 71 prt, ofs, err := p.producer.SendMessage(newProducerMessage(cp, payload)) 72 if prt != cp.Partition() { 73 // If this happens, something's up with the partitioner 74 logger.Warningf("[channel: %s] Blob destined for partition %d, but posted to %d instead", cp.Topic(), cp.Partition(), prt) 75 } 76 if err == nil { 77 logger.Debugf("[channel %s] Posted blob to the Kafka cluster (offset number: %d)", cp.Topic(), ofs) 78 } else { 79 logger.Infof("[channel %s] Failed to post blob to the Kafka cluster: %s", cp.Topic(), err) 80 } 81 return err 82 }