diff --git a/flume-config-filters/flume-config-filter-api/src/main/java/org/apache/flume/configfilter/ConfigFilterProvider.java b/flume-config-filters/flume-config-filter-api/src/main/java/org/apache/flume/configfilter/ConfigFilterProvider.java new file mode 100644 index 0000000000..784b7d1dbb --- /dev/null +++ b/flume-config-filters/flume-config-filter-api/src/main/java/org/apache/flume/configfilter/ConfigFilterProvider.java @@ -0,0 +1,38 @@ +/* + * 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. + */ +package org.apache.flume.configfilter; + +/** + * Provides one configuration filter type, selected by the {@code type} property of the filter configuration. + * + *

Providers are discovered with {@link java.util.ServiceLoader}: + * register implementations in {@code META-INF/services/org.apache.flume.configfilter.ConfigFilterProvider}. + */ +public interface ConfigFilterProvider { + + /** + * Returns the value of the {@code type} configuration property that selects this provider. + * + *

Types are compared case-insensitively. + */ + String getName(); + + /** + * Returns the filter class, which must have a public no-argument constructor. + */ + Class getComponentClass(); +} diff --git a/flume-core/pom.xml b/flume-core/pom.xml index 76f2ef9d05..79574fd7c0 100644 --- a/flume-core/pom.xml +++ b/flume-core/pom.xml @@ -67,6 +67,11 @@ log4j-api + + biz.aQute.bnd + biz.aQute.bnd.annotation + + com.google.guava guava diff --git a/flume-core/src/main/java/org/apache/flume/channel/ChannelSelectorFactory.java b/flume-core/src/main/java/org/apache/flume/channel/ChannelSelectorFactory.java index 563c944f9e..960649f385 100644 --- a/flume-core/src/main/java/org/apache/flume/channel/ChannelSelectorFactory.java +++ b/flume-core/src/main/java/org/apache/flume/channel/ChannelSelectorFactory.java @@ -16,23 +16,34 @@ */ package org.apache.flume.channel; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import java.util.List; -import java.util.Locale; import java.util.Map; import org.apache.flume.Channel; import org.apache.flume.ChannelSelector; import org.apache.flume.Context; -import org.apache.flume.FlumeException; import org.apache.flume.conf.BasicConfigurationConstants; +import org.apache.flume.conf.ComponentWithClassName; import org.apache.flume.conf.Configurables; import org.apache.flume.conf.channel.ChannelSelectorConfiguration; import org.apache.flume.conf.channel.ChannelSelectorType; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.flume.spi.ChannelSelectorProvider; +import org.apache.flume.spi.ComponentRegistry; +@ServiceConsumer( + value = ChannelSelectorProvider.class, + resolution = Resolution.OPTIONAL, + cardinality = Cardinality.MULTIPLE) public class ChannelSelectorFactory { - private static final Logger logger = LogManager.getLogger(); + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = new ComponentRegistry<>( + ChannelSelectorProvider.class, + ChannelSelector.class, + "channel selector", + type -> ComponentWithClassName.getClassName(ChannelSelectorType.class, type)); public static ChannelSelector create(List channels, Map config) { @@ -62,31 +73,6 @@ private static ChannelSelector getSelectorForType(String type) { if (type == null || type.trim().length() == 0) { return new ReplicatingChannelSelector(); } - - String selectorClassName = type; - ChannelSelectorType selectorType = ChannelSelectorType.OTHER; - - try { - selectorType = ChannelSelectorType.valueOf(type.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException ex) { - logger.debug("Selector type {} is a custom type", type); - } - - if (!selectorType.equals(ChannelSelectorType.OTHER)) { - selectorClassName = selectorType.getChannelSelectorClassName(); - } - - ChannelSelector selector = null; - - try { - @SuppressWarnings("unchecked") - Class selectorClass = - (Class) Class.forName(selectorClassName); - selector = selectorClass.newInstance(); - } catch (Exception ex) { - throw new FlumeException("Unable to load selector type: " + type + ", class: " + selectorClassName, ex); - } - - return selector; + return REGISTRY.newInstance(type); } } diff --git a/flume-core/src/main/java/org/apache/flume/channel/DefaultChannelFactory.java b/flume-core/src/main/java/org/apache/flume/channel/DefaultChannelFactory.java index edd6d7b4cf..00341cbf89 100644 --- a/flume-core/src/main/java/org/apache/flume/channel/DefaultChannelFactory.java +++ b/flume-core/src/main/java/org/apache/flume/channel/DefaultChannelFactory.java @@ -16,50 +16,43 @@ */ package org.apache.flume.channel; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; -import java.util.Locale; import org.apache.flume.Channel; import org.apache.flume.ChannelFactory; import org.apache.flume.FlumeException; +import org.apache.flume.conf.ComponentWithClassName; import org.apache.flume.conf.channel.ChannelType; +import org.apache.flume.spi.ChannelProvider; +import org.apache.flume.spi.ComponentRegistry; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +@ServiceConsumer(value = ChannelProvider.class, resolution = Resolution.OPTIONAL, cardinality = Cardinality.MULTIPLE) public class DefaultChannelFactory implements ChannelFactory { private static final Logger logger = LogManager.getLogger(); + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = new ComponentRegistry<>( + ChannelProvider.class, + Channel.class, + "channel", + type -> ComponentWithClassName.getClassName(ChannelType.class, type)); + @Override public Channel create(String name, String type) throws FlumeException { Preconditions.checkNotNull(name, "name"); Preconditions.checkNotNull(type, "type"); - logger.info("Creating instance of channel {} type {}", name, type); - Class channelClass = getClass(type); - try { - return channelClass.newInstance(); - } catch (Exception ex) { - throw new FlumeException( - "Unable to create channel: " + name + ", type: " + type + ", class: " + channelClass.getName(), ex); - } + logger.info("Creating instance of channel {}, type {}", name, type); + return REGISTRY.newInstance(type); } - @SuppressWarnings("unchecked") @Override public Class getClass(String type) throws FlumeException { - String channelClassName = type; - ChannelType channelType = ChannelType.OTHER; - try { - channelType = ChannelType.valueOf(type.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException ex) { - logger.debug("Channel type {} is a custom type", type); - } - if (!channelType.equals(ChannelType.OTHER)) { - channelClassName = channelType.getChannelClassName(); - } - try { - return (Class) Class.forName(channelClassName); - } catch (Exception ex) { - throw new FlumeException("Unable to load channel type: " + type + ", class: " + channelClassName, ex); - } + Preconditions.checkNotNull(type, "type"); + return REGISTRY.getComponentClass(type); } } diff --git a/flume-core/src/main/java/org/apache/flume/channel/LoadBalancingChannelSelector.java b/flume-core/src/main/java/org/apache/flume/channel/LoadBalancingChannelSelector.java index dd4cb2cb46..580298eccb 100644 --- a/flume-core/src/main/java/org/apache/flume/channel/LoadBalancingChannelSelector.java +++ b/flume-core/src/main/java/org/apache/flume/channel/LoadBalancingChannelSelector.java @@ -16,6 +16,8 @@ */ package org.apache.flume.channel; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.util.Collections; @@ -23,9 +25,12 @@ import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import org.apache.flume.Channel; +import org.apache.flume.ChannelSelector; import org.apache.flume.Context; import org.apache.flume.conf.internal.SuppressFBWarnings; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.ChannelSelectorProvider; /** * Load balancing channel selector. This selector allows for load balancing @@ -143,4 +148,16 @@ public Channel getChannel() { return channels.get(pick); } } + + /** + * Provides the {@code load_balancing} channel selector type. + */ + @ServiceProvider(value = ChannelSelectorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements ChannelSelectorProvider { + + public Provider() { + super("load_balancing", LoadBalancingChannelSelector.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/channel/MemoryChannel.java b/flume-core/src/main/java/org/apache/flume/channel/MemoryChannel.java index 498b54b9b8..200d45022b 100644 --- a/flume-core/src/main/java/org/apache/flume/channel/MemoryChannel.java +++ b/flume-core/src/main/java/org/apache/flume/channel/MemoryChannel.java @@ -16,12 +16,15 @@ */ package org.apache.flume.channel; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.GuardedBy; +import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.annotations.InterfaceAudience; import org.apache.flume.annotations.InterfaceStability; @@ -31,6 +34,8 @@ import org.apache.flume.exception.ChannelException; import org.apache.flume.exception.ChannelFullException; import org.apache.flume.instrumentation.ChannelCounter; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.ChannelProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -396,4 +401,15 @@ int getBytesRemainingValue() { public long getTransactionCapacity() { return transCapacity; } + + /** + * Provides the {@code memory} channel type. + */ + @ServiceProvider(value = ChannelProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider implements ChannelProvider { + + public Provider() { + super("memory", MemoryChannel.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java b/flume-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java index 1d1fd6ae7e..5e24cdefdd 100644 --- a/flume-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java +++ b/flume-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java @@ -16,15 +16,20 @@ */ package org.apache.flume.channel; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.flume.Channel; +import org.apache.flume.ChannelSelector; import org.apache.flume.Context; import org.apache.flume.FlumeException; import org.apache.flume.conf.internal.SuppressFBWarnings; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.ChannelSelectorProvider; @SuppressFBWarnings("UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") public class MultiplexingChannelSelector extends AbstractChannelSelector { @@ -126,4 +131,16 @@ public void configure(Context context) { } } } + + /** + * Provides the {@code multiplexing} channel selector type. + */ + @ServiceProvider(value = ChannelSelectorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements ChannelSelectorProvider { + + public Provider() { + super("multiplexing", MultiplexingChannelSelector.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/channel/ReplicatingChannelSelector.java b/flume-core/src/main/java/org/apache/flume/channel/ReplicatingChannelSelector.java index bee2503f70..2594e6af0c 100644 --- a/flume-core/src/main/java/org/apache/flume/channel/ReplicatingChannelSelector.java +++ b/flume-core/src/main/java/org/apache/flume/channel/ReplicatingChannelSelector.java @@ -16,12 +16,17 @@ */ package org.apache.flume.channel; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.flume.Channel; +import org.apache.flume.ChannelSelector; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.ChannelSelectorProvider; /** * Replicating channel selector. This selector allows the event to be placed @@ -70,4 +75,16 @@ public void configure(Context context) { } } } + + /** + * Provides the {@code replicating} channel selector type. + */ + @ServiceProvider(value = ChannelSelectorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements ChannelSelectorProvider { + + public Provider() { + super("replicating", ReplicatingChannelSelector.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/channel/RoutableProxyChannelSelector.java b/flume-core/src/main/java/org/apache/flume/channel/RoutableProxyChannelSelector.java index 074895a275..0c405d7c1f 100644 --- a/flume-core/src/main/java/org/apache/flume/channel/RoutableProxyChannelSelector.java +++ b/flume-core/src/main/java/org/apache/flume/channel/RoutableProxyChannelSelector.java @@ -16,6 +16,8 @@ */ package org.apache.flume.channel; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -29,6 +31,8 @@ import org.apache.flume.Context; import org.apache.flume.conf.Configurables; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.ChannelSelectorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -124,4 +128,16 @@ private String getRequiredNonNull(Map map, String keyName, Strin } return value; } + + /** + * Provides the {@code routable_proxy} channel selector type. + */ + @ServiceProvider(value = ChannelSelectorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements ChannelSelectorProvider { + + public Provider() { + super("routable_proxy", RoutableProxyChannelSelector.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/conf/ComponentWithClassName.java b/flume-core/src/main/java/org/apache/flume/conf/ComponentWithClassName.java index 140e5b977f..6821518120 100644 --- a/flume-core/src/main/java/org/apache/flume/conf/ComponentWithClassName.java +++ b/flume-core/src/main/java/org/apache/flume/conf/ComponentWithClassName.java @@ -16,6 +16,21 @@ */ package org.apache.flume.conf; +import java.util.Locale; + public interface ComponentWithClassName { String getClassName(); + + /** + * Returns the class name of the enum constant named by a case-insensitive alias. + * + * @return the class name, or {@code null} if the alias is unknown or has no class. + */ + static & ComponentWithClassName> String getClassName(Class enumType, String alias) { + try { + return Enum.valueOf(enumType, alias.toUpperCase(Locale.ROOT)).getClassName(); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/conf/ConfigFilterFactory.java b/flume-core/src/main/java/org/apache/flume/conf/ConfigFilterFactory.java index 731f8cec80..4ba6b3c51b 100644 --- a/flume-core/src/main/java/org/apache/flume/conf/ConfigFilterFactory.java +++ b/flume-core/src/main/java/org/apache/flume/conf/ConfigFilterFactory.java @@ -16,48 +16,46 @@ */ package org.apache.flume.conf; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; -import java.util.Locale; import org.apache.flume.FlumeException; import org.apache.flume.conf.configfilter.ConfigFilterType; import org.apache.flume.configfilter.ConfigFilter; +import org.apache.flume.configfilter.ConfigFilterProvider; +import org.apache.flume.spi.ComponentRegistry; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +@ServiceConsumer( + value = ConfigFilterProvider.class, + resolution = Resolution.OPTIONAL, + cardinality = Cardinality.MULTIPLE) public class ConfigFilterFactory { private static final Logger logger = LogManager.getLogger(); + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = ComponentRegistry.of( + ConfigFilterProvider.class, + ConfigFilterProvider::getName, + ConfigFilterProvider::getComponentClass, + ConfigFilter.class, + "configfilter", + type -> ComponentWithClassName.getClassName(ConfigFilterType.class, type)); + public static ConfigFilter create(String name, String type) throws FlumeException { Preconditions.checkNotNull(name, "name"); Preconditions.checkNotNull(type, "type"); logger.info("Creating instance of configfilter {}, type {}", name, type); - Class aClass = getClass(type); - try { - ConfigFilter configFilter = aClass.newInstance(); - configFilter.setName(name); - return configFilter; - } catch (Exception ex) { - throw new FlumeException( - "Unable to create configfilter: " + name + ", type: " + type + ", class: " + aClass.getName(), ex); - } + ConfigFilter configFilter = REGISTRY.newInstance(type); + configFilter.setName(name); + return configFilter; } public static Class getClass(String type) throws FlumeException { - String classname = type; - ConfigFilterType srcType = ConfigFilterType.OTHER; - try { - srcType = ConfigFilterType.valueOf(type.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException ex) { - logger.debug("Configfilter type {} is a custom type", type); - } - if (srcType != ConfigFilterType.OTHER) { - classname = srcType.getClassName(); - } - try { - return (Class) Class.forName(classname); - } catch (Exception ex) { - throw new FlumeException("Unable to load configfilter type: " + type + ", class: " + classname, ex); - } + Preconditions.checkNotNull(type, "type"); + return REGISTRY.getComponentClass(type); } } diff --git a/flume-core/src/main/java/org/apache/flume/formatter/output/DefaultPathManager.java b/flume-core/src/main/java/org/apache/flume/formatter/output/DefaultPathManager.java index 984c0b9be0..172ea2433c 100644 --- a/flume-core/src/main/java/org/apache/flume/formatter/output/DefaultPathManager.java +++ b/flume-core/src/main/java/org/apache/flume/formatter/output/DefaultPathManager.java @@ -16,9 +16,13 @@ */ package org.apache.flume.formatter.output; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.io.File; import java.util.concurrent.atomic.AtomicInteger; import org.apache.flume.Context; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.PathManagerProvider; public class DefaultPathManager implements PathManager { @@ -101,4 +105,16 @@ public PathManager build(Context context) { return new DefaultPathManager(context); } } + + /** + * Provides the {@code default} path manager type. + */ + @ServiceProvider(value = PathManagerProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements PathManagerProvider { + + public Provider() { + super("default", DefaultPathManager.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/formatter/output/PathManagerFactory.java b/flume-core/src/main/java/org/apache/flume/formatter/output/PathManagerFactory.java index b6d3a017cb..7dc705be1b 100644 --- a/flume-core/src/main/java/org/apache/flume/formatter/output/PathManagerFactory.java +++ b/flume-core/src/main/java/org/apache/flume/formatter/output/PathManagerFactory.java @@ -16,64 +16,28 @@ */ package org.apache.flume.formatter.output; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; -import java.util.Locale; import org.apache.flume.Context; -import org.apache.flume.FlumeException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.flume.spi.ComponentRegistry; +import org.apache.flume.spi.PathManagerProvider; /** * Create PathManager instances. */ +@ServiceConsumer( + value = PathManagerProvider.class, + resolution = Resolution.OPTIONAL, + cardinality = Cardinality.MULTIPLE) public class PathManagerFactory { - private static final Logger logger = LogManager.getLogger(); - public static PathManager getInstance(String managerType, Context context) { + private static final ComponentRegistry REGISTRY = + new ComponentRegistry<>(PathManagerProvider.class, PathManager.Builder.class, "path manager"); + public static PathManager getInstance(String managerType, Context context) { Preconditions.checkNotNull(managerType, "path manager type must not be null"); - - // try to find builder class in enum of known output serializers - PathManagerType type; - try { - type = PathManagerType.valueOf(managerType.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException e) { - logger.debug("Not in enum, loading builder class: {}", managerType); - type = PathManagerType.OTHER; - } - Class builderClass = type.getBuilderClass(); - - // handle the case where they have specified their own builder in the config - if (builderClass == null) { - try { - Class c = Class.forName(managerType); - if (c != null && PathManager.Builder.class.isAssignableFrom(c)) { - builderClass = (Class) c; - } else { - String errMessage = "Unable to instantiate Builder from " + managerType - + ": does not appear to implement " + PathManager.Builder.class.getName(); - throw new FlumeException(errMessage); - } - } catch (ClassNotFoundException ex) { - logger.error("Class not found: " + managerType, ex); - throw new FlumeException(ex); - } - } - - // build the builder - PathManager.Builder builder; - try { - builder = builderClass.newInstance(); - } catch (InstantiationException ex) { - String errMessage = "Cannot instantiate builder: " + managerType; - logger.error(errMessage, ex); - throw new FlumeException(errMessage, ex); - } catch (IllegalAccessException ex) { - String errMessage = "Cannot instantiate builder: " + managerType; - logger.error(errMessage, ex); - throw new FlumeException(errMessage, ex); - } - - return builder.build(context); + return REGISTRY.newInstance(managerType).build(context); } } diff --git a/flume-core/src/main/java/org/apache/flume/formatter/output/RollTimePathManager.java b/flume-core/src/main/java/org/apache/flume/formatter/output/RollTimePathManager.java index 2b71f40947..b2ad14fde3 100644 --- a/flume-core/src/main/java/org/apache/flume/formatter/output/RollTimePathManager.java +++ b/flume-core/src/main/java/org/apache/flume/formatter/output/RollTimePathManager.java @@ -16,10 +16,14 @@ */ package org.apache.flume.formatter.output; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import org.apache.flume.Context; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.PathManagerProvider; /** * @@ -57,4 +61,16 @@ public PathManager build(Context context) { return new RollTimePathManager(context); } } + + /** + * Provides the {@code rolltime} path manager type. + */ + @ServiceProvider(value = PathManagerProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements PathManagerProvider { + + public Provider() { + super("rolltime", RollTimePathManager.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/HostInterceptor.java b/flume-core/src/main/java/org/apache/flume/interceptor/HostInterceptor.java index 8ee4ac5402..96ee14a03c 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/HostInterceptor.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/HostInterceptor.java @@ -23,12 +23,16 @@ import static org.apache.flume.interceptor.HostInterceptor.Constants.USE_IP; import static org.apache.flume.interceptor.HostInterceptor.Constants.USE_IP_DFLT; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.InterceptorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -163,4 +167,16 @@ public static class Constants { public static String HOST_HEADER = "hostHeader"; } + + /** + * Provides the {@code host} interceptor type. + */ + @ServiceProvider(value = InterceptorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements InterceptorProvider { + + public Provider() { + super("host", HostInterceptor.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/InterceptorBuilderFactory.java b/flume-core/src/main/java/org/apache/flume/interceptor/InterceptorBuilderFactory.java index 17035fb1a9..1bc8a4bb42 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/InterceptorBuilderFactory.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/InterceptorBuilderFactory.java @@ -16,33 +16,32 @@ */ package org.apache.flume.interceptor; -import java.util.Locale; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import org.apache.flume.interceptor.Interceptor.Builder; +import org.apache.flume.spi.ComponentRegistry; +import org.apache.flume.spi.InterceptorProvider; /** - * Factory used to register instances of Interceptors & their builders, - * as well as to instantiate the builders. + * Factory used to instantiate interceptor builders. */ +@ServiceConsumer( + value = InterceptorProvider.class, + resolution = Resolution.OPTIONAL, + cardinality = Cardinality.MULTIPLE) public class InterceptorBuilderFactory { - private static Class lookup(String name) { - try { - return InterceptorType.valueOf(name.toUpperCase(Locale.ENGLISH)).getBuilderClass(); - } catch (IllegalArgumentException e) { - return null; - } - } + private static final ComponentRegistry REGISTRY = + new ComponentRegistry<>(InterceptorProvider.class, Builder.class, "interceptor"); /** * Instantiate specified class, either alias or fully-qualified class name. + * + * @throws org.apache.flume.FlumeException if the type is unknown or the builder cannot be instantiated. */ public static Builder newInstance(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException { - - Class clazz = lookup(name); - if (clazz == null) { - clazz = (Class) Class.forName(name); - } - return clazz.newInstance(); + return REGISTRY.newInstance(name); } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/RegexExtractorInterceptor.java b/flume-core/src/main/java/org/apache/flume/interceptor/RegexExtractorInterceptor.java index a447f04e87..38250e895e 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/RegexExtractorInterceptor.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/RegexExtractorInterceptor.java @@ -16,6 +16,8 @@ */ package org.apache.flume.interceptor; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; @@ -27,6 +29,8 @@ import org.apache.commons.lang3.StringUtils; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.InterceptorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -225,4 +229,16 @@ public NameAndSerializer(String headerName, RegexExtractorInterceptorSerializer this.serializer = serializer; } } + + /** + * Provides the {@code regex_extractor} interceptor type. + */ + @ServiceProvider(value = InterceptorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements InterceptorProvider { + + public Provider() { + super("regex_extractor", RegexExtractorInterceptor.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/RegexFilteringInterceptor.java b/flume-core/src/main/java/org/apache/flume/interceptor/RegexFilteringInterceptor.java index ba31aa0298..b77caaceea 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/RegexFilteringInterceptor.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/RegexFilteringInterceptor.java @@ -21,11 +21,15 @@ import static org.apache.flume.interceptor.RegexFilteringInterceptor.Constants.EXCLUDE_EVENTS; import static org.apache.flume.interceptor.RegexFilteringInterceptor.Constants.REGEX; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.collect.Lists; import java.util.List; import java.util.regex.Pattern; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.InterceptorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -163,4 +167,16 @@ public static class Constants { public static final String EXCLUDE_EVENTS = "excludeEvents"; public static final boolean DEFAULT_EXCLUDE_EVENTS = false; } + + /** + * Provides the {@code regex_filter} interceptor type. + */ + @ServiceProvider(value = InterceptorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements InterceptorProvider { + + public Provider() { + super("regex_filter", RegexFilteringInterceptor.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/RemoveHeaderInterceptor.java b/flume-core/src/main/java/org/apache/flume/interceptor/RemoveHeaderInterceptor.java index 041339bbe5..f54fbf65bb 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/RemoveHeaderInterceptor.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/RemoveHeaderInterceptor.java @@ -16,6 +16,8 @@ */ package org.apache.flume.interceptor; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; @@ -28,6 +30,8 @@ import org.apache.flume.Context; import org.apache.flume.conf.LogPrivacyUtil; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.InterceptorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -173,4 +177,16 @@ public void configure(final Context context) { } } } + + /** + * Provides the {@code remove_header} interceptor type. + */ + @ServiceProvider(value = InterceptorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements InterceptorProvider { + + public Provider() { + super("remove_header", RemoveHeaderInterceptor.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/SearchAndReplaceInterceptor.java b/flume-core/src/main/java/org/apache/flume/interceptor/SearchAndReplaceInterceptor.java index 5b087f092f..18dfcf2786 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/SearchAndReplaceInterceptor.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/SearchAndReplaceInterceptor.java @@ -16,6 +16,8 @@ */ package org.apache.flume.interceptor; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import java.nio.charset.Charset; @@ -25,6 +27,8 @@ import org.apache.commons.lang3.StringUtils; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.InterceptorProvider; /** *

@@ -115,4 +119,16 @@ public Interceptor build() { return new SearchAndReplaceInterceptor(searchRegex, replaceString, charset); } } + + /** + * Provides the {@code search_replace} interceptor type. + */ + @ServiceProvider(value = InterceptorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements InterceptorProvider { + + public Provider() { + super("search_replace", SearchAndReplaceInterceptor.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/StaticInterceptor.java b/flume-core/src/main/java/org/apache/flume/interceptor/StaticInterceptor.java index 91e2573130..81483498a7 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/StaticInterceptor.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/StaticInterceptor.java @@ -16,10 +16,14 @@ */ package org.apache.flume.interceptor; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.util.List; import java.util.Map; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.InterceptorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -139,4 +143,16 @@ public static class Constants { public static final String PRESERVE = "preserveExisting"; public static final boolean PRESERVE_DEFAULT = true; } + + /** + * Provides the {@code static} interceptor type. + */ + @ServiceProvider(value = InterceptorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements InterceptorProvider { + + public Provider() { + super("static", StaticInterceptor.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/interceptor/TimestampInterceptor.java b/flume-core/src/main/java/org/apache/flume/interceptor/TimestampInterceptor.java index 233c0d8be6..21963cf30a 100644 --- a/flume-core/src/main/java/org/apache/flume/interceptor/TimestampInterceptor.java +++ b/flume-core/src/main/java/org/apache/flume/interceptor/TimestampInterceptor.java @@ -21,10 +21,14 @@ import static org.apache.flume.interceptor.TimestampInterceptor.Constants.DEFAULT_HEADER_NAME; import static org.apache.flume.interceptor.TimestampInterceptor.Constants.DEFAULT_PRESERVE; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.util.List; import java.util.Map; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.InterceptorProvider; /** * Simple Interceptor class that sets the current system timestamp on all events @@ -111,4 +115,16 @@ public static class Constants { public static final String CONFIG_HEADER_NAME = "headerName"; public static final String DEFAULT_HEADER_NAME = "timestamp"; } + + /** + * Provides the {@code timestamp} interceptor type. + */ + @ServiceProvider(value = InterceptorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements InterceptorProvider { + + public Provider() { + super("timestamp", TimestampInterceptor.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/serialization/BodyTextEventSerializer.java b/flume-core/src/main/java/org/apache/flume/serialization/BodyTextEventSerializer.java index 911f9794e0..c875f17db3 100644 --- a/flume-core/src/main/java/org/apache/flume/serialization/BodyTextEventSerializer.java +++ b/flume-core/src/main/java/org/apache/flume/serialization/BodyTextEventSerializer.java @@ -16,10 +16,14 @@ */ package org.apache.flume.serialization; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.io.IOException; import java.io.OutputStream; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.EventSerializerProvider; /** * This class simply writes the body of the event to the output stream @@ -80,4 +84,16 @@ public EventSerializer build(Context context, OutputStream out) { return s; } } + + /** + * Provides the {@code text} event serializer type. + */ + @ServiceProvider(value = EventSerializerProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements EventSerializerProvider { + + public Provider() { + super("text", BodyTextEventSerializer.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/serialization/EventDeserializerFactory.java b/flume-core/src/main/java/org/apache/flume/serialization/EventDeserializerFactory.java index fab1160daf..5ba3354349 100644 --- a/flume-core/src/main/java/org/apache/flume/serialization/EventDeserializerFactory.java +++ b/flume-core/src/main/java/org/apache/flume/serialization/EventDeserializerFactory.java @@ -16,66 +16,44 @@ */ package org.apache.flume.serialization; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; import java.util.Locale; import org.apache.flume.Context; -import org.apache.flume.FlumeException; import org.apache.flume.annotations.InterfaceAudience; import org.apache.flume.annotations.InterfaceStability; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.flume.spi.ComponentRegistry; +import org.apache.flume.spi.EventDeserializerProvider; @InterfaceAudience.Private @InterfaceStability.Stable +@ServiceConsumer( + value = EventDeserializerProvider.class, + resolution = Resolution.OPTIONAL, + cardinality = Cardinality.MULTIPLE) public class EventDeserializerFactory { - private static final Logger logger = LogManager.getLogger(); + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = new ComponentRegistry<>( + EventDeserializerProvider.class, + EventDeserializer.Builder.class, + "event deserializer", + EventDeserializerFactory::getLegacyClassName); public static EventDeserializer getInstance(String deserializerType, Context context, ResettableInputStream in) { + Preconditions.checkNotNull(deserializerType, "deserializer type must not be null"); + return REGISTRY.newInstance(deserializerType).build(context, in); + } - Preconditions.checkNotNull(deserializerType, "serializer type must not be null"); - - // try to find builder class in enum of known output serializers - EventDeserializerType type; + private static String getLegacyClassName(String type) { try { - type = EventDeserializerType.valueOf(deserializerType.toUpperCase(Locale.ENGLISH)); + Class builderClass = + EventDeserializerType.valueOf(type.toUpperCase(Locale.ROOT)).getBuilderClass(); + return builderClass != null ? builderClass.getName() : null; } catch (IllegalArgumentException e) { - logger.debug("Not in enum, loading builder class: {}", deserializerType); - type = EventDeserializerType.OTHER; - } - Class builderClass = type.getBuilderClass(); - - // handle the case where they have specified their own builder in the config - if (builderClass == null) { - try { - Class c = Class.forName(deserializerType); - if (c != null && EventDeserializer.Builder.class.isAssignableFrom(c)) { - builderClass = (Class) c; - } else { - String errMessage = "Unable to instantiate Builder from " + deserializerType - + ": does not appear to implement " + EventDeserializer.Builder.class.getName(); - throw new FlumeException(errMessage); - } - } catch (ClassNotFoundException ex) { - logger.error("Class not found: " + deserializerType, ex); - throw new FlumeException(ex); - } + return null; } - - // build the builder - EventDeserializer.Builder builder; - try { - builder = builderClass.newInstance(); - } catch (InstantiationException ex) { - String errMessage = "Cannot instantiate builder: " + deserializerType; - logger.error(errMessage, ex); - throw new FlumeException(errMessage, ex); - } catch (IllegalAccessException ex) { - String errMessage = "Cannot instantiate builder: " + deserializerType; - logger.error(errMessage, ex); - throw new FlumeException(errMessage, ex); - } - - return builder.build(context, in); } } diff --git a/flume-core/src/main/java/org/apache/flume/serialization/EventSerializerFactory.java b/flume-core/src/main/java/org/apache/flume/serialization/EventSerializerFactory.java index d0873c5765..ac3309ac9d 100644 --- a/flume-core/src/main/java/org/apache/flume/serialization/EventSerializerFactory.java +++ b/flume-core/src/main/java/org/apache/flume/serialization/EventSerializerFactory.java @@ -16,67 +16,45 @@ */ package org.apache.flume.serialization; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; import java.io.OutputStream; import java.util.Locale; import org.apache.flume.Context; -import org.apache.flume.FlumeException; import org.apache.flume.annotations.InterfaceAudience; import org.apache.flume.annotations.InterfaceStability; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.flume.spi.ComponentRegistry; +import org.apache.flume.spi.EventSerializerProvider; @InterfaceAudience.Private @InterfaceStability.Stable +@ServiceConsumer( + value = EventSerializerProvider.class, + resolution = Resolution.OPTIONAL, + cardinality = Cardinality.MULTIPLE) public class EventSerializerFactory { - private static final Logger logger = LogManager.getLogger(); + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = new ComponentRegistry<>( + EventSerializerProvider.class, + EventSerializer.Builder.class, + "event serializer", + EventSerializerFactory::getLegacyClassName); public static EventSerializer getInstance(String serializerType, Context context, OutputStream out) { - Preconditions.checkNotNull(serializerType, "serializer type must not be null"); + return REGISTRY.newInstance(serializerType).build(context, out); + } - // try to find builder class in enum of known output serializers - EventSerializerType type; + private static String getLegacyClassName(String type) { try { - type = EventSerializerType.valueOf(serializerType.toUpperCase(Locale.ENGLISH)); + Class builderClass = + EventSerializerType.valueOf(type.toUpperCase(Locale.ROOT)).getBuilderClass(); + return builderClass != null ? builderClass.getName() : null; } catch (IllegalArgumentException e) { - logger.debug("Not in enum, loading builder class: {}", serializerType); - type = EventSerializerType.OTHER; - } - Class builderClass = type.getBuilderClass(); - - // handle the case where they have specified their own builder in the config - if (builderClass == null) { - try { - Class c = Class.forName(serializerType); - if (c != null && EventSerializer.Builder.class.isAssignableFrom(c)) { - builderClass = (Class) c; - } else { - String errMessage = "Unable to instantiate Builder from " + serializerType - + ": does not appear to implement " + EventSerializer.Builder.class.getName(); - throw new FlumeException(errMessage); - } - } catch (ClassNotFoundException ex) { - logger.error("Class not found: " + serializerType, ex); - throw new FlumeException(ex); - } + return null; } - - // build the builder - EventSerializer.Builder builder; - try { - builder = builderClass.newInstance(); - } catch (InstantiationException ex) { - String errMessage = "Cannot instantiate builder: " + serializerType; - logger.error(errMessage, ex); - throw new FlumeException(errMessage, ex); - } catch (IllegalAccessException ex) { - String errMessage = "Cannot instantiate builder: " + serializerType; - logger.error(errMessage, ex); - throw new FlumeException(errMessage, ex); - } - - return builder.build(context, out); } } diff --git a/flume-core/src/main/java/org/apache/flume/serialization/HeaderAndBodyTextEventSerializer.java b/flume-core/src/main/java/org/apache/flume/serialization/HeaderAndBodyTextEventSerializer.java index 1a0dda42a5..2c7cdc6c99 100644 --- a/flume-core/src/main/java/org/apache/flume/serialization/HeaderAndBodyTextEventSerializer.java +++ b/flume-core/src/main/java/org/apache/flume/serialization/HeaderAndBodyTextEventSerializer.java @@ -16,10 +16,14 @@ */ package org.apache.flume.serialization; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.io.IOException; import java.io.OutputStream; import org.apache.flume.Context; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.EventSerializerProvider; /** * This class simply writes the body of the event to the output stream @@ -81,4 +85,16 @@ public EventSerializer build(Context context, OutputStream out) { return s; } } + + /** + * Provides the {@code header_and_text} event serializer type. + */ + @ServiceProvider(value = EventSerializerProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements EventSerializerProvider { + + public Provider() { + super("header_and_text", HeaderAndBodyTextEventSerializer.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/serialization/LineDeserializer.java b/flume-core/src/main/java/org/apache/flume/serialization/LineDeserializer.java index 2745b7f74f..a5a0b3f2b5 100644 --- a/flume-core/src/main/java/org/apache/flume/serialization/LineDeserializer.java +++ b/flume-core/src/main/java/org/apache/flume/serialization/LineDeserializer.java @@ -16,6 +16,8 @@ */ package org.apache.flume.serialization; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.collect.Lists; import java.io.IOException; import java.nio.charset.Charset; @@ -25,6 +27,8 @@ import org.apache.flume.annotations.InterfaceStability; import org.apache.flume.event.Event; import org.apache.flume.event.EventBuilder; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.EventDeserializerProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -155,4 +159,16 @@ public EventDeserializer build(Context context, ResettableInputStream in) { return new LineDeserializer(context, in); } } + + /** + * Provides the {@code line} event deserializer type. + */ + @ServiceProvider(value = EventDeserializerProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements EventDeserializerProvider { + + public Provider() { + super("line", LineDeserializer.Builder.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java b/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java index 371f211b83..63a12c66b3 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java +++ b/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java @@ -16,52 +16,42 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; -import java.util.Locale; import org.apache.flume.FlumeException; import org.apache.flume.Sink; import org.apache.flume.SinkFactory; +import org.apache.flume.conf.ComponentWithClassName; import org.apache.flume.conf.sink.SinkType; +import org.apache.flume.spi.ComponentRegistry; +import org.apache.flume.spi.SinkProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +@ServiceConsumer(value = SinkProvider.class, resolution = Resolution.OPTIONAL, cardinality = Cardinality.MULTIPLE) public class DefaultSinkFactory implements SinkFactory { private static final Logger logger = LogManager.getLogger(); + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = new ComponentRegistry<>( + SinkProvider.class, Sink.class, "sink", type -> ComponentWithClassName.getClassName(SinkType.class, type)); + @Override public Sink create(String name, String type) throws FlumeException { Preconditions.checkNotNull(name, "name"); Preconditions.checkNotNull(type, "type"); - logger.info("Creating instance of sink: {}, type: {}", name, type); - Class sinkClass = getClass(type); - try { - Sink sink = sinkClass.newInstance(); - sink.setName(name); - return sink; - } catch (Exception ex) { - throw new FlumeException( - "Unable to create sink: " + name + ", type: " + type + ", class: " + sinkClass.getName(), ex); - } + logger.info("Creating instance of sink {}, type {}", name, type); + Sink sink = REGISTRY.newInstance(type); + sink.setName(name); + return sink; } - @SuppressWarnings("unchecked") @Override public Class getClass(String type) throws FlumeException { - String sinkClassName = type; - SinkType sinkType = SinkType.OTHER; - try { - sinkType = SinkType.valueOf(type.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException ex) { - logger.debug("Sink type {} is a custom type", type); - } - if (!sinkType.equals(SinkType.OTHER)) { - sinkClassName = sinkType.getSinkClassName(); - } - try { - return (Class) Class.forName(sinkClassName); - } catch (Exception ex) { - throw new FlumeException("Unable to load sink type: " + type + ", class: " + sinkClassName, ex); - } + Preconditions.checkNotNull(type, "type"); + return REGISTRY.getComponentClass(type); } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkProcessor.java b/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkProcessor.java index af90198cea..7d1b188c49 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkProcessor.java +++ b/flume-core/src/main/java/org/apache/flume/sink/DefaultSinkProcessor.java @@ -16,11 +16,16 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import org.apache.flume.Context; import org.apache.flume.EventDeliveryException; import org.apache.flume.Sink.Status; +import org.apache.flume.SinkProcessor; import org.apache.flume.conf.ComponentConfiguration; import org.apache.flume.conf.ConfigurableComponent; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SinkProcessorProvider; /** * Default sink processor that only accepts a single sink, passing on process @@ -39,4 +44,16 @@ public Status process() throws EventDeliveryException { @Override public void configure(ComponentConfiguration conf) {} + + /** + * Provides the {@code default} sink processor type. + */ + @ServiceProvider(value = SinkProcessorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements SinkProcessorProvider { + + public Provider() { + super("default", DefaultSinkProcessor.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/FailoverSinkProcessor.java b/flume-core/src/main/java/org/apache/flume/sink/FailoverSinkProcessor.java index b12f555c98..9bd2f5faa8 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/FailoverSinkProcessor.java +++ b/flume-core/src/main/java/org/apache/flume/sink/FailoverSinkProcessor.java @@ -16,6 +16,8 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -28,7 +30,10 @@ import org.apache.flume.EventDeliveryException; import org.apache.flume.Sink; import org.apache.flume.Sink.Status; +import org.apache.flume.SinkProcessor; import org.apache.flume.conf.internal.SuppressFBWarnings; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SinkProcessorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -216,4 +221,16 @@ public void setSinks(List sinks) { this.sinks.put(sink.getName(), sink); } } + + /** + * Provides the {@code failover} sink processor type. + */ + @ServiceProvider(value = SinkProcessorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements SinkProcessorProvider { + + public Provider() { + super("failover", FailoverSinkProcessor.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/LoadBalancingSinkProcessor.java b/flume-core/src/main/java/org/apache/flume/sink/LoadBalancingSinkProcessor.java index 4ee638c626..721c0d5430 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/LoadBalancingSinkProcessor.java +++ b/flume-core/src/main/java/org/apache/flume/sink/LoadBalancingSinkProcessor.java @@ -16,6 +16,8 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Preconditions; import java.util.Iterator; import java.util.List; @@ -24,9 +26,12 @@ import org.apache.flume.FlumeException; import org.apache.flume.Sink; import org.apache.flume.Sink.Status; +import org.apache.flume.SinkProcessor; import org.apache.flume.conf.Configurable; import org.apache.flume.conf.internal.SuppressFBWarnings; import org.apache.flume.lifecycle.LifecycleAware; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SinkProcessorProvider; import org.apache.flume.util.OrderSelector; import org.apache.flume.util.RandomOrderSelector; import org.apache.flume.util.RoundRobinOrderSelector; @@ -267,4 +272,16 @@ public void informSinkFailed(Sink failedSink) { selector.informFailure(failedSink); } } + + /** + * Provides the {@code load_balance} sink processor type. + */ + @ServiceProvider(value = SinkProcessorProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider + implements SinkProcessorProvider { + + public Provider() { + super("load_balance", LoadBalancingSinkProcessor.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/LoggerSink.java b/flume-core/src/main/java/org/apache/flume/sink/LoggerSink.java index 939dfb2602..2a99f226a0 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/LoggerSink.java +++ b/flume-core/src/main/java/org/apache/flume/sink/LoggerSink.java @@ -16,14 +16,19 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Strings; import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.EventDeliveryException; +import org.apache.flume.Sink; import org.apache.flume.Transaction; import org.apache.flume.conf.Configurable; import org.apache.flume.core.EventHelper; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SinkProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -105,4 +110,15 @@ public Status process() throws EventDeliveryException { return result; } + + /** + * Provides the {@code logger} sink type. + */ + @ServiceProvider(value = SinkProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider implements SinkProvider { + + public Provider() { + super("logger", LoggerSink.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/NullSink.java b/flume-core/src/main/java/org/apache/flume/sink/NullSink.java index 4c8470f497..065686094f 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/NullSink.java +++ b/flume-core/src/main/java/org/apache/flume/sink/NullSink.java @@ -16,6 +16,8 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Preconditions; import org.apache.flume.Channel; import org.apache.flume.Context; @@ -26,6 +28,8 @@ import org.apache.flume.conf.BatchSizeSupported; import org.apache.flume.conf.Configurable; import org.apache.flume.event.Event; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SinkProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -146,4 +150,15 @@ public int getLogEveryNEvents() { public long getBatchSize() { return batchSize; } + + /** + * Provides the {@code null} sink type. + */ + @ServiceProvider(value = SinkProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider implements SinkProvider { + + public Provider() { + super("null", NullSink.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/RollingFileSink.java b/flume-core/src/main/java/org/apache/flume/sink/RollingFileSink.java index 687490688c..4d1201d865 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/RollingFileSink.java +++ b/flume-core/src/main/java/org/apache/flume/sink/RollingFileSink.java @@ -16,6 +16,8 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.BufferedOutputStream; @@ -29,6 +31,7 @@ import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.EventDeliveryException; +import org.apache.flume.Sink; import org.apache.flume.Transaction; import org.apache.flume.conf.BatchSizeSupported; import org.apache.flume.conf.Configurable; @@ -38,6 +41,8 @@ import org.apache.flume.instrumentation.SinkCounter; import org.apache.flume.serialization.EventSerializer; import org.apache.flume.serialization.EventSerializerFactory; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SinkProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -280,4 +285,15 @@ public void setRollInterval(long rollInterval) { public long getBatchSize() { return batchSize; } + + /** + * Provides the {@code file_roll} sink type. + */ + @ServiceProvider(value = SinkProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider implements SinkProvider { + + public Provider() { + super("file_roll", RollingFileSink.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/sink/SinkProcessorFactory.java b/flume-core/src/main/java/org/apache/flume/sink/SinkProcessorFactory.java index d5f15d1d38..ad29cec34c 100644 --- a/flume-core/src/main/java/org/apache/flume/sink/SinkProcessorFactory.java +++ b/flume-core/src/main/java/org/apache/flume/sink/SinkProcessorFactory.java @@ -16,25 +16,42 @@ */ package org.apache.flume.sink; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; import java.util.List; -import java.util.Locale; -import java.util.Map; import org.apache.flume.Context; import org.apache.flume.FlumeException; import org.apache.flume.Sink; import org.apache.flume.SinkProcessor; import org.apache.flume.conf.ComponentConfiguration; +import org.apache.flume.conf.ComponentWithClassName; import org.apache.flume.conf.Configurables; import org.apache.flume.conf.sink.SinkProcessorType; +import org.apache.flume.spi.ComponentRegistry; +import org.apache.flume.spi.SinkProcessorProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +@ServiceConsumer( + value = SinkProcessorProvider.class, + resolution = Resolution.OPTIONAL, + cardinality = Cardinality.MULTIPLE) public class SinkProcessorFactory { private static final Logger logger = LogManager.getLogger(); private static final String TYPE = "type"; + private static final String DEFAULT_TYPE = "default"; + + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = new ComponentRegistry<>( + SinkProcessorProvider.class, + SinkProcessor.class, + "sink processor", + type -> ComponentWithClassName.getClassName(SinkProcessorType.class, type)); + /** *

* Creates a sink processor and configures it using the provided context @@ -50,73 +67,33 @@ public class SinkProcessorFactory { * @throws FlumeException Runtime exception thrown in the case of an invalid * processor configuration */ - @SuppressWarnings("unchecked") public static SinkProcessor getProcessor(Context context, List sinks) { Preconditions.checkNotNull(context); Preconditions.checkNotNull(sinks); Preconditions.checkArgument(!sinks.isEmpty()); - Map params = context.getParameters(); - SinkProcessor processor; - String typeStr = params.get(TYPE); - SinkProcessorType type = SinkProcessorType.OTHER; - String processorClassName = typeStr; - try { - type = SinkProcessorType.valueOf(typeStr.toUpperCase(Locale.ENGLISH)); - } catch (Exception ex) { - logger.warn("Sink Processor type {} is a custom type", typeStr); - } - - if (!type.equals(SinkProcessorType.OTHER)) { - processorClassName = type.getSinkProcessorClassName(); - } - - logger.debug("Creating instance of sink processor type {}, class {}", typeStr, processorClassName); - Class processorClass = null; - try { - processorClass = (Class) Class.forName(processorClassName); - } catch (Exception ex) { - throw new FlumeException( - "Unable to load sink processor type: " + typeStr + ", class: " + type.getSinkProcessorClassName(), - ex); + String typeStr = context.getParameters().get(TYPE); + if (typeStr == null) { + throw new FlumeException("Sink processor type not specified"); } - try { - processor = processorClass.newInstance(); - } catch (Exception e) { - throw new FlumeException( - "Unable to create sink processor, type: " + typeStr + ", class: " + processorClassName, e); - } - + logger.debug("Creating instance of sink processor type {}", typeStr); + SinkProcessor processor = REGISTRY.newInstance(typeStr); processor.setSinks(sinks); Configurables.configure(processor, context); return processor; } - @SuppressWarnings("unchecked") public static SinkProcessor getProcessor(ComponentConfiguration conf, List sinks) { String typeStr = conf.getType(); - SinkProcessor processor; - SinkProcessorType type = SinkProcessorType.DEFAULT; - try { - type = SinkProcessorType.valueOf(typeStr.toUpperCase(Locale.ENGLISH)); - } catch (Exception ex) { - logger.warn("Sink type {} does not exist, using default", typeStr); - } - - Class processorClass = null; - try { - processorClass = (Class) Class.forName(type.getSinkProcessorClassName()); - } catch (Exception ex) { - throw new FlumeException( - "Unable to load sink processor type: " + typeStr + ", class: " + type.getSinkProcessorClassName(), - ex); - } - try { - processor = processorClass.newInstance(); - } catch (Exception e) { - throw new FlumeException( - "Unable to create processor, type: " + typeStr + ", class: " + type.getSinkProcessorClassName(), e); + String type = DEFAULT_TYPE; + if (typeStr != null) { + try { + REGISTRY.getComponentClass(typeStr); + type = typeStr; + } catch (FlumeException ex) { + logger.warn("Sink processor type {} does not exist, using default", typeStr, ex); + } } - + SinkProcessor processor = REGISTRY.newInstance(type); processor.setSinks(sinks); Configurables.configure(processor, conf); return processor; diff --git a/flume-core/src/main/java/org/apache/flume/source/DefaultSourceFactory.java b/flume-core/src/main/java/org/apache/flume/source/DefaultSourceFactory.java index c66e1115d2..75d64207e9 100644 --- a/flume-core/src/main/java/org/apache/flume/source/DefaultSourceFactory.java +++ b/flume-core/src/main/java/org/apache/flume/source/DefaultSourceFactory.java @@ -16,52 +16,45 @@ */ package org.apache.flume.source; +import aQute.bnd.annotation.Cardinality; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceConsumer; import com.google.common.base.Preconditions; -import java.util.Locale; import org.apache.flume.FlumeException; import org.apache.flume.Source; import org.apache.flume.SourceFactory; +import org.apache.flume.conf.ComponentWithClassName; import org.apache.flume.conf.source.SourceType; +import org.apache.flume.spi.ComponentRegistry; +import org.apache.flume.spi.SourceProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +@ServiceConsumer(value = SourceProvider.class, resolution = Resolution.OPTIONAL, cardinality = Cardinality.MULTIPLE) public class DefaultSourceFactory implements SourceFactory { private static final Logger logger = LogManager.getLogger(); + @SuppressWarnings("deprecation") + private static final ComponentRegistry REGISTRY = new ComponentRegistry<>( + SourceProvider.class, + Source.class, + "source", + type -> ComponentWithClassName.getClassName(SourceType.class, type)); + @Override public Source create(String name, String type) throws FlumeException { Preconditions.checkNotNull(name, "name"); Preconditions.checkNotNull(type, "type"); logger.info("Creating instance of source {}, type {}", name, type); - Class sourceClass = getClass(type); - try { - Source source = sourceClass.newInstance(); - source.setName(name); - return source; - } catch (Exception ex) { - throw new FlumeException( - "Unable to create source: " + name + ", type: " + type + ", class: " + sourceClass.getName(), ex); - } + Source source = REGISTRY.newInstance(type); + source.setName(name); + return source; } - @SuppressWarnings("unchecked") @Override public Class getClass(String type) throws FlumeException { - String sourceClassName = type; - SourceType srcType = SourceType.OTHER; - try { - srcType = SourceType.valueOf(type.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException ex) { - logger.debug("Source type {} is a custom type", type); - } - if (!srcType.equals(SourceType.OTHER)) { - sourceClassName = srcType.getSourceClassName(); - } - try { - return (Class) Class.forName(sourceClassName); - } catch (Exception ex) { - throw new FlumeException("Unable to load source type: " + type + ", class: " + sourceClassName, ex); - } + Preconditions.checkNotNull(type, "type"); + return REGISTRY.getComponentClass(type); } } diff --git a/flume-core/src/main/java/org/apache/flume/source/ExecSource.java b/flume-core/src/main/java/org/apache/flume/source/ExecSource.java index 3375d66406..d13c40975d 100644 --- a/flume-core/src/main/java/org/apache/flume/source/ExecSource.java +++ b/flume-core/src/main/java/org/apache/flume/source/ExecSource.java @@ -16,6 +16,8 @@ */ package org.apache.flume.source; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; @@ -43,6 +45,8 @@ import org.apache.flume.event.Event; import org.apache.flume.event.EventBuilder; import org.apache.flume.instrumentation.SourceCounter; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SourceProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -495,4 +499,15 @@ public void run() { } } } + + /** + * Provides the {@code exec} source type. + */ + @ServiceProvider(value = SourceProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider implements SourceProvider { + + public Provider() { + super("exec", ExecSource.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/source/NetcatSource.java b/flume-core/src/main/java/org/apache/flume/source/NetcatSource.java index 0e81586cf1..e475858e40 100644 --- a/flume-core/src/main/java/org/apache/flume/source/NetcatSource.java +++ b/flume-core/src/main/java/org/apache/flume/source/NetcatSource.java @@ -16,6 +16,8 @@ */ package org.apache.flume.source; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Charsets; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.IOException; @@ -43,6 +45,8 @@ import org.apache.flume.event.Event; import org.apache.flume.event.EventBuilder; import org.apache.flume.exception.ChannelException; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SourceProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -458,4 +462,15 @@ private int fill(CharBuffer buffer, Reader reader) throws IOException { return charsRead; } } + + /** + * Provides the {@code netcat} source type. + */ + @ServiceProvider(value = SourceProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider implements SourceProvider { + + public Provider() { + super("netcat", NetcatSource.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/source/SequenceGeneratorSource.java b/flume-core/src/main/java/org/apache/flume/source/SequenceGeneratorSource.java index fbd5b9d71b..d505e3b1c2 100644 --- a/flume-core/src/main/java/org/apache/flume/source/SequenceGeneratorSource.java +++ b/flume-core/src/main/java/org/apache/flume/source/SequenceGeneratorSource.java @@ -16,18 +16,23 @@ */ package org.apache.flume.source; +import aQute.bnd.annotation.Resolution; +import aQute.bnd.annotation.spi.ServiceProvider; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.List; import org.apache.flume.Context; import org.apache.flume.EventDeliveryException; import org.apache.flume.FlumeException; +import org.apache.flume.Source; import org.apache.flume.conf.BatchSizeSupported; import org.apache.flume.conf.Configurable; import org.apache.flume.event.Event; import org.apache.flume.event.EventBuilder; import org.apache.flume.exception.ChannelException; import org.apache.flume.instrumentation.SourceCounter; +import org.apache.flume.spi.AbstractComponentProvider; +import org.apache.flume.spi.SourceProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -117,4 +122,15 @@ protected void doStop() throws FlumeException { public long getBatchSize() { return batchSize; } + + /** + * Provides the {@code seq} source type. + */ + @ServiceProvider(value = SourceProvider.class, resolution = Resolution.OPTIONAL) + public static final class Provider extends AbstractComponentProvider implements SourceProvider { + + public Provider() { + super("seq", SequenceGeneratorSource.class); + } + } } diff --git a/flume-core/src/main/java/org/apache/flume/spi/AbstractComponentProvider.java b/flume-core/src/main/java/org/apache/flume/spi/AbstractComponentProvider.java new file mode 100644 index 0000000000..aa87f0d895 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/AbstractComponentProvider.java @@ -0,0 +1,43 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import java.util.Objects; + +/** + * Base class for providers that map a fixed name to a fixed component class. + */ +public abstract class AbstractComponentProvider implements ComponentProvider { + + private final String name; + private final Class componentClass; + + protected AbstractComponentProvider(String name, Class componentClass) { + this.name = Objects.requireNonNull(name, "name"); + this.componentClass = Objects.requireNonNull(componentClass, "componentClass"); + } + + @Override + public final String getName() { + return name; + } + + @Override + public final Class getComponentClass() { + return componentClass; + } +} diff --git a/flume-core/src/main/java/org/apache/flume/spi/ChannelProvider.java b/flume-core/src/main/java/org/apache/flume/spi/ChannelProvider.java new file mode 100644 index 0000000000..9b3dd552e8 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/ChannelProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.Channel; + +/** + * Provides one channel type, selected by the {@code type} property of the channel configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.ChannelProvider}. + */ +public interface ChannelProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/ChannelSelectorProvider.java b/flume-core/src/main/java/org/apache/flume/spi/ChannelSelectorProvider.java new file mode 100644 index 0000000000..1675a5fcb5 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/ChannelSelectorProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.ChannelSelector; + +/** + * Provides one channel selector type, selected by the {@code type} property of the channel selector configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.ChannelSelectorProvider}. + */ +public interface ChannelSelectorProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/ComponentProvider.java b/flume-core/src/main/java/org/apache/flume/spi/ComponentProvider.java new file mode 100644 index 0000000000..14798fb0aa --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/ComponentProvider.java @@ -0,0 +1,39 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +/** + * Provides one type of configurable component, such as a source or an interceptor. + * + *

Providers are discovered with {@link java.util.ServiceLoader} + * through the sub-interface of their component kind, such as {@link SourceProvider}. + * For components built through a builder, such as interceptors, the component class is the builder class. + */ +public interface ComponentProvider { + + /** + * Returns the value of the {@code type} configuration property that selects this provider. + * + *

Types are compared case-insensitively. + */ + String getName(); + + /** + * Returns the component class, which must have a public no-argument constructor. + */ + Class getComponentClass(); +} diff --git a/flume-core/src/main/java/org/apache/flume/spi/ComponentRegistry.java b/flume-core/src/main/java/org/apache/flume/spi/ComponentRegistry.java new file mode 100644 index 0000000000..d5bfc660ca --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/ComponentRegistry.java @@ -0,0 +1,252 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; +import java.util.TreeMap; +import java.util.function.Function; +import org.apache.flume.FlumeException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * Resolves the {@code type} configuration property of one component kind to a component class. + * + *

A type is either the name of a provider registered through {@link ServiceLoader}, + * compared case-insensitively, + * or the fully qualified name of the component class. + */ +public final class ComponentRegistry { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final Class providerType; + private final Function nameOf; + private final Function> componentClassOf; + private final Class componentType; + private final String kind; + private final Function legacyAliases; + + private volatile Providers providers; + + /** + * @param providerType the service interface of this component kind, such as {@link SourceProvider}. + * @param componentType the class all components of this kind extend. + * @param kind a human-readable name of the component kind, used in error messages. + */ + public ComponentRegistry(Class> providerType, Class componentType, String kind) { + this(providerType, componentType, kind, type -> null); + } + + /** + * Creates a registry that also accepts the aliases of a legacy type enum. + * + * @param legacyAliases maps a type to a class name, or {@code null} if the type is not a legacy alias. + * @deprecated Legacy aliases will be removed together with the type enums. + */ + @Deprecated + public ComponentRegistry( + Class> providerType, + Class componentType, + String kind, + Function legacyAliases) { + this( + providerType, + provider -> provider.getName(), + provider -> provider.getComponentClass(), + componentType, + kind, + legacyAliases); + } + + @SuppressWarnings("unchecked") + private

ComponentRegistry( + Class

providerType, + Function nameOf, + Function> componentClassOf, + Class componentType, + String kind, + Function legacyAliases) { + this.providerType = Objects.requireNonNull(providerType, "providerType"); + // Only applied to instances of `providerType` + this.nameOf = (Function) Objects.requireNonNull(nameOf, "nameOf"); + this.componentClassOf = (Function>) + Objects.requireNonNull(componentClassOf, "componentClassOf"); + this.componentType = Objects.requireNonNull(componentType, "componentType"); + this.kind = Objects.requireNonNull(kind, "kind"); + this.legacyAliases = Objects.requireNonNull(legacyAliases, "legacyAliases"); + } + + /** + * Creates a registry for a provider interface that does not extend {@link ComponentProvider}. + * + *

Used by component kinds whose API module does not depend on {@code flume-core}, + * such as {@code org.apache.flume.configfilter.ConfigFilterProvider}. + * + * @param providerType the service interface of this component kind. + * @param nameOf returns the name of a provider. + * @param componentClassOf returns the component class of a provider. + * @param componentType the class all components of this kind extend. + * @param kind a human-readable name of the component kind, used in error messages. + */ + public static ComponentRegistry of( + Class

providerType, + Function nameOf, + Function> componentClassOf, + Class componentType, + String kind) { + return new ComponentRegistry<>(providerType, nameOf, componentClassOf, componentType, kind, type -> null); + } + + /** + * Creates a registry for a provider interface that does not extend {@link ComponentProvider}, + * which also accepts the aliases of a legacy type enum. + * + * @param legacyAliases maps a type to a class name, or {@code null} if the type is not a legacy alias. + * @deprecated Legacy aliases will be removed together with the type enums. + * @see #of(Class, Function, Function, Class, String) + */ + @Deprecated + public static ComponentRegistry of( + Class

providerType, + Function nameOf, + Function> componentClassOf, + Class componentType, + String kind, + Function legacyAliases) { + return new ComponentRegistry<>(providerType, nameOf, componentClassOf, componentType, kind, legacyAliases); + } + + /** + * Returns the component class selected by a type. + * + * @throws FlumeException if the type is unknown or does not select a component of this kind. + */ + public Class getComponentClass(String type) throws FlumeException { + Objects.requireNonNull(type, "type"); + Providers current = getProviders(); + String name = type.toLowerCase(Locale.ROOT); + String conflict = current.conflicts.get(name); + if (conflict != null) { + throw new FlumeException(conflict); + } + Class registered = current.classes.get(name); + if (registered != null) { + return registered; + } + String legacyClassName = legacyAliases.apply(type); + String className = legacyClassName != null ? legacyClassName : type; + Class clazz; + try { + clazz = Class.forName(className, true, ComponentRegistry.class.getClassLoader()); + } catch (ClassNotFoundException | LinkageError e) { + throw new FlumeException( + "Unknown " + kind + " type " + type + ": add the artifact that provides it, or use one of " + + current.classes.keySet(), + e); + } + if (!componentType.isAssignableFrom(clazz)) { + throw new FlumeException("The " + kind + " type " + type + " selects " + clazz.getName() + + ", which does not implement " + componentType.getName()); + } + return clazz.asSubclass(componentType); + } + + /** + * Creates a new component of the given type, with its no-argument constructor. + * + * @throws FlumeException if the type is unknown or the component cannot be instantiated. + */ + public T newInstance(String type) throws FlumeException { + Class clazz = getComponentClass(type); + try { + return clazz.getConstructor().newInstance(); + } catch (ReflectiveOperationException | RuntimeException e) { + throw new FlumeException("Unable to create " + kind + " of type " + type + ", class " + clazz.getName(), e); + } + } + + private Providers getProviders() { + Providers current = providers; + if (current == null) { + current = loadProviders(); + providers = current; + } + return current; + } + + private Providers loadProviders() { + Map> classes = new TreeMap<>(); + Map owners = new HashMap<>(); + Map conflicts = new HashMap<>(); + Iterator iterator = ServiceLoader.load(providerType, ComponentRegistry.class.getClassLoader()) + .iterator(); + while (true) { + Object provider; + String name; + Class clazz; + try { + if (!iterator.hasNext()) { + break; + } + provider = iterator.next(); + name = nameOf.apply(provider).toLowerCase(Locale.ROOT); + clazz = componentClassOf.apply(provider); + } catch (ServiceConfigurationError | LinkageError e) { + // A broken provider must not prevent the other ones from loading + LOGGER.warn("Skipping a {} provider that failed to load.", kind, e); + continue; + } + Object previous = owners.putIfAbsent(name, provider); + if (previous == null) { + classes.put(name, clazz); + } else { + // Fail only when the ambiguous type is used + LOGGER.error( + "The {} type {} is provided by both {} and {}.", + kind, + name, + previous.getClass().getName(), + provider.getClass().getName()); + conflicts.put( + name, + "The " + kind + " type " + name + " is provided by both " + + previous.getClass().getName() + " and " + + provider.getClass().getName()); + } + } + return new Providers<>(Collections.unmodifiableMap(classes), Collections.unmodifiableMap(conflicts)); + } + + private static final class Providers { + + private final Map> classes; + private final Map conflicts; + + private Providers(Map> classes, Map conflicts) { + this.classes = classes; + this.conflicts = conflicts; + } + } +} diff --git a/flume-core/src/main/java/org/apache/flume/spi/EventDeserializerProvider.java b/flume-core/src/main/java/org/apache/flume/spi/EventDeserializerProvider.java new file mode 100644 index 0000000000..1c53586ba2 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/EventDeserializerProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.serialization.EventDeserializer; + +/** + * Provides one event deserializer type, selected by the {@code type} property of the event deserializer configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.EventDeserializerProvider}. + */ +public interface EventDeserializerProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/EventSerializerProvider.java b/flume-core/src/main/java/org/apache/flume/spi/EventSerializerProvider.java new file mode 100644 index 0000000000..1f35d23199 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/EventSerializerProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.serialization.EventSerializer; + +/** + * Provides one event serializer type, selected by the {@code type} property of the event serializer configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.EventSerializerProvider}. + */ +public interface EventSerializerProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/InterceptorProvider.java b/flume-core/src/main/java/org/apache/flume/spi/InterceptorProvider.java new file mode 100644 index 0000000000..54f0082ba2 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/InterceptorProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.interceptor.Interceptor; + +/** + * Provides one interceptor type, selected by the {@code type} property of the interceptor configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.InterceptorProvider}. + */ +public interface InterceptorProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/PathManagerProvider.java b/flume-core/src/main/java/org/apache/flume/spi/PathManagerProvider.java new file mode 100644 index 0000000000..fc09334c26 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/PathManagerProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.formatter.output.PathManager; + +/** + * Provides one path manager type, selected by the {@code type} property of the path manager configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.PathManagerProvider}. + */ +public interface PathManagerProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/SinkProcessorProvider.java b/flume-core/src/main/java/org/apache/flume/spi/SinkProcessorProvider.java new file mode 100644 index 0000000000..c7dbc2c0d3 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/SinkProcessorProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.SinkProcessor; + +/** + * Provides one sink processor type, selected by the {@code type} property of the sink processor configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.SinkProcessorProvider}. + */ +public interface SinkProcessorProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/SinkProvider.java b/flume-core/src/main/java/org/apache/flume/spi/SinkProvider.java new file mode 100644 index 0000000000..9dbcfa4259 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/SinkProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.Sink; + +/** + * Provides one sink type, selected by the {@code type} property of the sink configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.SinkProvider}. + */ +public interface SinkProvider extends ComponentProvider {} diff --git a/flume-core/src/main/java/org/apache/flume/spi/SourceProvider.java b/flume-core/src/main/java/org/apache/flume/spi/SourceProvider.java new file mode 100644 index 0000000000..e74452ec51 --- /dev/null +++ b/flume-core/src/main/java/org/apache/flume/spi/SourceProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import org.apache.flume.Source; + +/** + * Provides one source type, selected by the {@code type} property of the source configuration. + * + *

Register implementations in {@code META-INF/services/org.apache.flume.spi.SourceProvider}. + */ +public interface SourceProvider extends ComponentProvider {} diff --git a/flume-core/src/test/java/org/apache/flume/spi/TestComponentRegistry.java b/flume-core/src/test/java/org/apache/flume/spi/TestComponentRegistry.java new file mode 100644 index 0000000000..5560c87d68 --- /dev/null +++ b/flume-core/src/test/java/org/apache/flume/spi/TestComponentRegistry.java @@ -0,0 +1,131 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.Callable; +import org.apache.flume.FlumeException; +import org.junit.Test; + +public class TestComponentRegistry { + + /** Test-only component kind, registered in {@code META-INF/services}. */ + public interface FakeProvider extends ComponentProvider {} + + public static final class FakeComponent implements Runnable { + @Override + public void run() {} + } + + public static final class OtherFakeComponent implements Runnable { + @Override + public void run() {} + } + + public static final class UnregisteredComponent implements Runnable { + @Override + public void run() {} + } + + public static final class FakeProviderOne extends AbstractComponentProvider implements FakeProvider { + public FakeProviderOne() { + super("One", FakeComponent.class); + } + } + + public static final class DuplicateProviderA extends AbstractComponentProvider implements FakeProvider { + public DuplicateProviderA() { + super("duplicate", FakeComponent.class); + } + } + + public static final class DuplicateProviderB extends AbstractComponentProvider implements FakeProvider { + public DuplicateProviderB() { + super("duplicate", OtherFakeComponent.class); + } + } + + private final ComponentRegistry registry = + new ComponentRegistry<>(FakeProvider.class, Runnable.class, "fake component"); + + @Test + public void resolvesRegisteredNameIgnoringCase() { + assertEquals(FakeComponent.class, registry.getComponentClass("one")); + assertEquals(FakeComponent.class, registry.getComponentClass("ONE")); + } + + @Test + public void resolvesUnregisteredClassName() { + assertEquals(UnregisteredComponent.class, registry.getComponentClass(UnregisteredComponent.class.getName())); + } + + @Test + @SuppressWarnings("deprecation") + public void resolvesLegacyAlias() { + ComponentRegistry legacy = new ComponentRegistry<>( + FakeProvider.class, + Runnable.class, + "fake component", + type -> "legacy".equalsIgnoreCase(type) ? UnregisteredComponent.class.getName() : null); + assertEquals(UnregisteredComponent.class, legacy.getComponentClass("Legacy")); + // Registered names take precedence over legacy aliases + assertEquals(FakeComponent.class, legacy.getComponentClass("one")); + } + + @Test + public void supportsProvidersThatDoNotExtendComponentProvider() { + ComponentRegistry adapted = ComponentRegistry.of( + FakeProvider.class, + provider -> "adapted-" + provider.getName(), + FakeProvider::getComponentClass, + Runnable.class, + "fake component"); + assertEquals(FakeComponent.class, adapted.getComponentClass("adapted-one")); + assertEquals(UnregisteredComponent.class, adapted.getComponentClass(UnregisteredComponent.class.getName())); + } + + @Test + public void newInstanceCreatesDistinctInstances() { + Runnable first = registry.newInstance("one"); + Runnable second = registry.newInstance("one"); + assertTrue(first instanceof FakeComponent); + assertTrue(first != second); + } + + @Test + public void rejectsUnknownType() { + FlumeException e = assertThrows(FlumeException.class, () -> registry.getComponentClass("unknown")); + assertTrue(e.getMessage(), e.getMessage().contains("[duplicate, one]")); + } + + @Test + public void rejectsClassOfWrongKind() { + FlumeException e = + assertThrows(FlumeException.class, () -> registry.getComponentClass(Callable.class.getName())); + assertTrue(e.getMessage(), e.getMessage().contains(Runnable.class.getName())); + } + + @Test + public void rejectsAmbiguousName() { + FlumeException e = assertThrows(FlumeException.class, () -> registry.getComponentClass("duplicate")); + assertTrue(e.getMessage(), e.getMessage().contains(DuplicateProviderA.class.getName())); + assertTrue(e.getMessage(), e.getMessage().contains(DuplicateProviderB.class.getName())); + } +} diff --git a/flume-core/src/test/java/org/apache/flume/spi/TestCoreComponentProviders.java b/flume-core/src/test/java/org/apache/flume/spi/TestCoreComponentProviders.java new file mode 100644 index 0000000000..7414984d03 --- /dev/null +++ b/flume-core/src/test/java/org/apache/flume/spi/TestCoreComponentProviders.java @@ -0,0 +1,110 @@ +/* + * 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. + */ +package org.apache.flume.spi; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.Locale; +import java.util.ServiceLoader; +import java.util.function.Function; +import org.apache.flume.conf.channel.ChannelSelectorType; +import org.apache.flume.conf.channel.ChannelType; +import org.apache.flume.conf.sink.SinkProcessorType; +import org.apache.flume.conf.sink.SinkType; +import org.apache.flume.conf.source.SourceType; +import org.apache.flume.formatter.output.PathManagerType; +import org.apache.flume.interceptor.InterceptorType; +import org.apache.flume.serialization.EventDeserializerType; +import org.apache.flume.serialization.EventSerializerType; +import org.junit.Test; + +/** + * Checks that the providers in {@code flume-core} use the same names and classes as the legacy type enums. + */ +public class TestCoreComponentProviders { + + @Test + public void sources() { + check(SourceProvider.class, 3, name -> SourceType.valueOf(name).getClassName()); + } + + @Test + public void sinks() { + check(SinkProvider.class, 3, name -> SinkType.valueOf(name).getClassName()); + } + + @Test + public void channels() { + check(ChannelProvider.class, 1, name -> ChannelType.valueOf(name).getClassName()); + } + + @Test + public void channelSelectors() { + check(ChannelSelectorProvider.class, 4, name -> ChannelSelectorType.valueOf(name) + .getClassName()); + } + + @Test + public void sinkProcessors() { + check(SinkProcessorProvider.class, 3, name -> SinkProcessorType.valueOf(name) + .getClassName()); + } + + @Test + public void interceptors() { + check(InterceptorProvider.class, InterceptorType.values().length, name -> InterceptorType.valueOf(name) + .getBuilderClass() + .getName()); + } + + @Test + public void eventSerializers() { + check(EventSerializerProvider.class, 2, name -> EventSerializerType.valueOf(name) + .getBuilderClass() + .getName()); + } + + @Test + public void eventDeserializers() { + check(EventDeserializerProvider.class, 1, name -> EventDeserializerType.valueOf(name) + .getBuilderClass() + .getName()); + } + + @Test + public void pathManagers() { + check(PathManagerProvider.class, 2, name -> PathManagerType.valueOf(name) + .getBuilderClass() + .getName()); + } + + private static

> void check( + Class

providerType, int expectedCount, Function legacyClassName) { + int count = 0; + for (P provider : ServiceLoader.load(providerType)) { + String name = provider.getName(); + assertFalse(name, name.isEmpty()); + assertEquals( + name, + legacyClassName.apply(name.toUpperCase(Locale.ROOT)), + provider.getComponentClass().getName()); + count++; + } + assertEquals(providerType.getSimpleName(), expectedCount, count); + } +} diff --git a/flume-core/src/test/resources/META-INF/services/org.apache.flume.spi.TestComponentRegistry$FakeProvider b/flume-core/src/test/resources/META-INF/services/org.apache.flume.spi.TestComponentRegistry$FakeProvider new file mode 100644 index 0000000000..6aff301256 --- /dev/null +++ b/flume-core/src/test/resources/META-INF/services/org.apache.flume.spi.TestComponentRegistry$FakeProvider @@ -0,0 +1,5 @@ +org.apache.flume.spi.TestComponentRegistry$FakeProviderOne +# A missing provider is skipped +org.apache.flume.spi.TestComponentRegistry$MissingProvider +org.apache.flume.spi.TestComponentRegistry$DuplicateProviderA +org.apache.flume.spi.TestComponentRegistry$DuplicateProviderB diff --git a/src/changelog/.2.x.x/add_component_providers.xml b/src/changelog/.2.x.x/add_component_providers.xml new file mode 100644 index 0000000000..5a7ecf7b24 --- /dev/null +++ b/src/changelog/.2.x.x/add_component_providers.xml @@ -0,0 +1,7 @@ + + + Add the `org.apache.flume.spi` service provider interfaces, so that sources, sinks, channels, channel selectors, sink processors, interceptors, event serializers, event deserializers and path managers can register a short `type` alias through `ServiceLoader`. Configuration filters use `org.apache.flume.configfilter.ConfigFilterProvider`, so that they do not depend on `flume-core`. +