Flume 2.0.0 Developer Guide
Overview
Apache Flume is a distributed, reliable, and available system for efficiently collecting, aggregating and moving large amounts of log data from many different sources to a centralized data store.
Apache Flume is a top-level project at the Apache Software Foundation. Flume 1.x went into dormant status in 2024. This documentation applies to the 2.x codebase.
Architecture
Data flow model
An Event is a unit of data that flows through a Flume agent. The Event
flows from Source to Channel to Sink, and is represented by an
implementation of the Event interface. An Event carries a payload (byte
array) that is accompanied by an optional set of headers (string attributes).
A Flume agent is a process (JVM) that hosts the components that allow
Events to flow from an external source to a external destination.
A Source consumes Events having a specific format, and those
Events are delivered to the Source by an external source like a web
server. For example, an AvroSource can be used to receive Avro Event`s
from clients or from other Flume agents in the flow. When a `Source receives
an Event, it stores it into one or more Channel`s. The `Channel is
a passive store that holds the Event until that Event is consumed by a
Sink. One type of Channel available in Flume is the FileChannel
which uses the local filesystem as its backing store. A Sink is responsible
for removing an Event from the Channel and putting it into an external
repository like HDFS (in the case of an HDFSEventSink) or forwarding it to
the Source at the next hop of the flow. The Source and Sink within
the given agent run asynchronously with the Events staged in the
Channel.
Reliability
An Event is staged in a Flume agent’s Channel. Then it’s the
Sink’s responsibility to deliver the `Event to the next agent or
terminal repository (like HDFS) in the flow. The Sink removes an Event
from the Channel only after the Event is stored into the Channel of
the next agent or stored in the terminal repository. This is how the single-hop
message delivery semantics in Flume provide end-to-end reliability of the flow.
Flume uses a transactional approach to guarantee the reliable delivery of the
Event`s. The provided by the
Sources and Sinks encapsulate the
storage/retrieval of the Events in a `TransactionChannel. This ensures that the set of Events are reliably passed from
point to point in the flow. In the case of a multi-hop flow, the Sink from
the previous hop and the Source of the next hop both have their
Transactions open to ensure that the Event data is safely stored in
the Channel of the next hop.
Building Flume
Getting the source
Check-out the code using Git. Click here for the git repository root or at GitHub.
The Flume core development happens under the branch "trunk" so this command line can be used:
or
Many of the Flume components that have dependencies on third party products reside in their own GitHub repositories. For example, the Sources and Sinks that are based on Apache Avro or Apache Thrift to implement support for connectivity with other compatible services via Remote Procedure Call are located in the logging-flume-rpc GitHub project.
A full list of Flume repositories can be found by navigating to https://github.com/orgs/apache/repositories and then entering "logging-flume" in the search box.
Compile/test Flume
The Flume build is mavenized. You can compile Flume using the standard Maven commands:
-
Compile only:
mvn clean compile -
Compile and run unit tests:
mvn clean test -
Run individual test(s):
mvn clean test -Dtest=<Test1>,<Test2>,… -DfailIfNoTests=false -
Create tarball package:
mvn clean install -
Create tarball package (skip unit tests):
mvn clean install -DskipTests
Updating Protocol Buffer Version
File channel has a dependency on Protocol Buffer. When updating the version of Protocol Buffer used by Flume, it is necessary to regenerate the data access classes using the protoc compiler that is part of Protocol Buffer as follows.
-
Update version of Protocol Buffer in pom.xml
-
Add Apache license header to any of the generated files that are missing it
-
Rebuild and test Flume:
cd ../..; mvn clean install
Developing Flume Clients
Client
The client operates at the point of origin of events and delivers them to a
Flume agent. Clients typically operate in the process space of the application
they are consuming data from. Flume currently supports Avro, syslog,
and Http POST (with a JSON body) as ways to transfer data from a external
source. Additionally, there’s an ExecSource that can consume the output of a
local process as input to Flume. The Apache Logging project also has a
Flume Appender for Log4j 2, however it is currently not part of the Log4j2 or
Flume project’s release process.
It is quite possible to have a use case where these existing options are not
sufficient. In this case you can build a custom mechanism to send data to
Flume. There are two ways of achieving this. The first option is to create a
custom client that communicates with one of Flume’s existing Sources like
AvroSource or SyslogTcpSource. Here the client should convert its data
into messages understood by these Flume Source`s. The other option is to
write a custom Flume `Source that directly talks with your existing client
application using some IPC or RPC protocol, and then converts the client data
into Flume Events to be sent downstream. Note that all events stored
within the Channel of a Flume agent must exist as Flume `Event`s.
https://github.com/apache/logging-flume-samples provides an example client
that uses the Flume client API to send events to Flume.
Client SDK
Though Flume contains a number of built-in mechanisms (i.e. `Source`s) to ingest data, often one wants the ability to communicate with Flume directly from a custom application. The Flume Client SDK is a library that enables applications to connect to Flume and send data into Flume’s data flow over RPC.
RPC client interface
An implementation of Flume’s RpcClient interface encapsulates the RPC mechanism
supported by Flume. The user’s application can simply call the Flume Client
SDK’s append(Event) or appendBatch(List<Event>) to send data and not
worry about the underlying message exchange details. The user can provide the
required Event arg by either directly implementing the Event interface,
by using a convenience implementation such as the SimpleEvent class, or by using
EventBuilder’s overloaded `withBody() static helper methods.
RPC clients - Avro and Thrift
This content is provided by the Flume RPC module. See RPC clients - Avro and Thrift in the Flume RPC documentation.
Secure RPC client - Thrift
This content is provided by the Flume RPC module. See Secure RPC client - Thrift in the Flume RPC documentation.
Failover Client
This class wraps the default Avro RPC client to provide failover handling capability to clients. This takes a whitespace-separated list of <host>:<port> representing the Flume agents that make-up a failover group. The Failover RPC Client currently does not support thrift. If there’s a communication error with the currently selected host (i.e. agent) agent, then the failover client automatically fails-over to the next host in the list. For example:
// Setup properties for the failover
Properties props = new Properties();
props.put("client.type", "default_failover");
// List of hosts (space-separated list of user-chosen host aliases)
props.put("hosts", "h1 h2 h3");
// host/port pair for each host alias
String host1 = "host1.example.org:41414";
String host2 = "host2.example.org:41414";
String host3 = "host3.example.org:41414";
props.put("hosts.h1", host1);
props.put("hosts.h2", host2);
props.put("hosts.h3", host3);
// create the client with failover properties
RpcClient client = RpcClientFactory.getInstance(props);
For more flexibility, the failover Flume client implementation
(FailoverRpcClient) can be configured with these properties:
client.type = default_failover
hosts = h1 h2 h3 # at least one is required, but 2 or
# more makes better sense
hosts.h1 = host1.example.org:41414
hosts.h2 = host2.example.org:41414
hosts.h3 = host3.example.org:41414
max-attempts = 3 # Must be >=0 (default: number of hosts
# specified, 3 in this case). A '0'
# value doesn't make much sense because
# it will just cause an append call to
# immmediately fail. A '1' value means
# that the failover client will try only
# once to send the Event, and if it
# fails then there will be no failover
# to a second client, so this value
# causes the failover client to
# degenerate into just a default client.
# It makes sense to set this value to at
# least the number of hosts that you
# specified.
batch-size = 100 # Must be >=1 (default: 100)
connect-timeout = 20000 # Must be >=1000 (default: 20000)
request-timeout = 20000 # Must be >=1000 (default: 20000)
LoadBalancing RPC client
The Flume Client SDK also supports an RpcClient which load-balances among
multiple hosts. This type of client takes a whitespace-separated list of
<host>:<port> representing the Flume agents that make-up a load-balancing group.
This client can be configured with a load balancing strategy that either
randomly selects one of the configured hosts, or selects a host in a round-robin
fashion. You can also specify your own custom class that implements the
LoadBalancingRpcClient$HostSelector interface so that a custom selection
order is used. In that case, the FQCN of the custom class needs to be specified
as the value of the host-selector property. The LoadBalancing RPC Client
currently does not support thrift.
If backoff is enabled then the client will temporarily blacklist
hosts that fail, causing them to be excluded from being selected as a failover
host until a given timeout. When the timeout elapses, if the host is still
unresponsive then this is considered a sequential failure, and the timeout is
increased exponentially to avoid potentially getting stuck in long waits on
unresponsive hosts.
The maximum backoff time can be configured by setting maxBackoff (in
milliseconds). The maxBackoff default is 30 seconds (specified in the
OrderSelector class that’s the superclass of both load balancing
strategies). The backoff timeout will increase exponentially with each
sequential failure up to the maximum possible backoff timeout.
The maximum possible backoff is limited to 65536 seconds (about 18.2 hours).
For example:
// Setup properties for the load balancing
Properties props = new Properties();
props.put("client.type", "default_loadbalance");
// List of hosts (space-separated list of user-chosen host aliases)
props.put("hosts", "h1 h2 h3");
// host/port pair for each host alias
String host1 = "host1.example.org:41414";
String host2 = "host2.example.org:41414";
String host3 = "host3.example.org:41414";
props.put("hosts.h1", host1);
props.put("hosts.h2", host2);
props.put("hosts.h3", host3);
props.put("host-selector", "random"); // For random host selection
// props.put("host-selector", "round_robin"); // For round-robin host
// // selection
props.put("backoff", "true"); // Disabled by default.
props.put("maxBackoff", "10000"); // Defaults 0, which effectively
// becomes 30000 ms
// Create the client with load balancing properties
RpcClient client = RpcClientFactory.getInstance(props);
For more flexibility, the load-balancing Flume client implementation
(LoadBalancingRpcClient) can be configured with these properties:
client.type = default_loadbalance
hosts = h1 h2 h3 # At least 2 hosts are required
hosts.h1 = host1.example.org:41414
hosts.h2 = host2.example.org:41414
hosts.h3 = host3.example.org:41414
backoff = false # Specifies whether the client should
# back-off from (i.e. temporarily
# blacklist) a failed host
# (default: false).
maxBackoff = 0 # Max timeout in millis that a will
# remain inactive due to a previous
# failure with that host (default: 0,
# which effectively becomes 30000)
host-selector = round_robin # The host selection strategy used
# when load-balancing among hosts
# (default: round_robin).
# Other values are include "random"
# or the FQCN of a custom class
# that implements
# LoadBalancingRpcClient$HostSelector
batch-size = 100 # Must be >=1 (default: 100)
connect-timeout = 20000 # Must be >=1000 (default: 20000)
request-timeout = 20000 # Must be >=1000 (default: 20000)
Embedded agent
This content is provided by the Flume RPC module. See Embedded agent in the Flume RPC documentation.
Developing custom components
Transaction interface
The Transaction interface is the basis of reliability for Flume. All the
major components (ie. Source`s, .Sinks and `Channel`s) must use a
Flume `Transaction
A Transaction is implemented within a Channel implementation. Each
Source and Sink that is connected to a Channel must obtain a
Transaction object. The Sources use a ChannelProcessor
to manage the Transaction`s, the . The operation to stage an
Sinks manage them explicitly via
their configured `ChannelEvent (put it into a Channel) or extract an Event (take it out of a
Channel) is done inside an active Transaction. For example:
Channel ch = new MemoryChannel();
Transaction txn = ch.getTransaction();
txn.begin();
try {
// This try clause includes whatever Channel operations you want to do
Event eventToStage = EventBuilder.withBody("Hello Flume!",
Charset.forName("UTF-8"));
ch.put(eventToStage);
// Event takenEvent = ch.take();
// ...
txn.commit();
} catch (Throwable t) {
txn.rollback();
// Log exception, handle individual exceptions as needed
// re-throw all Errors
if (t instanceof Error) {
throw (Error)t;
}
} finally {
txn.close();
}
Here we get hold of a Transaction from a Channel. After begin()
returns, the Transaction is now active/open and the Event is then put
into the Channel. If the put is successful, then the Transaction is
committed and closed.
Providers
Flume finds the class for a component from the type property in its configuration. The
type can be the fully qualified class name of the component, or a short name, such as
memory or null, that a provider registers. Providers are found with Java’s
java.util.ServiceLoader, so a component in any jar on the classpath can be selected by its
short name. You do not need to change Flume itself.
Each kind of component has its own provider interface in the org.apache.flume.spi package.
All of them extend ComponentProvider<T>:
| Component | Provider interface |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ComponentProvider has two methods:
-
getName()returns the value of thetypeproperty that selects the component. Flume ignores case when it compares names. -
getComponentClass()returns the component class. The class must have a public no-argument constructor. For a component that is built with a builder, such as an interceptor, this is the builder class.
Most providers only map a fixed name to a fixed class, and AbstractComponentProvider does
that for you. By convention, the provider is a public static nested class named Provider
inside the component. Its public no-argument constructor passes the name and the class to
the superclass:
public class MySink extends AbstractSink implements Configurable {
// ... the Sink implementation ...
/**
* Provides the {@code mySink} sink type.
*/
public static final class Provider extends AbstractComponentProvider<Sink>
implements SinkProvider {
public Provider() {
super("mySink", MySink.class);
}
}
}
The provider must be registered so that the ServiceLoader can find it. Add the fully
qualified name of the provider class to a file in the jar. The file is named after the
provider interface:
com.example.flume.MySink$Provider
Note the $ between the component class and its nested Provider class. Flume’s own
components don’t write this file by hand. They use the @ServiceProvider annotation from
the bnd biz.aQute.bnd.annotation artifact, which generates the file at build time:
@ServiceProvider(value = SinkProvider.class, resolution = Resolution.OPTIONAL)
public static final class Provider extends AbstractComponentProvider<Sink>
implements SinkProvider {
...
}
After the provider is registered, the component can be configured by its short name:
a1.sinks.k1.type = mySink
Choose a name that other components are unlikely to use. If two providers register the same name, Flume logs an error when it loads the providers. It then fails with an error when a configuration uses that type. The fully qualified class name still works in that case. If a provider can’t be loaded, Flume logs a warning, skips that provider and loads the others.
Sink
The purpose of a Sink to extract Events from the Channel and
forward them to the next Flume Agent in the flow or store them in an external
repository. A Sink is associated with exactly one Channel, as
configured in the Flume properties file. There is one SinkRunner instance
associated with every configured Sink, and when the Flume framework calls
SinkRunner.start(), a new thread is created to drive the Sink (using
SinkRunner.PollingRunner as the thread’s Runnable). This thread manages
the Sink’s lifecycle. The Sink needs to implement the start() and
stop() methods that are part of the LifecycleAware interface. The
Sink.start() method should initialize the Sink and bring it to a state
where it can forward the Events to its next destination. The
Sink.process() method should do the core processing of extracting the
Event from the Channel and forwarding it. The Sink.stop() method
should do the necessary cleanup (e.g. releasing resources). The Sink
implementation also needs to implement the Configurable interface for
processing its own configuration settings. For example:
public class MySink extends AbstractSink implements Configurable {
private String myProp;
@Override
public void configure(Context context) {
String myProp = context.getString("myProp", "defaultValue");
// Process the myProp value (e.g. validation)
// Store myProp for later retrieval by process() method
this.myProp = myProp;
}
@Override
public void start() {
// Initialize the connection to the external repository (e.g. HDFS) that
// this Sink will forward Events to ..
}
@Override
public void stop () {
// Disconnect from the external respository and do any
// additional cleanup (e.g. releasing resources or nulling-out
// field values) ..
}
@Override
public Status process() throws EventDeliveryException {
Status status = null;
// Start transaction
Channel ch = getChannel();
Transaction txn = ch.getTransaction();
txn.begin();
try {
// This try clause includes whatever Channel operations you want to do
Event event = ch.take();
// Send the Event to the external repository.
// storeSomeData(e);
txn.commit();
status = Status.READY;
} catch (Throwable t) {
txn.rollback();
// Log exception, handle individual exceptions as needed
status = Status.BACKOFF;
// re-throw all Errors
if (t instanceof Error) {
throw (Error)t;
}
}
return status;
}
}
Source
The purpose of a Source is to receive data from an external client and store
it into the configured Channel. A Source can get an instance of its own
ChannelProcessor to process an Event, commited within a Channel
local transaction, in serial. In the case of an exception, required
Channels will propagate the exception, all Channels will rollback their
transaction, but events processed previously on other Channels will remain
committed.
Similar to the SinkRunner.PollingRunner Runnable, there’s
a PollingRunner Runnable that executes on a thread created when the
Flume framework calls PollableSourceRunner.start(). Each configured
PollableSource is associated with its own thread that runs a
PollingRunner. This thread manages the PollableSource’s lifecycle,
such as starting and stopping. A PollableSource implementation must
implement the start() and stop() methods that are declared in the
LifecycleAware interface. The runner of a PollableSource invokes that
Source’s `process() method. The process() method should check for
new data and store it into the Channel as Flume Events.
Note that there are actually two types of Sources. The PollableSource
was already mentioned. The other is the EventDrivenSource. The
EventDrivenSource, unlike the PollableSource, must have its own callback
mechanism that captures the new data and stores it into the Channel. The
EventDrivenSources are not each driven by their own thread like the
PollableSources are. Below is an example of a custom PollableSource:
public class MySource extends AbstractSource implements Configurable, PollableSource {
private String myProp;
@Override
public void configure(Context context) {
String myProp = context.getString("myProp", "defaultValue");
// Process the myProp value (e.g. validation, convert to another type, ...)
// Store myProp for later retrieval by process() method
this.myProp = myProp;
}
@Override
public void start() {
// Initialize the connection to the external client
}
@Override
public void stop () {
// Disconnect from external client and do any additional cleanup
// (e.g. releasing resources or nulling-out field values) ..
}
@Override
public Status process() throws EventDeliveryException {
Status status = null;
try {
// This try clause includes whatever Channel/Event operations you want to do
// Receive new data
Event e = getSomeData();
// Store the Event into this Source's associated Channel(s)
getChannelProcessor().processEvent(e);
status = Status.READY;
} catch (Throwable t) {
// Log exception, handle individual exceptions as needed
status = Status.BACKOFF;
// re-throw all Errors
if (t instanceof Error) {
throw (Error)t;
}
} finally {
txn.close();
}
return status;
}
}
Channel
Channels act as the intermediary between Sources and Sinks. A Source passes an event to the Channel, the Channel saves the event and then acknowledges that it has taken ownership of it as soon as possible. The Sink then retrieves the event, sends it downstream and then notifies the Channel that the event can be removed from the Channel.
public class MyChannel extends BasicChannelSemantics {
@Override
public void configure(Context context) {
// Read any configuration properties for the Channel
}
@Override
protected BasicTransactionSemantics createTransaction() {
return new MyTransaction();
}
private class MyTransaction extends BasicTransactionSemantics {
@Override
protected void doPut(Event event) throws InterruptedException {
// Stage the event to be stored when the transaction is committed
}
@Override
protected Event doTake() throws InterruptedException {
// Return the next available event, or null if the Channel is empty
return null;
}
@Override
protected void doCommit() throws InterruptedException {
// Make the staged puts durable and permanently remove the taken events
}
@Override
protected void doRollback() throws InterruptedException {
// Discard staged puts and return taken events to the Channel
}
}
}
Initializable
Flume Sources, Sinks, and Channels may implement the Intitializable interface. Doing so allows the component to have access the materialized configuration before any of the components have been started. While this ability is quite useful when using the standard configuration, it is less useful when configuring using Spring Boot as Spring’s autowiring generally can be used to accomplish the same thing.
This example shows a Sink being configured with the name of a Source. While initializing it will retrieve the Source from the configuration and save it. During event processing a new event will be sent to the Source, presumably after the event has be modified in some way.
public class NullInitSink extends NullSink implements Initializable {
private static final Logger logger = LoggerFactory.getLogger(NullInitSink.class);
private String sourceName = null;
private EventProcessor eventProcessor = null;
private long total = 0;
public NullInitSink() {
super();
}
@Override
public void configure(Context context) {
sourceName = context.getString("targetSource");
super.configure(context);
}
@Override
public void initialize(MaterializedConfiguration configuration) {
logger.debug("Locating source for event publishing");
for (Map.Entry<String, SourceRunner> entry : configuration.getSourceRunners().entrySet()) {
if (entry.getKey().equals(sourceName)) {
Source source = entry.getValue().getSource();
if (source instanceof EventProcessor) {
eventProcessor = (EventProcessor) source;
logger.debug("Found event processor {}", source.getName());
return;
}
}
}
logger.warn("No Source named {} found for republishing events.", sourceName);
}
@Override
public Status process() throws EventDeliveryException {
Status status = Status.READY;
Channel channel = getChannel();
Transaction transaction = channel.getTransaction();
Event event = null;
CounterGroup counterGroup = getCounterGroup();
long batchSize = getBatchSize();
long eventCounter = counterGroup.get("events.success");
try {
transaction.begin();
int i = 0;
for (i = 0; i < batchSize; i++) {
event = channel.take();
if (event != null) {
long id = Long.parseLong(new String(event.getBody()));
total += id;
event.getHeaders().put("Total", Long.toString(total));
eventProcessor.processEvent(event);
logger.info("Null sink {} successful processed event {}", getName(), id);
} else {
status = Status.BACKOFF;
break;
}
}
transaction.commit();
counterGroup.addAndGet("events.success", (long) Math.min(batchSize, i));
counterGroup.incrementAndGet("transaction.success");
} catch (Exception ex) {
transaction.rollback();
counterGroup.incrementAndGet("transaction.failed");
logger.error("Failed to deliver event. Exception follows.", ex);
throw new EventDeliveryException("Failed to deliver event: " + event, ex);
} finally {
transaction.close();
}
return status;
}
}