config.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package sarama
  2. import (
  3. "crypto/tls"
  4. "time"
  5. )
  6. // Config is used to pass multiple configuration options to Sarama's constructors.
  7. type Config struct {
  8. // Net is the namespace for network-level properties used by the Broker, and shared by the Client/Producer/Consumer.
  9. Net struct {
  10. MaxOpenRequests int // How many outstanding requests a connection is allowed to have before sending on it blocks (default 5).
  11. // All three of the below configurations are similar to the `socket.timeout.ms` setting in JVM kafka.
  12. DialTimeout time.Duration // How long to wait for the initial connection to succeed before timing out and returning an error (default 30s).
  13. ReadTimeout time.Duration // How long to wait for a response before timing out and returning an error (default 30s).
  14. WriteTimeout time.Duration // How long to wait for a transmit to succeed before timing out and returning an error (default 30s).
  15. // NOTE: these config values have no compatibility guarantees; they may change when Kafka releases its
  16. // official TLS support in version 0.9.
  17. TLS struct {
  18. Enable bool // Whether or not to use TLS when connecting to the broker (defaults to false).
  19. Config *tls.Config // The TLS configuration to use for secure connections if enabled (defaults to nil).
  20. }
  21. // KeepAlive specifies the keep-alive period for an active network connection.
  22. // If zero, keep-alives are disabled. (default is 0: disabled).
  23. KeepAlive time.Duration
  24. }
  25. // Metadata is the namespace for metadata management properties used by the Client, and shared by the Producer/Consumer.
  26. Metadata struct {
  27. Retry struct {
  28. Max int // The total number of times to retry a metadata request when the cluster is in the middle of a leader election (default 3).
  29. Backoff time.Duration // How long to wait for leader election to occur before retrying (default 250ms). Similar to the JVM's `retry.backoff.ms`.
  30. }
  31. // How frequently to refresh the cluster metadata in the background. Defaults to 10 minutes.
  32. // Set to 0 to disable. Similar to `topic.metadata.refresh.interval.ms` in the JVM version.
  33. RefreshFrequency time.Duration
  34. }
  35. // Producer is the namespace for configuration related to producing messages, used by the Producer.
  36. Producer struct {
  37. // The maximum permitted size of a message (defaults to 1000000). Should be set equal to or smaller than the broker's `message.max.bytes`.
  38. MaxMessageBytes int
  39. // The level of acknowledgement reliability needed from the broker (defaults to WaitForLocal).
  40. // Equivalent to the `request.required.acks` setting of the JVM producer.
  41. RequiredAcks RequiredAcks
  42. // The maximum duration the broker will wait the receipt of the number of RequiredAcks (defaults to 10 seconds).
  43. // This is only relevant when RequiredAcks is set to WaitForAll or a number > 1. Only supports millisecond resolution,
  44. // nanoseconds will be truncated. Equivalent to the JVM producer's `request.timeout.ms` setting.
  45. Timeout time.Duration
  46. // The type of compression to use on messages (defaults to no compression). Similar to `compression.codec` setting of the JVM producer.
  47. Compression CompressionCodec
  48. // Generates partitioners for choosing the partition to send messages to (defaults to hashing the message key).
  49. // Similar to the `partitioner.class` setting for the JVM producer.
  50. Partitioner PartitionerConstructor
  51. // Return specifies what channels will be populated. If they are set to true, you must read from
  52. // the respective channels to prevent deadlock.
  53. Return struct {
  54. // If enabled, successfully delivered messages will be returned on the Successes channel (default disabled).
  55. Successes bool
  56. // If enabled, messages that failed to deliver will be returned on the Errors channel, including error (default enabled).
  57. Errors bool
  58. }
  59. // The following config options control how often messages are batched up and sent to the broker. By default,
  60. // messages are sent as fast as possible, and all messages received while the current batch is in-flight are placed
  61. // into the subsequent batch.
  62. Flush struct {
  63. Bytes int // The best-effort number of bytes needed to trigger a flush. Use the global sarama.MaxRequestSize to set a hard upper limit.
  64. Messages int // The best-effort number of messages needed to trigger a flush. Use `MaxMessages` to set a hard upper limit.
  65. Frequency time.Duration // The best-effort frequency of flushes. Equivalent to `queue.buffering.max.ms` setting of JVM producer.
  66. // The maximum number of messages the producer will send in a single broker request.
  67. // Defaults to 0 for unlimited. Similar to `queue.buffering.max.messages` in the JVM producer.
  68. MaxMessages int
  69. }
  70. Retry struct {
  71. // The total number of times to retry sending a message (default 3).
  72. // Similar to the `message.send.max.retries` setting of the JVM producer.
  73. Max int
  74. // How long to wait for the cluster to settle between retries (default 100ms).
  75. // Similar to the `retry.backoff.ms` setting of the JVM producer.
  76. Backoff time.Duration
  77. }
  78. }
  79. // Consumer is the namespace for configuration related to consuming messages, used by the Consumer.
  80. Consumer struct {
  81. Retry struct {
  82. // How long to wait after a failing to read from a partition before trying again (default 2s).
  83. Backoff time.Duration
  84. }
  85. // Fetch is the namespace for controlling how many bytes are retrieved by any given request.
  86. Fetch struct {
  87. // The minimum number of message bytes to fetch in a request - the broker will wait until at least this many are available.
  88. // The default is 1, as 0 causes the consumer to spin when no messages are available. Equivalent to the JVM's `fetch.min.bytes`.
  89. Min int32
  90. // The default number of message bytes to fetch from the broker in each request (default 32768). This should be larger than the
  91. // majority of your messages, or else the consumer will spend a lot of time negotiating sizes and not actually consuming. Similar
  92. // to the JVM's `fetch.message.max.bytes`.
  93. Default int32
  94. // The maximum number of message bytes to fetch from the broker in a single request. Messages larger than this will return
  95. // ErrMessageTooLarge and will not be consumable, so you must be sure this is at least as large as your largest message.
  96. // Defaults to 0 (no limit). Similar to the JVM's `fetch.message.max.bytes`. The global `sarama.MaxResponseSize` still applies.
  97. Max int32
  98. }
  99. // The maximum amount of time the broker will wait for Consumer.Fetch.Min bytes to become available before it
  100. // returns fewer than that anyways. The default is 250ms, since 0 causes the consumer to spin when no events are available.
  101. // 100-500ms is a reasonable range for most cases. Kafka only supports precision up to milliseconds; nanoseconds will be truncated.
  102. // Equivalent to the JVM's `fetch.wait.max.ms`.
  103. MaxWaitTime time.Duration
  104. // The maximum amount of time the consumer expects a message takes to process for the user. If writing to the Messages channel
  105. // takes longer than this, that partition will stop fetching more messages until it can proceed again. Note that, since the
  106. // Messages channel is buffered, the actual grace time is (MaxProcessingTime * ChanneBufferSize). Defaults to 100ms.
  107. MaxProcessingTime time.Duration
  108. // Return specifies what channels will be populated. If they are set to true, you must read from
  109. // them to prevent deadlock.
  110. Return struct {
  111. // If enabled, any errors that occured while consuming are returned on the Errors channel (default disabled).
  112. Errors bool
  113. }
  114. // Offsets specifies configuration for how and when to commit consumed offsets. This currently requires the
  115. // manual use of an OffsetManager but will eventually be automated.
  116. Offsets struct {
  117. // How frequently to commit updated offsets. Defaults to 1s.
  118. CommitInterval time.Duration
  119. // The initial offset to use if no offset was previously committed. Should be OffsetNewest or OffsetOldest.
  120. // Defaults to OffsetNewest.
  121. Initial int64
  122. }
  123. }
  124. // A user-provided string sent with every request to the brokers for logging, debugging, and auditing purposes.
  125. // Defaults to "sarama", but you should probably set it to something specific to your application.
  126. ClientID string
  127. // The number of events to buffer in internal and external channels. This permits the producer and consumer to
  128. // continue processing some messages in the background while user code is working, greatly improving throughput.
  129. // Defaults to 256.
  130. ChannelBufferSize int
  131. }
  132. // NewConfig returns a new configuration instance with sane defaults.
  133. func NewConfig() *Config {
  134. c := &Config{}
  135. c.Net.MaxOpenRequests = 5
  136. c.Net.DialTimeout = 30 * time.Second
  137. c.Net.ReadTimeout = 30 * time.Second
  138. c.Net.WriteTimeout = 30 * time.Second
  139. c.Metadata.Retry.Max = 3
  140. c.Metadata.Retry.Backoff = 250 * time.Millisecond
  141. c.Metadata.RefreshFrequency = 10 * time.Minute
  142. c.Producer.MaxMessageBytes = 1000000
  143. c.Producer.RequiredAcks = WaitForLocal
  144. c.Producer.Timeout = 10 * time.Second
  145. c.Producer.Partitioner = NewHashPartitioner
  146. c.Producer.Retry.Max = 3
  147. c.Producer.Retry.Backoff = 100 * time.Millisecond
  148. c.Producer.Return.Errors = true
  149. c.Consumer.Fetch.Min = 1
  150. c.Consumer.Fetch.Default = 32768
  151. c.Consumer.Retry.Backoff = 2 * time.Second
  152. c.Consumer.MaxWaitTime = 250 * time.Millisecond
  153. c.Consumer.MaxProcessingTime = 100 * time.Millisecond
  154. c.Consumer.Return.Errors = false
  155. c.Consumer.Offsets.CommitInterval = 1 * time.Second
  156. c.Consumer.Offsets.Initial = OffsetNewest
  157. c.ChannelBufferSize = 256
  158. return c
  159. }
  160. // Validate checks a Config instance. It will return a
  161. // ConfigurationError if the specified values don't make sense.
  162. func (c *Config) Validate() error {
  163. // some configuration values should be warned on but not fail completely, do those first
  164. if c.Net.TLS.Enable == false && c.Net.TLS.Config != nil {
  165. Logger.Println("Net.TLS is disabled but a non-nil configuration was provided.")
  166. }
  167. if c.Producer.RequiredAcks > 1 {
  168. Logger.Println("Producer.RequiredAcks > 1 is deprecated and will raise an exception with kafka >= 0.8.2.0.")
  169. }
  170. if c.Producer.MaxMessageBytes >= int(MaxRequestSize) {
  171. Logger.Println("Producer.MaxMessageBytes is larger than MaxRequestSize; it will be ignored.")
  172. }
  173. if c.Producer.Flush.Bytes >= int(MaxRequestSize) {
  174. Logger.Println("Producer.Flush.Bytes is larger than MaxRequestSize; it will be ignored.")
  175. }
  176. if c.Producer.Timeout%time.Millisecond != 0 {
  177. Logger.Println("Producer.Timeout only supports millisecond resolution; nanoseconds will be truncated.")
  178. }
  179. if c.Consumer.MaxWaitTime < 100*time.Millisecond {
  180. Logger.Println("Consumer.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.")
  181. }
  182. if c.Consumer.MaxWaitTime%time.Millisecond != 0 {
  183. Logger.Println("Consumer.MaxWaitTime only supports millisecond precision; nanoseconds will be truncated.")
  184. }
  185. if c.ClientID == "sarama" {
  186. Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.")
  187. }
  188. // validate Net values
  189. switch {
  190. case c.Net.MaxOpenRequests <= 0:
  191. return ConfigurationError("Net.MaxOpenRequests must be > 0")
  192. case c.Net.DialTimeout <= 0:
  193. return ConfigurationError("Net.DialTimeout must be > 0")
  194. case c.Net.ReadTimeout <= 0:
  195. return ConfigurationError("Net.ReadTimeout must be > 0")
  196. case c.Net.WriteTimeout <= 0:
  197. return ConfigurationError("Net.WriteTimeout must be > 0")
  198. case c.Net.KeepAlive < 0:
  199. return ConfigurationError("Net.KeepAlive must be >= 0")
  200. }
  201. // validate the Metadata values
  202. switch {
  203. case c.Metadata.Retry.Max < 0:
  204. return ConfigurationError("Metadata.Retry.Max must be >= 0")
  205. case c.Metadata.Retry.Backoff < 0:
  206. return ConfigurationError("Metadata.Retry.Backoff must be >= 0")
  207. case c.Metadata.RefreshFrequency < 0:
  208. return ConfigurationError("Metadata.RefreshFrequency must be >= 0")
  209. }
  210. // validate the Producer values
  211. switch {
  212. case c.Producer.MaxMessageBytes <= 0:
  213. return ConfigurationError("Producer.MaxMessageBytes must be > 0")
  214. case c.Producer.RequiredAcks < -1:
  215. return ConfigurationError("Producer.RequiredAcks must be >= -1")
  216. case c.Producer.Timeout <= 0:
  217. return ConfigurationError("Producer.Timeout must be > 0")
  218. case c.Producer.Partitioner == nil:
  219. return ConfigurationError("Producer.Partitioner must not be nil")
  220. case c.Producer.Flush.Bytes < 0:
  221. return ConfigurationError("Producer.Flush.Bytes must be >= 0")
  222. case c.Producer.Flush.Messages < 0:
  223. return ConfigurationError("Producer.Flush.Messages must be >= 0")
  224. case c.Producer.Flush.Frequency < 0:
  225. return ConfigurationError("Producer.Flush.Frequency must be >= 0")
  226. case c.Producer.Flush.MaxMessages < 0:
  227. return ConfigurationError("Producer.Flush.MaxMessages must be >= 0")
  228. case c.Producer.Flush.MaxMessages > 0 && c.Producer.Flush.MaxMessages < c.Producer.Flush.Messages:
  229. return ConfigurationError("Producer.Flush.MaxMessages must be >= Producer.Flush.Messages when set")
  230. case c.Producer.Retry.Max < 0:
  231. return ConfigurationError("Producer.Retry.Max must be >= 0")
  232. case c.Producer.Retry.Backoff < 0:
  233. return ConfigurationError("Producer.Retry.Backoff must be >= 0")
  234. }
  235. // validate the Consumer values
  236. switch {
  237. case c.Consumer.Fetch.Min <= 0:
  238. return ConfigurationError("Consumer.Fetch.Min must be > 0")
  239. case c.Consumer.Fetch.Default <= 0:
  240. return ConfigurationError("Consumer.Fetch.Default must be > 0")
  241. case c.Consumer.Fetch.Max < 0:
  242. return ConfigurationError("Consumer.Fetch.Max must be >= 0")
  243. case c.Consumer.MaxWaitTime < 1*time.Millisecond:
  244. return ConfigurationError("Consumer.MaxWaitTime must be >= 1ms")
  245. case c.Consumer.MaxProcessingTime <= 0:
  246. return ConfigurationError("Consumer.MaxProcessingTime must be > 0")
  247. case c.Consumer.Retry.Backoff < 0:
  248. return ConfigurationError("Consumer.Retry.Backoff must be >= 0")
  249. case c.Consumer.Offsets.CommitInterval <= 0:
  250. return ConfigurationError("Consumer.Offsets.CommitInterval must be > 0")
  251. case c.Consumer.Offsets.Initial != OffsetOldest && c.Consumer.Offsets.Initial != OffsetNewest:
  252. return ConfigurationError("Consumer.Offsets.Initial must be OffsetOldest or OffsetNewest")
  253. }
  254. // validate misc shared values
  255. switch {
  256. case c.ChannelBufferSize < 0:
  257. return ConfigurationError("ChannelBufferSize must be >= 0")
  258. }
  259. return nil
  260. }