config.go 30 KB

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