config.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package sarama
  2. import (
  3. "crypto/tls"
  4. "regexp"
  5. "time"
  6. )
  7. const defaultClientID = "sarama"
  8. var validID = regexp.MustCompile(`\A[A-Za-z0-9._-]+\z`)
  9. // Config is used to pass multiple configuration options to Sarama's constructors.
  10. type Config struct {
  11. // Net is the namespace for network-level properties used by the Broker, and
  12. // shared by the Client/Producer/Consumer.
  13. Net struct {
  14. // How many outstanding requests a connection is allowed to have before
  15. // sending on it blocks (default 5).
  16. MaxOpenRequests int
  17. // All three of the below configurations are similar to the
  18. // `socket.timeout.ms` setting in JVM kafka. All of them default
  19. // to 30 seconds.
  20. DialTimeout time.Duration // How long to wait for the initial connection.
  21. ReadTimeout time.Duration // How long to wait for a response.
  22. WriteTimeout time.Duration // How long to wait for a transmit.
  23. TLS struct {
  24. // Whether or not to use TLS when connecting to the broker
  25. // (defaults to false).
  26. Enable bool
  27. // The TLS configuration to use for secure connections if
  28. // enabled (defaults to nil).
  29. Config *tls.Config
  30. }
  31. // SASL based authentication with broker. While there are multiple SASL authentication methods
  32. // the current implementation is limited to plaintext (SASL/PLAIN) authentication
  33. SASL struct {
  34. // Whether or not to use SASL authentication when connecting to the broker
  35. // (defaults to false).
  36. Enable bool
  37. //username and password for SASL/PLAIN authentication
  38. User string
  39. Password string
  40. }
  41. // KeepAlive specifies the keep-alive period for an active network connection.
  42. // If zero, keep-alives are disabled. (default is 0: disabled).
  43. KeepAlive time.Duration
  44. }
  45. // Metadata is the namespace for metadata management properties used by the
  46. // Client, and shared by the Producer/Consumer.
  47. Metadata struct {
  48. Retry struct {
  49. // The total number of times to retry a metadata request when the
  50. // cluster is in the middle of a leader election (default 3).
  51. Max int
  52. // How long to wait for leader election to occur before retrying
  53. // (default 250ms). Similar to the JVM's `retry.backoff.ms`.
  54. Backoff time.Duration
  55. }
  56. // How frequently to refresh the cluster metadata in the background.
  57. // Defaults to 10 minutes. Set to 0 to disable. Similar to
  58. // `topic.metadata.refresh.interval.ms` in the JVM version.
  59. RefreshFrequency time.Duration
  60. }
  61. // Producer is the namespace for configuration related to producing messages,
  62. // used by the Producer.
  63. Producer struct {
  64. // The maximum permitted size of a message (defaults to 1000000). Should be
  65. // set equal to or smaller than the broker's `message.max.bytes`.
  66. MaxMessageBytes int
  67. // The level of acknowledgement reliability needed from the broker (defaults
  68. // to WaitForLocal). Equivalent to the `request.required.acks` setting of the
  69. // JVM producer.
  70. RequiredAcks RequiredAcks
  71. // The maximum duration the broker will wait the receipt of the number of
  72. // RequiredAcks (defaults to 10 seconds). This is only relevant when
  73. // RequiredAcks is set to WaitForAll or a number > 1. Only supports
  74. // millisecond resolution, nanoseconds will be truncated. Equivalent to
  75. // the JVM producer's `request.timeout.ms` setting.
  76. Timeout time.Duration
  77. // The type of compression to use on messages (defaults to no compression).
  78. // Similar to `compression.codec` setting of the JVM producer.
  79. Compression CompressionCodec
  80. // Generates partitioners for choosing the partition to send messages to
  81. // (defaults to hashing the message key). Similar to the `partitioner.class`
  82. // setting for the JVM producer.
  83. Partitioner PartitionerConstructor
  84. // Return specifies what channels will be populated. If they are set to true,
  85. // you must read from the respective channels to prevent deadlock.
  86. Return struct {
  87. // If enabled, successfully delivered messages will be returned on the
  88. // Successes channel (default disabled).
  89. Successes bool
  90. // If enabled, messages that failed to deliver will be returned on the
  91. // Errors channel, including error (default enabled).
  92. Errors bool
  93. }
  94. // The following config options control how often messages are batched up and
  95. // sent to the broker. By default, messages are sent as fast as possible, and
  96. // all messages received while the current batch is in-flight are placed
  97. // into the subsequent batch.
  98. Flush struct {
  99. // The best-effort number of bytes needed to trigger a flush. Use the
  100. // global sarama.MaxRequestSize to set a hard upper limit.
  101. Bytes int
  102. // The best-effort number of messages needed to trigger a flush. Use
  103. // `MaxMessages` to set a hard upper limit.
  104. Messages int
  105. // The best-effort frequency of flushes. Equivalent to
  106. // `queue.buffering.max.ms` setting of JVM producer.
  107. Frequency time.Duration
  108. // The maximum number of messages the producer will send in a single
  109. // broker request. Defaults to 0 for unlimited. Similar to
  110. // `queue.buffering.max.messages` in the JVM producer.
  111. MaxMessages int
  112. }
  113. Retry struct {
  114. // The total number of times to retry sending a message (default 3).
  115. // Similar to the `message.send.max.retries` setting of the JVM producer.
  116. Max int
  117. // How long to wait for the cluster to settle between retries
  118. // (default 100ms). Similar to the `retry.backoff.ms` setting of the
  119. // JVM producer.
  120. Backoff time.Duration
  121. }
  122. }
  123. // Consumer is the namespace for configuration related to consuming messages,
  124. // used by the Consumer.
  125. //
  126. // Note that Sarama's Consumer type does not currently support automatic
  127. // consumer-group rebalancing and offset tracking. For Zookeeper-based
  128. // tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka
  129. // library builds on Sarama to add this support. For Kafka-based tracking
  130. // (Kafka 0.9 and later), the https://github.com/bsm/sarama-cluster library
  131. // builds on Sarama to add this support.
  132. Consumer struct {
  133. Retry struct {
  134. // How long to wait after a failing to read from a partition before
  135. // trying again (default 2s).
  136. Backoff time.Duration
  137. }
  138. // Fetch is the namespace for controlling how many bytes are retrieved by any
  139. // given request.
  140. Fetch struct {
  141. // The minimum number of message bytes to fetch in a request - the broker
  142. // will wait until at least this many are available. The default is 1,
  143. // as 0 causes the consumer to spin when no messages are available.
  144. // Equivalent to the JVM's `fetch.min.bytes`.
  145. Min int32
  146. // The default number of message bytes to fetch from the broker in each
  147. // request (default 32768). This should be larger than the majority of
  148. // your messages, or else the consumer will spend a lot of time
  149. // negotiating sizes and not actually consuming. Similar to the JVM's
  150. // `fetch.message.max.bytes`.
  151. Default int32
  152. // The maximum number of message bytes to fetch from the broker in a
  153. // single request. Messages larger than this will return
  154. // ErrMessageTooLarge and will not be consumable, so you must be sure
  155. // this is at least as large as your largest message. Defaults to 0
  156. // (no limit). Similar to the JVM's `fetch.message.max.bytes`. The
  157. // global `sarama.MaxResponseSize` still applies.
  158. Max int32
  159. }
  160. // The maximum amount of time the broker will wait for Consumer.Fetch.Min
  161. // bytes to become available before it returns fewer than that anyways. The
  162. // default is 250ms, since 0 causes the consumer to spin when no events are
  163. // available. 100-500ms is a reasonable range for most cases. Kafka only
  164. // supports precision up to milliseconds; nanoseconds will be truncated.
  165. // Equivalent to the JVM's `fetch.wait.max.ms`.
  166. MaxWaitTime time.Duration
  167. // The maximum amount of time the consumer expects a message takes to process
  168. // for the user. If writing to the Messages channel takes longer than this,
  169. // that partition will stop fetching more messages until it can proceed again.
  170. // Note that, since the Messages channel is buffered, the actual grace time is
  171. // (MaxProcessingTime * ChanneBufferSize). Defaults to 100ms.
  172. MaxProcessingTime time.Duration
  173. // Return specifies what channels will be populated. If they are set to true,
  174. // you must read from them to prevent deadlock.
  175. Return struct {
  176. // If enabled, any errors that occurred while consuming are returned on
  177. // the Errors channel (default disabled).
  178. Errors bool
  179. }
  180. // Offsets specifies configuration for how and when to commit consumed
  181. // offsets. This currently requires the manual use of an OffsetManager
  182. // but will eventually be automated.
  183. Offsets struct {
  184. // How frequently to commit updated offsets. Defaults to 1s.
  185. CommitInterval time.Duration
  186. // The initial offset to use if no offset was previously committed.
  187. // Should be OffsetNewest or OffsetOldest. Defaults to OffsetNewest.
  188. Initial int64
  189. // The retention duration for committed offsets. If zero, disabled
  190. // (in which case the `offsets.retention.minutes` option on the
  191. // broker will be used). Kafka only supports precision up to
  192. // milliseconds; nanoseconds will be truncated. Requires Kafka
  193. // broker version 0.9.0 or later.
  194. // (default is 0: disabled).
  195. Retention time.Duration
  196. }
  197. }
  198. // A user-provided string sent with every request to the brokers for logging,
  199. // debugging, and auditing purposes. Defaults to "sarama", but you should
  200. // probably set it to something specific to your application.
  201. ClientID string
  202. // The number of events to buffer in internal and external channels. This
  203. // permits the producer and consumer to continue processing some messages
  204. // in the background while user code is working, greatly improving throughput.
  205. // Defaults to 256.
  206. ChannelBufferSize int
  207. // The version of Kafka that Sarama will assume it is running against.
  208. // Defaults to the oldest supported stable version. Since Kafka provides
  209. // backwards-compatibility, setting it to a version older than you have
  210. // will not break anything, although it may prevent you from using the
  211. // latest features. Setting it to a version greater than you are actually
  212. // running may lead to random breakage.
  213. Version KafkaVersion
  214. }
  215. // NewConfig returns a new configuration instance with sane defaults.
  216. func NewConfig() *Config {
  217. c := &Config{}
  218. c.Net.MaxOpenRequests = 5
  219. c.Net.DialTimeout = 30 * time.Second
  220. c.Net.ReadTimeout = 30 * time.Second
  221. c.Net.WriteTimeout = 30 * time.Second
  222. c.Metadata.Retry.Max = 3
  223. c.Metadata.Retry.Backoff = 250 * time.Millisecond
  224. c.Metadata.RefreshFrequency = 10 * time.Minute
  225. c.Producer.MaxMessageBytes = 1000000
  226. c.Producer.RequiredAcks = WaitForLocal
  227. c.Producer.Timeout = 10 * time.Second
  228. c.Producer.Partitioner = NewHashPartitioner
  229. c.Producer.Retry.Max = 3
  230. c.Producer.Retry.Backoff = 100 * time.Millisecond
  231. c.Producer.Return.Errors = true
  232. c.Consumer.Fetch.Min = 1
  233. c.Consumer.Fetch.Default = 32768
  234. c.Consumer.Retry.Backoff = 2 * time.Second
  235. c.Consumer.MaxWaitTime = 250 * time.Millisecond
  236. c.Consumer.MaxProcessingTime = 100 * time.Millisecond
  237. c.Consumer.Return.Errors = false
  238. c.Consumer.Offsets.CommitInterval = 1 * time.Second
  239. c.Consumer.Offsets.Initial = OffsetNewest
  240. c.ClientID = defaultClientID
  241. c.ChannelBufferSize = 256
  242. c.Version = minVersion
  243. return c
  244. }
  245. // Validate checks a Config instance. It will return a
  246. // ConfigurationError if the specified values don't make sense.
  247. func (c *Config) Validate() error {
  248. // some configuration values should be warned on but not fail completely, do those first
  249. if c.Net.TLS.Enable == false && c.Net.TLS.Config != nil {
  250. Logger.Println("Net.TLS is disabled but a non-nil configuration was provided.")
  251. }
  252. if c.Net.SASL.Enable == false {
  253. if c.Net.SASL.User != "" {
  254. Logger.Println("Net.SASL is disabled but a non-empty username was provided.")
  255. }
  256. if c.Net.SASL.Password != "" {
  257. Logger.Println("Net.SASL is disabled but a non-empty password was provided.")
  258. }
  259. }
  260. if c.Producer.RequiredAcks > 1 {
  261. Logger.Println("Producer.RequiredAcks > 1 is deprecated and will raise an exception with kafka >= 0.8.2.0.")
  262. }
  263. if c.Producer.MaxMessageBytes >= int(MaxRequestSize) {
  264. Logger.Println("Producer.MaxMessageBytes is larger than MaxRequestSize; it will be ignored.")
  265. }
  266. if c.Producer.Flush.Bytes >= int(MaxRequestSize) {
  267. Logger.Println("Producer.Flush.Bytes is larger than MaxRequestSize; it will be ignored.")
  268. }
  269. if c.Producer.Timeout%time.Millisecond != 0 {
  270. Logger.Println("Producer.Timeout only supports millisecond resolution; nanoseconds will be truncated.")
  271. }
  272. if c.Consumer.MaxWaitTime < 100*time.Millisecond {
  273. Logger.Println("Consumer.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.")
  274. }
  275. if c.Consumer.MaxWaitTime%time.Millisecond != 0 {
  276. Logger.Println("Consumer.MaxWaitTime only supports millisecond precision; nanoseconds will be truncated.")
  277. }
  278. if c.Consumer.Offsets.Retention%time.Millisecond != 0 {
  279. Logger.Println("Consumer.Offsets.Retention only supports millisecond precision; nanoseconds will be truncated.")
  280. }
  281. if c.ClientID == defaultClientID {
  282. Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.")
  283. }
  284. // validate Net values
  285. switch {
  286. case c.Net.MaxOpenRequests <= 0:
  287. return ConfigurationError("Net.MaxOpenRequests must be > 0")
  288. case c.Net.DialTimeout <= 0:
  289. return ConfigurationError("Net.DialTimeout must be > 0")
  290. case c.Net.ReadTimeout <= 0:
  291. return ConfigurationError("Net.ReadTimeout must be > 0")
  292. case c.Net.WriteTimeout <= 0:
  293. return ConfigurationError("Net.WriteTimeout must be > 0")
  294. case c.Net.KeepAlive < 0:
  295. return ConfigurationError("Net.KeepAlive must be >= 0")
  296. case c.Net.SASL.Enable == true && c.Net.SASL.User == "":
  297. return ConfigurationError("Net.SASL.User must not be empty when SASL is enabled")
  298. case c.Net.SASL.Enable == true && c.Net.SASL.Password == "":
  299. return ConfigurationError("Net.SASL.Password must not be empty when SASL is enabled")
  300. }
  301. // validate the Metadata values
  302. switch {
  303. case c.Metadata.Retry.Max < 0:
  304. return ConfigurationError("Metadata.Retry.Max must be >= 0")
  305. case c.Metadata.Retry.Backoff < 0:
  306. return ConfigurationError("Metadata.Retry.Backoff must be >= 0")
  307. case c.Metadata.RefreshFrequency < 0:
  308. return ConfigurationError("Metadata.RefreshFrequency must be >= 0")
  309. }
  310. // validate the Producer values
  311. switch {
  312. case c.Producer.MaxMessageBytes <= 0:
  313. return ConfigurationError("Producer.MaxMessageBytes must be > 0")
  314. case c.Producer.RequiredAcks < -1:
  315. return ConfigurationError("Producer.RequiredAcks must be >= -1")
  316. case c.Producer.Timeout <= 0:
  317. return ConfigurationError("Producer.Timeout must be > 0")
  318. case c.Producer.Partitioner == nil:
  319. return ConfigurationError("Producer.Partitioner must not be nil")
  320. case c.Producer.Flush.Bytes < 0:
  321. return ConfigurationError("Producer.Flush.Bytes must be >= 0")
  322. case c.Producer.Flush.Messages < 0:
  323. return ConfigurationError("Producer.Flush.Messages must be >= 0")
  324. case c.Producer.Flush.Frequency < 0:
  325. return ConfigurationError("Producer.Flush.Frequency must be >= 0")
  326. case c.Producer.Flush.MaxMessages < 0:
  327. return ConfigurationError("Producer.Flush.MaxMessages must be >= 0")
  328. case c.Producer.Flush.MaxMessages > 0 && c.Producer.Flush.MaxMessages < c.Producer.Flush.Messages:
  329. return ConfigurationError("Producer.Flush.MaxMessages must be >= Producer.Flush.Messages when set")
  330. case c.Producer.Retry.Max < 0:
  331. return ConfigurationError("Producer.Retry.Max must be >= 0")
  332. case c.Producer.Retry.Backoff < 0:
  333. return ConfigurationError("Producer.Retry.Backoff must be >= 0")
  334. }
  335. // validate the Consumer values
  336. switch {
  337. case c.Consumer.Fetch.Min <= 0:
  338. return ConfigurationError("Consumer.Fetch.Min must be > 0")
  339. case c.Consumer.Fetch.Default <= 0:
  340. return ConfigurationError("Consumer.Fetch.Default must be > 0")
  341. case c.Consumer.Fetch.Max < 0:
  342. return ConfigurationError("Consumer.Fetch.Max must be >= 0")
  343. case c.Consumer.MaxWaitTime < 1*time.Millisecond:
  344. return ConfigurationError("Consumer.MaxWaitTime must be >= 1ms")
  345. case c.Consumer.MaxProcessingTime <= 0:
  346. return ConfigurationError("Consumer.MaxProcessingTime must be > 0")
  347. case c.Consumer.Retry.Backoff < 0:
  348. return ConfigurationError("Consumer.Retry.Backoff must be >= 0")
  349. case c.Consumer.Offsets.CommitInterval <= 0:
  350. return ConfigurationError("Consumer.Offsets.CommitInterval must be > 0")
  351. case c.Consumer.Offsets.Initial != OffsetOldest && c.Consumer.Offsets.Initial != OffsetNewest:
  352. return ConfigurationError("Consumer.Offsets.Initial must be OffsetOldest or OffsetNewest")
  353. }
  354. // validate misc shared values
  355. switch {
  356. case c.ChannelBufferSize < 0:
  357. return ConfigurationError("ChannelBufferSize must be >= 0")
  358. case !validID.MatchString(c.ClientID):
  359. return ConfigurationError("ClientID is invalid")
  360. }
  361. return nil
  362. }