config.go 16 KB

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