kafka-console-producer.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "strings"
  9. "github.com/Shopify/sarama"
  10. )
  11. var (
  12. 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")
  13. topic = flag.String("topic", "", "REQUIRED: the topic to produce to")
  14. key = flag.String("key", "", "The key of the message to produce. Can be empty.")
  15. value = flag.String("value", "", "REQUIRED: the value of the message to produce. You can also provide the value on stdin.")
  16. partitioner = flag.String("partitioner", "", "The partitioning scheme to use. Can be `hash`, `manual`, or `random`")
  17. partition = flag.Int("partition", -1, "The partition to produce to.")
  18. verbose = flag.Bool("verbose", false, "Turn on sarama logging to stderr")
  19. silent = flag.Bool("silent", false, "Turn off printing the message's topic, partition, and offset to stdout")
  20. logger = log.New(os.Stderr, "", log.LstdFlags)
  21. )
  22. func main() {
  23. flag.Parse()
  24. if *brokerList == "" {
  25. printUsageErrorAndExit("no -brokers specified. Alternatively, set the KAFKA_PEERS environment variable")
  26. }
  27. if *topic == "" {
  28. printUsageErrorAndExit("no -topic specified")
  29. }
  30. if *verbose {
  31. sarama.Logger = logger
  32. }
  33. config := sarama.NewConfig()
  34. config.Producer.RequiredAcks = sarama.WaitForAll
  35. switch *partitioner {
  36. case "":
  37. if *partition >= 0 {
  38. config.Producer.Partitioner = sarama.NewManualPartitioner
  39. } else {
  40. config.Producer.Partitioner = sarama.NewHashPartitioner
  41. }
  42. case "hash":
  43. config.Producer.Partitioner = sarama.NewHashPartitioner
  44. case "random":
  45. config.Producer.Partitioner = sarama.NewRandomPartitioner
  46. case "manual":
  47. config.Producer.Partitioner = sarama.NewManualPartitioner
  48. if *partition == -1 {
  49. printUsageErrorAndExit("-partition is required when partitioning manually")
  50. }
  51. default:
  52. printUsageErrorAndExit(fmt.Sprintf("Partitioner %s not supported.", *partitioner))
  53. }
  54. message := &sarama.ProducerMessage{Topic: *topic, Partition: int32(*partition)}
  55. if *key != "" {
  56. message.Key = sarama.StringEncoder(*key)
  57. }
  58. if *value != "" {
  59. message.Value = sarama.StringEncoder(*value)
  60. } else if stdinAvailable() {
  61. bytes, err := ioutil.ReadAll(os.Stdin)
  62. if err != nil {
  63. printErrorAndExit(66, "Failed to read data from the standard input: %s", err)
  64. }
  65. message.Value = sarama.ByteEncoder(bytes)
  66. } else {
  67. printUsageErrorAndExit("-value is required, or you have to provide the value on stdin")
  68. }
  69. producer, err := sarama.NewSyncProducer(strings.Split(*brokerList, ","), config)
  70. if err != nil {
  71. printErrorAndExit(69, "Failed to open Kafka producer: %s", err)
  72. }
  73. defer func() {
  74. if err := producer.Close(); err != nil {
  75. logger.Println("Failed to close Kafka producer cleanly:", err)
  76. }
  77. }()
  78. partition, offset, err := producer.SendMessage(message)
  79. if err != nil {
  80. printErrorAndExit(69, "Failed to produce message: %s", err)
  81. } else if !*silent {
  82. fmt.Printf("topic=%s\tpartition=%d\toffset=%d\n", *topic, partition, offset)
  83. }
  84. }
  85. func printErrorAndExit(code int, format string, values ...interface{}) {
  86. fmt.Fprintf(os.Stderr, "ERROR: %s\n", fmt.Sprintf(format, values...))
  87. fmt.Fprintln(os.Stderr)
  88. os.Exit(code)
  89. }
  90. func printUsageErrorAndExit(message string) {
  91. fmt.Fprintln(os.Stderr, "ERROR:", message)
  92. fmt.Fprintln(os.Stderr)
  93. fmt.Fprintln(os.Stderr, "Available command line options:")
  94. flag.PrintDefaults()
  95. os.Exit(64)
  96. }
  97. func stdinAvailable() bool {
  98. stat, _ := os.Stdin.Stat()
  99. return (stat.Mode() & os.ModeCharDevice) == 0
  100. }