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