Add km module kafka

This commit is contained in:
leewei
2023-02-14 14:57:39 +08:00
parent 229140f067
commit 469baad65b
4310 changed files with 736354 additions and 46204 deletions

120
docs/api.html Normal file
View File

@@ -0,0 +1,120 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script id="api-template" type="text/x-handlebars-template">
Kafka includes five core apis:
<ol>
<li>The <a href="#producerapi">Producer</a> API allows applications to send streams of data to topics in the Kafka cluster.
<li>The <a href="#consumerapi">Consumer</a> API allows applications to read streams of data from topics in the Kafka cluster.
<li>The <a href="#streamsapi">Streams</a> API allows transforming streams of data from input topics to output topics.
<li>The <a href="#connectapi">Connect</a> API allows implementing connectors that continually pull from some source system or application into Kafka or push from Kafka into some sink system or application.
<li>The <a href="#adminapi">Admin</a> API allows managing and inspecting topics, brokers, and other Kafka objects.
</ol>
Kafka exposes all its functionality over a language independent protocol which has clients available in many programming languages. However only the Java clients are maintained as part of the main Kafka project, the others are available as independent open source projects. A list of non-Java clients is available <a href="https://cwiki.apache.org/confluence/display/KAFKA/Clients">here</a>.
<h3><a id="producerapi" href="#producerapi">2.1 Producer API</a></h3>
The Producer API allows applications to send streams of data to topics in the Kafka cluster.
<p>
Examples showing how to use the producer are given in the
<a href="/{{version}}/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html" title="Kafka {{dotVersion}} Javadoc">javadocs</a>.
<p>
To use the producer, you can use the following maven dependency:
<pre class="brush: xml;">
&lt;dependency&gt;
&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
&lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
&lt;version&gt;{{fullDotVersion}}&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<h3><a id="consumerapi" href="#consumerapi">2.2 Consumer API</a></h3>
The Consumer API allows applications to read streams of data from topics in the Kafka cluster.
<p>
Examples showing how to use the consumer are given in the
<a href="/{{version}}/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html" title="Kafka {{dotVersion}} Javadoc">javadocs</a>.
<p>
To use the consumer, you can use the following maven dependency:
<pre class="brush: xml;">
&lt;dependency&gt;
&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
&lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
&lt;version&gt;{{fullDotVersion}}&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<h3><a id="streamsapi" href="#streamsapi">2.3 Streams API</a></h3>
The <a href="#streamsapi">Streams</a> API allows transforming streams of data from input topics to output topics.
<p>
Examples showing how to use this library are given in the
<a href="/{{version}}/javadoc/index.html?org/apache/kafka/streams/KafkaStreams.html" title="Kafka {{dotVersion}} Javadoc">javadocs</a>
<p>
Additional documentation on using the Streams API is available <a href="/{{version}}/documentation/streams">here</a>.
<p>
To use Kafka Streams you can use the following maven dependency:
<pre class="brush: xml;">
&lt;dependency&gt;
&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
&lt;artifactId&gt;kafka-streams&lt;/artifactId&gt;
&lt;version&gt;{{fullDotVersion}}&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>
When using Scala you may optionally include the <code>kafka-streams-scala</code> library. Additional documentation on using the Kafka Streams DSL for Scala is available <a href="/{{version}}/documentation/streams/developer-guide/dsl-api.html#scala-dsl">in the developer guide</a>.
<p>
To use Kafka Streams DSL for Scala for Scala {{scalaVersion}} you can use the following maven dependency:
<pre class="brush: xml;">
&lt;dependency&gt;
&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
&lt;artifactId&gt;kafka-streams-scala_{{scalaVersion}}&lt;/artifactId&gt;
&lt;version&gt;{{fullDotVersion}}&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<h3><a id="connectapi" href="#connectapi">2.4 Connect API</a></h3>
The Connect API allows implementing connectors that continually pull from some source data system into Kafka or push from Kafka into some sink data system.
<p>
Many users of Connect won't need to use this API directly, though, they can use pre-built connectors without needing to write any code. Additional information on using Connect is available <a href="/documentation.html#connect">here</a>.
<p>
Those who want to implement custom connectors can see the <a href="/{{version}}/javadoc/index.html?org/apache/kafka/connect" title="Kafka {{dotVersion}} Javadoc">javadoc</a>.
<p>
<h3><a id="adminapi" href="#adminapi">2.5 Admin API</a></h3>
The Admin API supports managing and inspecting topics, brokers, acls, and other Kafka objects.
<p>
To use the Admin API, add the following Maven dependency:
<pre class="brush: xml;">
&lt;dependency&gt;
&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
&lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
&lt;version&gt;{{fullDotVersion}}&lt;/version&gt;
&lt;/dependency&gt;
</pre>
For more information about the Admin APIs, see the <a href="/{{version}}/javadoc/index.html?org/apache/kafka/clients/admin/Admin.html" title="Kafka {{dotVersion}} Javadoc">javadoc</a>.
<p>
</script>
<div class="p-api"></div>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

293
docs/configuration.html Normal file
View File

@@ -0,0 +1,293 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script id="configuration-template" type="text/x-handlebars-template">
Kafka uses key-value pairs in the <a href="http://en.wikipedia.org/wiki/.properties">property file format</a> for configuration. These values can be supplied either from a file or programmatically.
<h3><a id="brokerconfigs" href="#brokerconfigs">3.1 Broker Configs</a></h3>
The essential configurations are the following:
<ul>
<li><code>broker.id</code>
<li><code>log.dirs</code>
<li><code>zookeeper.connect</code>
</ul>
Topic-level configurations and defaults are discussed in more detail <a href="#topicconfigs">below</a>.
<!--#include virtual="generated/kafka_config.html" -->
<p>More details about broker configuration can be found in the scala class <code>kafka.server.KafkaConfig</code>.</p>
<h4><a id="dynamicbrokerconfigs" href="#dynamicbrokerconfigs">3.1.1 Updating Broker Configs</a></h4>
From Kafka version 1.1 onwards, some of the broker configs can be updated without restarting the broker. See the
<code>Dynamic Update Mode</code> column in <a href="#brokerconfigs">Broker Configs</a> for the update mode of each broker config.
<ul>
<li><code>read-only</code>: Requires a broker restart for update</li>
<li><code>per-broker</code>: May be updated dynamically for each broker</li>
<li><code>cluster-wide</code>: May be updated dynamically as a cluster-wide default. May also be updated as a per-broker value for testing.</li>
</ul>
To alter the current broker configs for broker id 0 (for example, the number of log cleaner threads):
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --alter --add-config log.cleaner.threads=2
</pre>
To describe the current dynamic broker configs for broker id 0:
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --describe
</pre>
To delete a config override and revert to the statically configured or default value for broker id 0 (for example,
the number of log cleaner threads):
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --alter --delete-config log.cleaner.threads
</pre>
Some configs may be configured as a cluster-wide default to maintain consistent values across the whole cluster. All brokers
in the cluster will process the cluster default update. For example, to update log cleaner threads on all brokers:
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-default --alter --add-config log.cleaner.threads=2
</pre>
To describe the currently configured dynamic cluster-wide default configs:
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-default --describe
</pre>
All configs that are configurable at cluster level may also be configured at per-broker level (e.g. for testing).
If a config value is defined at different levels, the following order of precedence is used:
<ul>
<li>Dynamic per-broker config stored in ZooKeeper</li>
<li>Dynamic cluster-wide default config stored in ZooKeeper</li>
<li>Static broker config from <code>server.properties</code></li>
<li>Kafka default, see <a href="#brokerconfigs">broker configs</a></li>
</ul>
<h5>Updating Password Configs Dynamically</h5>
<p>Password config values that are dynamically updated are encrypted before storing in ZooKeeper. The broker config
<code>password.encoder.secret</code> must be configured in <code>server.properties</code> to enable dynamic update
of password configs. The secret may be different on different brokers.</p>
<p>The secret used for password encoding may be rotated with a rolling restart of brokers. The old secret used for encoding
passwords currently in ZooKeeper must be provided in the static broker config <code>password.encoder.old.secret</code> and
the new secret must be provided in <code>password.encoder.secret</code>. All dynamic password configs stored in ZooKeeper
will be re-encoded with the new secret when the broker starts up.</p>
<p>In Kafka 1.1.x, all dynamically updated password configs must be provided in every alter request when updating configs
using <code>kafka-configs.sh</code> even if the password config is not being altered. This constraint will be removed in
a future release.</p>
<h5>Updating Password Configs in ZooKeeper Before Starting Brokers</h5>
From Kafka 2.0.0 onwards, <code>kafka-configs.sh</code> enables dynamic broker configs to be updated using ZooKeeper before
starting brokers for bootstrapping. This enables all password configs to be stored in encrypted form, avoiding the need for
clear passwords in <code>server.properties</code>. The broker config <code>password.encoder.secret</code> must also be specified
if any password configs are included in the alter command. Additional encryption parameters may also be specified. Password
encoder configs will not be persisted in ZooKeeper. For example, to store SSL key password for listener <code>INTERNAL</code>
on broker 0:
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type brokers --entity-name 0 --alter --add-config
'listener.name.internal.ssl.key.password=key-password,password.encoder.secret=secret,password.encoder.iterations=8192'
</pre>
The configuration <code>listener.name.internal.ssl.key.password</code> will be persisted in ZooKeeper in encrypted
form using the provided encoder configs. The encoder secret and iterations are not persisted in ZooKeeper.
<h5>Updating SSL Keystore of an Existing Listener</h5>
Brokers may be configured with SSL keystores with short validity periods to reduce the risk of compromised certificates.
Keystores may be updated dynamically without restarting the broker. The config name must be prefixed with the listener prefix
<code>listener.name.{listenerName}.</code> so that only the keystore config of a specific listener is updated.
The following configs may be updated in a single alter request at per-broker level:
<ul>
<li><code>ssl.keystore.type</code></li>
<li><code>ssl.keystore.location</code></li>
<li><code>ssl.keystore.password</code></li>
<li><code>ssl.key.password</code></li>
</ul>
If the listener is the inter-broker listener, the update is allowed only if the new keystore is trusted by the truststore
configured for that listener. For other listeners, no trust validation is performed on the keystore by the broker. Certificates
must be signed by the same certificate authority that signed the old certificate to avoid any client authentication failures.
<h5>Updating SSL Truststore of an Existing Listener</h5>
Broker truststores may be updated dynamically without restarting the broker to add or remove certificates.
Updated truststore will be used to authenticate new client connections. The config name must be prefixed with the
listener prefix <code>listener.name.{listenerName}.</code> so that only the truststore config of a specific listener
is updated. The following configs may be updated in a single alter request at per-broker level:
<ul>
<li><code>ssl.truststore.type</code></li>
<li><code>ssl.truststore.location</code></li>
<li><code>ssl.truststore.password</code></li>
</ul>
If the listener is the inter-broker listener, the update is allowed only if the existing keystore for that listener is trusted by
the new truststore. For other listeners, no trust validation is performed by the broker before the update. Removal of CA certificates
used to sign client certificates from the new truststore can lead to client authentication failures.
<h5>Updating Default Topic Configuration</h5>
Default topic configuration options used by brokers may be updated without broker restart. The configs are applied to topics
without a topic config override for the equivalent per-topic config. One or more of these configs may be overridden at
cluster-default level used by all brokers.
<ul>
<li><code>log.segment.bytes</code></li>
<li><code>log.roll.ms</code></li>
<li><code>log.roll.hours</code></li>
<li><code>log.roll.jitter.ms</code></li>
<li><code>log.roll.jitter.hours</code></li>
<li><code>log.index.size.max.bytes</code></li>
<li><code>log.flush.interval.messages</code></li>
<li><code>log.flush.interval.ms</code></li>
<li><code>log.retention.bytes</code></li>
<li><code>log.retention.ms</code></li>
<li><code>log.retention.minutes</code></li>
<li><code>log.retention.hours</code></li>
<li><code>log.index.interval.bytes</code></li>
<li><code>log.cleaner.delete.retention.ms</code></li>
<li><code>log.cleaner.min.compaction.lag.ms</code></li>
<li><code>log.cleaner.max.compaction.lag.ms</code></li>
<li><code>log.cleaner.min.cleanable.ratio</code></li>
<li><code>log.cleanup.policy</code></li>
<li><code>log.segment.delete.delay.ms</code></li>
<li><code>unclean.leader.election.enable</code></li>
<li><code>min.insync.replicas</code></li>
<li><code>max.message.bytes</code></li>
<li><code>compression.type</code></li>
<li><code>log.preallocate</code></li>
<li><code>log.message.timestamp.type</code></li>
<li><code>log.message.timestamp.difference.max.ms</code></li>
</ul>
From Kafka version 2.0.0 onwards, unclean leader election is automatically enabled by the controller when the config
<code>unclean.leader.election.enable</code> is dynamically updated.
In Kafka version 1.1.x, changes to <code>unclean.leader.election.enable</code> take effect only when a new controller is elected.
Controller re-election may be forced by running:
<pre class="brush: bash;">
&gt; bin/zookeeper-shell.sh localhost
rmr /controller
</pre>
<h5>Updating Log Cleaner Configs</h5>
Log cleaner configs may be updated dynamically at cluster-default level used by all brokers. The changes take effect
on the next iteration of log cleaning. One or more of these configs may be updated:
<ul>
<li><code>log.cleaner.threads</code></li>
<li><code>log.cleaner.io.max.bytes.per.second</code></li>
<li><code>log.cleaner.dedupe.buffer.size</code></li>
<li><code>log.cleaner.io.buffer.size</code></li>
<li><code>log.cleaner.io.buffer.load.factor</code></li>
<li><code>log.cleaner.backoff.ms</code></li>
</ul>
<h5>Updating Thread Configs</h5>
The size of various thread pools used by the broker may be updated dynamically at cluster-default level used by all brokers.
Updates are restricted to the range <code>currentSize / 2</code> to <code>currentSize * 2</code> to ensure that config updates are
handled gracefully.
<ul>
<li><code>num.network.threads</code></li>
<li><code>num.io.threads</code></li>
<li><code>num.replica.fetchers</code></li>
<li><code>num.recovery.threads.per.data.dir</code></li>
<li><code>log.cleaner.threads</code></li>
<li><code>background.threads</code></li>
</ul>
<h5>Updating ConnectionQuota Configs</h5>
The maximum number of connections allowed for a given IP/host by the broker may be updated dynamically at cluster-default level used by all brokers.
The changes will apply for new connection creations and the existing connections count will be taken into account by the new limits.
<ul>
<li><code>max.connections.per.ip</code></li>
<li><code>max.connections.per.ip.overrides</code></li>
</ul>
<h5>Adding and Removing Listeners</h5>
<p>Listeners may be added or removed dynamically. When a new listener is added, security configs of the listener must be provided
as listener configs with the listener prefix <code>listener.name.{listenerName}.</code>. If the new listener uses SASL,
the JAAS configuration of the listener must be provided using the JAAS configuration property <code>sasl.jaas.config</code>
with the listener and mechanism prefix. See <a href="#security_jaas_broker">JAAS configuration for Kafka brokers</a> for details.</p>
<p>In Kafka version 1.1.x, the listener used by the inter-broker listener may not be updated dynamically. To update the inter-broker
listener to a new listener, the new listener may be added on all brokers without restarting the broker. A rolling restart is then
required to update <code>inter.broker.listener.name</code>.</p>
In addition to all the security configs of new listeners, the following configs may be updated dynamically at per-broker level:
<ul>
<li><code>listeners</code></li>
<li><code>advertised.listeners</code></li>
<li><code>listener.security.protocol.map</code></li>
</ul>
Inter-broker listener must be configured using the static broker configuration <code>inter.broker.listener.name</code>
or <code>inter.broker.security.protocol</code>.
<h3><a id="topicconfigs" href="#topicconfigs">3.2 Topic-Level Configs</a></h3>
Configurations pertinent to topics have both a server default as well an optional per-topic override. If no per-topic configuration is given the server default is used. The override can be set at topic creation time by giving one or more <code>--config</code> options. This example creates a topic named <i>my-topic</i> with a custom max message size and flush rate:
<pre class="brush: bash;">
&gt; bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic my-topic --partitions 1 \
--replication-factor 1 --config max.message.bytes=64000 --config flush.messages=1
</pre>
Overrides can also be changed or set later using the alter configs command. This example updates the max message size for <i>my-topic</i>:
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-topic
--alter --add-config max.message.bytes=128000
</pre>
To check overrides set on the topic you can do
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-topic --describe
</pre>
To remove an override you can do
<pre class="brush: bash;">
&gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-topic
--alter --delete-config max.message.bytes
</pre>
The following are the topic-level configurations. The server's default configuration for this property is given under the Server Default Property heading. A given server default config value only applies to a topic if it does not have an explicit topic config override.
<!--#include virtual="generated/topic_config.html" -->
<h3><a id="producerconfigs" href="#producerconfigs">3.3 Producer Configs</a></h3>
Below is the configuration of the producer:
<!--#include virtual="generated/producer_config.html" -->
<h3><a id="consumerconfigs" href="#consumerconfigs">3.4 Consumer Configs</a></h3>
Below is the configuration for the consumer:
<!--#include virtual="generated/consumer_config.html" -->
<h3><a id="connectconfigs" href="#connectconfigs">3.5 Kafka Connect Configs</a></h3>
Below is the configuration of the Kafka Connect framework.
<!--#include virtual="generated/connect_config.html" -->
<h4><a id="sourceconnectconfigs" href="#sourceconnectconfigs">3.5.1 Source Connector Configs</a></h4>
Below is the configuration of a source connector.
<!--#include virtual="generated/source_connector_config.html" -->
<h4><a id="sinkconnectconfigs" href="#sinkconnectconfigs">3.5.2 Sink Connector Configs</a></h4>
Below is the configuration of a sink connector.
<!--#include virtual="generated/sink_connector_config.html" -->
<h3><a id="streamsconfigs" href="#streamsconfigs">3.6 Kafka Streams Configs</a></h3>
Below is the configuration of the Kafka Streams client library.
<!--#include virtual="generated/streams_config.html" -->
<h3><a id="adminclientconfigs" href="#adminclientconfigs">3.7 Admin Configs</a></h3>
Below is the configuration of the Kafka Admin client library.
<!--#include virtual="generated/admin_client_config.html" -->
</script>
<div class="p-configuration"></div>

598
docs/connect.html Normal file
View File

@@ -0,0 +1,598 @@
<!--~
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~-->
<script id="connect-template" type="text/x-handlebars-template">
<h3><a id="connect_overview" href="#connect_overview">8.1 Overview</a></h3>
<p>Kafka Connect is a tool for scalably and reliably streaming data between Apache Kafka and other systems. It makes it simple to quickly define <i>connectors</i> that move large collections of data into and out of Kafka. Kafka Connect can ingest entire databases or collect metrics from all your application servers into Kafka topics, making the data available for stream processing with low latency. An export job can deliver data from Kafka topics into secondary storage and query systems or into batch systems for offline analysis.</p>
<p>Kafka Connect features include:</p>
<ul>
<li><b>A common framework for Kafka connectors</b> - Kafka Connect standardizes integration of other data systems with Kafka, simplifying connector development, deployment, and management</li>
<li><b>Distributed and standalone modes</b> - scale up to a large, centrally managed service supporting an entire organization or scale down to development, testing, and small production deployments</li>
<li><b>REST interface</b> - submit and manage connectors to your Kafka Connect cluster via an easy to use REST API</li>
<li><b>Automatic offset management</b> - with just a little information from connectors, Kafka Connect can manage the offset commit process automatically so connector developers do not need to worry about this error prone part of connector development</li>
<li><b>Distributed and scalable by default</b> - Kafka Connect builds on the existing group management protocol. More workers can be added to scale up a Kafka Connect cluster.</li>
<li><b>Streaming/batch integration</b> - leveraging Kafka's existing capabilities, Kafka Connect is an ideal solution for bridging streaming and batch data systems</li>
</ul>
<h3><a id="connect_user" href="#connect_user">8.2 User Guide</a></h3>
<p>The quickstart provides a brief example of how to run a standalone version of Kafka Connect. This section describes how to configure, run, and manage Kafka Connect in more detail.</p>
<h4><a id="connect_running" href="#connect_running">Running Kafka Connect</a></h4>
<p>Kafka Connect currently supports two modes of execution: standalone (single process) and distributed.</p>
<p>In standalone mode all work is performed in a single process. This configuration is simpler to setup and get started with and may be useful in situations where only one worker makes sense (e.g. collecting log files), but it does not benefit from some of the features of Kafka Connect such as fault tolerance. You can start a standalone process with the following command:</p>
<pre class="brush: bash;">
&gt; bin/connect-standalone.sh config/connect-standalone.properties connector1.properties [connector2.properties ...]
</pre>
<p>The first parameter is the configuration for the worker. This includes settings such as the Kafka connection parameters, serialization format, and how frequently to commit offsets. The provided example should work well with a local cluster running with the default configuration provided by <code>config/server.properties</code>. It will require tweaking to use with a different configuration or production deployment. All workers (both standalone and distributed) require a few configs:</p>
<ul>
<li><code>bootstrap.servers</code> - List of Kafka servers used to bootstrap connections to Kafka</li>
<li><code>key.converter</code> - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the keys in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.</li>
<li><code>value.converter</code> - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.</li>
</ul>
<p>The important configuration options specific to standalone mode are:</p>
<ul>
<li><code>offset.storage.file.filename</code> - File to store offset data in</li>
</ul>
<p>The parameters that are configured here are intended for producers and consumers used by Kafka Connect to access the configuration, offset and status topics. For configuration of the producers used by Kafka source tasks and the consumers used by Kafka sink tasks, the same parameters can be used but need to be prefixed with <code>producer.</code> and <code>consumer.</code> respectively. The only Kafka client parameter that is inherited without a prefix from the worker configuration is <code>bootstrap.servers</code>, which in most cases will be sufficient, since the same cluster is often used for all purposes. A notable exception is a secured cluster, which requires extra parameters to allow connections. These parameters will need to be set up to three times in the worker configuration, once for management access, once for Kafka sources and once for Kafka sinks.</p>
<p>Starting with 2.3.0, client configuration overrides can be configured individually per connector by using the prefixes <code>producer.override.</code> and <code>consumer.override.</code> for Kafka sources or Kafka sinks respectively. These overrides are included with the rest of the connector's configuration properties.</p>
<p>The remaining parameters are connector configuration files. You may include as many as you want, but all will execute within the same process (on different threads).</p>
<p>Distributed mode handles automatic balancing of work, allows you to scale up (or down) dynamically, and offers fault tolerance both in the active tasks and for configuration and offset commit data. Execution is very similar to standalone mode:</p>
<pre class="brush: bash;">
&gt; bin/connect-distributed.sh config/connect-distributed.properties
</pre>
<p>The difference is in the class which is started and the configuration parameters which change how the Kafka Connect process decides where to store configurations, how to assign work, and where to store offsets and task statues. In the distributed mode, Kafka Connect stores the offsets, configs and task statuses in Kafka topics. It is recommended to manually create the topics for offset, configs and statuses in order to achieve the desired the number of partitions and replication factors. If the topics are not yet created when starting Kafka Connect, the topics will be auto created with default number of partitions and replication factor, which may not be best suited for its usage.</p>
<p>In particular, the following configuration parameters, in addition to the common settings mentioned above, are critical to set before starting your cluster:</p>
<ul>
<li><code>group.id</code> (default <code>connect-cluster</code>) - unique name for the cluster, used in forming the Connect cluster group; note that this <b>must not conflict</b> with consumer group IDs</li>
<li><code>config.storage.topic</code> (default <code>connect-configs</code>) - topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, compacted topic. You may need to manually create the topic to ensure the correct configuration as auto created topics may have multiple partitions or be automatically configured for deletion rather than compaction</li>
<li><code>offset.storage.topic</code> (default <code>connect-offsets</code>) - topic to use for storing offsets; this topic should have many partitions, be replicated, and be configured for compaction</li>
<li><code>status.storage.topic</code> (default <code>connect-status</code>) - topic to use for storing statuses; this topic can have multiple partitions, and should be replicated and configured for compaction</li>
</ul>
<p>Note that in distributed mode the connector configurations are not passed on the command line. Instead, use the REST API described below to create, modify, and destroy connectors.</p>
<h4><a id="connect_configuring" href="#connect_configuring">Configuring Connectors</a></h4>
<p>Connector configurations are simple key-value mappings. For standalone mode these are defined in a properties file and passed to the Connect process on the command line. In distributed mode, they will be included in the JSON payload for the request that creates (or modifies) the connector.</p>
<p>Most configurations are connector dependent, so they can't be outlined here. However, there are a few common options:</p>
<ul>
<li><code>name</code> - Unique name for the connector. Attempting to register again with the same name will fail.</li>
<li><code>connector.class</code> - The Java class for the connector</li>
<li><code>tasks.max</code> - The maximum number of tasks that should be created for this connector. The connector may create fewer tasks if it cannot achieve this level of parallelism.</li>
<li><code>key.converter</code> - (optional) Override the default key converter set by the worker.</li>
<li><code>value.converter</code> - (optional) Override the default value converter set by the worker.</li>
</ul>
<p>The <code>connector.class</code> config supports several formats: the full name or alias of the class for this connector. If the connector is org.apache.kafka.connect.file.FileStreamSinkConnector, you can either specify this full name or use FileStreamSink or FileStreamSinkConnector to make the configuration a bit shorter.</p>
<p>Sink connectors also have a few additional options to control their input. Each sink connector must set one of the following:</p>
<ul>
<li><code>topics</code> - A comma-separated list of topics to use as input for this connector</li>
<li><code>topics.regex</code> - A Java regular expression of topics to use as input for this connector</li>
</ul>
<p>For any other options, you should consult the documentation for the connector.</p>
<h4><a id="connect_transforms" href="#connect_transforms">Transformations</a></h4>
<p>Connectors can be configured with transformations to make lightweight message-at-a-time modifications. They can be convenient for data massaging and event routing.</p>
<p>A transformation chain can be specified in the connector configuration.</p>
<ul>
<li><code>transforms</code> - List of aliases for the transformation, specifying the order in which the transformations will be applied.</li>
<li><code>transforms.$alias.type</code> - Fully qualified class name for the transformation.</li>
<li><code>transforms.$alias.$transformationSpecificConfig</code> Configuration properties for the transformation</li>
</ul>
<p>For example, lets take the built-in file source connector and use a transformation to add a static field.</p>
<p>Throughout the example we'll use schemaless JSON data format. To use schemaless format, we changed the following two lines in <code>connect-standalone.properties</code> from true to false:</p>
<pre class="brush: text;">
key.converter.schemas.enable
value.converter.schemas.enable
</pre>
<p>The file source connector reads each line as a String. We will wrap each line in a Map and then add a second field to identify the origin of the event. To do this, we use two transformations:</p>
<ul>
<li><b>HoistField</b> to place the input line inside a Map</li>
<li><b>InsertField</b> to add the static field. In this example we'll indicate that the record came from a file connector</li>
</ul>
<p>After adding the transformations, <code>connect-file-source.properties</code> file looks as following:</p>
<pre class="brush: text;">
name=local-file-source
connector.class=FileStreamSource
tasks.max=1
file=test.txt
topic=connect-test
transforms=MakeMap, InsertSource
transforms.MakeMap.type=org.apache.kafka.connect.transforms.HoistField$Value
transforms.MakeMap.field=line
transforms.InsertSource.type=org.apache.kafka.connect.transforms.InsertField$Value
transforms.InsertSource.static.field=data_source
transforms.InsertSource.static.value=test-file-source
</pre>
<p>All the lines starting with <code>transforms</code> were added for the transformations. You can see the two transformations we created: "InsertSource" and "MakeMap" are aliases that we chose to give the transformations. The transformation types are based on the list of built-in transformations you can see below. Each transformation type has additional configuration: HoistField requires a configuration called "field", which is the name of the field in the map that will include the original String from the file. InsertField transformation lets us specify the field name and the value that we are adding.</p>
<p>When we ran the file source connector on my sample file without the transformations, and then read them using <code>kafka-console-consumer.sh</code>, the results were:</p>
<pre class="brush: text;">
"foo"
"bar"
"hello world"
</pre>
<p>We then create a new file connector, this time after adding the transformations to the configuration file. This time, the results will be:</p>
<pre class="brush: json;">
{"line":"foo","data_source":"test-file-source"}
{"line":"bar","data_source":"test-file-source"}
{"line":"hello world","data_source":"test-file-source"}
</pre>
<p>You can see that the lines we've read are now part of a JSON map, and there is an extra field with the static value we specified. This is just one example of what you can do with transformations.</p>
<p>Several widely-applicable data and routing transformations are included with Kafka Connect:</p>
<ul>
<li>InsertField - Add a field using either static data or record metadata</li>
<li>ReplaceField - Filter or rename fields</li>
<li>MaskField - Replace field with valid null value for the type (0, empty string, etc)</li>
<li>ValueToKey</li>
<li>HoistField - Wrap the entire event as a single field inside a Struct or a Map</li>
<li>ExtractField - Extract a specific field from Struct and Map and include only this field in results</li>
<li>SetSchemaMetadata - modify the schema name or version</li>
<li>TimestampRouter - Modify the topic of a record based on original topic and timestamp. Useful when using a sink that needs to write to different tables or indexes based on timestamps</li>
<li>RegexRouter - modify the topic of a record based on original topic, replacement string and a regular expression</li>
</ul>
<p>Details on how to configure each transformation are listed below:</p>
<!--#include virtual="generated/connect_transforms.html" -->
<h4><a id="connect_rest" href="#connect_rest">REST API</a></h4>
<p>Since Kafka Connect is intended to be run as a service, it also provides a REST API for managing connectors. The REST API server can be configured using the <code>listeners</code> configuration option.
This field should contain a list of listeners in the following format: <code>protocol://host:port,protocol2://host2:port2</code>. Currently supported protocols are <code>http</code> and <code>https</code>.
For example:</p>
<pre class="brush: text;">
listeners=http://localhost:8080,https://localhost:8443
</pre>
<p>By default, if no <code>listeners</code> are specified, the REST server runs on port 8083 using the HTTP protocol. When using HTTPS, the configuration has to include the SSL configuration.
By default, it will use the <code>ssl.*</code> settings. In case it is needed to use different configuration for the REST API than for connecting to Kafka brokers, the fields can be prefixed with <code>listeners.https</code>.
When using the prefix, only the prefixed options will be used and the <code>ssl.*</code> options without the prefix will be ignored. Following fields can be used to configure HTTPS for the REST API:</p>
<ul>
<li><code>ssl.keystore.location</code></li>
<li><code>ssl.keystore.password</code></li>
<li><code>ssl.keystore.type</code></li>
<li><code>ssl.key.password</code></li>
<li><code>ssl.truststore.location</code></li>
<li><code>ssl.truststore.password</code></li>
<li><code>ssl.truststore.type</code></li>
<li><code>ssl.enabled.protocols</code></li>
<li><code>ssl.provider</code></li>
<li><code>ssl.protocol</code></li>
<li><code>ssl.cipher.suites</code></li>
<li><code>ssl.keymanager.algorithm</code></li>
<li><code>ssl.secure.random.implementation</code></li>
<li><code>ssl.trustmanager.algorithm</code></li>
<li><code>ssl.endpoint.identification.algorithm</code></li>
<li><code>ssl.client.auth</code></li>
</ul>
<p>The REST API is used not only by users to monitor / manage Kafka Connect. It is also used for the Kafka Connect cross-cluster communication. Requests received on the follower nodes REST API will be forwarded to the leader node REST API.
In case the URI under which is given host reachable is different from the URI which it listens on, the configuration options <code>rest.advertised.host.name</code>, <code>rest.advertised.port</code> and <code>rest.advertised.listener</code>
can be used to change the URI which will be used by the follower nodes to connect with the leader. When using both HTTP and HTTPS listeners, the <code>rest.advertised.listener</code> option can be also used to define which listener
will be used for the cross-cluster communication. When using HTTPS for communication between nodes, the same <code>ssl.*</code> or <code>listeners.https</code> options will be used to configure the HTTPS client.</p>
<p>The following are the currently supported REST API endpoints:</p>
<ul>
<li><code>GET /connectors</code> - return a list of active connectors</li>
<li><code>POST /connectors</code> - create a new connector; the request body should be a JSON object containing a string <code>name</code> field and an object <code>config</code> field with the connector configuration parameters</li>
<li><code>GET /connectors/{name}</code> - get information about a specific connector</li>
<li><code>GET /connectors/{name}/config</code> - get the configuration parameters for a specific connector</li>
<li><code>PUT /connectors/{name}/config</code> - update the configuration parameters for a specific connector</li>
<li><code>GET /connectors/{name}/status</code> - get current status of the connector, including if it is running, failed, paused, etc., which worker it is assigned to, error information if it has failed, and the state of all its tasks</li>
<li><code>GET /connectors/{name}/tasks</code> - get a list of tasks currently running for a connector</li>
<li><code>GET /connectors/{name}/tasks/{taskid}/status</code> - get current status of the task, including if it is running, failed, paused, etc., which worker it is assigned to, and error information if it has failed</li>
<li><code>PUT /connectors/{name}/pause</code> - pause the connector and its tasks, which stops message processing until the connector is resumed</li>
<li><code>PUT /connectors/{name}/resume</code> - resume a paused connector (or do nothing if the connector is not paused)</li>
<li><code>POST /connectors/{name}/restart</code> - restart a connector (typically because it has failed)</li>
<li><code>POST /connectors/{name}/tasks/{taskId}/restart</code> - restart an individual task (typically because it has failed)</li>
<li><code>DELETE /connectors/{name}</code> - delete a connector, halting all tasks and deleting its configuration</li>
<li><code>GET /connectors/{name}/topics</code> - get the set of topics that a specific connector is using since the connector was created or since a request to reset its set of active topics was issued</li>
<li><code>PUT /connectors/{name}/topics/reset</code> - send a request to empty the set of active topics of a connector</li>
</ul>
<p>Kafka Connect also provides a REST API for getting information about connector plugins:</p>
<ul>
<li><code>GET /connector-plugins</code>- return a list of connector plugins installed in the Kafka Connect cluster. Note that the API only checks for connectors on the worker that handles the request, which means you may see inconsistent results, especially during a rolling upgrade if you add new connector jars</li>
<li><code>PUT /connector-plugins/{connector-type}/config/validate</code> - validate the provided configuration values against the configuration definition. This API performs per config validation, returns suggested values and error messages during validation.</li>
</ul>
<p>The following is a supported REST request at the top-level (root) endpoint:</p>
<ul>
<li><code>GET /</code>- return basic information about the Kafka Connect cluster such as the version of the Connect worker that serves the REST request (including git commit ID of the source code) and the Kafka cluster ID that is connected to.
</ul>
<h3><a id="connect_development" href="#connect_development">8.3 Connector Development Guide</a></h3>
<p>This guide describes how developers can write new connectors for Kafka Connect to move data between Kafka and other systems. It briefly reviews a few key concepts and then describes how to create a simple connector.</p>
<h4><a id="connect_concepts" href="#connect_concepts">Core Concepts and APIs</a></h4>
<h5><a id="connect_connectorsandtasks" href="#connect_connectorsandtasks">Connectors and Tasks</a></h5>
<p>To copy data between Kafka and another system, users create a <code>Connector</code> for the system they want to pull data from or push data to. Connectors come in two flavors: <code>SourceConnectors</code> import data from another system (e.g. <code>JDBCSourceConnector</code> would import a relational database into Kafka) and <code>SinkConnectors</code> export data (e.g. <code>HDFSSinkConnector</code> would export the contents of a Kafka topic to an HDFS file).</p>
<p><code>Connectors</code> do not perform any data copying themselves: their configuration describes the data to be copied, and the <code>Connector</code> is responsible for breaking that job into a set of <code>Tasks</code> that can be distributed to workers. These <code>Tasks</code> also come in two corresponding flavors: <code>SourceTask</code> and <code>SinkTask</code>.</p>
<p>With an assignment in hand, each <code>Task</code> must copy its subset of the data to or from Kafka. In Kafka Connect, it should always be possible to frame these assignments as a set of input and output streams consisting of records with consistent schemas. Sometimes this mapping is obvious: each file in a set of log files can be considered a stream with each parsed line forming a record using the same schema and offsets stored as byte offsets in the file. In other cases it may require more effort to map to this model: a JDBC connector can map each table to a stream, but the offset is less clear. One possible mapping uses a timestamp column to generate queries incrementally returning new data, and the last queried timestamp can be used as the offset.</p>
<h5><a id="connect_streamsandrecords" href="#connect_streamsandrecords">Streams and Records</a></h5>
<p>Each stream should be a sequence of key-value records. Both the keys and values can have complex structure -- many primitive types are provided, but arrays, objects, and nested data structures can be represented as well. The runtime data format does not assume any particular serialization format; this conversion is handled internally by the framework.</p>
<p>In addition to the key and value, records (both those generated by sources and those delivered to sinks) have associated stream IDs and offsets. These are used by the framework to periodically commit the offsets of data that have been processed so that in the event of failures, processing can resume from the last committed offsets, avoiding unnecessary reprocessing and duplication of events.</p>
<h5><a id="connect_dynamicconnectors" href="#connect_dynamicconnectors">Dynamic Connectors</a></h5>
<p>Not all jobs are static, so <code>Connector</code> implementations are also responsible for monitoring the external system for any changes that might require reconfiguration. For example, in the <code>JDBCSourceConnector</code> example, the <code>Connector</code> might assign a set of tables to each <code>Task</code>. When a new table is created, it must discover this so it can assign the new table to one of the <code>Tasks</code> by updating its configuration. When it notices a change that requires reconfiguration (or a change in the number of <code>Tasks</code>), it notifies the framework and the framework updates any corresponding <code>Tasks</code>.</p>
<h4><a id="connect_developing" href="#connect_developing">Developing a Simple Connector</a></h4>
<p>Developing a connector only requires implementing two interfaces, the <code>Connector</code> and <code>Task</code>. A simple example is included with the source code for Kafka in the <code>file</code> package. This connector is meant for use in standalone mode and has implementations of a <code>SourceConnector</code>/<code>SourceTask</code> to read each line of a file and emit it as a record and a <code>SinkConnector</code>/<code>SinkTask</code> that writes each record to a file.</p>
<p>The rest of this section will walk through some code to demonstrate the key steps in creating a connector, but developers should also refer to the full example source code as many details are omitted for brevity.</p>
<h5><a id="connect_connectorexample" href="#connect_connectorexample">Connector Example</a></h5>
<p>We'll cover the <code>SourceConnector</code> as a simple example. <code>SinkConnector</code> implementations are very similar. Start by creating the class that inherits from <code>SourceConnector</code> and add a couple of fields that will store parsed configuration information (the filename to read from and the topic to send data to):</p>
<pre class="brush: java;">
public class FileStreamSourceConnector extends SourceConnector {
private String filename;
private String topic;
</pre>
<p>The easiest method to fill in is <code>taskClass()</code>, which defines the class that should be instantiated in worker processes to actually read the data:</p>
<pre class="brush: java;">
@Override
public Class&lt;? extends Task&gt; taskClass() {
return FileStreamSourceTask.class;
}
</pre>
<p>We will define the <code>FileStreamSourceTask</code> class below. Next, we add some standard lifecycle methods, <code>start()</code> and <code>stop()</code></p>:
<pre class="brush: java;">
@Override
public void start(Map&lt;String, String&gt; props) {
// The complete version includes error handling as well.
filename = props.get(FILE_CONFIG);
topic = props.get(TOPIC_CONFIG);
}
@Override
public void stop() {
// Nothing to do since no background monitoring is required.
}
</pre>
<p>Finally, the real core of the implementation is in <code>taskConfigs()</code>. In this case we are only
handling a single file, so even though we may be permitted to generate more tasks as per the
<code>maxTasks</code> argument, we return a list with only one entry:</p>
<pre class="brush: java;">
@Override
public List&lt;Map&lt;String, String&gt;&gt; taskConfigs(int maxTasks) {
ArrayList&lt;Map&lt;String, String&gt;&gt; configs = new ArrayList&lt;&gt;();
// Only one input stream makes sense.
Map&lt;String, String&gt; config = new HashMap&lt;&gt;();
if (filename != null)
config.put(FILE_CONFIG, filename);
config.put(TOPIC_CONFIG, topic);
configs.add(config);
return configs;
}
</pre>
<p>Although not used in the example, <code>SourceTask</code> also provides two APIs to commit offsets in the source system: <code>commit</code> and <code>commitRecord</code>. The APIs are provided for source systems which have an acknowledgement mechanism for messages. Overriding these methods allows the source connector to acknowledge messages in the source system, either in bulk or individually, once they have been written to Kafka.
The <code>commit</code> API stores the offsets in the source system, up to the offsets that have been returned by <code>poll</code>. The implementation of this API should block until the commit is complete. The <code>commitRecord</code> API saves the offset in the source system for each <code>SourceRecord</code> after it is written to Kafka. As Kafka Connect will record offsets automatically, <code>SourceTask</code>s are not required to implement them. In cases where a connector does need to acknowledge messages in the source system, only one of the APIs is typically required.</p>
<p>Even with multiple tasks, this method implementation is usually pretty simple. It just has to determine the number of input tasks, which may require contacting the remote service it is pulling data from, and then divvy them up. Because some patterns for splitting work among tasks are so common, some utilities are provided in <code>ConnectorUtils</code> to simplify these cases.</p>
<p>Note that this simple example does not include dynamic input. See the discussion in the next section for how to trigger updates to task configs.</p>
<h5><a id="connect_taskexample" href="#connect_taskexample">Task Example - Source Task</a></h5>
<p>Next we'll describe the implementation of the corresponding <code>SourceTask</code>. The implementation is short, but too long to cover completely in this guide. We'll use pseudo-code to describe most of the implementation, but you can refer to the source code for the full example.</p>
<p>Just as with the connector, we need to create a class inheriting from the appropriate base <code>Task</code> class. It also has some standard lifecycle methods:</p>
<pre class="brush: java;">
public class FileStreamSourceTask extends SourceTask {
String filename;
InputStream stream;
String topic;
@Override
public void start(Map&lt;String, String&gt; props) {
filename = props.get(FileStreamSourceConnector.FILE_CONFIG);
stream = openOrThrowError(filename);
topic = props.get(FileStreamSourceConnector.TOPIC_CONFIG);
}
@Override
public synchronized void stop() {
stream.close();
}
</pre>
<p>These are slightly simplified versions, but show that these methods should be relatively simple and the only work they should perform is allocating or freeing resources. There are two points to note about this implementation. First, the <code>start()</code> method does not yet handle resuming from a previous offset, which will be addressed in a later section. Second, the <code>stop()</code> method is synchronized. This will be necessary because <code>SourceTasks</code> are given a dedicated thread which they can block indefinitely, so they need to be stopped with a call from a different thread in the Worker.</p>
<p>Next, we implement the main functionality of the task, the <code>poll()</code> method which gets events from the input system and returns a <code>List&lt;SourceRecord&gt;</code>:</p>
<pre class="brush: java;">
@Override
public List&lt;SourceRecord&gt; poll() throws InterruptedException {
try {
ArrayList&lt;SourceRecord&gt; records = new ArrayList&lt;&gt;();
while (streamValid(stream) &amp;&amp; records.isEmpty()) {
LineAndOffset line = readToNextLine(stream);
if (line != null) {
Map&lt;String, Object&gt; sourcePartition = Collections.singletonMap("filename", filename);
Map&lt;String, Object&gt; sourceOffset = Collections.singletonMap("position", streamOffset);
records.add(new SourceRecord(sourcePartition, sourceOffset, topic, Schema.STRING_SCHEMA, line));
} else {
Thread.sleep(1);
}
}
return records;
} catch (IOException e) {
// Underlying stream was killed, probably as a result of calling stop. Allow to return
// null, and driving thread will handle any shutdown if necessary.
}
return null;
}
</pre>
<p>Again, we've omitted some details, but we can see the important steps: the <code>poll()</code> method is going to be called repeatedly, and for each call it will loop trying to read records from the file. For each line it reads, it also tracks the file offset. It uses this information to create an output <code>SourceRecord</code> with four pieces of information: the source partition (there is only one, the single file being read), source offset (byte offset in the file), output topic name, and output value (the line, and we include a schema indicating this value will always be a string). Other variants of the <code>SourceRecord</code> constructor can also include a specific output partition, a key, and headers.</p>
<p>Note that this implementation uses the normal Java <code>InputStream</code> interface and may sleep if data is not available. This is acceptable because Kafka Connect provides each task with a dedicated thread. While task implementations have to conform to the basic <code>poll()</code> interface, they have a lot of flexibility in how they are implemented. In this case, an NIO-based implementation would be more efficient, but this simple approach works, is quick to implement, and is compatible with older versions of Java.</p>
<h5><a id="connect_sinktasks" href="#connect_sinktasks">Sink Tasks</a></h5>
<p>The previous section described how to implement a simple <code>SourceTask</code>. Unlike <code>SourceConnector</code> and <code>SinkConnector</code>, <code>SourceTask</code> and <code>SinkTask</code> have very different interfaces because <code>SourceTask</code> uses a pull interface and <code>SinkTask</code> uses a push interface. Both share the common lifecycle methods, but the <code>SinkTask</code> interface is quite different:</p>
<pre class="brush: java;">
public abstract class SinkTask implements Task {
public void initialize(SinkTaskContext context) {
this.context = context;
}
public abstract void put(Collection&lt;SinkRecord&gt; records);
public void flush(Map&lt;TopicPartition, OffsetAndMetadata&gt; currentOffsets) {
}
</pre>
<p>The <code>SinkTask</code> documentation contains full details, but this interface is nearly as simple as the <code>SourceTask</code>. The <code>put()</code> method should contain most of the implementation, accepting sets of <code>SinkRecords</code>, performing any required translation, and storing them in the destination system. This method does not need to ensure the data has been fully written to the destination system before returning. In fact, in many cases internal buffering will be useful so an entire batch of records can be sent at once, reducing the overhead of inserting events into the downstream data store. The <code>SinkRecords</code> contain essentially the same information as <code>SourceRecords</code>: Kafka topic, partition, offset, the event key and value, and optional headers.</p>
<p>The <code>flush()</code> method is used during the offset commit process, which allows tasks to recover from failures and resume from a safe point such that no events will be missed. The method should push any outstanding data to the destination system and then block until the write has been acknowledged. The <code>offsets</code> parameter can often be ignored, but is useful in some cases where implementations want to store offset information in the destination store to provide exactly-once
delivery. For example, an HDFS connector could do this and use atomic move operations to make sure the <code>flush()</code> operation atomically commits the data and offsets to a final location in HDFS.</p>
<h5><a id="connect_resuming" href="#connect_resuming">Resuming from Previous Offsets</a></h5>
<p>The <code>SourceTask</code> implementation included a stream ID (the input filename) and offset (position in the file) with each record. The framework uses this to commit offsets periodically so that in the case of a failure, the task can recover and minimize the number of events that are reprocessed and possibly duplicated (or to resume from the most recent offset if Kafka Connect was stopped gracefully, e.g. in standalone mode or due to a job reconfiguration). This commit process is completely automated by the framework, but only the connector knows how to seek back to the right position in the input stream to resume from that location.</p>
<p>To correctly resume upon startup, the task can use the <code>SourceContext</code> passed into its <code>initialize()</code> method to access the offset data. In <code>initialize()</code>, we would add a bit more code to read the offset (if it exists) and seek to that position:</p>
<pre class="brush: java;">
stream = new FileInputStream(filename);
Map&lt;String, Object&gt; offset = context.offsetStorageReader().offset(Collections.singletonMap(FILENAME_FIELD, filename));
if (offset != null) {
Long lastRecordedOffset = (Long) offset.get("position");
if (lastRecordedOffset != null)
seekToOffset(stream, lastRecordedOffset);
}
</pre>
<p>Of course, you might need to read many keys for each of the input streams. The <code>OffsetStorageReader</code> interface also allows you to issue bulk reads to efficiently load all offsets, then apply them by seeking each input stream to the appropriate position.</p>
<h4><a id="connect_dynamicio" href="#connect_dynamicio">Dynamic Input/Output Streams</a></h4>
<p>Kafka Connect is intended to define bulk data copying jobs, such as copying an entire database rather than creating many jobs to copy each table individually. One consequence of this design is that the set of input or output streams for a connector can vary over time.</p>
<p>Source connectors need to monitor the source system for changes, e.g. table additions/deletions in a database. When they pick up changes, they should notify the framework via the <code>ConnectorContext</code> object that reconfiguration is necessary. For example, in a <code>SourceConnector</code>:</p>
<pre class="brush: java;">
if (inputsChanged())
this.context.requestTaskReconfiguration();
</pre>
<p>The framework will promptly request new configuration information and update the tasks, allowing them to gracefully commit their progress before reconfiguring them. Note that in the <code>SourceConnector</code> this monitoring is currently left up to the connector implementation. If an extra thread is required to perform this monitoring, the connector must allocate it itself.</p>
<p>Ideally this code for monitoring changes would be isolated to the <code>Connector</code> and tasks would not need to worry about them. However, changes can also affect tasks, most commonly when one of their input streams is destroyed in the input system, e.g. if a table is dropped from a database. If the <code>Task</code> encounters the issue before the <code>Connector</code>, which will be common if the <code>Connector</code> needs to poll for changes, the <code>Task</code> will need to handle the subsequent error. Thankfully, this can usually be handled simply by catching and handling the appropriate exception.</p>
<p><code>SinkConnectors</code> usually only have to handle the addition of streams, which may translate to new entries in their outputs (e.g., a new database table). The framework manages any changes to the Kafka input, such as when the set of input topics changes because of a regex subscription. <code>SinkTasks</code> should expect new input streams, which may require creating new resources in the downstream system, such as a new table in a database. The trickiest situation to handle in these cases may be conflicts between multiple <code>SinkTasks</code> seeing a new input stream for the first time and simultaneously trying to create the new resource. <code>SinkConnectors</code>, on the other hand, will generally require no special code for handling a dynamic set of streams.</p>
<h4><a id="connect_configs" href="#connect_configs">Connect Configuration Validation</a></h4>
<p>Kafka Connect allows you to validate connector configurations before submitting a connector to be executed and can provide feedback about errors and recommended values. To take advantage of this, connector developers need to provide an implementation of <code>config()</code> to expose the configuration definition to the framework.</p>
<p>The following code in <code>FileStreamSourceConnector</code> defines the configuration and exposes it to the framework.</p>
<pre class="brush: java;">
private static final ConfigDef CONFIG_DEF = new ConfigDef()
.define(FILE_CONFIG, Type.STRING, Importance.HIGH, "Source filename.")
.define(TOPIC_CONFIG, Type.STRING, Importance.HIGH, "The topic to publish data to");
public ConfigDef config() {
return CONFIG_DEF;
}
</pre>
<p><code>ConfigDef</code> class is used for specifying the set of expected configurations. For each configuration, you can specify the name, the type, the default value, the documentation, the group information, the order in the group, the width of the configuration value and the name suitable for display in the UI. Plus, you can provide special validation logic used for single configuration validation by overriding the <code>Validator</code> class. Moreover, as there may be dependencies between configurations, for example, the valid values and visibility of a configuration may change according to the values of other configurations. To handle this, <code>ConfigDef</code> allows you to specify the dependents of a configuration and to provide an implementation of <code>Recommender</code> to get valid values and set visibility of a configuration given the current configuration values.</p>
<p>Also, the <code>validate()</code> method in <code>Connector</code> provides a default validation implementation which returns a list of allowed configurations together with configuration errors and recommended values for each configuration. However, it does not use the recommended values for configuration validation. You may provide an override of the default implementation for customized configuration validation, which may use the recommended values.</p>
<h4><a id="connect_schemas" href="#connect_schemas">Working with Schemas</a></h4>
<p>The FileStream connectors are good examples because they are simple, but they also have trivially structured data -- each line is just a string. Almost all practical connectors will need schemas with more complex data formats.</p>
<p>To create more complex data, you'll need to work with the Kafka Connect <code>data</code> API. Most structured records will need to interact with two classes in addition to primitive types: <code>Schema</code> and <code>Struct</code>.</p>
<p>The API documentation provides a complete reference, but here is a simple example creating a <code>Schema</code> and <code>Struct</code>:</p>
<pre class="brush: java;">
Schema schema = SchemaBuilder.struct().name(NAME)
.field("name", Schema.STRING_SCHEMA)
.field("age", Schema.INT_SCHEMA)
.field("admin", SchemaBuilder.bool().defaultValue(false).build())
.build();
Struct struct = new Struct(schema)
.put("name", "Barbara Liskov")
.put("age", 75);
</pre>
<p>If you are implementing a source connector, you'll need to decide when and how to create schemas. Where possible, you should avoid recomputing them as much as possible. For example, if your connector is guaranteed to have a fixed schema, create it statically and reuse a single instance.</p>
<p>However, many connectors will have dynamic schemas. One simple example of this is a database connector. Considering even just a single table, the schema will not be predefined for the entire connector (as it varies from table to table). But it also may not be fixed for a single table over the lifetime of the connector since the user may execute an <code>ALTER TABLE</code> command. The connector must be able to detect these changes and react appropriately.</p>
<p>Sink connectors are usually simpler because they are consuming data and therefore do not need to create schemas. However, they should take just as much care to validate that the schemas they receive have the expected format. When the schema does not match -- usually indicating the upstream producer is generating invalid data that cannot be correctly translated to the destination system -- sink connectors should throw an exception to indicate this error to the system.</p>
<h4><a id="connect_administration" href="#connect_administration">Kafka Connect Administration</a></h4>
<p>
Kafka Connect's <a href="#connect_rest">REST layer</a> provides a set of APIs to enable administration of the cluster. This includes APIs to view the configuration of connectors and the status of their tasks, as well as to alter their current behavior (e.g. changing configuration and restarting tasks).
</p>
<p>
When a connector is first submitted to the cluster, a rebalance is triggered between the Connect workers in order to distribute the load that consists of the tasks of the new connector.
This same rebalancing procedure is also used when connectors increase or decrease the number of tasks they require, when a connector's configuration is changed, or when a
worker is added or removed from the group as part of an intentional upgrade of the Connect cluster or due to a failure.
</p>
<p>
In versions prior to 2.3.0, the Connect workers would rebalance the full set of connectors and their tasks in the cluster as a simple way to make sure that each worker has approximately the same amount of work.
This behavior can be still enabled by setting <code>connect.protocol=eager</code>.
</p>
<p>
Starting with 2.3.0, Kafka Connect is using by default a protocol that performs
<a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-415%3A+Incremental+Cooperative+Rebalancing+in+Kafka+Connect">incremental cooperative rebalancing</a>
that incrementally balances the connectors and tasks across the Connect workers, affecting only tasks that are new, to be removed, or need to move from one worker to another.
Other tasks are not stopped and restarted during the rebalance, as they would have been with the old protocol.
</p>
<p>
If a Connect worker leaves the group, intentionally or due to a failure, Connect waits for <code>scheduled.rebalance.max.delay.ms</code> before triggering a rebalance.
This delay defaults to five minutes (<code>300000ms</code>) to tolerate failures or upgrades of workers without immediately redistributing the load of a departing worker.
If this worker returns within the configured delay, it gets its previously assigned tasks in full.
However, this means that the tasks will remain unassigned until the time specified by <code>scheduled.rebalance.max.delay.ms</code> elapses.
If a worker does not return within that time limit, Connect will reassign those tasks among the remaining workers in the Connect cluster.
</p>
<p>
The new Connect protocol is enabled when all the workers that form the Connect cluster are configured with <code>connect.protocol=compatible</code>, which is also the default value when this property is missing.
Therefore, upgrading to the new Connect protocol happens automatically when all the workers upgrade to 2.3.0.
A rolling upgrade of the Connect cluster will activate incremental cooperative rebalancing when the last worker joins on version 2.3.0.
</p>
<p>
You can use the REST API to view the current status of a connector and its tasks, including the ID of the worker to which each was assigned. For example, the <code>GET /connectors/file-source/status</code> request shows the status of a connector named <code>file-source</code>:
</p>
<pre class="brush: json;">
{
"name": "file-source",
"connector": {
"state": "RUNNING",
"worker_id": "192.168.1.208:8083"
},
"tasks": [
{
"id": 0,
"state": "RUNNING",
"worker_id": "192.168.1.209:8083"
}
]
}
</pre>
<p>
Connectors and their tasks publish status updates to a shared topic (configured with <code>status.storage.topic</code>) which all workers in the cluster monitor. Because the workers consume this topic asynchronously, there is typically a (short) delay before a state change is visible through the status API. The following states are possible for a connector or one of its tasks:
</p>
<ul>
<li><b>UNASSIGNED:</b> The connector/task has not yet been assigned to a worker.</li>
<li><b>RUNNING:</b> The connector/task is running.</li>
<li><b>PAUSED:</b> The connector/task has been administratively paused.</li>
<li><b>FAILED:</b> The connector/task has failed (usually by raising an exception, which is reported in the status output).</li>
<li><b>DESTROYED:</b> The connector/task has been administratively removed and will stop appearing in the Connect cluster.</li>
</ul>
<p>
In most cases, connector and task states will match, though they may be different for short periods of time when changes are occurring or if tasks have failed. For example, when a connector is first started, there may be a noticeable delay before the connector and its tasks have all transitioned to the RUNNING state. States will also diverge when tasks fail since Connect does not automatically restart failed tasks. To restart a connector/task manually, you can use the restart APIs listed above. Note that if you try to restart a task while a rebalance is taking place, Connect will return a 409 (Conflict) status code. You can retry after the rebalance completes, but it might not be necessary since rebalances effectively restart all the connectors and tasks in the cluster.
</p>
<p>
Starting with 2.5.0, Kafka Connect uses the <code>status.storage.topic</code> to also store information related to the topics that each connector is using. Connect Workers use these per-connector topic status updates to respond to requests to the REST endpoint <code>GET /connectors/{name}/topics</code> by returning the set of topic names that a connector is using. A request to the REST endpoint <code>PUT /connectors/{name}/topics/reset</code> resets the set of active topics for a connector and allows a new set to be populated, based on the connector's latest pattern of topic usage. Upon connector deletion, the set of the connector's active topics is also deleted. Topic tracking is enabled by default but can be disabled by setting <code>topic.tracking.enable=false</code>. If you want to disallow requests to reset the active topics of connectors during runtime, set the Worker property <code>topic.tracking.allow.reset=false</code>.
</p>
<p>
It's sometimes useful to temporarily stop the message processing of a connector. For example, if the remote system is undergoing maintenance, it would be preferable for source connectors to stop polling it for new data instead of filling logs with exception spam. For this use case, Connect offers a pause/resume API. While a source connector is paused, Connect will stop polling it for additional records. While a sink connector is paused, Connect will stop pushing new messages to it. The pause state is persistent, so even if you restart the cluster, the connector will not begin message processing again until the task has been resumed. Note that there may be a delay before all of a connector's tasks have transitioned to the PAUSED state since it may take time for them to finish whatever processing they were in the middle of when being paused. Additionally, failed tasks will not transition to the PAUSED state until they have been restarted.
</p>
</script>
<div class="p-connect"></div>

View File

@@ -1,241 +0,0 @@
CREATE DATABASE IF NOT EXISTS `kafka_manager`;
USE `kafka_manager`;
CREATE TABLE `account` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用户名',
`password` varchar(256) NOT NULL DEFAULT '' COMMENT '密码',
`role` int(16) NOT NULL DEFAULT '0' COMMENT '角色类型, 0:普通用户',
`status` int(16) NOT NULL DEFAULT '0' COMMENT '0标识使用中-1标识已废弃',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='账号表';
INSERT INTO account(username, password, role) VALUES ('admin', '21232f297a57a5a743894a0e4a801fc3', 2);
CREATE TABLE `alarm_rule` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`alarm_name` varchar(128) NOT NULL DEFAULT '' COMMENT '告警名字',
`strategy_expressions` text COMMENT '表达式',
`strategy_filters` text COMMENT '过滤条件',
`strategy_actions` text COMMENT '响应',
`principals` varchar(512) NOT NULL DEFAULT '' COMMENT '负责人',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '-1:逻辑删除, 0:关闭, 1:正常',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_alarm_name` (`alarm_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='告警规则表';
CREATE TABLE `broker` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`cluster_id` bigint(128) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`broker_id` int(11) NOT NULL DEFAULT '-1' COMMENT 'BrokerID',
`host` varchar(128) NOT NULL DEFAULT '' COMMENT 'Broker主机名',
`port` int(32) NOT NULL DEFAULT '-1' COMMENT 'Broker端口',
`timestamp` bigint(128) NOT NULL DEFAULT '-1' COMMENT '启动时间',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '状态0有效-1无效',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_cluster_id_broker_id` (`cluster_id`,`broker_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Broker信息表';
CREATE TABLE `broker_metrics` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',
`cluster_id` bigint(11) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`broker_id` int(11) NOT NULL DEFAULT '-1' COMMENT 'BrokerID',
`bytes_in` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒字节流入',
`bytes_out` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒字节流出',
`bytes_rejected` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒被拒绝字节数',
`messages_in` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒消息数流入',
`fail_fetch_request` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒消费失败数',
`fail_produce_request` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒失败生产数',
`fetch_consumer_request` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒消费请求数',
`produce_request` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒生产数',
`request_handler_idl_percent` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '请求处理器繁忙百分比',
`network_processor_idl_percent` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '网络处理器繁忙百分比',
`request_queue_size` bigint(20) NOT NULL DEFAULT '0' COMMENT '请求列表大小',
`response_queue_size` bigint(20) NOT NULL DEFAULT '0' COMMENT '响应列表大小',
`log_flush_time` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '刷日志时间',
`total_time_produce_mean` double(53,2) NOT NULL DEFAULT '0.00' COMMENT 'produce请求处理总时间-平均值',
`total_time_produce_99th` double(53,2) NOT NULL DEFAULT '0.00' COMMENT 'produce请求处理总时间-99分位',
`total_time_fetch_consumer_mean` double(53,2) NOT NULL DEFAULT '0.00' COMMENT 'fetch请求总时间-平均值',
`total_time_fetch_consumer_99th` double(53,2) NOT NULL DEFAULT '0.00' COMMENT 'fetch请求总时间-99分位',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_cluster_id_broker_id_gmt_create` (`cluster_id`,`broker_id`,`gmt_create`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='BrokerMetric信息表';
CREATE TABLE `cluster` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '集群ID',
`cluster_name` varchar(128) NOT NULL DEFAULT '' COMMENT '集群名称',
`zookeeper` varchar(512) NOT NULL DEFAULT '' COMMENT 'ZK地址',
`bootstrap_servers` varchar(512) NOT NULL DEFAULT '' COMMENT 'Server地址',
`kafka_version` varchar(32) NOT NULL DEFAULT '' COMMENT 'Kafka版本',
`alarm_flag` int(4) NOT NULL DEFAULT '0' COMMENT '0:不开启告警, 1开启告警',
`security_protocol` varchar(512) NOT NULL DEFAULT '' COMMENT '安全协议',
`sasl_mechanism` varchar(512) NOT NULL DEFAULT '' COMMENT '安全机制',
`sasl_jaas_config` varchar(512) NOT NULL DEFAULT '' COMMENT 'Jaas配置',
`status` int(4) NOT NULL DEFAULT '0' COMMENT '删除标记, 0表示未删除, -1表示删除',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_cluster_name` (`cluster_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cluster表';
CREATE TABLE `cluster_metrics` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',
`cluster_id` bigint(11) NOT NULL DEFAULT '0' COMMENT '集群ID',
`topic_num` int(11) NOT NULL DEFAULT '0' COMMENT 'Topic数',
`partition_num` int(11) NOT NULL DEFAULT '0' COMMENT '分区数',
`broker_num` int(11) NOT NULL DEFAULT '0' COMMENT 'Broker数',
`bytes_in` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒流入(B)',
`bytes_out` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒流出(B)',
`bytes_rejected` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒拒绝(B)',
`messages_in` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒消息数(条)',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_cluster_id_gmt_create` (`cluster_id`,`gmt_create`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='ClusterMetrics信息';
CREATE TABLE `controller` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',
`cluster_id` bigint(20) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`broker_id` int(11) NOT NULL DEFAULT '-1' COMMENT 'BrokerId',
`host` varchar(256) NOT NULL DEFAULT '' COMMENT '主机名',
`timestamp` bigint(20) NOT NULL DEFAULT '-1' COMMENT 'Controller变更时间',
`version` int(11) NOT NULL DEFAULT '-1' COMMENT 'Controller格式版本',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_cluster_id_broker_id_timestamp` (`cluster_id`,`broker_id`,`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Controller历史变更记录表';
CREATE TABLE `migration_task` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',
`cluster_id` bigint(128) NOT NULL DEFAULT '0' COMMENT '集群ID',
`topic_name` varchar(256) NOT NULL DEFAULT '' COMMENT 'Topic名称',
`reassignment_json` text COMMENT '任务参数',
`real_throttle` bigint(20) NOT NULL DEFAULT '0' COMMENT '实际限流值(B/s)',
`operator` varchar(128) NOT NULL DEFAULT '' COMMENT '操作人',
`description` varchar(256) NOT NULL DEFAULT '' COMMENT '备注说明',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '任务状态',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '任务创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '任务修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Topic迁移信息';
CREATE TABLE `operation_history` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`cluster_id` bigint(128) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`topic_name` varchar(128) NOT NULL DEFAULT '' COMMENT 'Topic名称',
`operator` varchar(128) NOT NULL DEFAULT '' COMMENT '操作人',
`operation` varchar(256) NOT NULL DEFAULT '' COMMENT '操作描述',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='操作记录表';
CREATE TABLE `order_partition` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`cluster_id` bigint(20) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`cluster_name` varchar(256) NOT NULL DEFAULT '' COMMENT '集群名称',
`topic_name` varchar(256) NOT NULL DEFAULT '' COMMENT 'Topic名称',
`applicant` varchar(128) NOT NULL DEFAULT '' COMMENT '申请人',
`peak_bytes_in` bigint(20) NOT NULL DEFAULT '0' COMMENT '峰值流量',
`description` text COMMENT '备注信息',
`order_status` int(16) NOT NULL DEFAULT '0' COMMENT '工单状态',
`approver` varchar(128) NOT NULL DEFAULT '' COMMENT '审批人',
`opinion` varchar(256) NOT NULL DEFAULT '' COMMENT '审批意见',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '状态0标识有效-1无效',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='分区申请工单';
CREATE TABLE `order_topic` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`cluster_id` bigint(20) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`cluster_name` varchar(256) NOT NULL DEFAULT '' COMMENT '集群名称',
`topic_name` varchar(256) NOT NULL DEFAULT '' COMMENT 'Topic名称',
`retention_time` bigint(20) NOT NULL DEFAULT '-1' COMMENT '保留时间(ms)',
`partition_num` int(16) NOT NULL DEFAULT '-1' COMMENT '分区数',
`replica_num` int(16) NOT NULL DEFAULT '-1' COMMENT '副本数',
`regions` varchar(128) NOT NULL DEFAULT '' COMMENT 'RegionId列表',
`brokers` varchar(128) NOT NULL DEFAULT '' COMMENT 'Broker列表',
`peak_bytes_in` bigint(20) NOT NULL DEFAULT '0' COMMENT '峰值流入流量(KB)',
`applicant` varchar(128) NOT NULL DEFAULT '' COMMENT '申请人',
`principals` varchar(256) NOT NULL DEFAULT '' COMMENT '负责人',
`description` text COMMENT '备注信息',
`order_status` int(16) NOT NULL DEFAULT '0' COMMENT '工单状态',
`approver` varchar(128) NOT NULL DEFAULT '' COMMENT '审批人',
`opinion` varchar(256) NOT NULL DEFAULT '' COMMENT '审批意见',
`status` int(16) NOT NULL DEFAULT '0' COMMENT '状态0标识有效-1无效',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Topic申请工单';
CREATE TABLE `region` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`cluster_id` bigint(20) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`region_name` varchar(256) NOT NULL DEFAULT '' COMMENT 'Region名称',
`broker_list` varchar(256) NOT NULL DEFAULT '' COMMENT 'Broker列表',
`level` int(16) NOT NULL DEFAULT '0' COMMENT 'Region重要等级, 0级普通, 1极重要2级极重要',
`operator` varchar(45) NOT NULL DEFAULT '' COMMENT '操作人',
`description` text COMMENT '备注说明',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '状态0正常-1废弃1容量已满',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_cluster_id_region_name` (`cluster_id`,`region_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Region信息表';
CREATE TABLE `topic` (
`id` bigint(128) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`cluster_id` bigint(128) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`topic_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT 'Topic名称',
`applicant` varchar(256) NOT NULL DEFAULT '' COMMENT '申请人',
`principals` varchar(256) NOT NULL DEFAULT '' COMMENT '负责人',
`description` text COMMENT '备注信息',
`status` int(16) NOT NULL DEFAULT '0' COMMENT '0标识使用中-1标识已废弃',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_cluster_id_topic_name` (`cluster_id`,`topic_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Topic信息表';
CREATE TABLE `topic_favorite` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id',
`username` varchar(128) NOT NULL DEFAULT '' COMMENT '用户名',
`cluster_id` bigint(20) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`topic_name` varchar(512) NOT NULL DEFAULT '' COMMENT 'Topic名称',
`status` int(16) NOT NULL DEFAULT '0' COMMENT '删除标记, 0表示未删除, -1表示删除',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_username_cluster_id_topic_name` (`username`,`cluster_id`,`topic_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户收藏的Topic表';
CREATE TABLE `topic_metrics` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',
`cluster_id` bigint(11) NOT NULL DEFAULT '-1' COMMENT '集群ID',
`topic_name` varchar(256) NOT NULL DEFAULT '' COMMENT 'Topic名称',
`messages_in` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒进入消息条数',
`bytes_in` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒字节流入',
`bytes_out` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒字节流出',
`bytes_rejected` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒拒绝字节数',
`total_produce_requests` double(53,2) NOT NULL DEFAULT '0.00' COMMENT '每秒请求数',
`gmt_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_cluster_id_topic_name_gmt_create` (`cluster_id`,`topic_name`,`gmt_create`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='TopicMetrics表';

660
docs/design.html Normal file
View File

@@ -0,0 +1,660 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script id="design-template" type="text/x-handlebars-template">
<h3><a id="majordesignelements" href="#majordesignelements">4.1 Motivation</a></h3>
<p>
We designed Kafka to be able to act as a unified platform for handling all the real-time data feeds <a href="#introduction">a large company might have</a>. To do this we had to think through a fairly broad set of use cases.
<p>
It would have to have high-throughput to support high volume event streams such as real-time log aggregation.
<p>
It would need to deal gracefully with large data backlogs to be able to support periodic data loads from offline systems.
<p>
It also meant the system would have to handle low-latency delivery to handle more traditional messaging use-cases.
<p>
We wanted to support partitioned, distributed, real-time processing of these feeds to create new, derived feeds. This motivated our partitioning and consumer model.
<p>
Finally in cases where the stream is fed into other data systems for serving, we knew the system would have to be able to guarantee fault-tolerance in the presence of machine failures.
<p>
Supporting these uses led us to a design with a number of unique elements, more akin to a database log than a traditional messaging system. We will outline some elements of the design in the following sections.
<h3><a id="persistence" href="#persistence">4.2 Persistence</a></h3>
<h4><a id="design_filesystem" href="#design_filesystem">Don't fear the filesystem!</a></h4>
<p>
Kafka relies heavily on the filesystem for storing and caching messages. There is a general perception that "disks are slow" which makes people skeptical that a persistent structure can offer competitive performance.
In fact disks are both much slower and much faster than people expect depending on how they are used; and a properly designed disk structure can often be as fast as the network.
<p>
The key fact about disk performance is that the throughput of hard drives has been diverging from the latency of a disk seek for the last decade. As a result the performance of linear writes on a <a href="http://en.wikipedia.org/wiki/Non-RAID_drive_architectures">JBOD</a>
configuration with six 7200rpm SATA RAID-5 array is about 600MB/sec but the performance of random writes is only about 100k/sec&mdash;a difference of over 6000X. These linear reads and writes are the most
predictable of all usage patterns, and are heavily optimized by the operating system. A modern operating system provides read-ahead and write-behind techniques that prefetch data in large block multiples and
group smaller logical writes into large physical writes. A further discussion of this issue can be found in this <a href="http://queue.acm.org/detail.cfm?id=1563874">ACM Queue article</a>; they actually find that
<a href="http://deliveryimages.acm.org/10.1145/1570000/1563874/jacobs3.jpg">sequential disk access can in some cases be faster than random memory access!</a>
<p>
To compensate for this performance divergence, modern operating systems have become increasingly aggressive in their use of main memory for disk caching. A modern OS will happily divert <i>all</i> free memory to
disk caching with little performance penalty when the memory is reclaimed. All disk reads and writes will go through this unified cache. This feature cannot easily be turned off without using direct I/O, so even
if a process maintains an in-process cache of the data, this data will likely be duplicated in OS pagecache, effectively storing everything twice.
<p>
Furthermore, we are building on top of the JVM, and anyone who has spent any time with Java memory usage knows two things:
<ol>
<li>The memory overhead of objects is very high, often doubling the size of the data stored (or worse).</li>
<li>Java garbage collection becomes increasingly fiddly and slow as the in-heap data increases.</li>
</ol>
<p>
As a result of these factors using the filesystem and relying on pagecache is superior to maintaining an in-memory cache or other structure&mdash;we at least double the available cache by having automatic access
to all free memory, and likely double again by storing a compact byte structure rather than individual objects. Doing so will result in a cache of up to 28-30GB on a 32GB machine without GC penalties.
Furthermore, this cache will stay warm even if the service is restarted, whereas the in-process cache will need to be rebuilt in memory (which for a 10GB cache may take 10 minutes) or else it will need to start
with a completely cold cache (which likely means terrible initial performance). This also greatly simplifies the code as all logic for maintaining coherency between the cache and filesystem is now in the OS,
which tends to do so more efficiently and more correctly than one-off in-process attempts. If your disk usage favors linear reads then read-ahead is effectively pre-populating this cache with useful data on each
disk read.
<p>
This suggests a design which is very simple: rather than maintain as much as possible in-memory and flush it all out to the filesystem in a panic when we run out of space, we invert that. All data is immediately
written to a persistent log on the filesystem without necessarily flushing to disk. In effect this just means that it is transferred into the kernel's pagecache.
<p>
This style of pagecache-centric design is described in an <a href="http://varnish-cache.org/wiki/ArchitectNotes">article</a> on the design of Varnish here (along with a healthy dose of arrogance).
<h4><a id="design_constanttime" href="#design_constanttime">Constant Time Suffices</a></h4>
<p>
The persistent data structure used in messaging systems are often a per-consumer queue with an associated BTree or other general-purpose random access data structures to maintain metadata about messages.
BTrees are the most versatile data structure available, and make it possible to support a wide variety of transactional and non-transactional semantics in the messaging system.
They do come with a fairly high cost, though: Btree operations are O(log N). Normally O(log N) is considered essentially equivalent to constant time, but this is not true for disk operations.
Disk seeks come at 10 ms a pop, and each disk can do only one seek at a time so parallelism is limited. Hence even a handful of disk seeks leads to very high overhead.
Since storage systems mix very fast cached operations with very slow physical disk operations, the observed performance of tree structures is often superlinear as data increases with fixed cache--i.e. doubling
your data makes things much worse than twice as slow.
<p>
Intuitively a persistent queue could be built on simple reads and appends to files as is commonly the case with logging solutions. This structure has the advantage that all operations are O(1) and reads do not
block writes or each other. This has obvious performance advantages since the performance is completely decoupled from the data size&mdash;one server can now take full advantage of a number of cheap,
low-rotational speed 1+TB SATA drives. Though they have poor seek performance, these drives have acceptable performance for large reads and writes and come at 1/3 the price and 3x the capacity.
<p>
Having access to virtually unlimited disk space without any performance penalty means that we can provide some features not usually found in a messaging system. For example, in Kafka, instead of attempting to
delete messages as soon as they are consumed, we can retain messages for a relatively long period (say a week). This leads to a great deal of flexibility for consumers, as we will describe.
<h3><a id="maximizingefficiency" href="#maximizingefficiency">4.3 Efficiency</a></h3>
<p>
We have put significant effort into efficiency. One of our primary use cases is handling web activity data, which is very high volume: each page view may generate dozens of writes. Furthermore, we assume each
message published is read by at least one consumer (often many), hence we strive to make consumption as cheap as possible.
<p>
We have also found, from experience building and running a number of similar systems, that efficiency is a key to effective multi-tenant operations. If the downstream infrastructure service can easily become a
bottleneck due to a small bump in usage by the application, such small changes will often create problems. By being very fast we help ensure that the application will tip-over under load before the infrastructure.
This is particularly important when trying to run a centralized service that supports dozens or hundreds of applications on a centralized cluster as changes in usage patterns are a near-daily occurrence.
<p>
We discussed disk efficiency in the previous section. Once poor disk access patterns have been eliminated, there are two common causes of inefficiency in this type of system: too many small I/O operations, and
excessive byte copying.
<p>
The small I/O problem happens both between the client and the server and in the server's own persistent operations.
<p>
To avoid this, our protocol is built around a "message set" abstraction that naturally groups messages together. This allows network requests to group messages together and amortize the overhead of the network
roundtrip rather than sending a single message at a time. The server in turn appends chunks of messages to its log in one go, and the consumer fetches large linear chunks at a time.
<p>
This simple optimization produces orders of magnitude speed up. Batching leads to larger network packets, larger sequential disk operations, contiguous memory blocks, and so on, all of which allows Kafka to turn
a bursty stream of random message writes into linear writes that flow to the consumers.
<p>
The other inefficiency is in byte copying. At low message rates this is not an issue, but under load the impact is significant. To avoid this we employ a standardized binary message format that is shared by the
producer, the broker, and the consumer (so data chunks can be transferred without modification between them).
<p>
The message log maintained by the broker is itself just a directory of files, each populated by a sequence of message sets that have been written to disk in the same format used by the producer and consumer.
Maintaining this common format allows optimization of the most important operation: network transfer of persistent log chunks. Modern unix operating systems offer a highly optimized code path for transferring data
out of pagecache to a socket; in Linux this is done with the <a href="http://man7.org/linux/man-pages/man2/sendfile.2.html">sendfile system call</a>.
<p>
To understand the impact of sendfile, it is important to understand the common data path for transfer of data from file to socket:
<ol>
<li>The operating system reads data from the disk into pagecache in kernel space</li>
<li>The application reads the data from kernel space into a user-space buffer</li>
<li>The application writes the data back into kernel space into a socket buffer</li>
<li>The operating system copies the data from the socket buffer to the NIC buffer where it is sent over the network</li>
</ol>
<p>
This is clearly inefficient, there are four copies and two system calls. Using sendfile, this re-copying is avoided by allowing the OS to send the data from pagecache to the network directly. So in this optimized
path, only the final copy to the NIC buffer is needed.
<p>
We expect a common use case to be multiple consumers on a topic. Using the zero-copy optimization above, data is copied into pagecache exactly once and reused on each consumption instead of being stored in memory
and copied out to user-space every time it is read. This allows messages to be consumed at a rate that approaches the limit of the network connection.
<p>
This combination of pagecache and sendfile means that on a Kafka cluster where the consumers are mostly caught up you will see no read activity on the disks whatsoever as they will be serving data entirely from cache.
<p>
For more background on the sendfile and zero-copy support in Java, see this <a href="https://developer.ibm.com/articles/j-zerocopy/">article</a>.
<h4><a id="design_compression" href="#design_compression">End-to-end Batch Compression</a></h4>
<p>
In some cases the bottleneck is actually not CPU or disk but network bandwidth. This is particularly true for a data pipeline that needs to send messages between data centers over a wide-area network. Of course,
the user can always compress its messages one at a time without any support needed from Kafka, but this can lead to very poor compression ratios as much of the redundancy is due to repetition between messages of
the same type (e.g. field names in JSON or user agents in web logs or common string values). Efficient compression requires compressing multiple messages together rather than compressing each message individually.
<p>
Kafka supports this with an efficient batching format. A batch of messages can be clumped together compressed and sent to the server in this form. This batch of messages will be written in compressed form and will
remain compressed in the log and will only be decompressed by the consumer.
<p>
Kafka supports GZIP, Snappy, LZ4 and ZStandard compression protocols. More details on compression can be found <a href="https://cwiki.apache.org/confluence/display/KAFKA/Compression">here</a>.
<h3><a id="theproducer" href="#theproducer">4.4 The Producer</a></h3>
<h4><a id="design_loadbalancing" href="#design_loadbalancing">Load balancing</a></h4>
<p>
The producer sends data directly to the broker that is the leader for the partition without any intervening routing tier. To help the producer do this all Kafka nodes can answer a request for metadata about which
servers are alive and where the leaders for the partitions of a topic are at any given time to allow the producer to appropriately direct its requests.
<p>
The client controls which partition it publishes messages to. This can be done at random, implementing a kind of random load balancing, or it can be done by some semantic partitioning function. We expose the interface
for semantic partitioning by allowing the user to specify a key to partition by and using this to hash to a partition (there is also an option to override the partition function if need be). For example if the key
chosen was a user id then all data for a given user would be sent to the same partition. This in turn will allow consumers to make locality assumptions about their consumption. This style of partitioning is explicitly
designed to allow locality-sensitive processing in consumers.
<h4><a id="design_asyncsend" href="#design_asyncsend">Asynchronous send</a></h4>
<p>
Batching is one of the big drivers of efficiency, and to enable batching the Kafka producer will attempt to accumulate data in memory and to send out larger batches in a single request. The batching can be configured
to accumulate no more than a fixed number of messages and to wait no longer than some fixed latency bound (say 64k or 10 ms). This allows the accumulation of more bytes to send, and few larger I/O operations on the
servers. This buffering is configurable and gives a mechanism to trade off a small amount of additional latency for better throughput.
<p>
Details on <a href="#producerconfigs">configuration</a> and the <a href="http://kafka.apache.org/082/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html">api</a> for the producer can be found
elsewhere in the documentation.
<h3><a id="theconsumer" href="#theconsumer">4.5 The Consumer</a></h3>
The Kafka consumer works by issuing "fetch" requests to the brokers leading the partitions it wants to consume. The consumer specifies its offset in the log with each request and receives back a chunk of log
beginning from that position. The consumer thus has significant control over this position and can rewind it to re-consume data if need be.
<h4><a id="design_pull" href="#design_pull">Push vs. pull</a></h4>
<p>
An initial question we considered is whether consumers should pull data from brokers or brokers should push data to the consumer. In this respect Kafka follows a more traditional design, shared by most messaging
systems, where data is pushed to the broker from the producer and pulled from the broker by the consumer. Some logging-centric systems, such as <a href="http://github.com/facebook/scribe">Scribe</a> and
<a href="http://flume.apache.org/">Apache Flume</a>, follow a very different push-based path where data is pushed downstream. There are pros and cons to both approaches. However, a push-based system has difficulty
dealing with diverse consumers as the broker controls the rate at which data is transferred. The goal is generally for the consumer to be able to consume at the maximum possible rate; unfortunately, in a push
system this means the consumer tends to be overwhelmed when its rate of consumption falls below the rate of production (a denial of service attack, in essence). A pull-based system has the nicer property that
the consumer simply falls behind and catches up when it can. This can be mitigated with some kind of backoff protocol by which the consumer can indicate it is overwhelmed, but getting the rate of transfer to
fully utilize (but never over-utilize) the consumer is trickier than it seems. Previous attempts at building systems in this fashion led us to go with a more traditional pull model.
<p>
Another advantage of a pull-based system is that it lends itself to aggressive batching of data sent to the consumer. A push-based system must choose to either send a request immediately or accumulate more data
and then send it later without knowledge of whether the downstream consumer will be able to immediately process it. If tuned for low latency, this will result in sending a single message at a time only for the
transfer to end up being buffered anyway, which is wasteful. A pull-based design fixes this as the consumer always pulls all available messages after its current position in the log (or up to some configurable max
size). So one gets optimal batching without introducing unnecessary latency.
<p>
The deficiency of a naive pull-based system is that if the broker has no data the consumer may end up polling in a tight loop, effectively busy-waiting for data to arrive. To avoid this we have parameters in our
pull request that allow the consumer request to block in a "long poll" waiting until data arrives (and optionally waiting until a given number of bytes is available to ensure large transfer sizes).
<p>
You could imagine other possible designs which would be only pull, end-to-end. The producer would locally write to a local log, and brokers would pull from that with consumers pulling from them. A similar type of
"store-and-forward" producer is often proposed. This is intriguing but we felt not very suitable for our target use cases which have thousands of producers. Our experience running persistent data systems at
scale led us to feel that involving thousands of disks in the system across many applications would not actually make things more reliable and would be a nightmare to operate. And in practice we have found that we
can run a pipeline with strong SLAs at large scale without a need for producer persistence.
<h4><a id="design_consumerposition" href="#design_consumerposition">Consumer Position</a></h4>
Keeping track of <i>what</i> has been consumed is, surprisingly, one of the key performance points of a messaging system.
<p>
Most messaging systems keep metadata about what messages have been consumed on the broker. That is, as a message is handed out to a consumer, the broker either records that fact locally immediately or it may wait
for acknowledgement from the consumer. This is a fairly intuitive choice, and indeed for a single machine server it is not clear where else this state could go. Since the data structures used for storage in many
messaging systems scale poorly, this is also a pragmatic choice--since the broker knows what is consumed it can immediately delete it, keeping the data size small.
<p>
What is perhaps not obvious is that getting the broker and consumer to come into agreement about what has been consumed is not a trivial problem. If the broker records a message as <b>consumed</b> immediately every
time it is handed out over the network, then if the consumer fails to process the message (say because it crashes or the request times out or whatever) that message will be lost. To solve this problem, many messaging
systems add an acknowledgement feature which means that messages are only marked as <b>sent</b> not <b>consumed</b> when they are sent; the broker waits for a specific acknowledgement from the consumer to record the
message as <b>consumed</b>. This strategy fixes the problem of losing messages, but creates new problems. First of all, if the consumer processes the message but fails before it can send an acknowledgement then the
message will be consumed twice. The second problem is around performance, now the broker must keep multiple states about every single message (first to lock it so it is not given out a second time, and then to mark
it as permanently consumed so that it can be removed). Tricky problems must be dealt with, like what to do with messages that are sent but never acknowledged.
<p>
Kafka handles this differently. Our topic is divided into a set of totally ordered partitions, each of which is consumed by exactly one consumer within each subscribing consumer group at any given time. This means
that the position of a consumer in each partition is just a single integer, the offset of the next message to consume. This makes the state about what has been consumed very small, just one number for each partition.
This state can be periodically checkpointed. This makes the equivalent of message acknowledgements very cheap.
<p>
There is a side benefit of this decision. A consumer can deliberately <i>rewind</i> back to an old offset and re-consume data. This violates the common contract of a queue, but turns out to be an essential feature
for many consumers. For example, if the consumer code has a bug and is discovered after some messages are consumed, the consumer can re-consume those messages once the bug is fixed.
<h4><a id="design_offlineload" href="#design_offlineload">Offline Data Load</a></h4>
Scalable persistence allows for the possibility of consumers that only periodically consume such as batch data loads that periodically bulk-load data into an offline system such as Hadoop or a relational data
warehouse.
<p>
In the case of Hadoop we parallelize the data load by splitting the load over individual map tasks, one for each node/topic/partition combination, allowing full parallelism in the loading. Hadoop provides the task
management, and tasks which fail can restart without danger of duplicate data&mdash;they simply restart from their original position.
<h4><a id="static_membership" href="#static_membership">Static Membership</a></h4>
Static membership aims to improve the availability of stream applications, consumer groups and other applications built on top of the group rebalance protocol.
The rebalance protocol relies on the group coordinator to allocate entity ids to group members. These generated ids are ephemeral and will change when members restart and rejoin.
For consumer based apps, this "dynamic membership" can cause a large percentage of tasks re-assigned to different instances during administrative operations
such as code deploys, configuration updates and periodic restarts. For large state applications, shuffled tasks need a long time to recover their local states before processing
and cause applications to be partially or entirely unavailable. Motivated by this observation, Kafkas group management protocol allows group members to provide persistent entity ids.
Group membership remains unchanged based on those ids, thus no rebalance will be triggered.
<p>
If you want to use static membership,
<ul>
<li>Upgrade both broker cluster and client apps to 2.3 or beyond, and also make sure the upgraded brokers are using <code>inter.broker.protocol.version</code>
of 2.3 or beyond as well.</li>
<li>Set the config <code>ConsumerConfig#GROUP_INSTANCE_ID_CONFIG</code> to a unique value for each consumer instance under one group.</li>
<li>For Kafka Streams applications, it is sufficient to set a unique <code>ConsumerConfig#GROUP_INSTANCE_ID_CONFIG</code> per KafkaStreams instance,
independent of the number of used threads for an instance.</li>
</ul>
If your broker is on an older version than 2.3, but you choose to set <code>ConsumerConfig#GROUP_INSTANCE_ID_CONFIG</code> on the client side, the application will detect
the broker version and then throws an UnsupportedException. If you accidentally configure duplicate ids for different instances,
a fencing mechanism on broker side will inform your duplicate client to shutdown immediately by triggering a <code>org.apache.kafka.common.errors.FencedInstanceIdException</code>.
For more details, see
<a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-345%3A+Introduce+static+membership+protocol+to+reduce+consumer+rebalances">KIP-345</a>
<h3><a id="semantics" href="#semantics">4.6 Message Delivery Semantics</a></h3>
<p>
Now that we understand a little about how producers and consumers work, let's discuss the semantic guarantees Kafka provides between producer and consumer. Clearly there are multiple possible message delivery
guarantees that could be provided:
<ul>
<li>
<i>At most once</i>&mdash;Messages may be lost but are never redelivered.
</li>
<li>
<i>At least once</i>&mdash;Messages are never lost but may be redelivered.
</li>
<li>
<i>Exactly once</i>&mdash;this is what people actually want, each message is delivered once and only once.
</li>
</ul>
It's worth noting that this breaks down into two problems: the durability guarantees for publishing a message and the guarantees when consuming a message.
<p>
Many systems claim to provide "exactly once" delivery semantics, but it is important to read the fine print, most of these claims are misleading (i.e. they don't translate to the case where consumers or producers
can fail, cases where there are multiple consumer processes, or cases where data written to disk can be lost).
<p>
Kafka's semantics are straight-forward. When publishing a message we have a notion of the message being "committed" to the log. Once a published message is committed it will not be lost as long as one broker that
replicates the partition to which this message was written remains "alive". The definition of committed message, alive partition as well as a description of which types of failures we attempt to handle will be
described in more detail in the next section. For now let's assume a perfect, lossless broker and try to understand the guarantees to the producer and consumer. If a producer attempts to publish a message and
experiences a network error it cannot be sure if this error happened before or after the message was committed. This is similar to the semantics of inserting into a database table with an autogenerated key.
<p>
Prior to 0.11.0.0, if a producer failed to receive a response indicating that a message was committed, it had little choice but to resend the message. This provides at-least-once delivery semantics since the
message may be written to the log again during resending if the original request had in fact succeeded. Since 0.11.0.0, the Kafka producer also supports an idempotent delivery option which guarantees that resending
will not result in duplicate entries in the log. To achieve this, the broker assigns each producer an ID and deduplicates messages using a sequence number that is sent by the producer along with every message.
Also beginning with 0.11.0.0, the producer supports the ability to send messages to multiple topic partitions using transaction-like semantics: i.e. either all messages are successfully written or none of them are.
The main use case for this is exactly-once processing between Kafka topics (described below).
<p>
Not all use cases require such strong guarantees. For uses which are latency sensitive we allow the producer to specify the durability level it desires. If the producer specifies that it wants to wait on the message
being committed this can take on the order of 10 ms. However the producer can also specify that it wants to perform the send completely asynchronously or that it wants to wait only until the leader (but not
necessarily the followers) have the message.
<p>
Now let's describe the semantics from the point-of-view of the consumer. All replicas have the exact same log with the same offsets. The consumer controls its position in this log. If the consumer never crashed it
could just store this position in memory, but if the consumer fails and we want this topic partition to be taken over by another process the new process will need to choose an appropriate position from which to start
processing. Let's say the consumer reads some messages -- it has several options for processing the messages and updating its position.
<ol>
<li>It can read the messages, then save its position in the log, and finally process the messages. In this case there is a possibility that the consumer process crashes after saving its position but before saving
the output of its message processing. In this case the process that took over processing would start at the saved position even though a few messages prior to that position had not been processed. This corresponds
to "at-most-once" semantics as in the case of a consumer failure messages may not be processed.
<li>It can read the messages, process the messages, and finally save its position. In this case there is a possibility that the consumer process crashes after processing messages but before saving its position.
In this case when the new process takes over the first few messages it receives will already have been processed. This corresponds to the "at-least-once" semantics in the case of consumer failure. In many cases
messages have a primary key and so the updates are idempotent (receiving the same message twice just overwrites a record with another copy of itself).
</ol>
<p>
So what about exactly once semantics (i.e. the thing you actually want)? When consuming from a Kafka topic and producing to another topic (as in a <a href="https://kafka.apache.org/documentation/streams">Kafka Streams</a>
application), we can leverage the new transactional producer capabilities in 0.11.0.0 that were mentioned above. The consumer's position is stored as a message in a topic, so we can write the offset to Kafka in the
same transaction as the output topics receiving the processed data. If the transaction is aborted, the consumer's position will revert to its old value and the produced data on the output topics will not be visible
to other consumers, depending on their "isolation level." In the default "read_uncommitted" isolation level, all messages are visible to consumers even if they were part of an aborted transaction,
but in "read_committed," the consumer will only return messages from transactions which were committed (and any messages which were not part of a transaction).
<p>
When writing to an external system, the limitation is in the need to coordinate the consumer's position with what is actually stored as output. The classic way of achieving this would be to introduce a two-phase
commit between the storage of the consumer position and the storage of the consumers output. But this can be handled more simply and generally by letting the consumer store its offset in the same place as
its output. This is better because many of the output systems a consumer might want to write to will not support a two-phase commit. As an example of this, consider a
<a href="https://kafka.apache.org/documentation/#connect">Kafka Connect</a> connector which populates data in HDFS along with the offsets of the data it reads so that it is guaranteed that either data and
offsets are both updated or neither is. We follow similar patterns for many other data systems which require these stronger semantics and for which the messages do not have a primary key to allow for deduplication.
<p>
So effectively Kafka supports exactly-once delivery in <a href="https://kafka.apache.org/documentation/streams">Kafka Streams</a>, and the transactional producer/consumer can be used generally to provide
exactly-once delivery when transferring and processing data between Kafka topics. Exactly-once delivery for other destination systems generally requires cooperation with such systems, but Kafka provides the
offset which makes implementing this feasible (see also <a href="https://kafka.apache.org/documentation/#connect">Kafka Connect</a>). Otherwise, Kafka guarantees at-least-once delivery by default, and allows
the user to implement at-most-once delivery by disabling retries on the producer and committing offsets in the consumer prior to processing a batch of messages.
<h3><a id="replication" href="#replication">4.7 Replication</a></h3>
<p>
Kafka replicates the log for each topic's partitions across a configurable number of servers (you can set this replication factor on a topic-by-topic basis). This allows automatic failover to these replicas when a
server in the cluster fails so messages remain available in the presence of failures.
<p>
Other messaging systems provide some replication-related features, but, in our (totally biased) opinion, this appears to be a tacked-on thing, not heavily used, and with large downsides: replicas are inactive,
throughput is heavily impacted, it requires fiddly manual configuration, etc. Kafka is meant to be used with replication by default&mdash;in fact we implement un-replicated topics as replicated topics where the
replication factor is one.
<p>
The unit of replication is the topic partition. Under non-failure conditions, each partition in Kafka has a single leader and zero or more followers. The total number of replicas including the leader constitute the
replication factor. All reads and writes go to the leader of the partition. Typically, there are many more partitions than brokers and the leaders are evenly distributed among brokers. The logs on the followers are
identical to the leader's log&mdash;all have the same offsets and messages in the same order (though, of course, at any given time the leader may have a few as-yet unreplicated messages at the end of its log).
<p>
Followers consume messages from the leader just as a normal Kafka consumer would and apply them to their own log. Having the followers pull from the leader has the nice property of allowing the follower to naturally
batch together log entries they are applying to their log.
<p>
As with most distributed systems automatically handling failures requires having a precise definition of what it means for a node to be "alive". For Kafka node liveness has two conditions
<ol>
<li>A node must be able to maintain its session with ZooKeeper (via ZooKeeper's heartbeat mechanism)
<li>If it is a follower it must replicate the writes happening on the leader and not fall "too far" behind
</ol>
We refer to nodes satisfying these two conditions as being "in sync" to avoid the vagueness of "alive" or "failed". The leader keeps track of the set of "in sync" nodes. If a follower dies, gets stuck, or falls
behind, the leader will remove it from the list of in sync replicas. The determination of stuck and lagging replicas is controlled by the replica.lag.time.max.ms configuration.
<p>
In distributed systems terminology we only attempt to handle a "fail/recover" model of failures where nodes suddenly cease working and then later recover (perhaps without knowing that they have died). Kafka does not
handle so-called "Byzantine" failures in which nodes produce arbitrary or malicious responses (perhaps due to bugs or foul play).
<p>
We can now more precisely define that a message is considered committed when all in sync replicas for that partition have applied it to their log.
Only committed messages are ever given out to the consumer. This means that the consumer need not worry about potentially seeing a message that could be lost if the leader fails. Producers, on the other hand,
have the option of either waiting for the message to be committed or not, depending on their preference for tradeoff between latency and durability. This preference is controlled by the acks setting that the
producer uses.
Note that topics have a setting for the "minimum number" of in-sync replicas that is checked when the producer requests acknowledgment that a message
has been written to the full set of in-sync replicas. If a less stringent acknowledgement is requested by the producer, then the message can be committed, and consumed,
even if the number of in-sync replicas is lower than the minimum (e.g. it can be as low as just the leader).
<p>
The guarantee that Kafka offers is that a committed message will not be lost, as long as there is at least one in sync replica alive, at all times.
<p>
Kafka will remain available in the presence of node failures after a short fail-over period, but may not remain available in the presence of network partitions.
<h4><a id="design_replicatedlog" href="#design_replicatedlog">Replicated Logs: Quorums, ISRs, and State Machines (Oh my!)</a></h4>
At its heart a Kafka partition is a replicated log. The replicated log is one of the most basic primitives in distributed data systems, and there are many approaches for implementing one. A replicated log can be
used by other systems as a primitive for implementing other distributed systems in the <a href="http://en.wikipedia.org/wiki/State_machine_replication">state-machine style</a>.
<p>
A replicated log models the process of coming into consensus on the order of a series of values (generally numbering the log entries 0, 1, 2, ...). There are many ways to implement this, but the simplest and fastest
is with a leader who chooses the ordering of values provided to it. As long as the leader remains alive, all followers need to only copy the values and ordering the leader chooses.
<p>
Of course if leaders didn't fail we wouldn't need followers! When the leader does die we need to choose a new leader from among the followers. But followers themselves may fall behind or crash so we must ensure we
choose an up-to-date follower. The fundamental guarantee a log replication algorithm must provide is that if we tell the client a message is committed, and the leader fails, the new leader we elect must also have
that message. This yields a tradeoff: if the leader waits for more followers to acknowledge a message before declaring it committed then there will be more potentially electable leaders.
<p>
If you choose the number of acknowledgements required and the number of logs that must be compared to elect a leader such that there is guaranteed to be an overlap, then this is called a Quorum.
<p>
A common approach to this tradeoff is to use a majority vote for both the commit decision and the leader election. This is not what Kafka does, but let's explore it anyway to understand the tradeoffs. Let's say we
have 2<i>f</i>+1 replicas. If <i>f</i>+1 replicas must receive a message prior to a commit being declared by the leader, and if we elect a new leader by electing the follower with the most complete log from at least
<i>f</i>+1 replicas, then, with no more than <i>f</i> failures, the leader is guaranteed to have all committed messages. This is because among any <i>f</i>+1 replicas, there must be at least one replica that contains
all committed messages. That replica's log will be the most complete and therefore will be selected as the new leader. There are many remaining details that each algorithm must handle (such as precisely defined what
makes a log more complete, ensuring log consistency during leader failure or changing the set of servers in the replica set) but we will ignore these for now.
<p>
This majority vote approach has a very nice property: the latency is dependent on only the fastest servers. That is, if the replication factor is three, the latency is determined by the faster follower not the slower one.
<p>
There are a rich variety of algorithms in this family including ZooKeeper's
<a href="http://web.archive.org/web/20140602093727/http://www.stanford.edu/class/cs347/reading/zab.pdf">Zab</a>,
<a href="https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf">Raft</a>,
and <a href="http://pmg.csail.mit.edu/papers/vr-revisited.pdf">Viewstamped Replication</a>.
The most similar academic publication we are aware of to Kafka's actual implementation is
<a href="http://research.microsoft.com/apps/pubs/default.aspx?id=66814">PacificA</a> from Microsoft.
<p>
The downside of majority vote is that it doesn't take many failures to leave you with no electable leaders. To tolerate one failure requires three copies of the data, and to tolerate two failures requires five copies
of the data. In our experience having only enough redundancy to tolerate a single failure is not enough for a practical system, but doing every write five times, with 5x the disk space requirements and 1/5th the
throughput, is not very practical for large volume data problems. This is likely why quorum algorithms more commonly appear for shared cluster configuration such as ZooKeeper but are less common for primary data
storage. For example in HDFS the namenode's high-availability feature is built on a <a href="http://blog.cloudera.com/blog/2012/10/quorum-based-journaling-in-cdh4-1">majority-vote-based journal</a>, but this more
expensive approach is not used for the data itself.
<p>
Kafka takes a slightly different approach to choosing its quorum set. Instead of majority vote, Kafka dynamically maintains a set of in-sync replicas (ISR) that are caught-up to the leader. Only members of this set
are eligible for election as leader. A write to a Kafka partition is not considered committed until <i>all</i> in-sync replicas have received the write. This ISR set is persisted to ZooKeeper whenever it changes.
Because of this, any replica in the ISR is eligible to be elected leader. This is an important factor for Kafka's usage model where there are many partitions and ensuring leadership balance is important.
With this ISR model and <i>f+1</i> replicas, a Kafka topic can tolerate <i>f</i> failures without losing committed messages.
<p>
For most use cases we hope to handle, we think this tradeoff is a reasonable one. In practice, to tolerate <i>f</i> failures, both the majority vote and the ISR approach will wait for the same number of replicas to
acknowledge before committing a message (e.g. to survive one failure a majority quorum needs three replicas and one acknowledgement and the ISR approach requires two replicas and one acknowledgement).
The ability to commit without the slowest servers is an advantage of the majority vote approach. However, we think it is ameliorated by allowing the client to choose whether they block on the message commit or not,
and the additional throughput and disk space due to the lower required replication factor is worth it.
<p>
Another important design distinction is that Kafka does not require that crashed nodes recover with all their data intact. It is not uncommon for replication algorithms in this space to depend on the existence of
"stable storage" that cannot be lost in any failure-recovery scenario without potential consistency violations. There are two primary problems with this assumption. First, disk errors are the most common problem we
observe in real operation of persistent data systems and they often do not leave data intact. Secondly, even if this were not a problem, we do not want to require the use of fsync on every write for our consistency
guarantees as this can reduce performance by two to three orders of magnitude. Our protocol for allowing a replica to rejoin the ISR ensures that before rejoining, it must fully re-sync again even if it lost unflushed
data in its crash.
<h4><a id="design_uncleanleader" href="#design_uncleanleader">Unclean leader election: What if they all die?</a></h4>
Note that Kafka's guarantee with respect to data loss is predicated on at least one replica remaining in sync. If all the nodes replicating a partition die, this guarantee no longer holds.
<p>
However a practical system needs to do something reasonable when all the replicas die. If you are unlucky enough to have this occur, it is important to consider what will happen. There are two behaviors that could be
implemented:
<ol>
<li>Wait for a replica in the ISR to come back to life and choose this replica as the leader (hopefully it still has all its data).
<li>Choose the first replica (not necessarily in the ISR) that comes back to life as the leader.
</ol>
<p>
This is a simple tradeoff between availability and consistency. If we wait for replicas in the ISR, then we will remain unavailable as long as those replicas are down. If such replicas were destroyed or their data
was lost, then we are permanently down. If, on the other hand, a non-in-sync replica comes back to life and we allow it to become leader, then its log becomes the source of truth even though it is not guaranteed to
have every committed message. By default from version 0.11.0.0, Kafka chooses the first strategy and favor waiting for a consistent replica. This behavior can be changed using
configuration property unclean.leader.election.enable, to support use cases where uptime is preferable to consistency.
<p>
This dilemma is not specific to Kafka. It exists in any quorum-based scheme. For example in a majority voting scheme, if a majority of servers suffer a permanent failure, then you must either choose to lose 100% of
your data or violate consistency by taking what remains on an existing server as your new source of truth.
<h4><a id="design_ha" href="#design_ha">Availability and Durability Guarantees</a></h4>
When writing to Kafka, producers can choose whether they wait for the message to be acknowledged by 0,1 or all (-1) replicas.
Note that "acknowledgement by all replicas" does not guarantee that the full set of assigned replicas have received the message. By default, when acks=all, acknowledgement happens as soon as all the current in-sync
replicas have received the message. For example, if a topic is configured with only two replicas and one fails (i.e., only one in sync replica remains), then writes that specify acks=all will succeed. However, these
writes could be lost if the remaining replica also fails.
Although this ensures maximum availability of the partition, this behavior may be undesirable to some users who prefer durability over availability. Therefore, we provide two topic-level configurations that can be
used to prefer message durability over availability:
<ol>
<li> Disable unclean leader election - if all replicas become unavailable, then the partition will remain unavailable until the most recent leader becomes available again. This effectively prefers unavailability
over the risk of message loss. See the previous section on Unclean Leader Election for clarification. </li>
<li> Specify a minimum ISR size - the partition will only accept writes if the size of the ISR is above a certain minimum, in order to prevent the loss of messages that were written to just a single replica,
which subsequently becomes unavailable. This setting only takes effect if the producer uses acks=all and guarantees that the message will be acknowledged by at least this many in-sync replicas.
This setting offers a trade-off between consistency and availability. A higher setting for minimum ISR size guarantees better consistency since the message is guaranteed to be written to more replicas which reduces
the probability that it will be lost. However, it reduces availability since the partition will be unavailable for writes if the number of in-sync replicas drops below the minimum threshold. </li>
</ol>
<h4><a id="design_replicamanagment" href="#design_replicamanagment">Replica Management</a></h4>
The above discussion on replicated logs really covers only a single log, i.e. one topic partition. However a Kafka cluster will manage hundreds or thousands of these partitions. We attempt to balance partitions
within a cluster in a round-robin fashion to avoid clustering all partitions for high-volume topics on a small number of nodes. Likewise we try to balance leadership so that each node is the leader for a proportional
share of its partitions.
<p>
It is also important to optimize the leadership election process as that is the critical window of unavailability. A naive implementation of leader election would end up running an election per partition for all
partitions a node hosted when that node failed. Instead, we elect one of the brokers as the "controller". This controller detects failures at the broker level and is responsible for changing the leader of all
affected partitions in a failed broker. The result is that we are able to batch together many of the required leadership change notifications which makes the election process far cheaper and faster for a large number
of partitions. If the controller fails, one of the surviving brokers will become the new controller.
<h3><a id="compaction" href="#compaction">4.8 Log Compaction</a></h3>
Log compaction ensures that Kafka will always retain at least the last known value for each message key within the log of data for a single topic partition. It addresses use cases and scenarios such as restoring
state after application crashes or system failure, or reloading caches after application restarts during operational maintenance. Let's dive into these use cases in more detail and then describe how compaction works.
<p>
So far we have described only the simpler approach to data retention where old log data is discarded after a fixed period of time or when the log reaches some predetermined size. This works well for temporal event
data such as logging where each record stands alone. However an important class of data streams are the log of changes to keyed, mutable data (for example, the changes to a database table).
<p>
Let's discuss a concrete example of such a stream. Say we have a topic containing user email addresses; every time a user updates their email address we send a message to this topic using their user id as the
primary key. Now say we send the following messages over some time period for a user with id 123, each message corresponding to a change in email address (messages for other ids are omitted):
<pre class="brush: text;">
123 => bill@microsoft.com
.
.
.
123 => bill@gatesfoundation.org
.
.
.
123 => bill@gmail.com
</pre>
Log compaction gives us a more granular retention mechanism so that we are guaranteed to retain at least the last update for each primary key (e.g. <code>bill@gmail.com</code>). By doing this we guarantee that the
log contains a full snapshot of the final value for every key not just keys that changed recently. This means downstream consumers can restore their own state off this topic without us having to retain a complete
log of all changes.
<p>
Let's start by looking at a few use cases where this is useful, then we'll see how it can be used.
<ol>
<li><i>Database change subscription</i>. It is often necessary to have a data set in multiple data systems, and often one of these systems is a database of some kind (either a RDBMS or perhaps a new-fangled key-value
store). For example you might have a database, a cache, a search cluster, and a Hadoop cluster. Each change to the database will need to be reflected in the cache, the search cluster, and eventually in Hadoop.
In the case that one is only handling the real-time updates you only need recent log. But if you want to be able to reload the cache or restore a failed search node you may need a complete data set.
<li><i>Event sourcing</i>. This is a style of application design which co-locates query processing with application design and uses a log of changes as the primary store for the application.
<li><i>Journaling for high-availability</i>. A process that does local computation can be made fault-tolerant by logging out changes that it makes to its local state so another process can reload these changes and
carry on if it should fail. A concrete example of this is handling counts, aggregations, and other "group by"-like processing in a stream query system. Samza, a real-time stream-processing framework,
<a href="http://samza.apache.org/learn/documentation/0.7.0/container/state-management.html">uses this feature</a> for exactly this purpose.
</ol>
In each of these cases one needs primarily to handle the real-time feed of changes, but occasionally, when a machine crashes or data needs to be re-loaded or re-processed, one needs to do a full load.
Log compaction allows feeding both of these use cases off the same backing topic.
This style of usage of a log is described in more detail in <a href="http://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying">this blog post</a>.
<p>
The general idea is quite simple. If we had infinite log retention, and we logged each change in the above cases, then we would have captured the state of the system at each time from when it first began.
Using this complete log, we could restore to any point in time by replaying the first N records in the log. This hypothetical complete log is not very practical for systems that update a single record many times
as the log will grow without bound even for a stable dataset. The simple log retention mechanism which throws away old updates will bound space but the log is no longer a way to restore the current state&mdash;now
restoring from the beginning of the log no longer recreates the current state as old updates may not be captured at all.
<p>
Log compaction is a mechanism to give finer-grained per-record retention, rather than the coarser-grained time-based retention. The idea is to selectively remove records where we have a more recent update with the
same primary key. This way the log is guaranteed to have at least the last state for each key.
<p>
This retention policy can be set per-topic, so a single cluster can have some topics where retention is enforced by size or time and other topics where retention is enforced by compaction.
<p>
This functionality is inspired by one of LinkedIn's oldest and most successful pieces of infrastructure&mdash;a database changelog caching service called <a href="https://github.com/linkedin/databus">Databus</a>.
Unlike most log-structured storage systems Kafka is built for subscription and organizes data for fast linear reads and writes. Unlike Databus, Kafka acts as a source-of-truth store so it is useful even in
situations where the upstream data source would not otherwise be replayable.
<h4><a id="design_compactionbasics" href="#design_compactionbasics">Log Compaction Basics</a></h4>
Here is a high-level picture that shows the logical structure of a Kafka log with the offset for each message.
<p>
<img class="centered" src="/{{version}}/images/log_cleaner_anatomy.png">
<p>
The head of the log is identical to a traditional Kafka log. It has dense, sequential offsets and retains all messages. Log compaction adds an option for handling the tail of the log. The picture above shows a log
with a compacted tail. Note that the messages in the tail of the log retain the original offset assigned when they were first written&mdash;that never changes. Note also that all offsets remain valid positions in
the log, even if the message with that offset has been compacted away; in this case this position is indistinguishable from the next highest offset that does appear in the log. For example, in the picture above the
offsets 36, 37, and 38 are all equivalent positions and a read beginning at any of these offsets would return a message set beginning with 38.
<p>
Compaction also allows for deletes. A message with a key and a null payload will be treated as a delete from the log. This delete marker will cause any prior message with that key to be removed (as would any new
message with that key), but delete markers are special in that they will themselves be cleaned out of the log after a period of time to free up space. The point in time at which deletes are no longer retained is
marked as the "delete retention point" in the above diagram.
<p>
The compaction is done in the background by periodically recopying log segments. Cleaning does not block reads and can be throttled to use no more than a configurable amount of I/O throughput to avoid impacting
producers and consumers. The actual process of compacting a log segment looks something like this:
<p>
<img class="centered" src="/{{version}}/images/log_compaction.png">
<p>
<h4><a id="design_compactionguarantees" href="#design_compactionguarantees">What guarantees does log compaction provide?</a></h4>
Log compaction guarantees the following:
<ol>
<li>Any consumer that stays caught-up to within the head of the log will see every message that is written; these messages will have sequential offsets. The topic's <code>min.compaction.lag.ms</code> can be used to
guarantee the minimum length of time must pass after a message is written before it could be compacted. I.e. it provides a lower bound on how long each message will remain in the (uncompacted) head.
The topic's <code>max.compaction.lag.ms</code> can be used to guarantee the maximum delay between the time a message is written and the time the message becomes eligible for compaction.
<li>Ordering of messages is always maintained. Compaction will never re-order messages, just remove some.
<li>The offset for a message never changes. It is the permanent identifier for a position in the log.
<li>Any consumer progressing from the start of the log will see at least the final state of all records in the order they were written. Additionally, all delete markers for deleted records will be seen, provided
the consumer reaches the head of the log in a time period less than the topic's <code>delete.retention.ms</code> setting (the default is 24 hours). In other words: since the removal of delete markers happens
concurrently with reads, it is possible for a consumer to miss delete markers if it lags by more than <code>delete.retention.ms</code>.
</ol>
<h4><a id="design_compactiondetails" href="#design_compactiondetails">Log Compaction Details</a></h4>
Log compaction is handled by the log cleaner, a pool of background threads that recopy log segment files, removing records whose key appears in the head of the log. Each compactor thread works as follows:
<ol>
<li>It chooses the log that has the highest ratio of log head to log tail
<li>It creates a succinct summary of the last offset for each key in the head of the log
<li>It recopies the log from beginning to end removing keys which have a later occurrence in the log. New, clean segments are swapped into the log immediately so the additional disk space required is just one
additional log segment (not a fully copy of the log).
<li>The summary of the log head is essentially just a space-compact hash table. It uses exactly 24 bytes per entry. As a result with 8GB of cleaner buffer one cleaner iteration can clean around 366GB of log head
(assuming 1k messages).
</ol>
<p>
<h4><a id="design_compactionconfig" href="#design_compactionconfig">Configuring The Log Cleaner</a></h4>
The log cleaner is enabled by default. This will start the pool of cleaner threads.
To enable log cleaning on a particular topic, add the log-specific property
<pre class="brush: text;"> log.cleanup.policy=compact</pre>
The <code>log.cleanup.policy</code> property is a broker configuration setting defined
in the broker's <code>server.properties</code> file; it affects all of the topics
in the cluster that do not have a configuration override in place as documented
<a href="/documentation.html#brokerconfigs">here</a>.
The log cleaner can be configured to retain a minimum amount of the uncompacted "head" of the log. This is enabled by setting the compaction time lag.
<pre class="brush: text;"> log.cleaner.min.compaction.lag.ms</pre>
This can be used to prevent messages newer than a minimum message age from being subject to compaction. If not set, all log segments are eligible for compaction except for the last segment, i.e. the one currently
being written to. The active segment will not be compacted even if all of its messages are older than the minimum compaction time lag.
The log cleaner can be configured to ensure a maximum delay after which the uncompacted "head" of the log becomes eligible for log compaction.
<pre class="brush: text;"> log.cleaner.max.compaction.lag.ms</pre>
This can be used to prevent log with low produce rate from remaining ineligible for compaction for an unbounded duration. If not set, logs that do not exceed min.cleanable.dirty.ratio are not compacted.
Note that this compaction deadline is not a hard guarantee since it is still subjected to the availability of log cleaner threads and the actual compaction time.
You will want to monitor the uncleanable-partitions-count, max-clean-time-secs and max-compaction-delay-secs metrics.
<p>
Further cleaner configurations are described <a href="/documentation.html#brokerconfigs">here</a>.
<h3><a id="design_quotas" href="#design_quotas">4.9 Quotas</a></h3>
<p>
Kafka cluster has the ability to enforce quotas on requests to control the broker resources used by clients. Two types
of client quotas can be enforced by Kafka brokers for each group of clients sharing a quota:
<ol>
<li>Network bandwidth quotas define byte-rate thresholds (since 0.9)</li>
<li>Request rate quotas define CPU utilization thresholds as a percentage of network and I/O threads (since 0.11)</li>
</ol>
</p>
<h4><a id="design_quotasnecessary" href="#design_quotasnecessary">Why are quotas necessary?</a></h4>
<p>
It is possible for producers and consumers to produce/consume very high volumes of data or generate requests at a very high
rate and thus monopolize broker resources, cause network saturation and generally DOS other clients and the brokers themselves.
Having quotas protects against these issues and is all the more important in large multi-tenant clusters where a small set of badly behaved clients can degrade user experience for the well behaved ones.
In fact, when running Kafka as a service this even makes it possible to enforce API limits according to an agreed upon contract.
</p>
<h4><a id="design_quotasgroups" href="#design_quotasgroups">Client groups</a></h4>
The identity of Kafka clients is the user principal which represents an authenticated user in a secure cluster. In a cluster that supports unauthenticated clients, user principal is a grouping of unauthenticated
users
chosen by the broker using a configurable <code>PrincipalBuilder</code>. Client-id is a logical grouping of clients with a meaningful name chosen by the client application. The tuple (user, client-id) defines
a secure logical group of clients that share both user principal and client-id.
<p>
Quotas can be applied to (user, client-id), user or client-id groups. For a given connection, the most specific quota matching the connection is applied. All connections of a quota group share the quota configured for the group.
For example, if (user="test-user", client-id="test-client") has a produce quota of 10MB/sec, this is shared across all producer instances of user "test-user" with the client-id "test-client".
</p>
<h4><a id="design_quotasconfig" href="#design_quotasconfig">Quota Configuration</a></h4>
<p>
Quota configuration may be defined for (user, client-id), user and client-id groups. It is possible to override the default quota at any of the quota levels that needs a higher (or even lower) quota.
The mechanism is similar to the per-topic log config overrides.
User and (user, client-id) quota overrides are written to ZooKeeper under <i><b>/config/users</b></i> and client-id quota overrides are written under <i><b>/config/clients</b></i>.
These overrides are read by all brokers and are effective immediately. This lets us change quotas without having to do a rolling restart of the entire cluster. See <a href="#quotas">here</a> for details.
Default quotas for each group may also be updated dynamically using the same mechanism.
</p>
<p>
The order of precedence for quota configuration is:
<ol>
<li>/config/users/&lt;user&gt;/clients/&lt;client-id&gt;</li>
<li>/config/users/&lt;user&gt;/clients/&lt;default&gt;</li>
<li>/config/users/&lt;user&gt;</li>
<li>/config/users/&lt;default&gt;/clients/&lt;client-id&gt;</li>
<li>/config/users/&lt;default&gt;/clients/&lt;default&gt;</li>
<li>/config/users/&lt;default&gt;</li>
<li>/config/clients/&lt;client-id&gt;</li>
<li>/config/clients/&lt;default&gt;</li>
</ol>
Broker properties (quota.producer.default, quota.consumer.default) can also be used to set defaults of network bandwidth quotas for client-id groups. These properties are being deprecated and will be removed in a later release.
Default quotas for client-id can be set in Zookeeper similar to the other quota overrides and defaults.
</p>
<h4><a id="design_quotasbandwidth" href="#design_quotasbandwidth">Network Bandwidth Quotas</a></h4>
<p>
Network bandwidth quotas are defined as the byte rate threshold for each group of clients sharing a quota.
By default, each unique client group receives a fixed quota in bytes/sec as configured by the cluster.
This quota is defined on a per-broker basis. Each group of clients can publish/fetch a maximum of X bytes/sec
per broker before clients are throttled.
</p>
<h4><a id="design_quotascpu" href="#design_quotascpu">Request Rate Quotas</a></h4>
<p>
Request rate quotas are defined as the percentage of time a client can utilize on request handler I/O
threads and network threads of each broker within a quota window. A quota of <tt>n%</tt> represents
<tt>n%</tt> of one thread, so the quota is out of a total capacity of <tt>((num.io.threads + num.network.threads) * 100)%</tt>.
Each group of clients may use a total percentage of upto <tt>n%</tt> across all I/O and network threads in a quota
window before being throttled. Since the number of threads allocated for I/O and network threads are typically based
on the number of cores available on the broker host, request rate quotas represent the total percentage of CPU
that may be used by each group of clients sharing the quota.
</p>
<h4><a id="design_quotasenforcement" href="#design_quotasenforcement">Enforcement</a></h4>
<p>
By default, each unique client group receives a fixed quota as configured by the cluster.
This quota is defined on a per-broker basis. Each client can utilize this quota per broker before it gets throttled. We decided that defining these quotas per broker is much better than
having a fixed cluster wide bandwidth per client because that would require a mechanism to share client quota usage among all the brokers. This can be harder to get right than the quota implementation itself!
</p>
<p>
How does a broker react when it detects a quota violation? In our solution, the broker first computes the amount of delay needed to bring the violating client under its quota
and returns a response with the delay immediately. In case of a fetch request, the response will not contain any data. Then, the broker mutes the channel to the client,
not to process requests from the client anymore, until the delay is over. Upon receiving a response with a non-zero delay duration, the Kafka client will also refrain from
sending further requests to the broker during the delay. Therefore, requests from a throttled client are effectively blocked from both sides.
Even with older client implementations that do not respect the delay response from the broker, the back pressure applied by the broker via muting its socket channel
can still handle the throttling of badly behaving clients. Those clients who sent further requests to the throttled channel will receive responses only after the delay is over.
</p>
<p>
Byte-rate and thread utilization are measured over multiple small windows (e.g. 30 windows of 1 second each) in order to detect and correct quota violations quickly. Typically, having large measurement windows
(for e.g. 10 windows of 30 seconds each) leads to large bursts of traffic followed by long delays which is not great in terms of user experience.
</p>
</script>
<div class="p-design"></div>

83
docs/documentation.html Normal file
View File

@@ -0,0 +1,83 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script><!--#include virtual="js/templateData.js" --></script>
<!--#include virtual="../includes/_header.htm" -->
<!--#include virtual="../includes/_top.htm" -->
<div class="content documentation documentation--current">
<!--#include virtual="../includes/_nav.htm" -->
<div class="right">
<!--#include virtual="../includes/_docs_banner.htm" -->
<h1>Documentation</h1>
<h3>Kafka 2.5 Documentation</h3>
Prior releases: <a href="/07/documentation.html">0.7.x</a>, <a href="/08/documentation.html">0.8.0</a>, <a href="/081/documentation.html">0.8.1.X</a>, <a href="/082/documentation.html">0.8.2.X</a>, <a href="/090/documentation.html">0.9.0.X</a>, <a href="/0100/documentation.html">0.10.0.X</a>, <a href="/0101/documentation.html">0.10.1.X</a>, <a href="/0102/documentation.html">0.10.2.X</a>, <a href="/0110/documentation.html">0.11.0.X</a>, <a href="/10/documentation.html">1.0.X</a>, <a href="/11/documentation.html">1.1.X</a>, <a href="/20/documentation.html">2.0.X</a>, <a href="/21/documentation.html">2.1.X</a>, <a href="/22/documentation.html">2.2.X</a>, <a href="/23/documentation.html">2.3.X</a>, <a href="/24/documentation.html">2.4.X</a>.
<!--#include virtual="toc.html" -->
<h2><a id="gettingStarted" href="#gettingStarted">1. Getting Started</a></h2>
<h3><a id="introduction" href="#introduction">1.1 Introduction</a></h3>
<!--#include virtual="introduction.html" -->
<h3><a id="uses" href="#uses">1.2 Use Cases</a></h3>
<!--#include virtual="uses.html" -->
<h3><a id="quickstart" href="#quickstart">1.3 Quick Start</a></h3>
<!--#include virtual="quickstart.html" -->
<h3><a id="ecosystem" href="#ecosystem">1.4 Ecosystem</a></h3>
<!--#include virtual="ecosystem.html" -->
<h3><a id="upgrade" href="#upgrade">1.5 Upgrading From Previous Versions</a></h3>
<!--#include virtual="upgrade.html" -->
<h2><a id="api" href="#api">2. APIs</a></h2>
<!--#include virtual="api.html" -->
<h2><a id="configuration" href="#configuration">3. Configuration</a></h2>
<!--#include virtual="configuration.html" -->
<h2><a id="design" href="#design">4. Design</a></h2>
<!--#include virtual="design.html" -->
<h2><a id="implementation" href="#implementation">5. Implementation</a></h2>
<!--#include virtual="implementation.html" -->
<h2><a id="operations" href="#operations">6. Operations</a></h2>
<!--#include virtual="ops.html" -->
<h2><a id="security" href="#security">7. Security</a></h2>
<!--#include virtual="security.html" -->
<h2><a id="connect" href="#connect">8. Kafka Connect</a></h2>
<!--#include virtual="connect.html" -->
<h2><a id="streams" href="/documentation/streams">9. Kafka Streams</a></h2>
<p>
Kafka Streams is a client library for processing and analyzing data stored in Kafka. It builds upon important stream processing concepts such as properly distinguishing between event time and processing time, windowing support, exactly-once processing semantics and simple yet efficient management of application state.
</p>
<p>
Kafka Streams has a <b>low barrier to entry</b>: You can quickly write and run a small-scale proof-of-concept on a single machine; and you only need to run additional instances of your application on multiple machines to scale up to high-volume production workloads. Kafka Streams transparently handles the load balancing of multiple instances of the same application by leveraging Kafka's parallelism model.
</p>
<p>Learn More about Kafka Streams read <a href="/documentation/streams">this</a> Section.</p>
<!--#include virtual="../includes/_footer.htm" -->
<!--#include virtual="../includes/_docs_footer.htm" -->

View File

@@ -0,0 +1,18 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--#include virtual="../documentation.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../streams/architecture.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../streams/core-concepts.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/app-reset-tool.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/config-streams.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/datatypes.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/dsl-api.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/dsl-topology-naming.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/index.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/interactive-queries.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/manage-topics.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/memory-mgmt.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/processor-api.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/running-app.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/security.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/testing.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../../streams/developer-guide/write-streams.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../streams/index.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../streams/quickstart.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../streams/tutorial.html" -->

View File

@@ -0,0 +1,19 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- should always link the latest release's documentation -->
<!--#include virtual="../../streams/upgrade-guide.html" -->

18
docs/ecosystem.html Normal file
View File

@@ -0,0 +1,18 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
There are a plethora of tools that integrate with Kafka outside the main distribution. The <a href="https://cwiki.apache.org/confluence/display/KAFKA/Ecosystem"> ecosystem page</a> lists many of these, including stream processing systems, Hadoop integration, monitoring, and deployment tools.

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
docs/images/icons/NYT.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 818 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
docs/images/icons/line.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 676 B

BIN
docs/images/icons/new-york.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

BIN
docs/images/icons/rabobank.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 985 B

BIN
docs/images/icons/zalando.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

BIN
docs/images/kafka-apis.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

BIN
docs/images/kafka_log.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

BIN
docs/images/log_anatomy.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 411 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

313
docs/implementation.html Normal file
View File

@@ -0,0 +1,313 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script id="implementation-template" type="text/x-handlebars-template">
<h3><a id="networklayer" href="#networklayer">5.1 Network Layer</a></h3>
<p>
The network layer is a fairly straight-forward NIO server, and will not be described in great detail. The sendfile implementation is done by giving the <code>MessageSet</code> interface a <code>writeTo</code> method. This allows the file-backed message set to use the more efficient <code>transferTo</code> implementation instead of an in-process buffered write. The threading model is a single acceptor thread and <i>N</i> processor threads which handle a fixed number of connections each. This design has been pretty thoroughly tested <a href="http://sna-projects.com/blog/2009/08/introducing-the-nio-socketserver-implementation">elsewhere</a> and found to be simple to implement and fast. The protocol is kept quite simple to allow for future implementation of clients in other languages.
</p>
<h3><a id="messages" href="#messages">5.2 Messages</a></h3>
<p>
Messages consist of a variable-length header, a variable-length opaque key byte array and a variable-length opaque value byte array. The format of the header is described in the following section.
Leaving the key and value opaque is the right decision: there is a great deal of progress being made on serialization libraries right now, and any particular choice is unlikely to be right for all uses. Needless to say a particular application using Kafka would likely mandate a particular serialization type as part of its usage. The <code>RecordBatch</code> interface is simply an iterator over messages with specialized methods for bulk reading and writing to an NIO <code>Channel</code>.</p>
<h3><a id="messageformat" href="#messageformat">5.3 Message Format</a></h3>
<p>
Messages (aka Records) are always written in batches. The technical term for a batch of messages is a record batch, and a record batch contains one or more records. In the degenerate case, we could have a record batch containing a single record.
Record batches and records have their own headers. The format of each is described below. </p>
<h4><a id="recordbatch" href="#recordbatch">5.3.1 Record Batch</a></h4>
<p> The following is the on-disk format of a RecordBatch. </p>
<p><pre class="brush: java;">
baseOffset: int64
batchLength: int32
partitionLeaderEpoch: int32
magic: int8 (current magic value is 2)
crc: int32
attributes: int16
bit 0~2:
0: no compression
1: gzip
2: snappy
3: lz4
4: zstd
bit 3: timestampType
bit 4: isTransactional (0 means not transactional)
bit 5: isControlBatch (0 means not a control batch)
bit 6~15: unused
lastOffsetDelta: int32
firstTimestamp: int64
maxTimestamp: int64
producerId: int64
producerEpoch: int16
baseSequence: int32
records: [Record]
</pre></p>
<p> Note that when compression is enabled, the compressed record data is serialized directly following the count of the number of records. </p>
<p>The CRC covers the data from the attributes to the end of the batch (i.e. all the bytes that follow the CRC). It is located after the magic byte, which
means that clients must parse the magic byte before deciding how to interpret the bytes between the batch length and the magic byte. The partition leader
epoch field is not included in the CRC computation to avoid the need to recompute the CRC when this field is assigned for every batch that is received by
the broker. The CRC-32C (Castagnoli) polynomial is used for the computation.</p>
<p>On compaction: unlike the older message formats, magic v2 and above preserves the first and last offset/sequence numbers from the original batch when the log is cleaned. This is required in order to be able to restore the
producer's state when the log is reloaded. If we did not retain the last sequence number, for example, then after a partition leader failure, the producer might see an OutOfSequence error. The base sequence number must
be preserved for duplicate checking (the broker checks incoming Produce requests for duplicates by verifying that the first and last sequence numbers of the incoming batch match the last from that producer). As a result,
it is possible to have empty batches in the log when all the records in the batch are cleaned but batch is still retained in order to preserve a producer's last sequence number. One oddity here is that the baseTimestamp
field is not preserved during compaction, so it will change if the first record in the batch is compacted away.</p>
<h5><a id="controlbatch" href="#controlbatch">5.3.1.1 Control Batches</a></h5>
<p>A control batch contains a single record called the control record. Control records should not be passed on to applications. Instead, they are used by consumers to filter out aborted transactional messages.</p>
<p> The key of a control record conforms to the following schema: </p>
<p><pre class="brush: java">
version: int16 (current version is 0)
type: int16 (0 indicates an abort marker, 1 indicates a commit)
</pre></p>
<p>The schema for the value of a control record is dependent on the type. The value is opaque to clients.</p>
<h4><a id="record" href="#record">5.3.2 Record</a></h4>
<p>Record level headers were introduced in Kafka 0.11.0. The on-disk format of a record with Headers is delineated below. </p>
<p><pre class="brush: java;">
length: varint
attributes: int8
bit 0~7: unused
timestampDelta: varint
offsetDelta: varint
keyLength: varint
key: byte[]
valueLen: varint
value: byte[]
Headers => [Header]
</pre></p>
<h5><a id="recordheader" href="#recordheader">5.3.2.1 Record Header</a></h5>
<p><pre class="brush: java;">
headerKeyLength: varint
headerKey: String
headerValueLength: varint
Value: byte[]
</pre></p>
<p>We use the same varint encoding as Protobuf. More information on the latter can be found <a href="https://developers.google.com/protocol-buffers/docs/encoding#varints">here</a>. The count of headers in a record
is also encoded as a varint.</p>
<h4><a id="messageset" href="#messageset">5.3.3 Old Message Format</a></h4>
<p>
Prior to Kafka 0.11, messages were transferred and stored in <i>message sets</i>. In a message set, each message has its own metadata. Note that although message sets are represented as an array,
they are not preceded by an int32 array size like other array elements in the protocol.
</p>
<b>Message Set:</b><br>
<p><pre class="brush: java;">
MessageSet (Version: 0) => [offset message_size message]
offset => INT64
message_size => INT32
message => crc magic_byte attributes key value
crc => INT32
magic_byte => INT8
attributes => INT8
bit 0~2:
0: no compression
1: gzip
2: snappy
bit 3~7: unused
key => BYTES
value => BYTES
</pre></p>
<p><pre class="brush: java;">
MessageSet (Version: 1) => [offset message_size message]
offset => INT64
message_size => INT32
message => crc magic_byte attributes timestamp key value
crc => INT32
magic_byte => INT8
attributes => INT8
bit 0~2:
0: no compression
1: gzip
2: snappy
3: lz4
bit 3: timestampType
0: create time
1: log append time
bit 4~7: unused
timestamp => INT64
key => BYTES
value => BYTES
</pre></p>
<p>
In versions prior to Kafka 0.10, the only supported message format version (which is indicated in the magic value) was 0. Message format version 1 was introduced with timestamp support in version 0.10.
<ul>
<li>Similarly to version 2 above, the lowest bits of attributes represent the compression type.</li>
<li>In version 1, the producer should always set the timestamp type bit to 0. If the topic is configured to use log append time,
(through either broker level config log.message.timestamp.type = LogAppendTime or topic level config message.timestamp.type = LogAppendTime),
the broker will overwrite the timestamp type and the timestamp in the message set.</li>
<li>The highest bits of attributes must be set to 0.</li>
</ul>
</p>
<p>In message format versions 0 and 1 Kafka supports recursive messages to enable compression. In this case the message's attributes must be set
to indicate one of the compression types and the value field will contain a message set compressed with that type. We often refer
to the nested messages as "inner messages" and the wrapping message as the "outer message." Note that the key should be null
for the outer message and its offset will be the offset of the last inner message.
</p>
<p>When receiving recursive version 0 messages, the broker decompresses them and each inner message is assigned an offset individually.
In version 1, to avoid server side re-compression, only the wrapper message will be assigned an offset. The inner messages
will have relative offsets. The absolute offset can be computed using the offset from the outer message, which corresponds
to the offset assigned to the last inner message.
</p>
<p>The crc field contains the CRC32 (and not CRC-32C) of the subsequent message bytes (i.e. from magic byte to the value).</p>
<h3><a id="log" href="#log">5.4 Log</a></h3>
<p>
A log for a topic named "my_topic" with two partitions consists of two directories (namely <code>my_topic_0</code> and <code>my_topic_1</code>) populated with data files containing the messages for that topic. The format of the log files is a sequence of "log entries""; each log entry is a 4 byte integer <i>N</i> storing the message length which is followed by the <i>N</i> message bytes. Each message is uniquely identified by a 64-bit integer <i>offset</i> giving the byte position of the start of this message in the stream of all messages ever sent to that topic on that partition. The on-disk format of each message is given below. Each log file is named with the offset of the first message it contains. So the first file created will be 00000000000.kafka, and each additional file will have an integer name roughly <i>S</i> bytes from the previous file where <i>S</i> is the max log file size given in the configuration.
</p>
<p>
The exact binary format for records is versioned and maintained as a standard interface so record batches can be transferred between producer, broker, and client without recopying or conversion when desirable. The previous section included details about the on-disk format of records.</p>
</p>
<p>
The use of the message offset as the message id is unusual. Our original idea was to use a GUID generated by the producer, and maintain a mapping from GUID to offset on each broker. But since a consumer must maintain an ID for each server, the global uniqueness of the GUID provides no value. Furthermore, the complexity of maintaining the mapping from a random id to an offset requires a heavy weight index structure which must be synchronized with disk, essentially requiring a full persistent random-access data structure. Thus to simplify the lookup structure we decided to use a simple per-partition atomic counter which could be coupled with the partition id and node id to uniquely identify a message; this makes the lookup structure simpler, though multiple seeks per consumer request are still likely. However once we settled on a counter, the jump to directly using the offset seemed natural&mdash;both after all are monotonically increasing integers unique to a partition. Since the offset is hidden from the consumer API this decision is ultimately an implementation detail and we went with the more efficient approach.
</p>
<img class="centered" src="/{{version}}/images/kafka_log.png">
<h4><a id="impl_writes" href="#impl_writes">Writes</a></h4>
<p>
The log allows serial appends which always go to the last file. This file is rolled over to a fresh file when it reaches a configurable size (say 1GB). The log takes two configuration parameters: <i>M</i>, which gives the number of messages to write before forcing the OS to flush the file to disk, and <i>S</i>, which gives a number of seconds after which a flush is forced. This gives a durability guarantee of losing at most <i>M</i> messages or <i>S</i> seconds of data in the event of a system crash.
</p>
<h4><a id="impl_reads" href="#impl_reads">Reads</a></h4>
<p>
Reads are done by giving the 64-bit logical offset of a message and an <i>S</i>-byte max chunk size. This will return an iterator over the messages contained in the <i>S</i>-byte buffer. <i>S</i> is intended to be larger than any single message, but in the event of an abnormally large message, the read can be retried multiple times, each time doubling the buffer size, until the message is read successfully. A maximum message and buffer size can be specified to make the server reject messages larger than some size, and to give a bound to the client on the maximum it needs to ever read to get a complete message. It is likely that the read buffer ends with a partial message, this is easily detected by the size delimiting.
</p>
<p>
The actual process of reading from an offset requires first locating the log segment file in which the data is stored, calculating the file-specific offset from the global offset value, and then reading from that file offset. The search is done as a simple binary search variation against an in-memory range maintained for each file.
</p>
<p>
The log provides the capability of getting the most recently written message to allow clients to start subscribing as of "right now". This is also useful in the case the consumer fails to consume its data within its SLA-specified number of days. In this case when the client attempts to consume a non-existent offset it is given an OutOfRangeException and can either reset itself or fail as appropriate to the use case.
</p>
<p> The following is the format of the results sent to the consumer.
<pre class="brush: text;">
MessageSetSend (fetch result)
total length : 4 bytes
error code : 2 bytes
message 1 : x bytes
...
message n : x bytes
</pre>
<pre class="brush: text;">
MultiMessageSetSend (multiFetch result)
total length : 4 bytes
error code : 2 bytes
messageSetSend 1
...
messageSetSend n
</pre>
<h4><a id="impl_deletes" href="#impl_deletes">Deletes</a></h4>
<p>
Data is deleted one log segment at a time. The log manager applies two metrics to identify segments which are
eligible for deletion: time and size. For time-based policies, the record timestamps are considered, with the
largest timestamp in a segment file (order of records is not relevant) defining the retention time for the
entire segment. Size-based retention is disabled by default. When enabled the log manager keeps deleting the
oldest segment file until the overall size of the partition is within the configured limit again. If both
policies are enabled at the same time, a segment that is eligible for deletion due to either policy will be
deleted. To avoid locking reads while still allowing deletes that modify the segment list we use a copy-on-write
style segment list implementation that provides consistent views to allow a binary search to proceed on an
immutable static snapshot view of the log segments while deletes are progressing.
</p>
<h4><a id="impl_guarantees" href="#impl_guarantees">Guarantees</a></h4>
<p>
The log provides a configuration parameter <i>M</i> which controls the maximum number of messages that are written before forcing a flush to disk. On startup a log recovery process is run that iterates over all messages in the newest log segment and verifies that each message entry is valid. A message entry is valid if the sum of its size and offset are less than the length of the file AND the CRC32 of the message payload matches the CRC stored with the message. In the event corruption is detected the log is truncated to the last valid offset.
</p>
<p>
Note that two kinds of corruption must be handled: truncation in which an unwritten block is lost due to a crash, and corruption in which a nonsense block is ADDED to the file. The reason for this is that in general the OS makes no guarantee of the write order between the file inode and the actual block data so in addition to losing written data the file can gain nonsense data if the inode is updated with a new size but a crash occurs before the block containing that data is written. The CRC detects this corner case, and prevents it from corrupting the log (though the unwritten messages are, of course, lost).
</p>
<h3><a id="distributionimpl" href="#distributionimpl">5.5 Distribution</a></h3>
<h4><a id="impl_offsettracking" href="#impl_offsettracking">Consumer Offset Tracking</a></h4>
<p>
Kafka consumer tracks the maximum offset it has consumed in each partition and has the capability to commit offsets so
that it can resume from those offsets in the event of a restart. Kafka provides the option to store all the offsets for
a given consumer group in a designated broker (for that group) called the group coordinator. i.e., any consumer instance
in that consumer group should send its offset commits and fetches to that group coordinator (broker). Consumer groups are
assigned to coordinators based on their group names. A consumer can look up its coordinator by issuing a FindCoordinatorRequest
to any Kafka broker and reading the FindCoordinatorResponse which will contain the coordinator details. The consumer
can then proceed to commit or fetch offsets from the coordinator broker. In case the coordinator moves, the consumer will
need to rediscover the coordinator. Offset commits can be done automatically or manually by consumer instance.
</p>
<p>
When the group coordinator receives an OffsetCommitRequest, it appends the request to a special <a href="#compaction">compacted</a> Kafka topic named <i>__consumer_offsets</i>.
The broker sends a successful offset commit response to the consumer only after all the replicas of the offsets topic receive the offsets.
In case the offsets fail to replicate within a configurable timeout, the offset commit will fail and the consumer may retry the commit after backing off.
The brokers periodically compact the offsets topic since it only needs to maintain the most recent offset commit per partition.
The coordinator also caches the offsets in an in-memory table in order to serve offset fetches quickly.
</p>
<p>
When the coordinator receives an offset fetch request, it simply returns the last committed offset vector from the offsets cache.
In case coordinator was just started or if it just became the coordinator for a new set of consumer groups (by becoming a leader for a partition of the offsets topic),
it may need to load the offsets topic partition into the cache. In this case, the offset fetch will fail with an
CoordinatorLoadInProgressException and the consumer may retry the OffsetFetchRequest after backing off.
</p>
<h4><a id="impl_zookeeper" href="#impl_zookeeper">ZooKeeper Directories</a></h4>
<p>
The following gives the ZooKeeper structures and algorithms used for co-ordination between consumers and brokers.
</p>
<h4><a id="impl_zknotation" href="#impl_zknotation">Notation</a></h4>
<p>
When an element in a path is denoted [xyz], that means that the value of xyz is not fixed and there is in fact a ZooKeeper znode for each possible value of xyz. For example /topics/[topic] would be a directory named /topics containing a sub-directory for each topic name. Numerical ranges are also given such as [0...5] to indicate the subdirectories 0, 1, 2, 3, 4. An arrow -> is used to indicate the contents of a znode. For example /hello -> world would indicate a znode /hello containing the value "world".
</p>
<h4><a id="impl_zkbroker" href="#impl_zkbroker">Broker Node Registry</a></h4>
<pre class="brush: json;">
/brokers/ids/[0...N] --> {"jmx_port":...,"timestamp":...,"endpoints":[...],"host":...,"version":...,"port":...} (ephemeral node)
</pre>
<p>
This is a list of all present broker nodes, each of which provides a unique logical broker id which identifies it to consumers (which must be given as part of its configuration). On startup, a broker node registers itself by creating a znode with the logical broker id under /brokers/ids. The purpose of the logical broker id is to allow a broker to be moved to a different physical machine without affecting consumers. An attempt to register a broker id that is already in use (say because two servers are configured with the same broker id) results in an error.
</p>
<p>
Since the broker registers itself in ZooKeeper using ephemeral znodes, this registration is dynamic and will disappear if the broker is shutdown or dies (thus notifying consumers it is no longer available).
</p>
<h4><a id="impl_zktopic" href="#impl_zktopic">Broker Topic Registry</a></h4>
<pre class="brush: json;">
/brokers/topics/[topic]/partitions/[0...N]/state --> {"controller_epoch":...,"leader":...,"version":...,"leader_epoch":...,"isr":[...]} (ephemeral node)
</pre>
<p>
Each broker registers itself under the topics it maintains and stores the number of partitions for that topic.
</p>
<h4><a id="impl_clusterid" href="#impl_clusterid">Cluster Id</a></h4>
<p>
The cluster id is a unique and immutable identifier assigned to a Kafka cluster. The cluster id can have a maximum of 22 characters and the allowed characters are defined by the regular expression [a-zA-Z0-9_\-]+, which corresponds to the characters used by the URL-safe Base64 variant with no padding. Conceptually, it is auto-generated when a cluster is started for the first time.
</p>
<p>
Implementation-wise, it is generated when a broker with version 0.10.1 or later is successfully started for the first time. The broker tries to get the cluster id from the <code>/cluster/id</code> znode during startup. If the znode does not exist, the broker generates a new cluster id and creates the znode with this cluster id.
</p>
<h4><a id="impl_brokerregistration" href="#impl_brokerregistration">Broker node registration</a></h4>
<p>
The broker nodes are basically independent, so they only publish information about what they have. When a broker joins, it registers itself under the broker node registry directory and writes information about its host name and port. The broker also register the list of existing topics and their logical partitions in the broker topic registry. New topics are registered dynamically when they are created on the broker.
</p>
</script>
<div class="p-implementation"></div>

View File

@@ -1,63 +0,0 @@
---
![kafka-manager-logo](./assets/images/common/logo_name.png)
**一站式`Apache Kafka`集群指标监控与运维管控平台**
---
# 安装手册
## 环境依赖
- `Maven`(后端打包依赖)
- `node 10+`(前端打包依赖)
- `Java 8+`(运行环境需要)
- `MySQL`(数据存储)
---
## 环境初始化
执行[create_mysql_table.sql](./create_mysql_table.sql)中的SQL命令从而创建所需的MySQL库及表默认创建的库名是`kafka_manager`
```
# 示例:
mysql -uXXXX -pXXX -h XXX.XXX.XXX.XXX -PXXXX < ./create_mysql_table.sql
```
---
## 打包
```bash
# 前端工程包
cd kafka-manager-opensource/console
npm install
npm run prod-build
mv dist/* ../web/src/main/resources/templates
# 后端工程包
cd ..
mvn install
```
---
## 启动
```
# application.yml 是配置文件
cp web/src/main/resources/application.yml web/target/
cd web/target/
nohup java -jar kafka-manager-web-1.0.0-SNAPSHOT.jar --spring.config.location=./application.yml > /dev/null 2>&1 &
```
## 使用
本地启动的话,访问`http://localhost:8080`,输入帐号及密码进行登录。更多参考:[kafka-manager使用手册](./user_cn_guide.md)

215
docs/introduction.html Normal file
View File

@@ -0,0 +1,215 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script><!--#include virtual="js/templateData.js" --></script>
<script id="introduction-template" type="text/x-handlebars-template">
<h3> Apache Kafka&reg; is <i>a distributed streaming platform</i>. What exactly does that mean?</h3>
<p>A streaming platform has three key capabilities:</p>
<ul>
<li>Publish and subscribe to streams of records, similar to a message queue or enterprise messaging system.
<li>Store streams of records in a fault-tolerant durable way.
<li>Process streams of records as they occur.
</ul>
<p>Kafka is generally used for two broad classes of applications:</p>
<ul>
<li>Building real-time streaming data pipelines that reliably get data between systems or applications
<li>Building real-time streaming applications that transform or react to the streams of data
</ul>
<p>To understand how Kafka does these things, let's dive in and explore Kafka's capabilities from the bottom up.</p>
<p>First a few concepts:</p>
<ul>
<li>Kafka is run as a cluster on one or more servers that can span multiple datacenters.
<li>The Kafka cluster stores streams of <i>records</i> in categories called <i>topics</i>.
<li>Each record consists of a key, a value, and a timestamp.
</ul>
<p>Kafka has five core APIs:</p>
<div style="overflow: hidden;">
<ul style="float: left; width: 40%;">
<li>The <a href="/documentation.html#producerapi">Producer API</a> allows an application to publish a stream of records to one or more Kafka topics.
<li>The <a href="/documentation.html#consumerapi">Consumer API</a> allows an application to subscribe to one or more topics and process the stream of records produced to them.
<li>The <a href="/documentation/streams">Streams API</a> allows an application to act as a <i>stream processor</i>, consuming an input stream from one or more topics and producing an output stream to one or more output topics, effectively transforming the input streams to output streams.
<li>The <a href="/documentation.html#connect">Connector API</a> allows building and running reusable producers or consumers that connect Kafka topics to existing applications or data systems. For example, a connector to a relational database might capture every change to a table.
<li>The <a href="/documentation.html#adminapi">Admin API</a> allows managing and inspecting topics, brokers and other Kafka objects.
</ul>
<img src="/{{version}}/images/kafka-apis.png" style="float: right; width: 50%;">
</div>
<p>
In Kafka the communication between the clients and the servers is done with a simple, high-performance, language agnostic <a href="https://kafka.apache.org/protocol.html">TCP protocol</a>. This protocol is versioned and maintains backwards compatibility with older versions. We provide a Java client for Kafka, but clients are available in <a href="https://cwiki.apache.org/confluence/display/KAFKA/Clients">many languages</a>.</p>
<h4><a id="intro_topics" href="#intro_topics">Topics and Logs</a></h4>
<p>Let's first dive into the core abstraction Kafka provides for a stream of records&mdash;the topic.</p>
<p>A topic is a category or feed name to which records are published. Topics in Kafka are always multi-subscriber; that is, a topic can have zero, one, or many consumers that subscribe to the data written to it.</p>
<p> For each topic, the Kafka cluster maintains a partitioned log that looks like this: </p>
<img class="centered" src="/{{version}}/images/log_anatomy.png">
<p> Each partition is an ordered, immutable sequence of records that is continually appended to&mdash;a structured commit log. The records in the partitions are each assigned a sequential id number called the <i>offset</i> that uniquely identifies each record within the partition.
</p>
<p>
The Kafka cluster durably persists all published records&mdash;whether or not they have been consumed&mdash;using a configurable retention period. For example, if the retention policy is set to two days, then for the two days after a record is published, it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so storing data for a long time is not a problem.
</p>
<img class="centered" src="/{{version}}/images/log_consumer.png" style="width:400px">
<p>
In fact, the only metadata retained on a per-consumer basis is the offset or position of that consumer in the log. This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads records, but, in fact, since the position is controlled by the consumer it can consume records in any order it likes. For example a consumer can reset to an older offset to reprocess data from the past or skip ahead to the most recent record and start consuming from "now".
</p>
<p>
This combination of features means that Kafka consumers are very cheap&mdash;they can come and go without much impact on the cluster or on other consumers. For example, you can use our command line tools to "tail" the contents of any topic without changing what is consumed by any existing consumers.
</p>
<p>
The partitions in the log serve several purposes. First, they allow the log to scale beyond a size that will fit on a single server. Each individual partition must fit on the servers that host it, but a topic may have many partitions so it can handle an arbitrary amount of data. Second they act as the unit of parallelism&mdash;more on that in a bit.
</p>
<h4><a id="intro_distribution" href="#intro_distribution">Distribution</a></h4>
<p>
The partitions of the log are distributed over the servers in the Kafka cluster with each server handling data and requests for a share of the partitions. Each partition is replicated across a configurable number of servers for fault tolerance.
</p>
<p>
Each partition has one server which acts as the "leader" and zero or more servers which act as "followers". The leader handles all read and write requests for the partition while the followers passively replicate the leader. If the leader fails, one of the followers will automatically become the new leader. Each server acts as a leader for some of its partitions and a follower for others so load is well balanced within the cluster.
</p>
<h4><a id="intro_geo-replication" href="#intro_geo-replication">Geo-Replication</a></h4>
<p>Kafka MirrorMaker provides geo-replication support for your clusters. With MirrorMaker, messages are replicated across multiple datacenters or cloud regions. You can use this in active/passive scenarios for backup and recovery; or in active/active scenarios to place data closer to your users, or support data locality requirements. </p>
<h4><a id="intro_producers" href="#intro_producers">Producers</a></h4>
<p>
Producers publish data to the topics of their choice. The producer is responsible for choosing which record to assign to which partition within the topic. This can be done in a round-robin fashion simply to balance load or it can be done according to some semantic partition function (say based on some key in the record). More on the use of partitioning in a second!
</p>
<h4><a id="intro_consumers" href="#intro_consumers">Consumers</a></h4>
<p>
Consumers label themselves with a <i>consumer group</i> name, and each record published to a topic is delivered to one consumer instance within each subscribing consumer group. Consumer instances can be in separate processes or on separate machines.
</p>
<p>
If all the consumer instances have the same consumer group, then the records will effectively be load balanced over the consumer instances.</p>
<p>
If all the consumer instances have different consumer groups, then each record will be broadcast to all the consumer processes.
</p>
<img class="centered" src="/{{version}}/images/consumer-groups.png">
<p>
A two server Kafka cluster hosting four partitions (P0-P3) with two consumer groups. Consumer group A has two consumer instances and group B has four.
</p>
<p>
More commonly, however, we have found that topics have a small number of consumer groups, one for each "logical subscriber". Each group is composed of many consumer instances for scalability and fault tolerance. This is nothing more than publish-subscribe semantics where the subscriber is a cluster of consumers instead of a single process.
</p>
<p>
The way consumption is implemented in Kafka is by dividing up the partitions in the log over the consumer instances so that each instance is the exclusive consumer of a "fair share" of partitions at any point in time. This process of maintaining membership in the group is handled by the Kafka protocol dynamically. If new instances join the group they will take over some partitions from other members of the group; if an instance dies, its partitions will be distributed to the remaining instances.
</p>
<p>
Kafka only provides a total order over records <i>within</i> a partition, not between different partitions in a topic. Per-partition ordering combined with the ability to partition data by key is sufficient for most applications. However, if you require a total order over records this can be achieved with a topic that has only one partition, though this will mean only one consumer process per consumer group.
</p>
<h4><a id="intro_multi-tenancy" href="#intro_multi-tenancy">Multi-tenancy</a></h4>
<p>You can deploy Kafka as a multi-tenant solution. Multi-tenancy is enabled by configuring which topics can produce or consume data. There is also operations support for quotas. Administrators can define and enforce quotas on requests to control the broker resources that are used by clients. For more information, see the <a href="https://kafka.apache.org/documentation/#security">security documentation</a>. </p>
<h4><a id="intro_guarantees" href="#intro_guarantees">Guarantees</a></h4>
<p>
At a high-level Kafka gives the following guarantees:
</p>
<ul>
<li>Messages sent by a producer to a particular topic partition will be appended in the order they are sent. That is, if a record M1 is sent by the same producer as a record M2, and M1 is sent first, then M1 will have a lower offset than M2 and appear earlier in the log.
<li>A consumer instance sees records in the order they are stored in the log.
<li>For a topic with replication factor N, we will tolerate up to N-1 server failures without losing any records committed to the log.
</ul>
<p>
More details on these guarantees are given in the design section of the documentation.
</p>
<h4><a id="kafka_mq" href="#kafka_mq">Kafka as a Messaging System</a></h4>
<p>
How does Kafka's notion of streams compare to a traditional enterprise messaging system?
</p>
<p>
Messaging traditionally has two models: <a href="http://en.wikipedia.org/wiki/Message_queue">queuing</a> and <a href="http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish-subscribe</a>. In a queue, a pool of consumers may read from a server and each record goes to one of them; in publish-subscribe the record is broadcast to all consumers. Each of these two models has a strength and a weakness. The strength of queuing is that it allows you to divide up the processing of data over multiple consumer instances, which lets you scale your processing. Unfortunately, queues aren't multi-subscriber&mdash;once one process reads the data it's gone. Publish-subscribe allows you broadcast data to multiple processes, but has no way of scaling processing since every message goes to every subscriber.
</p>
<p>
The consumer group concept in Kafka generalizes these two concepts. As with a queue the consumer group allows you to divide up processing over a collection of processes (the members of the consumer group). As with publish-subscribe, Kafka allows you to broadcast messages to multiple consumer groups.
</p>
<p>
The advantage of Kafka's model is that every topic has both these properties&mdash;it can scale processing and is also multi-subscriber&mdash;there is no need to choose one or the other.
</p>
<p>
Kafka has stronger ordering guarantees than a traditional messaging system, too.
</p>
<p>
A traditional queue retains records in-order on the server, and if multiple consumers consume from the queue then the server hands out records in the order they are stored. However, although the server hands out records in order, the records are delivered asynchronously to consumers, so they may arrive out of order on different consumers. This effectively means the ordering of the records is lost in the presence of parallel consumption. Messaging systems often work around this by having a notion of "exclusive consumer" that allows only one process to consume from a queue, but of course this means that there is no parallelism in processing.
</p>
<p>
Kafka does it better. By having a notion of parallelism&mdash;the partition&mdash;within the topics, Kafka is able to provide both ordering guarantees and load balancing over a pool of consumer processes. This is achieved by assigning the partitions in the topic to the consumers in the consumer group so that each partition is consumed by exactly one consumer in the group. By doing this we ensure that the consumer is the only reader of that partition and consumes the data in order. Since there are many partitions this still balances the load over many consumer instances. Note however that there cannot be more consumer instances in a consumer group than partitions.
</p>
<h4 id="kafka_storage">Kafka as a Storage System</h4>
<p>
Any message queue that allows publishing messages decoupled from consuming them is effectively acting as a storage system for the in-flight messages. What is different about Kafka is that it is a very good storage system.
</p>
<p>
Data written to Kafka is written to disk and replicated for fault-tolerance. Kafka allows producers to wait on acknowledgement so that a write isn't considered complete until it is fully replicated and guaranteed to persist even if the server written to fails.
</p>
<p>
The disk structures Kafka uses scale well&mdash;Kafka will perform the same whether you have 50 KB or 50 TB of persistent data on the server.
</p>
<p>
As a result of taking storage seriously and allowing the clients to control their read position, you can think of Kafka as a kind of special purpose distributed filesystem dedicated to high-performance, low-latency commit log storage, replication, and propagation.
</p>
<p>
For details about the Kafka's commit log storage and replication design, please read <a href="https://kafka.apache.org/documentation/#design">this</a> page.
</p>
<h4>Kafka for Stream Processing</h4>
<p>
It isn't enough to just read, write, and store streams of data, the purpose is to enable real-time processing of streams.
</p>
<p>
In Kafka a stream processor is anything that takes continual streams of data from input topics, performs some processing on this input, and produces continual streams of data to output topics.
</p>
<p>
For example, a retail application might take in input streams of sales and shipments, and output a stream of reorders and price adjustments computed off this data.
</p>
<p>
It is possible to do simple processing directly using the producer and consumer APIs. However for more complex transformations Kafka provides a fully integrated <a href="/documentation/streams">Streams API</a>. This allows building applications that do non-trivial processing that compute aggregations off of streams or join streams together.
</p>
<p>
This facility helps solve the hard problems this type of application faces: handling out-of-order data, reprocessing input as code changes, performing stateful computations, etc.
</p>
<p>
The streams API builds on the core primitives Kafka provides: it uses the producer and consumer APIs for input, uses Kafka for stateful storage, and uses the same group mechanism for fault tolerance among the stream processor instances.
</p>
<h4>Putting the Pieces Together</h4>
<p>
This combination of messaging, storage, and stream processing may seem unusual but it is essential to Kafka's role as a streaming platform.
</p>
<p>
A distributed file system like HDFS allows storing static files for batch processing. Effectively a system like this allows storing and processing <i>historical</i> data from the past.
</p>
<p>
A traditional enterprise messaging system allows processing future messages that will arrive after you subscribe. Applications built in this way process future data as it arrives.
</p>
<p>
Kafka combines both of these capabilities, and the combination is critical both for Kafka usage as a platform for streaming applications as well as for streaming data pipelines.
</p>
<p>
By combining storage and low-latency subscriptions, streaming applications can treat both past and future data the same way. That is a single application can process historical, stored data but rather than ending when it reaches the last record it can keep processing as future data arrives. This is a generalized notion of stream processing that subsumes batch processing as well as message-driven applications.
</p>
<p>
Likewise for streaming data pipelines the combination of subscription to real-time events make it possible to use Kafka for very low-latency pipelines; but the ability to store data reliably make it possible to use it for critical data where the delivery of data must be guaranteed or for integration with offline systems that load data only periodically or may go down for extended periods of time for maintenance. The stream processing facilities make it possible to transform data as it arrives.
</p>
<p>
For more information on the guarantees, APIs, and capabilities Kafka provides see the rest of the <a href="/documentation.html">documentation</a>.
</p>
</script>
<div class="p-introduction"></div>

24
docs/js/templateData.js Normal file
View File

@@ -0,0 +1,24 @@
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Define variables for doc templates
var context={
"version": "25",
"dotVersion": "2.5",
"fullDotVersion": "2.5.2-SNAPSHOT",
"scalaVersion": "2.12"
};

34
docs/migration.html Normal file
View File

@@ -0,0 +1,34 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--#include virtual="../includes/_header.htm" -->
<h2><a id="migration" href="#migration">Migrating from 0.7.x to 0.8</a></h2>
0.8 is our first (and hopefully last) release with a non-backwards-compatible wire protocol, ZooKeeper layout, and on-disk data format. This was a chance for us to clean up a lot of cruft and start fresh. This means performing a no-downtime upgrade is more painful than normal&mdash;you cannot just swap in the new code in-place.
<h3><a id="migration_steps" href="#migration_steps">Migration Steps</a></h3>
<ol>
<li>Setup a new cluster running 0.8.
<li>Use the 0.7 to 0.8 <a href="tools.html">migration tool</a> to mirror data from the 0.7 cluster into the 0.8 cluster.
<li>When the 0.8 cluster is fully caught up, redeploy all data <i>consumers</i> running the 0.8 client and reading from the 0.8 cluster.
<li>Finally migrate all 0.7 producers to 0.8 client publishing data to the 0.8 cluster.
<li>Decommission the 0.7 cluster.
<li>Drink.
</ol>
<!--#include virtual="../includes/_footer.htm" -->

2234
docs/ops.html Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,106 @@
#### 环境要求
- Java11
- IDEA 示例以2022.3.1版本为准,其他版本可能存在差异)
- Gradle 5.6.2 (自动下载,无需提前准备)
#### 环境配置
##### 1. **下载源码**
```
$ git clone https://giturl/kafka.git
```
##### 2. **切换分支**
```
$ git checkout -b kafka-2.5.0-d-350-dev origin/kafka-2.5.0-d-350
```
##### 3. **生成IDEA项目文件**
```
$ cd kafka
$ ./gradlew idea
```
然后使用IDEA打开kafka.ipr文件
##### 4. **IDEA配置**
下载Scala插件 ![kafka-dev-idea-scala-plugin](assets/kafka-dev-idea-scala-plugin.png)
Project Settings -> Project -> Project JDK改为Java11 ![IDEA JDK](assets/kafka-dev-jdk.png)
##### 5. **生成消息协议文件**
```
./gradlew jar
或者
./gradlew clients:processMessages
```
> 至此已经可以正常在IDEA下查看Kafka源码了
##### 6. **编译Kafka Release包**
```
./gradlew clean releaseTarGz
```
或者IDEA上执行
![Release](assets/kafka-dev-build-release.png)
#### 运行环境
##### 1. **修改配置文件**
**config/server.properties**
主要修改以下配置
```
broker.id=0 // Broker节点ID可以保持默认
listeners=PLAINTEXT://:9092 // 监听地址,或者认证方式参考以下额外参数
log.dirs=kafka-logs // 数据目录
zookeeper.connect=localhost:2181 // ZK地址
认证方式额外参数(根据实际情况调整):
listeners=SASL_PLAINTEXT://:9093,PLAINTEXT://:9092
sasl.enabled.mechanisms=PLAIN
security.inter.broker.protocol=SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
增强版Kafka额外配置参数
cluster.id=0 // LogiKM中接入的集群ID
gateway.url=http://logikm-ip:8080/gateway // LogiKM地址
```
##### 2. **修改IDEA运行配置**
![kafka-dev-idea-run-config](assets/kafka-dev-idea-run-config.png)
> 记得Add VM options
```
VM options: -Dlog4j.configuration=file:config/log4j.properties -Dkafka.logs.dir=server-logs
Main class: kafka.Kafka
Program arguments: config/server.properties
如果是认证方式额外参数:
-Djava.security.auth.login.config=config/kafka_server_jaas.conf
```
##### 3. **运行Kafka**
![kafka-dev-run-kafka](assets/kafka-dev-run-kafka.png)

View File

@@ -0,0 +1,129 @@
#### 1. 功能范围
功能包含增加节点、集群均衡、范围均衡、Topic黑名单。Topic迁移、节点下线本次不实现设计的时候需考虑进去避免后期无法实现或者成本过高。容量红线触发自动均衡本期不考虑均衡算法优先实现Topic leader、副本、磁盘均衡后续逐步实现其他维度。
#### 2. 指标采集
通过KS3采集指标写入ES需要计算到每个分区的指标只要Leader分区的指标副本指标根据Leader分区指标进行推导
**采集周期:** 每分钟
**相关指标:** 共计4个分区磁盘使用、分区流入流量、分区流出流量、分区CPU使用率
1. 分区Log磁盘使用大小关联指标kafka.log:type=Log,name=Size,topic=yy_topic_b,partition=0
2. 分区流入流量根据当前节点的Leader数计算出每个分区平均流入流量关连指标kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec,topic=yy_topic_b Attributes=OneMinuteRate
3. 分区流出流量根据当前节点的Leader数计算出每个分区平均流量关连指标kafka.server:type=BrokerTopicMetrics,name=BytesOutPerSec,topic=yy_topic_b Attributes=OneMinuteRate
4. 分区CPU使用率当前节点CPU使用率 \* PartitonBytesIn / (BrokerBytesIn \* 3 + BrokerReplicationBytesIn \*1)副本CPU使用率为Leader使用率 / 3关连指标java.lang:type=OperatingSystem Attributes=ProcessCpuLoad本期不考虑
**计算方法:** 计算方法有两种一种是由分区驱动首先生产1分钟整个集群的指标快照然后根据Topic元数据分别查询每个Topic分区的Leader所在节点根据当前节点的Leader数量平均计算当前分区的指标。
另一种是在采集时进行计算由指标驱动指标由多个采集节点进行采集每个采集节点需要维护对应Topic的元数据元数据有效期为1分钟采集到Topic指标之后根据当前节点Leader分布情况分别计算出各个分区的平均指标比如Topic A的BytesIn指标为10240当前节点分布的Leader分区有0、5那么0分区和5分区的指标值分别为5120可由标准采集扩展processor进行计算处理
**放弃方案:**
由采集模块采集标准指标写入ES然后再由样本模块定期查询ES进行分区维度指标计算需要额外协调或者降低实时性否则很难确定是否采集完成
**存储格式:**
| **Cluster** | **IP** | **Broker** **ID** | **Topic** | **Partition** | **NW** **IN** | **NW** **OUT** | **Disk** **Size** | **Cpu** **Load** | **Create** **Time** |
| ----------- | ------ | ------------------ | --------- | ------------- | -------------- | --------------- | ------------------ | ----------------- | -------------------- |
#### 3. 模型计算
- 根据集群配置查询最近N小时的样本数据计算每个Topic分区的平均指标
- 根据集群的副本、Leader、Topic、Rack等元数据信息抽象出虚拟集群(Class类),根据均衡目标算法来改变虚拟集群(Class类)中的元数据分布。
- 根据真实集群与虚拟集群元数据分布的不同提取出需要的副本迁移任务、Leader切换任务
#### 4. 均衡算法
输入参数指标计算周期、均衡节点范围、均衡维度有顺序、各维度均衡区间、Topic黑名单、下线节点列表应用到副本、迁移Topic列表应用到副本
输出结果迁移总览、迁移概览、迁移明细、reassignment json file其中迁移明细为副本从哪个节点迁移到哪个节点上
均衡维度:
1. Rack感知(副本迁移)
1. 默认维度
2. 迁移策略
- Broker每个副本AR分配列表存在2个以上相同的Rack则迁移到不同的Rack
2. Topic Leader数平均分布(Leader切换、副本迁移)
1. 默认维度
2. 迁移策略
- 每台Broker的Topic Leader分布数\>=Topic的Leader总数/broker总数
3. Topic副本数平均分布(副本迁移)
1. 默认维度
2. 迁移策略
- 每台Broker相同Topic副本分布个数\>upperLimit迁出
- 每台Broker相同Topic副本分布个数\<lowerLimit迁入
4. 磁盘使用率平均分布(副本迁移)
1. 可选维度
2. 迁移策略
- 磁盘使用率\>upperThreshold副本降序迁出
- 磁盘使用率\<lowerThreshold迁入
5. 网络流入使用率平均分布(副本迁移)
1. 可选维度
2. 迁移策略
- 流入\> upperThreshold副本降序迁出
- 流入\<lowerThreshold迁入
6. 网络流出使用率平均分布(Leader切换、副本迁移)
1. 可选维度
2. 迁移策略
- 流出\>upperThreshold副本降序进行Leader切换
- 切换后流量依然\> upperThreshold则需要把Leader副本迁出
- 流出\<lowerThreshold则需要把follower切换成Leader
- 切换后流量依然\< lowerThreshold则需要进行副本迁入
7. CPU使用率平均分布
1. 可选维度
2.
#### 5. 均衡执行
输入参数并行度、限速、执行策略、reassignment json file
处理:
- 并行度定义导致有流入或流出流量各计算一个并行度流出统计在Leader上比如一个分区0 \[10,11,12\] -\> \[10,11,15\] 那么10计入一个并行度15计入一个并行度
- 根据并行度拆分任务对于小于2.4版本Kafka按照并行度拆分各个小的子任务分别执行每个节点迁入或迁出副本数不大于并行度限制。对于大于等于2.4版本Kafka根据节点并行度动态增加副本迁移数。
- 根据集群metadata元数据查询所有URP分区优先迁移

View File

@@ -0,0 +1,165 @@
# Kafka引擎-DiDi Kafka HA方案
## 背景
- 多区域集群部署跨Region提供数据灾备能力解决跨机房带宽、延迟问题优先本地读写
- 同区域多集群部署跨AZ提供集群切换能力切换对用户无感知无需修改本地配置或者重启应用
- 消费者Offset同步尽量减少集群切换时导致的数据重复消费
## 开源方案
MirrorMaker主要基于消费者→ 生产者模型实现先由消费者将数据拉取下来拆包然后再由生产者封包发送到备份Topic需要额外资源部署MM服务在Kafka 2.4版本增加了MM2的实现2.7版本增加Group offset同步MM2和MM对比最大的改变是MM基于Topic维度进行同步MM2基于分区维度进行同步这样就可以实现保证消息Offset相对一致
![ha-replication-mm2](assets/ha-replication-mm2.png)
## 滴滴方案
### 设计方案
整个方案同时具备**数据复制的能力**和**灾备切换的能力**
通过使用基于副本复制数据的Fetcher实现跨集群数据复制能力能保证主备Topic数据和Offset完全一致并且不依赖外部资源数据复制链路简单高效。同时能够实现跨Kafka版本实现数据复制。
通过在服务端控制客户端元数据的方式实现灾备切换能力配合Gateway使用在客户端不需要修改任何配置的情况下实现跨集群灾备切换并保证在源集群未宕机的情况下客户端生产、消费数据不重不丢。
#### 数据复制能力
![ha-replication-plus1](assets/ha-replication-plus1.png)
1. Topic分为正常Topic和镜像Topic两种镜像Topic和正常Topic保持完全一致包括Topic名称、分区数、消息Offset、Leader epoch、配置
2. 镜像Topic只能由MirrorFetcher进行数据写入外部生产者无法对镜像Topic写入数据
3. 镜像Topic的Follower和正常Topic的Follower功能完全一致
4. 镜像Topic的Leader既有正常Topic的Leader部分特性也有正常Topic的Follower的部分特性镜像Topic的Leader相对于主Topic的Leader来说它是一个Follower而相对于镜像Topic的Follower来说它又是一个Leader
5. 镜像Topic可以提供数据读取服务可以降低主Topic流出带宽压力
6. 组件MirrorFetcher负责同步Topic数据包括普通Topic和内部Topic \_\_consumer_offsets\_\_consumer_offsets用于同步消费组的offset和metadata信息
7. 组件MirrorCoordinator负责管理MirrorFetcher线程源集群Leader切换启动新任务、停止任务
8. 组件MirrorCoordinator负责同步Topic config、ACL、分区数量主Topic分区扩容之后备Topic分区会自动扩容备Topic分区数\>=主Topic分区数
#### 灾备切换能力
1. 组件Forwarder负责将客户端请求转发发生切时请求会转发到备集群中去
2. 组件Breaker负责阻断客户端请求致使客户端进行元数据变更达到切换目的
**转发的请求:** Gateway、Broker会根据客户端标识转发以下请求
- API_VERSIONS
- METADATA
- FIND_COORDINATOR
- INIT_PRODUCER_ID
**阻断的请求:** Broker会根据客户端标识阻断以下请求
- PRODUCE
- FETCH
- OFFSET_COMMIT
- OFFSET_FETCH
- JOIN_GROUP
- HEARTBEAT
- OFFSET_FOR_LEADER_EPOCH
**生产者灾备流程图**
![ha-replication-plus2](assets/ha-replication-plus2.png)
**消费者灾备流程图**
![ha-replication-plus3](assets/ha-replication-plus3.png)
### 使用规范
1. 目前版本只能实现两个集群间互备,不能加入第三个集群
2. Topic高可用不适合用在事务、幂等场景
3. 保证AppID只在同一个集群中使用如果AppID出现在多个集群中只有最后一个集群中的Topic是可用的
4. 尽量保证AppID的权限范围最小每个生产者或消费者实例组使用一个AppID最佳
5. 集群超级管理账号不能被用作高可用AppID
用户平台接入集群的超级管理员账号不能被配置为HA AppID否则引发集群元数据无法访问问题
6. 主备集群中Topic \_\_consumer_offsets的分区数要相同
目前版本Group offset和Group metadata是通过MirrorFetcher实现同步所以要保证两个集群的分区数相同
7. (建议) 生产者retries设置防止切换过程中丢数
Kafka2.0版本以下需要手动设置Kafka2.1+ retries默认值从0改为2147483647
8. 建议消费者客户端避免使用版本2.5.0, 2.5.1, 2.6.0, 2.6.1, 2.7.0建议使用2.6.2, 2.7.1, 2.8.0以上版本
以上客户端存在查找协调器BUG导致客户端不再消费数据 [*KAFKA-10793*](https://issues.apache.org/jira/browse/KAFKA-10793)
9. 建议建议在有条件的情况下保证各个集群的BrokerID唯一尽量降低BrokerID重复
BrokerID唯一可以更优雅的进行集群灾备切换不唯一也可以实现不做强制限制
### 适用场景
#### Topic跨集群迁移
Topic保障等级变化、集群容量限制等因素导致Topic需要从一个集群迁移到另外一个集群上DiDi Kafka HA方案可以在不需要用户配合的情况下随意在集群间迁移Topic
迁移中
![ha-replication-plus4](assets/ha-replication-plus4.png)
迁移后
![ha-replication-plus5](assets/ha-replication-plus5.png)
#### 集群迁移机房或者集群升级
由于业务调整或者机房调整需要将集群迁移到另外一个机房目前一般会采用扩容节点再缩容的方式实现往往我们在迁移集群的过程中会伴随着集群版本升级或者一些系统参数调整给迁移带来很大的风险。DiDi Kafka HA方案可以在两个独立的集群上实现Topic迁移不需要用户配合同时可以跨版本迁移。迁移流程同上
集群升级跨大版本集群升级风险比较大升级节点对整个集群的稳定性都可能产生影响一些系统配置调整也很难在集群滚动升级中实现比如ControlPlane与DataPlane的拆分。DiDi Kafka HA方案可以实现部分Topic增量迁移降低整个升级过程中的风险。
#### 跨集群Topic灾备
对于保障等级比较高的业务提供Topic跨集群容灾功能当集群不稳定或者不可用时可以快速切换到备集群进行正常读写操作
正常运行
![ha-replication-plus6](assets/ha-replication-plus6.png)
集群不可用时切换到备集群
![ha-replication-plus7](assets/ha-replication-plus7.png)
#### Topic读写分离、就近读、负载均衡
对于一些热点Topic下游有过多消费者一般流出带宽压力比较大可以复制出多个副本Topic来降低这种压力。
复制出一个读Topic降低主Topic读取压力
![ha-replication-plus8](assets/ha-replication-plus8.png)
也可以通过跨区域复制Topic降低专线带宽压力
![ha-replication-plus9](assets/ha-replication-plus9.png)

View File

@@ -0,0 +1,226 @@
## 背景
目前灾备方案使用客户端User唯一标识做灾备切换能有效保障整个客户端元数据统一切换。目前用户存量场景存在Kafka User共享使用情况但是各个客户端对Topic的访问是互相独立的为了兼容这种场景实现客户端能独立进行灾备切换而不影响其他客户端连带切换。
## 方案
### Client端兼容方案二
**client.id 格式:** ~~HA#AppId#TopicName~~ InstanceID
一个InstanceID可以对应多个Topic
**约束:** AppID下每个客户端实例使用相同的InstanceID并且不同客户端实例的InstanceID不能重复
> 客户端实例定义最好是每个生产者、消费者实例使用一套InstanceID次之是应用粒度一个应用使用一套InstanceID但是存在访问多个Topic会存在一些关联切换情况
>
> 注意客户端每次启动都使用相同的InstanceID不能每次启动都生成新的InstanceID
**InstanceID生成方式**
1. 由平台申请生成InstanceID可以在Topic申请时为每一个Topic产生一个InstanceID或者多个Topic申请一个InstanceID
2. 由用户自己控制直接在客户端设置一个ID
**InstanceID和Topic对应关系**
1. 声明式由平台申请InstanceID与Topic绑定关系
2. 自动化:从引擎侧上报的连接信息中自动获取(客户端未启动过这种场景获取不到)
引擎侧上报用户访问信息已有TopicName、AppID、访问类型生产、消费、ClientID
**平台切换:**
用户选择切换方式:用户维度、用户+InstanceID维度
用户维度跟现有逻辑保持一致用户下所有Topic同时切换
用户+InstanceID维度切换Topic时如果用户下InstanceID绑定了Topic则只切换这个InstanceID否则整个用户进行切换
**Gateway、引擎处理**
如果AppID+InstanceID绑定了集群则按这个集群进行转发否则按AppID粒度进行转发
### Server端兼容方案
#### 现状
灾备Gateway、Broker会根据客户端标识转发以下请求
- API_VERSIONS
- METADATAnull、empty、some topics
- FIND_COORDINATOR
- INIT_PRODUCER_ID // 无事务、幂等场景可忽略
Broker会根据客户端标识阻断以下请求
- PRODUCE
- FETCH
- OFFSET_COMMIT
- OFFSET_FETCH
- JOIN_GROUP
- HEARTBEAT
- OFFSET_FOR_LEADER_EPOCH
#### 流程
每个节点建立连接后会发送API_VERSIONS请求获取节点协议版本信息
**生产者:**
1. 生产者启动后会先向引导地址发送METADATAtopics=empty请求只请求集群地址的元数据并更新缓存中metadata的nodes信息
2. 当发送一条消息后生产者刷新元数据发送METADATAtopics=some topics请求
**消费者:**
1. 消费者启动后会向引导地址发送METADATAtopics=empty请求只请求集群地址的元数据并更新缓存中metadata的nodes信息
2. 消费者启动后会向引导地址发送FIND_COORDINATOR请求获取Coordinator地址
3. 客户端向Coordinator发起连接后续发送JOIN_GROUP、SYNC_GROUP
4. 随后会更新客户端元数据,发送元数据请求
如果订阅类型为AUTO_TOPICS会向引导地址发送METADATAtopics=some topics请求
如果订阅类型为AUTO_PATTERN则会向引导地址发送**METADATAtopics=null**请求null为all topics元数据请求
**请求归类:**
- **无信息**
- API_VERSIONS
- METADATAnull、empty
- **含Topic信息**(多个)
- METADATAsome topics
- PRODUCE
- FETCH
- OFFSET_FOR_LEADER_EPOCH
- **含Group信息**
- FIND_COORDINATOR
- OFFSET_COMMIT
- OFFSET_FETCH
- JOIN_GROUP
- HEARTBEAT
#### 改造
根据更细粒度客户端标识进行转发和阻断对于生产者使用AppID#TopicName消费者使用AppID#TopicName或AppID##GroupName作为客户端标识
> 限制1要求AppID#TopicName或AppID##GroupName全局唯一
>
> 限制2要求客户端只访问一个Topic待定
1. **客户端标识获取**
通过解析请求协议内容获取对应的标识符
Topic AppID#TopicName
GroupAppID##GroupName
2. **请求协议处理**
根据优先级AppID##GroupName、AppID#TopicName、AppID获取客户端标识是否绑定集群如果绑定集群进行响应转发或者阻断
3. **无标识请求处理**
- API_VERSIONS
客户端发送API_VERSIONS到Gateway由Gateway直接响应给客户端GW的APIs信息不进行转发由于GW是基于2.5版本的灾备也是基于2.5版本),这里需要判断是不是灾备场景,非灾备场景继续按原有逻辑进行处理
- METADATA
empty情况这种情况是客户端第一次启动时发出的请求nodes信息由Gateway直接响应给客户端GW地址不进行转发
null情况这种情况时消费者采用正则的方式进行订阅需要返回用户有权限的所有Topic列表Gateway无法处理这种场景
4. **多Topic处理**
方案1只处理单一Topic情况如果出现多个Topic按AppID粒度进行转发或阻断
方案2平台维护AppID#TopicList与集群绑定关系当请求的Topic集合为维护的子集时按照细粒度转发否则使用AppID粒度进行转发或阻断
5. **平台改造**
维护平台增加AppID#TopicName和AppID##GroupName与集群绑定关系
切换如果AppID下Topic维护了细粒度绑定关系切换时则不关联其他Topic未维护细粒度绑定关系的Topic切换时不关联出其他已经维护了细粒度绑定关系的Topic
#### 总结
**前提假设:** 1. Gateway版本与Broker版本一致 2. 明确了解用户客户端访问Topic范围
**局限性:** 不支持消费者采用正则模式的订阅方式
只有在平台管理员能够明确了解共享用户的使用情况下才可以使用这种兼容方案否则可能会导致客户端访问集群元数据混乱部分Topic访问失败的情况。平台做大之后平台管理员很难了解每一个用户的使用情况也许当下是规范的后续可能会产生使用交叉情况所以这个兼容方案制作临时使用长期优先在平台侧进行细粒度管控。
### Client端兼容方案一
通过在客户端增加client.id配置生成更细粒度的标识由服务器端进行识别转发
client.id 格式: HA#AppId#TopicName
1. 在Gateway和Broker的ZK中维护AppId#TopicName与集群的绑定关系
2. Gateway和Broker识别客户端ClientID以HA开头则此ClientID是一个细粒度灾备标识根据AppId#TopicName获取集群绑定关系,将请求转发到实际集群
---
**0.10.0.0 Protocol version**
METADATA V1满足正常使用
GROUP_COORDINATOR_REQUEST V0 10 FindCoordinatorRequest V1+增加key_type默认为0group
API_VERSIONS V0
Gateway为2.5版本如果客户端是2.5服务端是0.10客户端将以2.5版本协议进行发送

View File

@@ -0,0 +1,53 @@
**测试环境:**
单条消息大小1KB随机10000条
测试环境CPU: E5-2630 v4 20C40T 内存128G 磁盘2T NVME ES3600P 版本Dkafka2.5.0 JVM-Xmx8G -Xms8G
服务器端参数num.network.threads=6 num.io.threads=32 num.replica.fetchers=10 didi.mirror.num.fetchers=10
客户端参数batch.size=16384 linger.ms=100
主集群单个Topic 10个分区2个副本Leader都分布到同一台机器上副本都分布在同一台机器上
备集群单个Topic 10个分区1个副本Leader都分布到同一台机器上
线程数副本fetcher线程10、Mirror fetcher线程10、MM tasks数10
**非压缩场景**
| 性能对比 | 主集群写入 | 副本同步 | Mirror同步 | MM2同步 |
| :-------: | :--------: | :------: | :---------: | :---------: |
| MessageIn | 626399/s | - | 537576/s | 263450/s |
| BytesIn | 619MB/s | 540MB/s | **538MB/s** | **259MB/s** |
| CPU使用率 | 898.3% | - | 284% | 1558% |
**LZ4压缩场景**
| 性能对比 | 主集群写入 | 副本同步 | Mirror同步 | MM2同步 |
| :-------: | :--------: | :------: | :-----------: | :---------: |
| MessageIn | 770503/s | - | 542501/s | 242615/s |
| BytesIn | 761.5MB/s | 570MB/s | **557.8MB/s** | **245MB/s** |
| CPU使用率 | 757.7% | - | 352% | 1802% |
**结论:** Mirror同步性能和副本同步原理相同性能接近Mirror同步在不使用额外资源的情况下性能比MM2同步高出2倍+**MM2同步在需要额外18核心CPU的情况下达到Mirror同步不到一半的性能**。压测场景下属于理想环境每次发送的Batch都是满载的性能效果会比较好实际线上环境会比较复杂而副本同步和Mirror同步受Batch大小因素基本无影响一次可以拉取多个batch进行写入MM2的性能会受Batch大小因素影响会比较大具体详见以下补充测试。
**PS**
1. 由于是随机消息所以lz4压缩率比较低
2. 由于缺少系统监控图表cpu使用率使用瞬时值上下会有一些偏差
3. 副本同步缺乏消息数指标,流量以刚刚出现积压时流量为准
**补充LZ4压缩场景 batch.size=5120 模拟batch内消息不足**
| 性能对比 | 主集群写入 | 副本同步 | Mirror同步 | MM2同步 |
| :-------: | :--------: | :------: | :-----------: | :---------: |
| MessageIn | 570503/s | - | 549520/s | 102615/s |
| BytesIn | 598.2MB/s | 570MB/s | **549.7MB/s** | **105MB/s** |
| CPU使用率 | 2010% | - | 328.8% | 1284% |
在一个batch包含消息数比较少请求数多的情况下MM2性能明显降低而Mirror同步基本无影响性能相差5倍

Some files were not shown because too many files have changed in this diff Show More