config.go 20 KB

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