kafka-console-producer.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "strings"
  9. "github.com/Shopify/sarama"
  10. "github.com/Shopify/sarama/tools/tls"
  11. "github.com/rcrowley/go-metrics"
  12. )
  13. var (
  14. brokerList = flag.String("brokers", os.Getenv("KAFKA_PEERS"), "The comma separated list of brokers in the Kafka cluster. You can also set the KAFKA_PEERS environment variable")
  15. topic = flag.String("topic", "", "REQUIRED: the topic to produce to")
  16. key = flag.String("key", "", "The key of the message to produce. Can be empty.")
  17. value = flag.String("value", "", "REQUIRED: the value of the message to produce. You can also provide the value on stdin.")
  18. partitioner = flag.String("partitioner", "", "The partitioning scheme to use. Can be `hash`, `manual`, or `random`")
  19. partition = flag.Int("partition", -1, "The partition to produce to.")
  20. verbose = flag.Bool("verbose", false, "Turn on sarama logging to stderr")
  21. showMetrics = flag.Bool("metrics", false, "Output metrics on successful publish to stderr")
  22. silent = flag.Bool("silent", false, "Turn off printing the message's topic, partition, and offset to stdout")
  23. tlsEnabled = flag.Bool("tls-enabled", false, "Whether to enable TLS")
  24. tlsSkipVerify = flag.Bool("tls-skip-verify", false, "Whether skip TLS server cert verification")
  25. tlsClientCert = flag.String("tls-client-cert", "", "Client cert for client authentication (use with -tls-enabled and -tls-client-key)")
  26. tlsClientKey = flag.String("tls-client-key", "", "Client key for client authentication (use with tls-enabled and -tls-client-cert)")
  27. logger = log.New(os.Stderr, "", log.LstdFlags)
  28. )
  29. func main() {
  30. flag.Parse()
  31. if *brokerList == "" {
  32. printUsageErrorAndExit("no -brokers specified. Alternatively, set the KAFKA_PEERS environment variable")
  33. }
  34. if *topic == "" {
  35. printUsageErrorAndExit("no -topic specified")
  36. }
  37. if *verbose {
  38. sarama.Logger = logger
  39. }
  40. config := sarama.NewConfig()
  41. config.Producer.RequiredAcks = sarama.WaitForAll
  42. config.Producer.Return.Successes = true
  43. if *tlsEnabled {
  44. tlsConfig, err := tls.NewConfig(*tlsClientCert, *tlsClientKey)
  45. if err != nil {
  46. printErrorAndExit(69, "Failed to create TLS config: %s", err)
  47. }
  48. config.Net.TLS.Enable = true
  49. config.Net.TLS.Config = tlsConfig
  50. config.Net.TLS.Config.InsecureSkipVerify = *tlsSkipVerify
  51. }
  52. switch *partitioner {
  53. case "":
  54. if *partition >= 0 {
  55. config.Producer.Partitioner = sarama.NewManualPartitioner
  56. } else {
  57. config.Producer.Partitioner = sarama.NewHashPartitioner
  58. }
  59. case "hash":
  60. config.Producer.Partitioner = sarama.NewHashPartitioner
  61. case "random":
  62. config.Producer.Partitioner = sarama.NewRandomPartitioner
  63. case "manual":
  64. config.Producer.Partitioner = sarama.NewManualPartitioner
  65. if *partition == -1 {
  66. printUsageErrorAndExit("-partition is required when partitioning manually")
  67. }
  68. default:
  69. printUsageErrorAndExit(fmt.Sprintf("Partitioner %s not supported.", *partitioner))
  70. }
  71. message := &sarama.ProducerMessage{Topic: *topic, Partition: int32(*partition)}
  72. if *key != "" {
  73. message.Key = sarama.StringEncoder(*key)
  74. }
  75. if *value != "" {
  76. message.Value = sarama.StringEncoder(*value)
  77. } else if stdinAvailable() {
  78. bytes, err := ioutil.ReadAll(os.Stdin)
  79. if err != nil {
  80. printErrorAndExit(66, "Failed to read data from the standard input: %s", err)
  81. }
  82. message.Value = sarama.ByteEncoder(bytes)
  83. } else {
  84. printUsageErrorAndExit("-value is required, or you have to provide the value on stdin")
  85. }
  86. producer, err := sarama.NewSyncProducer(strings.Split(*brokerList, ","), config)
  87. if err != nil {
  88. printErrorAndExit(69, "Failed to open Kafka producer: %s", err)
  89. }
  90. defer func() {
  91. if err := producer.Close(); err != nil {
  92. logger.Println("Failed to close Kafka producer cleanly:", err)
  93. }
  94. }()
  95. partition, offset, err := producer.SendMessage(message)
  96. if err != nil {
  97. printErrorAndExit(69, "Failed to produce message: %s", err)
  98. } else if !*silent {
  99. fmt.Printf("topic=%s\tpartition=%d\toffset=%d\n", *topic, partition, offset)
  100. }
  101. if *showMetrics {
  102. metrics.WriteOnce(config.MetricRegistry, os.Stderr)
  103. }
  104. }
  105. func printErrorAndExit(code int, format string, values ...interface{}) {
  106. fmt.Fprintf(os.Stderr, "ERROR: %s\n", fmt.Sprintf(format, values...))
  107. fmt.Fprintln(os.Stderr)
  108. os.Exit(code)
  109. }
  110. func printUsageErrorAndExit(message string) {
  111. fmt.Fprintln(os.Stderr, "ERROR:", message)
  112. fmt.Fprintln(os.Stderr)
  113. fmt.Fprintln(os.Stderr, "Available command line options:")
  114. flag.PrintDefaults()
  115. os.Exit(64)
  116. }
  117. func stdinAvailable() bool {
  118. stat, _ := os.Stdin.Stat()
  119. return (stat.Mode() & os.ModeCharDevice) == 0
  120. }