config.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. "golang.org/x/net/proxy"
  12. )
  13. const defaultClientID = "sarama"
  14. var validID = regexp.MustCompile(`\A[A-Za-z0-9._-]+\z`)
  15. // Config is used to pass multiple configuration options to Sarama's constructors.
  16. type Config struct {
  17. // Admin is the namespace for ClusterAdmin properties used by the administrative Kafka client.
  18. Admin struct {
  19. // The maximum duration the administrative Kafka client will wait for ClusterAdmin operations,
  20. // including topics, brokers, configurations and ACLs (defaults to 3 seconds).
  21. Timeout time.Duration
  22. }
  23. // Net is the namespace for network-level properties used by the Broker, and
  24. // shared by the Client/Producer/Consumer.
  25. Net struct {
  26. // How many outstanding requests a connection is allowed to have before
  27. // sending on it blocks (default 5).
  28. MaxOpenRequests int
  29. // All three of the below configurations are similar to the
  30. // `socket.timeout.ms` setting in JVM kafka. All of them default
  31. // to 30 seconds.
  32. DialTimeout time.Duration // How long to wait for the initial connection.
  33. ReadTimeout time.Duration // How long to wait for a response.
  34. WriteTimeout time.Duration // How long to wait for a transmit.
  35. TLS struct {
  36. // Whether or not to use TLS when connecting to the broker
  37. // (defaults to false).
  38. Enable bool
  39. // The TLS configuration to use for secure connections if
  40. // enabled (defaults to nil).
  41. Config *tls.Config
  42. }
  43. // SASL based authentication with broker. While there are multiple SASL authentication methods
  44. // the current implementation is limited to plaintext (SASL/PLAIN) authentication
  45. SASL struct {
  46. // Whether or not to use SASL authentication when connecting to the broker
  47. // (defaults to false).
  48. Enable bool
  49. // SASLMechanism is the name of the enabled SASL mechanism.
  50. // Possible values: OAUTHBEARER, PLAIN (defaults to PLAIN).
  51. Mechanism SASLMechanism
  52. // Whether or not to send the Kafka SASL handshake first if enabled
  53. // (defaults to true). You should only set this to false if you're using
  54. // a non-Kafka SASL proxy.
  55. Handshake bool
  56. //username and password for SASL/PLAIN or SASL/SCRAM authentication
  57. User string
  58. Password string
  59. // authz id used for SASL/SCRAM authentication
  60. SCRAMAuthzID string
  61. // SCRAMClient is a user provided implementation of a SCRAM
  62. // client used to perform the SCRAM exchange with the server.
  63. SCRAMClient SCRAMClient
  64. // TokenProvider is a user-defined callback for generating
  65. // access tokens for SASL/OAUTHBEARER auth. See the
  66. // AccessTokenProvider interface docs for proper implementation
  67. // guidelines.
  68. TokenProvider AccessTokenProvider
  69. }
  70. // KeepAlive specifies the keep-alive period for an active network connection.
  71. // If zero, keep-alives are disabled. (default is 0: disabled).
  72. KeepAlive time.Duration
  73. // LocalAddr is the local address to use when dialing an
  74. // address. The address must be of a compatible type for the
  75. // network being dialed.
  76. // If nil, a local address is automatically chosen.
  77. LocalAddr net.Addr
  78. Proxy struct {
  79. // Whether or not to use proxy when connecting to the broker
  80. // (defaults to false).
  81. Enable bool
  82. // The proxy dialer to use enabled (defaults to nil).
  83. Dialer proxy.Dialer
  84. }
  85. }
  86. // Metadata is the namespace for metadata management properties used by the
  87. // Client, and shared by the Producer/Consumer.
  88. Metadata struct {
  89. Retry struct {
  90. // The total number of times to retry a metadata request when the
  91. // cluster is in the middle of a leader election (default 3).
  92. Max int
  93. // How long to wait for leader election to occur before retrying
  94. // (default 250ms). Similar to the JVM's `retry.backoff.ms`.
  95. Backoff time.Duration
  96. // Called to compute backoff time dynamically. Useful for implementing
  97. // more sophisticated backoff strategies. This takes precedence over
  98. // `Backoff` if set.
  99. BackoffFunc func(retries, maxRetries int) time.Duration
  100. }
  101. // How frequently to refresh the cluster metadata in the background.
  102. // Defaults to 10 minutes. Set to 0 to disable. Similar to
  103. // `topic.metadata.refresh.interval.ms` in the JVM version.
  104. RefreshFrequency time.Duration
  105. // Whether to maintain a full set of metadata for all topics, or just
  106. // the minimal set that has been necessary so far. The full set is simpler
  107. // and usually more convenient, but can take up a substantial amount of
  108. // memory if you have many topics and partitions. Defaults to true.
  109. Full bool
  110. }
  111. // Producer is the namespace for configuration related to producing messages,
  112. // used by the Producer.
  113. Producer struct {
  114. // The maximum permitted size of a message (defaults to 1000000). Should be
  115. // set equal to or smaller than the broker's `message.max.bytes`.
  116. MaxMessageBytes int
  117. // The level of acknowledgement reliability needed from the broker (defaults
  118. // to WaitForLocal). Equivalent to the `request.required.acks` setting of the
  119. // JVM producer.
  120. RequiredAcks RequiredAcks
  121. // The maximum duration the broker will wait the receipt of the number of
  122. // RequiredAcks (defaults to 10 seconds). This is only relevant when
  123. // RequiredAcks is set to WaitForAll or a number > 1. Only supports
  124. // millisecond resolution, nanoseconds will be truncated. Equivalent to
  125. // the JVM producer's `request.timeout.ms` setting.
  126. Timeout time.Duration
  127. // The type of compression to use on messages (defaults to no compression).
  128. // Similar to `compression.codec` setting of the JVM producer.
  129. Compression CompressionCodec
  130. // The level of compression to use on messages. The meaning depends
  131. // on the actual compression type used and defaults to default compression
  132. // level for the codec.
  133. CompressionLevel int
  134. // Generates partitioners for choosing the partition to send messages to
  135. // (defaults to hashing the message key). Similar to the `partitioner.class`
  136. // setting for the JVM producer.
  137. Partitioner PartitionerConstructor
  138. // If enabled, the producer will ensure that exactly one copy of each message is
  139. // written.
  140. Idempotent bool
  141. // Return specifies what channels will be populated. If they are set to true,
  142. // you must read from the respective channels to prevent deadlock. If,
  143. // however, this config is used to create a `SyncProducer`, both must be set
  144. // to true and you shall not read from the channels since the producer does
  145. // this internally.
  146. Return struct {
  147. // If enabled, successfully delivered messages will be returned on the
  148. // Successes channel (default disabled).
  149. Successes bool
  150. // If enabled, messages that failed to deliver will be returned on the
  151. // Errors channel, including error (default enabled).
  152. Errors bool
  153. }
  154. // The following config options control how often messages are batched up and
  155. // sent to the broker. By default, messages are sent as fast as possible, and
  156. // all messages received while the current batch is in-flight are placed
  157. // into the subsequent batch.
  158. Flush struct {
  159. // The best-effort number of bytes needed to trigger a flush. Use the
  160. // global sarama.MaxRequestSize to set a hard upper limit.
  161. Bytes int
  162. // The best-effort number of messages needed to trigger a flush. Use
  163. // `MaxMessages` to set a hard upper limit.
  164. Messages int
  165. // The best-effort frequency of flushes. Equivalent to
  166. // `queue.buffering.max.ms` setting of JVM producer.
  167. Frequency time.Duration
  168. // The maximum number of messages the producer will send in a single
  169. // broker request. Defaults to 0 for unlimited. Similar to
  170. // `queue.buffering.max.messages` in the JVM producer.
  171. MaxMessages int
  172. }
  173. Retry struct {
  174. // The total number of times to retry sending a message (default 3).
  175. // Similar to the `message.send.max.retries` setting of the JVM producer.
  176. Max int
  177. // How long to wait for the cluster to settle between retries
  178. // (default 100ms). Similar to the `retry.backoff.ms` setting of the
  179. // JVM producer.
  180. Backoff time.Duration
  181. // Called to compute backoff time dynamically. Useful for implementing
  182. // more sophisticated backoff strategies. This takes precedence over
  183. // `Backoff` if set.
  184. BackoffFunc func(retries, maxRetries int) time.Duration
  185. }
  186. }
  187. // Consumer is the namespace for configuration related to consuming messages,
  188. // used by the Consumer.
  189. Consumer struct {
  190. // Group is the namespace for configuring consumer group.
  191. Group struct {
  192. Session struct {
  193. // The timeout used to detect consumer failures when using Kafka's group management facility.
  194. // The consumer sends periodic heartbeats to indicate its liveness to the broker.
  195. // If no heartbeats are received by the broker before the expiration of this session timeout,
  196. // then the broker will remove this consumer from the group and initiate a rebalance.
  197. // Note that the value must be in the allowable range as configured in the broker configuration
  198. // by `group.min.session.timeout.ms` and `group.max.session.timeout.ms` (default 10s)
  199. Timeout time.Duration
  200. }
  201. Heartbeat struct {
  202. // The expected time between heartbeats to the consumer coordinator when using Kafka's group
  203. // management facilities. Heartbeats are used to ensure that the consumer's session stays active and
  204. // to facilitate rebalancing when new consumers join or leave the group.
  205. // The value must be set lower than Consumer.Group.Session.Timeout, but typically should be set no
  206. // higher than 1/3 of that value.
  207. // It can be adjusted even lower to control the expected time for normal rebalances (default 3s)
  208. Interval time.Duration
  209. }
  210. Rebalance struct {
  211. // Strategy for allocating topic partitions to members (default BalanceStrategyRange)
  212. Strategy BalanceStrategy
  213. // The maximum allowed time for each worker to join the group once a rebalance has begun.
  214. // This is basically a limit on the amount of time needed for all tasks to flush any pending
  215. // data and commit offsets. If the timeout is exceeded, then the worker will be removed from
  216. // the group, which will cause offset commit failures (default 60s).
  217. Timeout time.Duration
  218. Retry struct {
  219. // When a new consumer joins a consumer group the set of consumers attempt to "rebalance"
  220. // the load to assign partitions to each consumer. If the set of consumers changes while
  221. // this assignment is taking place the rebalance will fail and retry. This setting controls
  222. // the maximum number of attempts before giving up (default 4).
  223. Max int
  224. // Backoff time between retries during rebalance (default 2s)
  225. Backoff time.Duration
  226. }
  227. }
  228. Member struct {
  229. // Custom metadata to include when joining the group. The user data for all joined members
  230. // can be retrieved by sending a DescribeGroupRequest to the broker that is the
  231. // coordinator for the group.
  232. UserData []byte
  233. }
  234. }
  235. Retry struct {
  236. // How long to wait after a failing to read from a partition before
  237. // trying again (default 2s).
  238. Backoff time.Duration
  239. // Called to compute backoff time dynamically. Useful for implementing
  240. // more sophisticated backoff strategies. This takes precedence over
  241. // `Backoff` if set.
  242. BackoffFunc func(retries int) time.Duration
  243. }
  244. // Fetch is the namespace for controlling how many bytes are retrieved by any
  245. // given request.
  246. Fetch struct {
  247. // The minimum number of message bytes to fetch in a request - the broker
  248. // will wait until at least this many are available. The default is 1,
  249. // as 0 causes the consumer to spin when no messages are available.
  250. // Equivalent to the JVM's `fetch.min.bytes`.
  251. Min int32
  252. // The default number of message bytes to fetch from the broker in each
  253. // request (default 1MB). This should be larger than the majority of
  254. // your messages, or else the consumer will spend a lot of time
  255. // negotiating sizes and not actually consuming. Similar to the JVM's
  256. // `fetch.message.max.bytes`.
  257. Default int32
  258. // The maximum number of message bytes to fetch from the broker in a
  259. // single request. Messages larger than this will return
  260. // ErrMessageTooLarge and will not be consumable, so you must be sure
  261. // this is at least as large as your largest message. Defaults to 0
  262. // (no limit). Similar to the JVM's `fetch.message.max.bytes`. The
  263. // global `sarama.MaxResponseSize` still applies.
  264. Max int32
  265. }
  266. // The maximum amount of time the broker will wait for Consumer.Fetch.Min
  267. // bytes to become available before it returns fewer than that anyways. The
  268. // default is 250ms, since 0 causes the consumer to spin when no events are
  269. // available. 100-500ms is a reasonable range for most cases. Kafka only
  270. // supports precision up to milliseconds; nanoseconds will be truncated.
  271. // Equivalent to the JVM's `fetch.wait.max.ms`.
  272. MaxWaitTime time.Duration
  273. // The maximum amount of time the consumer expects a message takes to
  274. // process for the user. If writing to the Messages channel takes longer
  275. // than this, that partition will stop fetching more messages until it
  276. // can proceed again.
  277. // Note that, since the Messages channel is buffered, the actual grace time is
  278. // (MaxProcessingTime * ChanneBufferSize). Defaults to 100ms.
  279. // If a message is not written to the Messages channel between two ticks
  280. // of the expiryTicker then a timeout is detected.
  281. // Using a ticker instead of a timer to detect timeouts should typically
  282. // result in many fewer calls to Timer functions which may result in a
  283. // significant performance improvement if many messages are being sent
  284. // and timeouts are infrequent.
  285. // The disadvantage of using a ticker instead of a timer is that
  286. // timeouts will be less accurate. That is, the effective timeout could
  287. // be between `MaxProcessingTime` and `2 * MaxProcessingTime`. For
  288. // example, if `MaxProcessingTime` is 100ms then a delay of 180ms
  289. // between two messages being sent may not be recognized as a timeout.
  290. MaxProcessingTime time.Duration
  291. // Return specifies what channels will be populated. If they are set to true,
  292. // you must read from them to prevent deadlock.
  293. Return struct {
  294. // If enabled, any errors that occurred while consuming are returned on
  295. // the Errors channel (default disabled).
  296. Errors bool
  297. }
  298. // Offsets specifies configuration for how and when to commit consumed
  299. // offsets. This currently requires the manual use of an OffsetManager
  300. // but will eventually be automated.
  301. Offsets struct {
  302. // How frequently to commit updated offsets. Defaults to 1s.
  303. CommitInterval time.Duration
  304. // The initial offset to use if no offset was previously committed.
  305. // Should be OffsetNewest or OffsetOldest. Defaults to OffsetNewest.
  306. Initial int64
  307. // The retention duration for committed offsets. If zero, disabled
  308. // (in which case the `offsets.retention.minutes` option on the
  309. // broker will be used). Kafka only supports precision up to
  310. // milliseconds; nanoseconds will be truncated. Requires Kafka
  311. // broker version 0.9.0 or later.
  312. // (default is 0: disabled).
  313. Retention time.Duration
  314. Retry struct {
  315. // The total number of times to retry failing commit
  316. // requests during OffsetManager shutdown (default 3).
  317. Max int
  318. }
  319. }
  320. // IsolationLevel support 2 mode:
  321. // - use `ReadUncommitted` (default) to consume and return all messages in message channel
  322. // - use `ReadCommitted` to hide messages that are part of an aborted transaction
  323. IsolationLevel IsolationLevel
  324. }
  325. // A user-provided string sent with every request to the brokers for logging,
  326. // debugging, and auditing purposes. Defaults to "sarama", but you should
  327. // probably set it to something specific to your application.
  328. ClientID string
  329. // The number of events to buffer in internal and external channels. This
  330. // permits the producer and consumer to continue processing some messages
  331. // in the background while user code is working, greatly improving throughput.
  332. // Defaults to 256.
  333. ChannelBufferSize int
  334. // The version of Kafka that Sarama will assume it is running against.
  335. // Defaults to the oldest supported stable version. Since Kafka provides
  336. // backwards-compatibility, setting it to a version older than you have
  337. // will not break anything, although it may prevent you from using the
  338. // latest features. Setting it to a version greater than you are actually
  339. // running may lead to random breakage.
  340. Version KafkaVersion
  341. // The registry to define metrics into.
  342. // Defaults to a local registry.
  343. // If you want to disable metrics gathering, set "metrics.UseNilMetrics" to "true"
  344. // prior to starting Sarama.
  345. // See Examples on how to use the metrics registry
  346. MetricRegistry metrics.Registry
  347. }
  348. // NewConfig returns a new configuration instance with sane defaults.
  349. func NewConfig() *Config {
  350. c := &Config{}
  351. c.Admin.Timeout = 3 * time.Second
  352. c.Net.MaxOpenRequests = 5
  353. c.Net.DialTimeout = 30 * time.Second
  354. c.Net.ReadTimeout = 30 * time.Second
  355. c.Net.WriteTimeout = 30 * time.Second
  356. c.Net.SASL.Handshake = true
  357. c.Metadata.Retry.Max = 3
  358. c.Metadata.Retry.Backoff = 250 * time.Millisecond
  359. c.Metadata.RefreshFrequency = 10 * time.Minute
  360. c.Metadata.Full = true
  361. c.Producer.MaxMessageBytes = 1000000
  362. c.Producer.RequiredAcks = WaitForLocal
  363. c.Producer.Timeout = 10 * time.Second
  364. c.Producer.Partitioner = NewHashPartitioner
  365. c.Producer.Retry.Max = 3
  366. c.Producer.Retry.Backoff = 100 * time.Millisecond
  367. c.Producer.Return.Errors = true
  368. c.Producer.CompressionLevel = CompressionLevelDefault
  369. c.Consumer.Fetch.Min = 1
  370. c.Consumer.Fetch.Default = 1024 * 1024
  371. c.Consumer.Retry.Backoff = 2 * time.Second
  372. c.Consumer.MaxWaitTime = 250 * time.Millisecond
  373. c.Consumer.MaxProcessingTime = 100 * time.Millisecond
  374. c.Consumer.Return.Errors = false
  375. c.Consumer.Offsets.CommitInterval = 1 * time.Second
  376. c.Consumer.Offsets.Initial = OffsetNewest
  377. c.Consumer.Offsets.Retry.Max = 3
  378. c.Consumer.Group.Session.Timeout = 10 * time.Second
  379. c.Consumer.Group.Heartbeat.Interval = 3 * time.Second
  380. c.Consumer.Group.Rebalance.Strategy = BalanceStrategyRange
  381. c.Consumer.Group.Rebalance.Timeout = 60 * time.Second
  382. c.Consumer.Group.Rebalance.Retry.Max = 4
  383. c.Consumer.Group.Rebalance.Retry.Backoff = 2 * time.Second
  384. c.ClientID = defaultClientID
  385. c.ChannelBufferSize = 256
  386. c.Version = MinVersion
  387. c.MetricRegistry = metrics.NewRegistry()
  388. return c
  389. }
  390. // Validate checks a Config instance. It will return a
  391. // ConfigurationError if the specified values don't make sense.
  392. func (c *Config) Validate() error {
  393. // some configuration values should be warned on but not fail completely, do those first
  394. if !c.Net.TLS.Enable && c.Net.TLS.Config != nil {
  395. Logger.Println("Net.TLS is disabled but a non-nil configuration was provided.")
  396. }
  397. if !c.Net.SASL.Enable {
  398. if c.Net.SASL.User != "" {
  399. Logger.Println("Net.SASL is disabled but a non-empty username was provided.")
  400. }
  401. if c.Net.SASL.Password != "" {
  402. Logger.Println("Net.SASL is disabled but a non-empty password was provided.")
  403. }
  404. }
  405. if c.Producer.RequiredAcks > 1 {
  406. Logger.Println("Producer.RequiredAcks > 1 is deprecated and will raise an exception with kafka >= 0.8.2.0.")
  407. }
  408. if c.Producer.MaxMessageBytes >= int(MaxRequestSize) {
  409. Logger.Println("Producer.MaxMessageBytes must be smaller than MaxRequestSize; it will be ignored.")
  410. }
  411. if c.Producer.Flush.Bytes >= int(MaxRequestSize) {
  412. Logger.Println("Producer.Flush.Bytes must be smaller than MaxRequestSize; it will be ignored.")
  413. }
  414. if (c.Producer.Flush.Bytes > 0 || c.Producer.Flush.Messages > 0) && c.Producer.Flush.Frequency == 0 {
  415. Logger.Println("Producer.Flush: Bytes or Messages are set, but Frequency is not; messages may not get flushed.")
  416. }
  417. if c.Producer.Timeout%time.Millisecond != 0 {
  418. Logger.Println("Producer.Timeout only supports millisecond resolution; nanoseconds will be truncated.")
  419. }
  420. if c.Consumer.MaxWaitTime < 100*time.Millisecond {
  421. Logger.Println("Consumer.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.")
  422. }
  423. if c.Consumer.MaxWaitTime%time.Millisecond != 0 {
  424. Logger.Println("Consumer.MaxWaitTime only supports millisecond precision; nanoseconds will be truncated.")
  425. }
  426. if c.Consumer.Offsets.Retention%time.Millisecond != 0 {
  427. Logger.Println("Consumer.Offsets.Retention only supports millisecond precision; nanoseconds will be truncated.")
  428. }
  429. if c.Consumer.Group.Session.Timeout%time.Millisecond != 0 {
  430. Logger.Println("Consumer.Group.Session.Timeout only supports millisecond precision; nanoseconds will be truncated.")
  431. }
  432. if c.Consumer.Group.Heartbeat.Interval%time.Millisecond != 0 {
  433. Logger.Println("Consumer.Group.Heartbeat.Interval only supports millisecond precision; nanoseconds will be truncated.")
  434. }
  435. if c.Consumer.Group.Rebalance.Timeout%time.Millisecond != 0 {
  436. Logger.Println("Consumer.Group.Rebalance.Timeout only supports millisecond precision; nanoseconds will be truncated.")
  437. }
  438. if c.ClientID == defaultClientID {
  439. Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.")
  440. }
  441. // validate Net values
  442. switch {
  443. case c.Net.MaxOpenRequests <= 0:
  444. return ConfigurationError("Net.MaxOpenRequests must be > 0")
  445. case c.Net.DialTimeout <= 0:
  446. return ConfigurationError("Net.DialTimeout must be > 0")
  447. case c.Net.ReadTimeout <= 0:
  448. return ConfigurationError("Net.ReadTimeout must be > 0")
  449. case c.Net.WriteTimeout <= 0:
  450. return ConfigurationError("Net.WriteTimeout must be > 0")
  451. case c.Net.KeepAlive < 0:
  452. return ConfigurationError("Net.KeepAlive must be >= 0")
  453. case c.Net.SASL.Enable:
  454. if c.Net.SASL.Mechanism == "" {
  455. c.Net.SASL.Mechanism = SASLTypePlaintext
  456. }
  457. switch c.Net.SASL.Mechanism {
  458. case SASLTypePlaintext:
  459. if c.Net.SASL.User == "" {
  460. return ConfigurationError("Net.SASL.User must not be empty when SASL is enabled")
  461. }
  462. if c.Net.SASL.Password == "" {
  463. return ConfigurationError("Net.SASL.Password must not be empty when SASL is enabled")
  464. }
  465. case SASLTypeOAuth:
  466. if c.Net.SASL.TokenProvider == nil {
  467. return ConfigurationError("An AccessTokenProvider instance must be provided to Net.SASL.TokenProvider")
  468. }
  469. case SASLTypeSCRAMSHA256, SASLTypeSCRAMSHA512:
  470. if c.Net.SASL.User == "" {
  471. return ConfigurationError("Net.SASL.User must not be empty when SASL is enabled")
  472. }
  473. if c.Net.SASL.Password == "" {
  474. return ConfigurationError("Net.SASL.Password must not be empty when SASL is enabled")
  475. }
  476. if c.Net.SASL.SCRAMClient == nil {
  477. return ConfigurationError("A SCRAMClient instance must be provided to Net.SASL.SCRAMClient")
  478. }
  479. default:
  480. msg := fmt.Sprintf("The SASL mechanism configuration is invalid. Possible values are `%s`, `%s`, `%s` and `%s`",
  481. SASLTypeOAuth, SASLTypePlaintext, SASLTypeSCRAMSHA256, SASLTypeSCRAMSHA512)
  482. return ConfigurationError(msg)
  483. }
  484. }
  485. // validate the Admin values
  486. switch {
  487. case c.Admin.Timeout <= 0:
  488. return ConfigurationError("Admin.Timeout must be > 0")
  489. }
  490. // validate the Metadata values
  491. switch {
  492. case c.Metadata.Retry.Max < 0:
  493. return ConfigurationError("Metadata.Retry.Max must be >= 0")
  494. case c.Metadata.Retry.Backoff < 0:
  495. return ConfigurationError("Metadata.Retry.Backoff must be >= 0")
  496. case c.Metadata.RefreshFrequency < 0:
  497. return ConfigurationError("Metadata.RefreshFrequency must be >= 0")
  498. }
  499. // validate the Producer values
  500. switch {
  501. case c.Producer.MaxMessageBytes <= 0:
  502. return ConfigurationError("Producer.MaxMessageBytes must be > 0")
  503. case c.Producer.RequiredAcks < -1:
  504. return ConfigurationError("Producer.RequiredAcks must be >= -1")
  505. case c.Producer.Timeout <= 0:
  506. return ConfigurationError("Producer.Timeout must be > 0")
  507. case c.Producer.Partitioner == nil:
  508. return ConfigurationError("Producer.Partitioner must not be nil")
  509. case c.Producer.Flush.Bytes < 0:
  510. return ConfigurationError("Producer.Flush.Bytes must be >= 0")
  511. case c.Producer.Flush.Messages < 0:
  512. return ConfigurationError("Producer.Flush.Messages must be >= 0")
  513. case c.Producer.Flush.Frequency < 0:
  514. return ConfigurationError("Producer.Flush.Frequency must be >= 0")
  515. case c.Producer.Flush.MaxMessages < 0:
  516. return ConfigurationError("Producer.Flush.MaxMessages must be >= 0")
  517. case c.Producer.Flush.MaxMessages > 0 && c.Producer.Flush.MaxMessages < c.Producer.Flush.Messages:
  518. return ConfigurationError("Producer.Flush.MaxMessages must be >= Producer.Flush.Messages when set")
  519. case c.Producer.Retry.Max < 0:
  520. return ConfigurationError("Producer.Retry.Max must be >= 0")
  521. case c.Producer.Retry.Backoff < 0:
  522. return ConfigurationError("Producer.Retry.Backoff must be >= 0")
  523. }
  524. if c.Producer.Compression == CompressionLZ4 && !c.Version.IsAtLeast(V0_10_0_0) {
  525. return ConfigurationError("lz4 compression requires Version >= V0_10_0_0")
  526. }
  527. if c.Producer.Compression == CompressionGZIP {
  528. if c.Producer.CompressionLevel != CompressionLevelDefault {
  529. if _, err := gzip.NewWriterLevel(ioutil.Discard, c.Producer.CompressionLevel); err != nil {
  530. return ConfigurationError(fmt.Sprintf("gzip compression does not work with level %d: %v", c.Producer.CompressionLevel, err))
  531. }
  532. }
  533. }
  534. if c.Producer.Idempotent {
  535. if !c.Version.IsAtLeast(V0_11_0_0) {
  536. return ConfigurationError("Idempotent producer requires Version >= V0_11_0_0")
  537. }
  538. if c.Producer.Retry.Max == 0 {
  539. return ConfigurationError("Idempotent producer requires Producer.Retry.Max >= 1")
  540. }
  541. if c.Producer.RequiredAcks != WaitForAll {
  542. return ConfigurationError("Idempotent producer requires Producer.RequiredAcks to be WaitForAll")
  543. }
  544. if c.Net.MaxOpenRequests > 1 {
  545. return ConfigurationError("Idempotent producer requires Net.MaxOpenRequests to be 1")
  546. }
  547. }
  548. // validate the Consumer values
  549. switch {
  550. case c.Consumer.Fetch.Min <= 0:
  551. return ConfigurationError("Consumer.Fetch.Min must be > 0")
  552. case c.Consumer.Fetch.Default <= 0:
  553. return ConfigurationError("Consumer.Fetch.Default must be > 0")
  554. case c.Consumer.Fetch.Max < 0:
  555. return ConfigurationError("Consumer.Fetch.Max must be >= 0")
  556. case c.Consumer.MaxWaitTime < 1*time.Millisecond:
  557. return ConfigurationError("Consumer.MaxWaitTime must be >= 1ms")
  558. case c.Consumer.MaxProcessingTime <= 0:
  559. return ConfigurationError("Consumer.MaxProcessingTime must be > 0")
  560. case c.Consumer.Retry.Backoff < 0:
  561. return ConfigurationError("Consumer.Retry.Backoff must be >= 0")
  562. case c.Consumer.Offsets.CommitInterval <= 0:
  563. return ConfigurationError("Consumer.Offsets.CommitInterval must be > 0")
  564. case c.Consumer.Offsets.Initial != OffsetOldest && c.Consumer.Offsets.Initial != OffsetNewest:
  565. return ConfigurationError("Consumer.Offsets.Initial must be OffsetOldest or OffsetNewest")
  566. case c.Consumer.Offsets.Retry.Max < 0:
  567. return ConfigurationError("Consumer.Offsets.Retry.Max must be >= 0")
  568. case c.Consumer.IsolationLevel != ReadUncommitted && c.Consumer.IsolationLevel != ReadCommitted:
  569. return ConfigurationError("Consumer.IsolationLevel must be ReadUncommitted or ReadCommitted")
  570. }
  571. // validate IsolationLevel
  572. if c.Consumer.IsolationLevel == ReadCommitted && !c.Version.IsAtLeast(V0_11_0_0) {
  573. return ConfigurationError("ReadCommitted requires Version >= V0_11_0_0")
  574. }
  575. // validate the Consumer Group values
  576. switch {
  577. case c.Consumer.Group.Session.Timeout <= 2*time.Millisecond:
  578. return ConfigurationError("Consumer.Group.Session.Timeout must be >= 2ms")
  579. case c.Consumer.Group.Heartbeat.Interval < 1*time.Millisecond:
  580. return ConfigurationError("Consumer.Group.Heartbeat.Interval must be >= 1ms")
  581. case c.Consumer.Group.Heartbeat.Interval >= c.Consumer.Group.Session.Timeout:
  582. return ConfigurationError("Consumer.Group.Heartbeat.Interval must be < Consumer.Group.Session.Timeout")
  583. case c.Consumer.Group.Rebalance.Strategy == nil:
  584. return ConfigurationError("Consumer.Group.Rebalance.Strategy must not be empty")
  585. case c.Consumer.Group.Rebalance.Timeout <= time.Millisecond:
  586. return ConfigurationError("Consumer.Group.Rebalance.Timeout must be >= 1ms")
  587. case c.Consumer.Group.Rebalance.Retry.Max < 0:
  588. return ConfigurationError("Consumer.Group.Rebalance.Retry.Max must be >= 0")
  589. case c.Consumer.Group.Rebalance.Retry.Backoff < 0:
  590. return ConfigurationError("Consumer.Group.Rebalance.Retry.Backoff must be >= 0")
  591. }
  592. // validate misc shared values
  593. switch {
  594. case c.ChannelBufferSize < 0:
  595. return ConfigurationError("ChannelBufferSize must be >= 0")
  596. case !validID.MatchString(c.ClientID):
  597. return ConfigurationError("ClientID is invalid")
  598. }
  599. return nil
  600. }