config.go 33 KB

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