flume學習(九):自定義攔截器

問題導讀

1.如何添加攔截器RegexExtractorExtInterceptor?
2.改動的內容中是如何增加兩個配置參數?








還是針對學習八中的那個需求,我們現在換一種實現方式,採用攔截器來實現。

先回想一下,spooldir source可以將文件名作爲header中的key:basename寫入到event的header當中去。試想一下,如果有一個攔截器可以攔截這個event,然後抽取header中這個key的值,將其拆分成3段,每一段都放入到header中,這樣就可以實現那個需求了。

遺憾的是,flume沒有提供可以攔截header的攔截器。不過有一個抽取body內容的攔截器:RegexExtractorInterceptor,看起來也很強大,以下是一個官方文檔的示例:
If the Flume event body contained 1:2:3.4foobar5 and the following configuration was used


a1.sources.r1.interceptors.i1.regex = (\\d):(\\d):(\\d)
a1.sources.r1.interceptors.i1.serializers = s1 s2 s3
a1.sources.r1.interceptors.i1.serializers.s1.name = one
a1.sources.r1.interceptors.i1.serializers.s2.name = two
a1.sources.r1.interceptors.i1.serializers.s3.name = three
The extracted event will contain the same body but the following headers will have been added one=>1, two=>2, three=>3

大概意思就是,通過這樣的配置,event body中如果有1:2:3.4foobar5 這樣的內容,這會通過正則的規則抽取具體部分的內容,然後設置到header當中去。

於是決定打這個攔截器的主義,覺得只要把代碼稍微改改,從攔截body改爲攔截header中的具體key,就OK了。翻開源碼,哎呀,很工整,改起來沒難度,以下是我新增的一個攔截器:RegexExtractorExtInterceptor:
  1. package com.besttone.flume;

  2. import java.util.List;
  3. import java.util.Map;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;

  6. import org.apache.commons.lang.StringUtils;
  7. import org.apache.flume.Context;
  8. import org.apache.flume.Event;
  9. import org.apache.flume.interceptor.Interceptor;
  10. import org.apache.flume.interceptor.RegexExtractorInterceptorPassThroughSerializer;
  11. import org.apache.flume.interceptor.RegexExtractorInterceptorSerializer;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;

  14. import com.google.common.base.Charsets;
  15. import com.google.common.base.Preconditions;
  16. import com.google.common.base.Throwables;
  17. import com.google.common.collect.Lists;

  18. /**
  19. * Interceptor that extracts matches using a specified regular expression and
  20. * appends the matches to the event headers using the specified serializers</p>
  21. * Note that all regular expression matching occurs through Java's built in
  22. * java.util.regex package</p>. Properties:
  23. * <p>
  24. * regex: The regex to use
  25. * <p>
  26. * serializers: Specifies the group the serializer will be applied to, and the
  27. * name of the header that will be added. If no serializer is specified for a
  28. * group the default {@link RegexExtractorInterceptorPassThroughSerializer} will
  29. * be used
  30. * <p>
  31. * Sample config:
  32. * <p>
  33. * agent.sources.r1.channels = c1
  34. * <p>
  35. * agent.sources.r1.type = SEQ
  36. * <p>
  37. * agent.sources.r1.interceptors = i1
  38. * <p>
  39. * agent.sources.r1.interceptors.i1.type = REGEX_EXTRACTOR
  40. * <p>
  41. * agent.sources.r1.interceptors.i1.regex = (WARNING)|(ERROR)|(FATAL)
  42. * <p>
  43. * agent.sources.r1.interceptors.i1.serializers = s1 s2
  44. * agent.sources.r1.interceptors.i1.serializers.s1.type =
  45. * com.blah.SomeSerializer agent.sources.r1.interceptors.i1.serializers.s1.name
  46. * = warning agent.sources.r1.interceptors.i1.serializers.s2.type =
  47. * org.apache.flume.interceptor.RegexExtractorInterceptorTimestampSerializer
  48. * agent.sources.r1.interceptors.i1.serializers.s2.name = error
  49. * agent.sources.r1.interceptors.i1.serializers.s2.dateFormat = yyyy-MM-dd
  50. * </code>
  51. * </p>
  52. * 
  53. * <pre>
  54. * Example 1:
  55. * </p>
  56. * EventBody: 1:2:3.4foobar5</p> Configuration:
  57. * agent.sources.r1.interceptors.i1.regex = (\\d):(\\d):(\\d)
  58. * </p>
  59. * agent.sources.r1.interceptors.i1.serializers = s1 s2 s3
  60. * agent.sources.r1.interceptors.i1.serializers.s1.name = one
  61. * agent.sources.r1.interceptors.i1.serializers.s2.name = two
  62. * agent.sources.r1.interceptors.i1.serializers.s3.name = three
  63. * </p>
  64. * results in an event with the the following
  65. * 
  66. * body: 1:2:3.4foobar5 headers: one=>1, two=>2, three=3
  67. * 
  68. * Example 2:
  69. * 
  70. * EventBody: 1:2:3.4foobar5
  71. * 
  72. * Configuration: agent.sources.r1.interceptors.i1.regex = (\\d):(\\d):(\\d)
  73. * <p>
  74. * agent.sources.r1.interceptors.i1.serializers = s1 s2
  75. * agent.sources.r1.interceptors.i1.serializers.s1.name = one
  76. * agent.sources.r1.interceptors.i1.serializers.s2.name = two
  77. * <p>
  78. * 
  79. * results in an event with the the following
  80. * 
  81. * body: 1:2:3.4foobar5 headers: one=>1, two=>2
  82. * </pre>
  83. */
  84. public class RegexExtractorExtInterceptor implements Interceptor {

  85.         static final String REGEX = "regex";
  86.         static final String SERIALIZERS = "serializers";

  87.         // 增加代碼開始

  88.         static final String EXTRACTOR_HEADER = "extractorHeader";
  89.         static final boolean DEFAULT_EXTRACTOR_HEADER = false;
  90.         static final String EXTRACTOR_HEADER_KEY = "extractorHeaderKey";

  91.         // 增加代碼結束

  92.         private static final Logger logger = LoggerFactory
  93.                         .getLogger(RegexExtractorExtInterceptor.class);

  94.         private final Pattern regex;
  95.         private final List<NameAndSerializer> serializers;

  96.         // 增加代碼開始

  97.         private final boolean extractorHeader;
  98.         private final String extractorHeaderKey;

  99.         // 增加代碼結束

  100.         private RegexExtractorExtInterceptor(Pattern regex,
  101.                         List<NameAndSerializer> serializers, boolean extractorHeader,
  102.                         String extractorHeaderKey) {
  103.                 this.regex = regex;
  104.                 this.serializers = serializers;
  105.                 this.extractorHeader = extractorHeader;
  106.                 this.extractorHeaderKey = extractorHeaderKey;
  107.         }

  108.         @Override
  109.         public void initialize() {
  110.                 // NO-OP...
  111.         }

  112.         @Override
  113.         public void close() {
  114.                 // NO-OP...
  115.         }

  116.         @Override
  117.         public Event intercept(Event event) {
  118.                 String tmpStr;
  119.                 if(extractorHeader)
  120.                 {
  121.                         tmpStr = event.getHeaders().get(extractorHeaderKey);
  122.                 }
  123.                 else
  124.                 {
  125.                         tmpStr=new String(event.getBody(),
  126.                                         Charsets.UTF_8);
  127.                 }
  128.                 
  129.                 Matcher matcher = regex.matcher(tmpStr);
  130.                 Map<String, String> headers = event.getHeaders();
  131.                 if (matcher.find()) {
  132.                         for (int group = 0, count = matcher.groupCount(); group < count; group++) {
  133.                                 int groupIndex = group + 1;
  134.                                 if (groupIndex > serializers.size()) {
  135.                                         if (logger.isDebugEnabled()) {
  136.                                                 logger.debug(
  137.                                                                 "Skipping group {} to {} due to missing serializer",
  138.                                                                 group, count);
  139.                                         }
  140.                                         break;
  141.                                 }
  142.                                 NameAndSerializer serializer = serializers.get(group);
  143.                                 if (logger.isDebugEnabled()) {
  144.                                         logger.debug("Serializing {} using {}",
  145.                                                         serializer.headerName, serializer.serializer);
  146.                                 }
  147.                                 headers.put(serializer.headerName, serializer.serializer
  148.                                                 .serialize(matcher.group(groupIndex)));
  149.                         }
  150.                 }
  151.                 return event;
  152.         }

  153.         @Override
  154.         public List<Event> intercept(List<Event> events) {
  155.                 List<Event> intercepted = Lists.newArrayListWithCapacity(events.size());
  156.                 for (Event event : events) {
  157.                         Event interceptedEvent = intercept(event);
  158.                         if (interceptedEvent != null) {
  159.                                 intercepted.add(interceptedEvent);
  160.                         }
  161.                 }
  162.                 return intercepted;
  163.         }

  164.         public static class Builder implements Interceptor.Builder {

  165.                 private Pattern regex;
  166.                 private List<NameAndSerializer> serializerList;

  167.                 // 增加代碼開始

  168.                 private boolean extractorHeader;
  169.                 private String extractorHeaderKey;

  170.                 // 增加代碼結束

  171.                 private final RegexExtractorInterceptorSerializer defaultSerializer = new RegexExtractorInterceptorPassThroughSerializer();

  172.                 @Override
  173.                 public void configure(Context context) {
  174.                         String regexString = context.getString(REGEX);
  175.                         Preconditions.checkArgument(!StringUtils.isEmpty(regexString),
  176.                                         "Must supply a valid regex string");

  177.                         regex = Pattern.compile(regexString);
  178.                         regex.pattern();
  179.                         regex.matcher("").groupCount();
  180.                         configureSerializers(context);

  181.                         // 增加代碼開始
  182.                         extractorHeader = context.getBoolean(EXTRACTOR_HEADER,
  183.                                         DEFAULT_EXTRACTOR_HEADER);

  184.                         if (extractorHeader) {
  185.                                 extractorHeaderKey = context.getString(EXTRACTOR_HEADER_KEY);
  186.                                 Preconditions.checkArgument(
  187.                                                 !StringUtils.isEmpty(extractorHeaderKey),
  188.                                                 "必須指定要抽取內容的header key");
  189.                         }
  190.                         // 增加代碼結束
  191.                 }

  192.                 private void configureSerializers(Context context) {
  193.                         String serializerListStr = context.getString(SERIALIZERS);
  194.                         Preconditions.checkArgument(
  195.                                         !StringUtils.isEmpty(serializerListStr),
  196.                                         "Must supply at least one name and serializer");

  197.                         String[] serializerNames = serializerListStr.split("\\s+");

  198.                         Context serializerContexts = new Context(
  199.                                         context.getSubProperties(SERIALIZERS + "."));

  200.                         serializerList = Lists
  201.                                         .newArrayListWithCapacity(serializerNames.length);
  202.                         for (String serializerName : serializerNames) {
  203.                                 Context serializerContext = new Context(
  204.                                                 serializerContexts.getSubProperties(serializerName
  205.                                                                 + "."));
  206.                                 String type = serializerContext.getString("type", "DEFAULT");
  207.                                 String name = serializerContext.getString("name");
  208.                                 Preconditions.checkArgument(!StringUtils.isEmpty(name),
  209.                                                 "Supplied name cannot be empty.");

  210.                                 if ("DEFAULT".equals(type)) {
  211.                                         serializerList.add(new NameAndSerializer(name,
  212.                                                         defaultSerializer));
  213.                                 } else {
  214.                                         serializerList.add(new NameAndSerializer(name,
  215.                                                         getCustomSerializer(type, serializerContext)));
  216.                                 }
  217.                         }
  218.                 }

  219.                 private RegexExtractorInterceptorSerializer getCustomSerializer(
  220.                                 String clazzName, Context context) {
  221.                         try {
  222.                                 RegexExtractorInterceptorSerializer serializer = (RegexExtractorInterceptorSerializer) Class
  223.                                                 .forName(clazzName).newInstance();
  224.                                 serializer.configure(context);
  225.                                 return serializer;
  226.                         } catch (Exception e) {
  227.                                 logger.error("Could not instantiate event serializer.", e);
  228.                                 Throwables.propagate(e);
  229.                         }
  230.                         return defaultSerializer;
  231.                 }

  232.                 @Override
  233.                 public Interceptor build() {
  234.                         Preconditions.checkArgument(regex != null,
  235.                                         "Regex pattern was misconfigured");
  236.                         Preconditions.checkArgument(serializerList.size() > 0,
  237.                                         "Must supply a valid group match id list");
  238.                         return new RegexExtractorExtInterceptor(regex, serializerList,
  239.                                         extractorHeader, extractorHeaderKey);
  240.                 }
  241.         }

  242.         static class NameAndSerializer {
  243.                 private final String headerName;
  244.                 private final RegexExtractorInterceptorSerializer serializer;

  245.                 public NameAndSerializer(String headerName,
  246.                                 RegexExtractorInterceptorSerializer serializer) {
  247.                         this.headerName = headerName;
  248.                         this.serializer = serializer;
  249.                 }
  250.         }
  251. }

複製代碼
簡單說明一下改動的內容:

增加了兩個配置參數:
extractorHeader   是否抽取的是header部分,默認爲false,即和原始的攔截器功能一致,抽取的是event body的內容
extractorHeaderKey 抽取的header的指定的key的內容,當extractorHeader爲true時,必須指定該參數。

按照第八講的方法,我們將該類打成jar包,作爲flume的插件放到了/var/lib/flume-ng/plugins.d/RegexExtractorExtInterceptor/lib目錄下,重新啓動flume,將該攔截器加載到classpath中。

最終的flume.conf如下:
  1. tier1.sources=source1
  2. tier1.channels=channel1
  3. tier1.sinks=sink1
  4. tier1.sources.source1.type=spooldir
  5. tier1.sources.source1.spoolDir=/opt/logs
  6. tier1.sources.source1.fileHeader=true
  7. tier1.sources.source1.basenameHeader=true
  8. tier1.sources.source1.interceptors=i1
  9. tier1.sources.source1.interceptors.i1.type=com.besttone.flume.RegexExtractorExtInterceptor$Builder
  10. tier1.sources.source1.interceptors.i1.regex=(.*)\\.(.*)\\.(.*)
  11. tier1.sources.source1.interceptors.i1.extractorHeader=true
  12. tier1.sources.source1.interceptors.i1.extractorHeaderKey=basename
  13. tier1.sources.source1.interceptors.i1.serializers=s1 s2 s3
  14. tier1.sources.source1.interceptors.i1.serializers.s1.name=one
  15. tier1.sources.source1.interceptors.i1.serializers.s2.name=two
  16. tier1.sources.source1.interceptors.i1.serializers.s3.name=three
  17. tier1.sources.source1.channels=channel1
  18. tier1.sinks.sink1.type=hdfs
  19. tier1.sinks.sink1.channel=channel1
  20. tier1.sinks.sink1.hdfs.path=hdfs://master68:8020/flume/events/%{one}/%{three}
  21. tier1.sinks.sink1.hdfs.round=true
  22. tier1.sinks.sink1.hdfs.roundValue=10
  23. tier1.sinks.sink1.hdfs.roundUnit=minute
  24. tier1.sinks.sink1.hdfs.fileType=DataStream
  25. tier1.sinks.sink1.hdfs.writeFormat=Text
  26. tier1.sinks.sink1.hdfs.rollInterval=0
  27. tier1.sinks.sink1.hdfs.rollSize=10240
  28. tier1.sinks.sink1.hdfs.rollCount=0
  29. tier1.sinks.sink1.hdfs.idleTimeout=60
  30. tier1.channels.channel1.type=memory
  31. tier1.channels.channel1.capacity=10000
  32. tier1.channels.channel1.transactionCapacity=1000
  33. tier1.channels.channel1.keep-alive=30

複製代碼
我把source type改回了內置的spooldir,而不是上一講自定義的source,然後添加了一個攔截器i1,type是自定義的攔截器:

com.besttone.flume.RegexExtractorExtInterceptor$Builder,正則表達式按“.”分隔抽取三部分,分別放到header中的key:one,two,three當中去,即a.log.2014-07-31,通過攔截器後,在header當中就會增加三個key: one=a,two=log,three=2014-07-31。

這時候我們在tier1.sinks.sink1.hdfs.path=hdfs://master68:8020/flume/events/%{one}/%{three}。
就實現了和前面第八講一模一樣的需求。

也可以看到,自定義攔截器的改動成本非常小,比自定義source小多了,我們這就增加了一個類,就實現了該功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章