flume学习(七):自定义source

本文介绍了一种将文件名及生成日期作为事件头(header)存储到HDFS的方法,并确保不同事件存储于各自目录下。通过扩展spoolingdirectorysource功能,实现文件按日期自动归档。

按照以往的惯例,还是需求驱动学习,需求是:

我想实现一个功能,就在读一个文件的时候,将文件的名字和文件生成的日期作为event的header传到hdfs上时,不同的event存到不同的目录下,如一个文件是a.log.2014-07-25在hdfs上是存到/a/2014-07-25目录下,a.log.2014-07-26存到/a/2014-07-26目录下,就是每个文件对应自己的目录,这个要怎么实现。


带着这个问题,我又重新翻看了官方的文档,发现一个spooling directory source跟这个需求稍微有点吻合:它监视指定的文件夹下面有没有写入新的文件,有的话,就会把该文件内容传递给sink,然后将该文件后缀标示为.complete,表示已处理。提供了参数可以将文件名和文件全路径名添加到event的header中去。


现有的功能不能满足我们的需求,但是至少提供了一个方向:它能将文件名放入header!

当时就在祈祷源代码不要太复杂,这样我们在这个地方稍微修改修改,把文件名拆分一下,然后再放入header,这样就完成了我们想要的功能了。

于是就打开了源代码,果然不复杂,代码结构非常清晰,按照我的思路,稍微改了一下,就实现了这个功能,主要修改了与spooling directory source代码相关的三个类,分别是:ReliableSpoolingFileEventExtReader,SpoolDirectorySourceConfigurationExtConstants,SpoolDirectoryExtSource(在原类名的基础上增加了:Ext)代码如下:

[java]  view plain  copy
  1. /* 
  2.  * Licensed to the Apache Software Foundation (ASF) under one 
  3.  * or more contributor license agreements.  See the NOTICE file 
  4.  * distributed with this work for additional information 
  5.  * regarding copyright ownership.  The ASF licenses this file 
  6.  * to you under the Apache License, Version 2.0 (the 
  7.  * "License"); you may not use this file except in compliance 
  8.  * with the License.  You may obtain a copy of the License at 
  9.  * 
  10.  * http://www.apache.org/licenses/LICENSE-2.0 
  11.  * 
  12.  * Unless required by applicable law or agreed to in writing, 
  13.  * software distributed under the License is distributed on an 
  14.  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
  15.  * KIND, either express or implied.  See the License for the 
  16.  * specific language governing permissions and limitations 
  17.  * under the License. 
  18.  */  
  19.   
  20. package com.bbaiggey.flume;  
  21.   
  22. import java.io.File;  
  23. import java.io.FileFilter;  
  24. import java.io.FileNotFoundException;  
  25. import java.io.IOException;  
  26. import java.nio.charset.Charset;  
  27. import java.util.Arrays;  
  28. import java.util.Collections;  
  29. import java.util.Comparator;  
  30. import java.util.List;  
  31. import java.util.regex.Matcher;  
  32. import java.util.regex.Pattern;  
  33.   
  34. import org.apache.flume.Context;  
  35. import org.apache.flume.Event;  
  36. import org.apache.flume.FlumeException;  
  37. import org.apache.flume.annotations.InterfaceAudience;  
  38. import org.apache.flume.annotations.InterfaceStability;  
  39. import org.apache.flume.client.avro.ReliableEventReader;  
  40. import org.apache.flume.serialization.DecodeErrorPolicy;  
  41. import org.apache.flume.serialization.DurablePositionTracker;  
  42. import org.apache.flume.serialization.EventDeserializer;  
  43. import org.apache.flume.serialization.EventDeserializerFactory;  
  44. import org.apache.flume.serialization.PositionTracker;  
  45. import org.apache.flume.serialization.ResettableFileInputStream;  
  46. import org.apache.flume.serialization.ResettableInputStream;  
  47. import org.apache.flume.tools.PlatformDetect;  
  48. import org.joda.time.DateTime;  
  49. import org.joda.time.format.DateTimeFormat;  
  50. import org.joda.time.format.DateTimeFormatter;  
  51. import org.slf4j.Logger;  
  52. import org.slf4j.LoggerFactory;  
  53.   
  54. import com.google.common.base.Charsets;  
  55. import com.google.common.base.Optional;  
  56. import com.google.common.base.Preconditions;  
  57. import com.google.common.io.Files;  
  58.   
  59. /** 
  60.  * <p/> 
  61.  * A {@link ReliableEventReader} which reads log data from files stored in a 
  62.  * spooling directory and renames each file once all of its data has been read 
  63.  * (through {@link EventDeserializer#readEvent()} calls). The user must 
  64.  * {@link #commit()} each read, to indicate that the lines have been fully 
  65.  * processed. 
  66.  * <p/> 
  67.  * Read calls will return no data if there are no files left to read. This 
  68.  * class, in general, is not thread safe. 
  69.  *  
  70.  * <p/> 
  71.  * This reader assumes that files with unique file names are left in the 
  72.  * spooling directory and not modified once they are placed there. Any user 
  73.  * behavior which violates these assumptions, when detected, will result in a 
  74.  * FlumeException being thrown. 
  75.  *  
  76.  * <p/> 
  77.  * This class makes the following guarantees, if above assumptions are met: 
  78.  * <ul> 
  79.  * <li>Once a log file has been renamed with the {@link #completedSuffix}, all 
  80.  * of its records have been read through the 
  81.  * {@link EventDeserializer#readEvent()} function and {@link #commit()}ed at 
  82.  * least once. 
  83.  * <li>All files in the spooling directory will eventually be opened and 
  84.  * delivered to a {@link #readEvents(int)} caller. 
  85.  * </ul> 
  86.  */  
  87. @InterfaceAudience.Private  
  88. @InterfaceStability.Evolving  
  89. public class ReliableSpoolingFileEventExtReader implements ReliableEventReader {  
  90.   
  91.     private static final Logger logger = LoggerFactory  
  92.             .getLogger(ReliableSpoolingFileEventExtReader.class);  
  93.   
  94.     static final String metaFileName = ".flumespool-main.meta";  
  95.   
  96.     private final File spoolDirectory;  
  97.     private final String completedSuffix;  
  98.     private final String deserializerType;  
  99.     private final Context deserializerContext;  
  100.     private final Pattern ignorePattern;  
  101.     private final File metaFile;  
  102.     private final boolean annotateFileName;  
  103.     private final boolean annotateBaseName;  
  104.     private final String fileNameHeader;  
  105.     private final String baseNameHeader;  
  106.   
  107.     // 添加参数开始  
  108.     private final boolean annotateFileNameExtractor;  
  109.     private final String fileNameExtractorHeader;  
  110.     private final Pattern fileNameExtractorPattern;  
  111.     private final boolean convertToTimestamp;  
  112.     private final String dateTimeFormat;  
  113.   
  114.     private final boolean splitFileName;  
  115.     private final String splitBy;  
  116.     private final String splitBaseNameHeader;  
  117.     // 添加参数结束  
  118.   
  119.     private final String deletePolicy;  
  120.     private final Charset inputCharset;  
  121.     private final DecodeErrorPolicy decodeErrorPolicy;  
  122.   
  123.     private Optional<FileInfo> currentFile = Optional.absent();  
  124.     /** Always contains the last file from which lines have been read. **/  
  125.     private Optional<FileInfo> lastFileRead = Optional.absent();  
  126.     private boolean committed = true;  
  127.   
  128.     /** 
  129.      * Create a ReliableSpoolingFileEventReader to watch the given directory. 
  130.      */  
  131.     private ReliableSpoolingFileEventExtReader(File spoolDirectory,  
  132.             String completedSuffix, String ignorePattern,  
  133.             String trackerDirPath, boolean annotateFileName,  
  134.             String fileNameHeader, boolean annotateBaseName,  
  135.             String baseNameHeader, String deserializerType,  
  136.             Context deserializerContext, String deletePolicy,  
  137.             String inputCharset, DecodeErrorPolicy decodeErrorPolicy,  
  138.             boolean annotateFileNameExtractor, String fileNameExtractorHeader,  
  139.             String fileNameExtractorPattern, boolean convertToTimestamp,  
  140.             String dateTimeFormat, boolean splitFileName, String splitBy,  
  141.             String splitBaseNameHeader) throws IOException {  
  142.   
  143.         // Sanity checks  
  144.         Preconditions.checkNotNull(spoolDirectory);  
  145.         Preconditions.checkNotNull(completedSuffix);  
  146.         Preconditions.checkNotNull(ignorePattern);  
  147.         Preconditions.checkNotNull(trackerDirPath);  
  148.         Preconditions.checkNotNull(deserializerType);  
  149.         Preconditions.checkNotNull(deserializerContext);  
  150.         Preconditions.checkNotNull(deletePolicy);  
  151.         Preconditions.checkNotNull(inputCharset);  
  152.   
  153.         // validate delete policy  
  154.         if (!deletePolicy.equalsIgnoreCase(DeletePolicy.NEVER.name())  
  155.                 && !deletePolicy  
  156.                         .equalsIgnoreCase(DeletePolicy.IMMEDIATE.name())) {  
  157.             throw new IllegalArgumentException("Delete policies other than "  
  158.                     + "NEVER and IMMEDIATE are not yet supported");  
  159.         }  
  160.   
  161.         if (logger.isDebugEnabled()) {  
  162.             logger.debug("Initializing {} with directory={}, metaDir={}, "  
  163.                     + "deserializer={}"new Object[] {  
  164.                     ReliableSpoolingFileEventExtReader.class.getSimpleName(),  
  165.                     spoolDirectory, trackerDirPath, deserializerType });  
  166.         }  
  167.   
  168.         // Verify directory exists and is readable/writable  
  169.         Preconditions  
  170.                 .checkState(  
  171.                         spoolDirectory.exists(),  
  172.                         "Directory does not exist: "  
  173.                                 + spoolDirectory.getAbsolutePath());  
  174.         Preconditions.checkState(spoolDirectory.isDirectory(),  
  175.                 "Path is not a directory: " + spoolDirectory.getAbsolutePath());  
  176.   
  177.         // Do a canary test to make sure we have access to spooling directory  
  178.         try {  
  179.             File canary = File.createTempFile("flume-spooldir-perm-check-",  
  180.                     ".canary", spoolDirectory);  
  181.             Files.write("testing flume file permissions\n", canary,  
  182.                     Charsets.UTF_8);  
  183.             List<String> lines = Files.readLines(canary, Charsets.UTF_8);  
  184.             Preconditions.checkState(!lines.isEmpty(), "Empty canary file %s",  
  185.                     canary);  
  186.             if (!canary.delete()) {  
  187.                 throw new IOException("Unable to delete canary file " + canary);  
  188.             }  
  189.             logger.debug("Successfully created and deleted canary file: {}",  
  190.                     canary);  
  191.         } catch (IOException e) {  
  192.             throw new FlumeException("Unable to read and modify files"  
  193.                     + " in the spooling directory: " + spoolDirectory, e);  
  194.         }  
  195.   
  196.         this.spoolDirectory = spoolDirectory;  
  197.         this.completedSuffix = completedSuffix;  
  198.         this.deserializerType = deserializerType;  
  199.         this.deserializerContext = deserializerContext;  
  200.         this.annotateFileName = annotateFileName;  
  201.         this.fileNameHeader = fileNameHeader;  
  202.         this.annotateBaseName = annotateBaseName;  
  203.         this.baseNameHeader = baseNameHeader;  
  204.         this.ignorePattern = Pattern.compile(ignorePattern);  
  205.         this.deletePolicy = deletePolicy;  
  206.         this.inputCharset = Charset.forName(inputCharset);  
  207.         this.decodeErrorPolicy = Preconditions.checkNotNull(decodeErrorPolicy);  
  208.   
  209.         // 增加代码开始  
  210.         this.annotateFileNameExtractor = annotateFileNameExtractor;  
  211.         this.fileNameExtractorHeader = fileNameExtractorHeader;  
  212.         this.fileNameExtractorPattern = Pattern  
  213.                 .compile(fileNameExtractorPattern);  
  214.         this.convertToTimestamp = convertToTimestamp;  
  215.         this.dateTimeFormat = dateTimeFormat;  
  216.   
  217.         this.splitFileName = splitFileName;  
  218.         this.splitBy = splitBy;  
  219.         this.splitBaseNameHeader = splitBaseNameHeader;  
  220.         // 增加代码结束  
  221.   
  222.         File trackerDirectory = new File(trackerDirPath);  
  223.   
  224.         // if relative path, treat as relative to spool directory  
  225.         if (!trackerDirectory.isAbsolute()) {  
  226.             trackerDirectory = new File(spoolDirectory, trackerDirPath);  
  227.         }  
  228.   
  229.         // ensure that meta directory exists  
  230.         if (!trackerDirectory.exists()) {  
  231.             if (!trackerDirectory.mkdir()) {  
  232.                 throw new IOException(  
  233.                         "Unable to mkdir nonexistent meta directory "  
  234.                                 + trackerDirectory);  
  235.             }  
  236.         }  
  237.   
  238.         // ensure that the meta directory is a directory  
  239.         if (!trackerDirectory.isDirectory()) {  
  240.             throw new IOException("Specified meta directory is not a directory"  
  241.                     + trackerDirectory);  
  242.         }  
  243.   
  244.         this.metaFile = new File(trackerDirectory, metaFileName);  
  245.     }  
  246.   
  247.     /** 
  248.      * Return the filename which generated the data from the last successful 
  249.      * {@link #readEvents(int)} call. Returns null if called before any file 
  250.      * contents are read. 
  251.      */  
  252.     public String getLastFileRead() {  
  253.         if (!lastFileRead.isPresent()) {  
  254.             return null;  
  255.         }  
  256.         return lastFileRead.get().getFile().getAbsolutePath();  
  257.     }  
  258.   
  259.     // public interface  
  260.     public Event readEvent() throws IOException {  
  261.         List<Event> events = readEvents(1);  
  262.         if (!events.isEmpty()) {  
  263.             return events.get(0);  
  264.         } else {  
  265.             return null;  
  266.         }  
  267.     }  
  268.   
  269.     public List<Event> readEvents(int numEvents) throws IOException {  
  270.         if (!committed) {  
  271.             if (!currentFile.isPresent()) {  
  272.                 throw new IllegalStateException("File should not roll when "  
  273.                         + "commit is outstanding.");  
  274.             }  
  275.             logger.info("Last read was never committed - resetting mark position.");  
  276.             currentFile.get().getDeserializer().reset();  
  277.         } else {  
  278.             // Check if new files have arrived since last call  
  279.             if (!currentFile.isPresent()) {  
  280.                 currentFile = getNextFile();  
  281.             }  
  282.             // Return empty list if no new files  
  283.             if (!currentFile.isPresent()) {  
  284.                 return Collections.emptyList();  
  285.             }  
  286.         }  
  287.   
  288.         EventDeserializer des = currentFile.get().getDeserializer();  
  289.         List<Event> events = des.readEvents(numEvents);  
  290.   
  291.         /* 
  292.          * It's possible that the last read took us just up to a file boundary. 
  293.          * If so, try to roll to the next file, if there is one. 
  294.          */  
  295.         if (events.isEmpty()) {  
  296.             retireCurrentFile();  
  297.             currentFile = getNextFile();  
  298.             if (!currentFile.isPresent()) {  
  299.                 return Collections.emptyList();  
  300.             }  
  301.             events = currentFile.get().getDeserializer().readEvents(numEvents);  
  302.         }  
  303.   
  304.         if (annotateFileName) {  
  305.             String filename = currentFile.get().getFile().getAbsolutePath();  
  306.             for (Event event : events) {  
  307.                 event.getHeaders().put(fileNameHeader, filename);  
  308.             }  
  309.         }  
  310.   
  311.         if (annotateBaseName) {  
  312.             String basename = currentFile.get().getFile().getName();  
  313.             for (Event event : events) {  
  314.                 event.getHeaders().put(baseNameHeader, basename);  
  315.             }  
  316.         }  
  317.   
  318.         // 增加代码开始  
  319.   
  320.         // 按正则抽取文件名的内容  
  321.         if (annotateFileNameExtractor) {  
  322.   
  323.             Matcher matcher = fileNameExtractorPattern.matcher(currentFile  
  324.                     .get().getFile().getName());  
  325.   
  326.             if (matcher.find()) {  
  327.                 String value = matcher.group();  
  328.                 if (convertToTimestamp) {  
  329.                     DateTimeFormatter formatter = DateTimeFormat  
  330.                             .forPattern(dateTimeFormat);  
  331.                     DateTime dateTime = formatter.parseDateTime(value);  
  332.   
  333.                     value = Long.toString(dateTime.getMillis());  
  334.                 }  
  335.   
  336.                 for (Event event : events) {  
  337.                     event.getHeaders().put(fileNameExtractorHeader, value);  
  338.                 }  
  339.             }  
  340.   
  341.         }  
  342.   
  343.         // 按分隔符拆分文件名  
  344.         if (splitFileName) {  
  345.             String[] splits = currentFile.get().getFile().getName()  
  346.                     .split(splitBy);  
  347.   
  348.             for (Event event : events) {  
  349.                 for (int i = 0; i < splits.length; i++) {  
  350.                     event.getHeaders().put(splitBaseNameHeader + i, splits[i]);  
  351.                 }  
  352.   
  353.             }  
  354.   
  355.         }  
  356.   
  357.         // 增加代码结束  
  358.   
  359.         committed = false;  
  360.         lastFileRead = currentFile;  
  361.         return events;  
  362.     }  
  363.   
  364.     @Override  
  365.     public void close() throws IOException {  
  366.         if (currentFile.isPresent()) {  
  367.             currentFile.get().getDeserializer().close();  
  368.             currentFile = Optional.absent();  
  369.         }  
  370.     }  
  371.   
  372.     /** Commit the last lines which were read. */  
  373.     @Override  
  374.     public void commit() throws IOException {  
  375.         if (!committed && currentFile.isPresent()) {  
  376.             currentFile.get().getDeserializer().mark();  
  377.             committed = true;  
  378.         }  
  379.     }  
  380.   
  381.     /** 
  382.      * Closes currentFile and attempt to rename it. 
  383.      *  
  384.      * If these operations fail in a way that may cause duplicate log entries, 
  385.      * an error is logged but no exceptions are thrown. If these operations fail 
  386.      * in a way that indicates potential misuse of the spooling directory, a 
  387.      * FlumeException will be thrown. 
  388.      *  
  389.      * @throws FlumeException 
  390.      *             if files do not conform to spooling assumptions 
  391.      */  
  392.     private void retireCurrentFile() throws IOException {  
  393.         Preconditions.checkState(currentFile.isPresent());  
  394.   
  395.         File fileToRoll = new File(currentFile.get().getFile()  
  396.                 .getAbsolutePath());  
  397.   
  398.         currentFile.get().getDeserializer().close();  
  399.   
  400.         // Verify that spooling assumptions hold  
  401.         if (fileToRoll.lastModified() != currentFile.get().getLastModified()) {  
  402.             String message = "File has been modified since being read: "  
  403.                     + fileToRoll;  
  404.             throw new IllegalStateException(message);  
  405.         }  
  406.         if (fileToRoll.length() != currentFile.get().getLength()) {  
  407.             String message = "File has changed size since being read: "  
  408.                     + fileToRoll;  
  409.             throw new IllegalStateException(message);  
  410.         }  
  411.   
  412.         if (deletePolicy.equalsIgnoreCase(DeletePolicy.NEVER.name())) {  
  413.             rollCurrentFile(fileToRoll);  
  414.         } else if (deletePolicy.equalsIgnoreCase(DeletePolicy.IMMEDIATE.name())) {  
  415.             deleteCurrentFile(fileToRoll);  
  416.         } else {  
  417.             // TODO: implement delay in the future  
  418.             throw new IllegalArgumentException("Unsupported delete policy: "  
  419.                     + deletePolicy);  
  420.         }  
  421.     }  
  422.   
  423.     /** 
  424.      * Rename the given spooled file 
  425.      *  
  426.      * @param fileToRoll 
  427.      * @throws IOException 
  428.      */  
  429.     private void rollCurrentFile(File fileToRoll) throws IOException {  
  430.   
  431.         File dest = new File(fileToRoll.getPath() + completedSuffix);  
  432.         logger.info("Preparing to move file {} to {}", fileToRoll, dest);  
  433.   
  434.         // Before renaming, check whether destination file name exists  
  435.         if (dest.exists() && PlatformDetect.isWindows()) {  
  436.             /* 
  437.              * If we are here, it means the completed file already exists. In 
  438.              * almost every case this means the user is violating an assumption 
  439.              * of Flume (that log files are placed in the spooling directory 
  440.              * with unique names). However, there is a corner case on Windows 
  441.              * systems where the file was already rolled but the rename was not 
  442.              * atomic. If that seems likely, we let it pass with only a warning. 
  443.              */  
  444.             if (Files.equal(currentFile.get().getFile(), dest)) {  
  445.                 logger.warn("Completed file " + dest  
  446.                         + " already exists, but files match, so continuing.");  
  447.                 boolean deleted = fileToRoll.delete();  
  448.                 if (!deleted) {  
  449.                     logger.error("Unable to delete file "  
  450.                             + fileToRoll.getAbsolutePath()  
  451.                             + ". It will likely be ingested another time.");  
  452.                 }  
  453.             } else {  
  454.                 String message = "File name has been re-used with different"  
  455.                         + " files. Spooling assumptions violated for " + dest;  
  456.                 throw new IllegalStateException(message);  
  457.             }  
  458.   
  459.             // Dest file exists and not on windows  
  460.         } else if (dest.exists()) {  
  461.             String message = "File name has been re-used with different"  
  462.                     + " files. Spooling assumptions violated for " + dest;  
  463.             throw new IllegalStateException(message);  
  464.   
  465.             // Destination file does not already exist. We are good to go!  
  466.         } else {  
  467.             boolean renamed = fileToRoll.renameTo(dest);  
  468.             if (renamed) {  
  469.                 logger.debug("Successfully rolled file {} to {}", fileToRoll,  
  470.                         dest);  
  471.   
  472.                 // now we no longer need the meta file  
  473.                 deleteMetaFile();  
  474.             } else {  
  475.                 /* 
  476.                  * If we are here then the file cannot be renamed for a reason 
  477.                  * other than that the destination file exists (actually, that 
  478.                  * remains possible w/ small probability due to TOC-TOU 
  479.                  * conditions). 
  480.                  */  
  481.                 String message = "Unable to move "  
  482.                         + fileToRoll  
  483.                         + " to "  
  484.                         + dest  
  485.                         + ". This will likely cause duplicate events. Please verify that "  
  486.                         + "flume has sufficient permissions to perform these operations.";  
  487.                 throw new FlumeException(message);  
  488.             }  
  489.         }  
  490.     }  
  491.   
  492.     /** 
  493.      * Delete the given spooled file 
  494.      *  
  495.      * @param fileToDelete 
  496.      * @throws IOException 
  497.      */  
  498.     private void deleteCurrentFile(File fileToDelete) throws IOException {  
  499.         logger.info("Preparing to delete file {}", fileToDelete);  
  500.         if (!fileToDelete.exists()) {  
  501.             logger.warn("Unable to delete nonexistent file: {}", fileToDelete);  
  502.             return;  
  503.         }  
  504.         if (!fileToDelete.delete()) {  
  505.             throw new IOException("Unable to delete spool file: "  
  506.                     + fileToDelete);  
  507.         }  
  508.         // now we no longer need the meta file  
  509.         deleteMetaFile();  
  510.     }  
  511.   
  512.     /** 
  513.      * Find and open the oldest file in the chosen directory. If two or more 
  514.      * files are equally old, the file name with lower lexicographical value is 
  515.      * returned. If the directory is empty, this will return an absent option. 
  516.      */  
  517.     private Optional<FileInfo> getNextFile() {  
  518.         /* Filter to exclude finished or hidden files */  
  519.         FileFilter filter = new FileFilter() {  
  520.             public boolean accept(File candidate) {  
  521.                 String fileName = candidate.getName();  
  522.                 if ((candidate.isDirectory())  
  523.                         || (fileName.endsWith(completedSuffix))  
  524.                         || (fileName.startsWith("."))  
  525.                         || ignorePattern.matcher(fileName).matches()) {  
  526.                     return false;  
  527.                 }  
  528.                 return true;  
  529.             }  
  530.         };  
  531.         List<File> candidateFiles = Arrays.asList(spoolDirectory  
  532.                 .listFiles(filter));  
  533.         if (candidateFiles.isEmpty()) {  
  534.             return Optional.absent();  
  535.         } else {  
  536.             Collections.sort(candidateFiles, new Comparator<File>() {  
  537.                 public int compare(File a, File b) {  
  538.                     int timeComparison = new Long(a.lastModified())  
  539.                             .compareTo(new Long(b.lastModified()));  
  540.                     if (timeComparison != 0) {  
  541.                         return timeComparison;  
  542.                     } else {  
  543.                         return a.getName().compareTo(b.getName());  
  544.                     }  
  545.                 }  
  546.             });  
  547.             File nextFile = candidateFiles.get(0);  
  548.             try {  
  549.                 // roll the meta file, if needed  
  550.                 String nextPath = nextFile.getPath();  
  551.                 PositionTracker tracker = DurablePositionTracker.getInstance(  
  552.                         metaFile, nextPath);  
  553.                 if (!tracker.getTarget().equals(nextPath)) {  
  554.                     tracker.close();  
  555.                     deleteMetaFile();  
  556.                     tracker = DurablePositionTracker.getInstance(metaFile,  
  557.                             nextPath);  
  558.                 }  
  559.   
  560.                 // sanity check  
  561.                 Preconditions  
  562.                         .checkState(  
  563.                                 tracker.getTarget().equals(nextPath),  
  564.                                 "Tracker target %s does not equal expected filename %s",  
  565.                                 tracker.getTarget(), nextPath);  
  566.   
  567.                 ResettableInputStream in = new ResettableFileInputStream(  
  568.                         nextFile, tracker,  
  569.                         ResettableFileInputStream.DEFAULT_BUF_SIZE,  
  570.                         inputCharset, decodeErrorPolicy);  
  571.                 EventDeserializer deserializer = EventDeserializerFactory  
  572.                         .getInstance(deserializerType, deserializerContext, in);  
  573.   
  574.                 return Optional.of(new FileInfo(nextFile, deserializer));  
  575.             } catch (FileNotFoundException e) {  
  576.                 // File could have been deleted in the interim  
  577.                 logger.warn("Could not find file: " + nextFile, e);  
  578.                 return Optional.absent();  
  579.             } catch (IOException e) {  
  580.                 logger.error("Exception opening file: " + nextFile, e);  
  581.                 return Optional.absent();  
  582.             }  
  583.         }  
  584.     }  
  585.   
  586.     private void deleteMetaFile() throws IOException {  
  587.         if (metaFile.exists() && !metaFile.delete()) {  
  588.             throw new IOException("Unable to delete old meta file " + metaFile);  
  589.         }  
  590.     }  
  591.   
  592.     /** An immutable class with information about a file being processed. */  
  593.     private static class FileInfo {  
  594.         private final File file;  
  595.         private final long length;  
  596.         private final long lastModified;  
  597.         private final EventDeserializer deserializer;  
  598.   
  599.         public FileInfo(File file, EventDeserializer deserializer) {  
  600.             this.file = file;  
  601.             this.length = file.length();  
  602.             this.lastModified = file.lastModified();  
  603.             this.deserializer = deserializer;  
  604.         }  
  605.   
  606.         public long getLength() {  
  607.             return length;  
  608.         }  
  609.   
  610.         public long getLastModified() {  
  611.             return lastModified;  
  612.         }  
  613.   
  614.         public EventDeserializer getDeserializer() {  
  615.             return deserializer;  
  616.         }  
  617.   
  618.         public File getFile() {  
  619.             return file;  
  620.         }  
  621.     }  
  622.   
  623.     @InterfaceAudience.Private  
  624.     @InterfaceStability.Unstable  
  625.     static enum DeletePolicy {  
  626.         NEVER, IMMEDIATE, DELAY  
  627.     }  
  628.   
  629.     /** 
  630.      * Special builder class for ReliableSpoolingFileEventReader 
  631.      */  
  632.     public static class Builder {  
  633.         private File spoolDirectory;  
  634.         private String completedSuffix = SpoolDirectorySourceConfigurationExtConstants.SPOOLED_FILE_SUFFIX;  
  635.         private String ignorePattern = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_IGNORE_PAT;  
  636.         private String trackerDirPath = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_TRACKER_DIR;  
  637.         private Boolean annotateFileName = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILE_HEADER;  
  638.         private String fileNameHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_HEADER_KEY;  
  639.         private Boolean annotateBaseName = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_BASENAME_HEADER;  
  640.         private String baseNameHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_BASENAME_HEADER_KEY;  
  641.         private String deserializerType = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_DESERIALIZER;  
  642.         private Context deserializerContext = new Context();  
  643.         private String deletePolicy = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_DELETE_POLICY;  
  644.         private String inputCharset = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_INPUT_CHARSET;  
  645.         private DecodeErrorPolicy decodeErrorPolicy = DecodeErrorPolicy  
  646.                 .valueOf(SpoolDirectorySourceConfigurationExtConstants.DEFAULT_DECODE_ERROR_POLICY  
  647.                         .toUpperCase());  
  648.   
  649.         // 增加代码开始  
  650.   
  651.         private Boolean annotateFileNameExtractor = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR;  
  652.         private String fileNameExtractorHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_HEADER_KEY;  
  653.         private String fileNameExtractorPattern = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_PATTERN;  
  654.         private Boolean convertToTimestamp = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP;  
  655.   
  656.         private String dateTimeFormat = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_DATETIME_FORMAT;  
  657.   
  658.         private Boolean splitFileName = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_SPLIT_FILENAME;  
  659.         private String splitBy = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_SPLITY_BY;  
  660.         private String splitBaseNameHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_SPLIT_BASENAME_HEADER;  
  661.   
  662.         public Builder annotateFileNameExtractor(  
  663.                 Boolean annotateFileNameExtractor) {  
  664.             this.annotateFileNameExtractor = annotateFileNameExtractor;  
  665.             return this;  
  666.         }  
  667.   
  668.         public Builder fileNameExtractorHeader(String fileNameExtractorHeader) {  
  669.             this.fileNameExtractorHeader = fileNameExtractorHeader;  
  670.             return this;  
  671.         }  
  672.   
  673.         public Builder fileNameExtractorPattern(String fileNameExtractorPattern) {  
  674.             this.fileNameExtractorPattern = fileNameExtractorPattern;  
  675.             return this;  
  676.         }  
  677.   
  678.         public Builder convertToTimestamp(Boolean convertToTimestamp) {  
  679.             this.convertToTimestamp = convertToTimestamp;  
  680.             return this;  
  681.         }  
  682.   
  683.         public Builder dateTimeFormat(String dateTimeFormat) {  
  684.             this.dateTimeFormat = dateTimeFormat;  
  685.             return this;  
  686.         }  
  687.   
  688.         public Builder splitFileName(Boolean splitFileName) {  
  689.             this.splitFileName = splitFileName;  
  690.             return this;  
  691.         }  
  692.   
  693.         public Builder splitBy(String splitBy) {  
  694.             this.splitBy = splitBy;  
  695.             return this;  
  696.         }  
  697.   
  698.         public Builder splitBaseNameHeader(String splitBaseNameHeader) {  
  699.             this.splitBaseNameHeader = splitBaseNameHeader;  
  700.             return this;  
  701.         }  
  702.   
  703.         // 增加代码结束  
  704.   
  705.         public Builder spoolDirectory(File directory) {  
  706.             this.spoolDirectory = directory;  
  707.             return this;  
  708.         }  
  709.   
  710.         public Builder completedSuffix(String completedSuffix) {  
  711.             this.completedSuffix = completedSuffix;  
  712.             return this;  
  713.         }  
  714.   
  715.         public Builder ignorePattern(String ignorePattern) {  
  716.             this.ignorePattern = ignorePattern;  
  717.             return this;  
  718.         }  
  719.   
  720.         public Builder trackerDirPath(String trackerDirPath) {  
  721.             this.trackerDirPath = trackerDirPath;  
  722.             return this;  
  723.         }  
  724.   
  725.         public Builder annotateFileName(Boolean annotateFileName) {  
  726.             this.annotateFileName = annotateFileName;  
  727.             return this;  
  728.         }  
  729.   
  730.         public Builder fileNameHeader(String fileNameHeader) {  
  731.             this.fileNameHeader = fileNameHeader;  
  732.             return this;  
  733.         }  
  734.   
  735.         public Builder annotateBaseName(Boolean annotateBaseName) {  
  736.             this.annotateBaseName = annotateBaseName;  
  737.             return this;  
  738.         }  
  739.   
  740.         public Builder baseNameHeader(String baseNameHeader) {  
  741.             this.baseNameHeader = baseNameHeader;  
  742.             return this;  
  743.         }  
  744.   
  745.         public Builder deserializerType(String deserializerType) {  
  746.             this.deserializerType = deserializerType;  
  747.             return this;  
  748.         }  
  749.   
  750.         public Builder deserializerContext(Context deserializerContext) {  
  751.             this.deserializerContext = deserializerContext;  
  752.             return this;  
  753.         }  
  754.   
  755.         public Builder deletePolicy(String deletePolicy) {  
  756.             this.deletePolicy = deletePolicy;  
  757.             return this;  
  758.         }  
  759.   
  760.         public Builder inputCharset(String inputCharset) {  
  761.             this.inputCharset = inputCharset;  
  762.             return this;  
  763.         }  
  764.   
  765.         public Builder decodeErrorPolicy(DecodeErrorPolicy decodeErrorPolicy) {  
  766.             this.decodeErrorPolicy = decodeErrorPolicy;  
  767.             return this;  
  768.         }  
  769.   
  770.         public ReliableSpoolingFileEventExtReader build() throws IOException {  
  771.             return new ReliableSpoolingFileEventExtReader(spoolDirectory,  
  772.                     completedSuffix, ignorePattern, trackerDirPath,  
  773.                     annotateFileName, fileNameHeader, annotateBaseName,  
  774.                     baseNameHeader, deserializerType, deserializerContext,  
  775.                     deletePolicy, inputCharset, decodeErrorPolicy,  
  776.                     annotateFileNameExtractor, fileNameExtractorHeader,  
  777.                     fileNameExtractorPattern, convertToTimestamp,  
  778.                     dateTimeFormat, splitFileName, splitBy, splitBaseNameHeader);  
  779.         }  
  780.     }  
  781.   
  782. }  

[java]  view plain  copy
  1. /* 
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  * contributor license agreements. See the NOTICE file distributed with this 
  4.  * work for additional information regarding copyright ownership. The ASF 
  5.  * licenses this file to you under the Apache License, Version 2.0 (the 
  6.  * "License"); you may not use this file except in compliance with the License. 
  7.  * You may obtain a copy of the License at 
  8.  * 
  9.  * http://www.apache.org/licenses/LICENSE-2.0 
  10.  * 
  11.  * Unless required by applicable law or agreed to in writing, software 
  12.  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
  13.  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
  14.  * License for the specific language governing permissions and limitations under 
  15.  * the License. 
  16.  */  
  17.   
  18. package com.bbaiggey.flume;  
  19.   
  20. import org.apache.flume.serialization.DecodeErrorPolicy;  
  21.   
  22. public class SpoolDirectorySourceConfigurationExtConstants {  
  23.     /** Directory where files are deposited. */  
  24.     public static final String SPOOL_DIRECTORY = "spoolDir";  
  25.   
  26.     /** Suffix appended to files when they are finished being sent. */  
  27.     public static final String SPOOLED_FILE_SUFFIX = "fileSuffix";  
  28.     public static final String DEFAULT_SPOOLED_FILE_SUFFIX = ".COMPLETED";  
  29.   
  30.     /** Header in which to put absolute path filename. */  
  31.     public static final String FILENAME_HEADER_KEY = "fileHeaderKey";  
  32.     public static final String DEFAULT_FILENAME_HEADER_KEY = "file";  
  33.   
  34.     /** Whether to include absolute path filename in a header. */  
  35.     public static final String FILENAME_HEADER = "fileHeader";  
  36.     public static final boolean DEFAULT_FILE_HEADER = false;  
  37.   
  38.     /** Header in which to put the basename of file. */  
  39.     public static final String BASENAME_HEADER_KEY = "basenameHeaderKey";  
  40.     public static final String DEFAULT_BASENAME_HEADER_KEY = "basename";  
  41.   
  42.     /** Whether to include the basename of a file in a header. */  
  43.     public static final String BASENAME_HEADER = "basenameHeader";  
  44.     public static final boolean DEFAULT_BASENAME_HEADER = false;  
  45.   
  46.     /** What size to batch with before sending to ChannelProcessor. */  
  47.     public static final String BATCH_SIZE = "batchSize";  
  48.     public static final int DEFAULT_BATCH_SIZE = 100;  
  49.   
  50.     /** Maximum number of lines to buffer between commits. */  
  51.     @Deprecated  
  52.     public static final String BUFFER_MAX_LINES = "bufferMaxLines";  
  53.     @Deprecated  
  54.     public static final int DEFAULT_BUFFER_MAX_LINES = 100;  
  55.   
  56.     /** Maximum length of line (in characters) in buffer between commits. */  
  57.     @Deprecated  
  58.     public static final String BUFFER_MAX_LINE_LENGTH = "bufferMaxLineLength";  
  59.     @Deprecated  
  60.     public static final int DEFAULT_BUFFER_MAX_LINE_LENGTH = 5000;  
  61.   
  62.     /** Pattern of files to ignore */  
  63.     public static final String IGNORE_PAT = "ignorePattern";  
  64.     public static final String DEFAULT_IGNORE_PAT = "^$"// no effect  
  65.   
  66.     /** Directory to store metadata about files being processed */  
  67.     public static final String TRACKER_DIR = "trackerDir";  
  68.     public static final String DEFAULT_TRACKER_DIR = ".flumespool";  
  69.   
  70.     /** Deserializer to use to parse the file data into Flume Events */  
  71.     public static final String DESERIALIZER = "deserializer";  
  72.     public static final String DEFAULT_DESERIALIZER = "LINE";  
  73.   
  74.     public static final String DELETE_POLICY = "deletePolicy";  
  75.     public static final String DEFAULT_DELETE_POLICY = "never";  
  76.   
  77.     /** Character set used when reading the input. */  
  78.     public static final String INPUT_CHARSET = "inputCharset";  
  79.     public static final String DEFAULT_INPUT_CHARSET = "UTF-8";  
  80.   
  81.     /** What to do when there is a character set decoding error. */  
  82.     public static final String DECODE_ERROR_POLICY = "decodeErrorPolicy";  
  83.     public static final String DEFAULT_DECODE_ERROR_POLICY = DecodeErrorPolicy.FAIL  
  84.             .name();  
  85.   
  86.     public static final String MAX_BACKOFF = "maxBackoff";  
  87.   
  88.     public static final Integer DEFAULT_MAX_BACKOFF = 4000;  
  89.   
  90.     // 增加代码开始  
  91.     public static final String FILENAME_EXTRACTOR = "fileExtractor";  
  92.     public static final boolean DEFAULT_FILENAME_EXTRACTOR = false;  
  93.   
  94.     public static final String FILENAME_EXTRACTOR_HEADER_KEY = "fileExtractorHeaderKey";  
  95.     public static final String DEFAULT_FILENAME_EXTRACTOR_HEADER_KEY = "fileExtractorHeader";  
  96.   
  97.     public static final String FILENAME_EXTRACTOR_PATTERN = "fileExtractorPattern";  
  98.     public static final String DEFAULT_FILENAME_EXTRACTOR_PATTERN = "(.)*";  
  99.   
  100.     public static final String FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP = "convertToTimestamp";  
  101.     public static final boolean DEFAULT_FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP = false;  
  102.   
  103.     public static final String FILENAME_EXTRACTOR_DATETIME_FORMAT = "dateTimeFormat";  
  104.     public static final String DEFAULT_FILENAME_EXTRACTOR_DATETIME_FORMAT = "yyyy-MM-dd";  
  105.   
  106.   
  107.     public static final String SPLIT_FILENAME = "splitFileName";  
  108.     public static final boolean DEFAULT_SPLIT_FILENAME = false;  
  109.   
  110.     public static final String SPLITY_BY = "splitBy";  
  111.     public static final String DEFAULT_SPLITY_BY = "\\.";  
  112.   
  113.     public static final String SPLIT_BASENAME_HEADER = "splitBaseNameHeader";  
  114.     public static final String DEFAULT_SPLIT_BASENAME_HEADER = "fileNameSplit";  
  115.     // 增加代码结束  
  116.   
  117. }  

[java]  view plain  copy
  1. package com.bbaiggey.flume;  
  2.   
  3. import static com.bbaiggey.flume.SpoolDirectorySourceConfigurationExtConstants.*;  
  4.   
  5.   
  6. import java.io.File;  
  7. import java.io.IOException;  
  8. import java.util.List;  
  9. import java.util.concurrent.Executors;  
  10. import java.util.concurrent.ScheduledExecutorService;  
  11. import java.util.concurrent.TimeUnit;  
  12.   
  13. import org.apache.flume.ChannelException;  
  14. import org.apache.flume.Context;  
  15. import org.apache.flume.Event;  
  16. import org.apache.flume.EventDrivenSource;  
  17. import org.apache.flume.FlumeException;  
  18. import org.apache.flume.conf.Configurable;  
  19. import org.apache.flume.instrumentation.SourceCounter;  
  20. import org.apache.flume.serialization.DecodeErrorPolicy;  
  21. import org.apache.flume.serialization.LineDeserializer;  
  22. import org.apache.flume.source.AbstractSource;  
  23. import org.slf4j.Logger;  
  24. import org.slf4j.LoggerFactory;  
  25.   
  26. import com.google.common.annotations.VisibleForTesting;  
  27. import com.google.common.base.Preconditions;  
  28. import com.google.common.base.Throwables;  
  29.   
  30. public class SpoolDirectoryExtSource extends AbstractSource implements  
  31.         Configurable, EventDrivenSource {  
  32.   
  33.     private static final Logger logger = LoggerFactory  
  34.             .getLogger(SpoolDirectoryExtSource.class);  
  35.   
  36.     // Delay used when polling for new files  
  37.     private static final int POLL_DELAY_MS = 500;  
  38.   
  39.     /* Config options */  
  40.     private String completedSuffix;  
  41.     private String spoolDirectory;  
  42.     private boolean fileHeader;  
  43.     private String fileHeaderKey;  
  44.     private boolean basenameHeader;  
  45.     private String basenameHeaderKey;  
  46.     private int batchSize;  
  47.     private String ignorePattern;  
  48.     private String trackerDirPath;  
  49.     private String deserializerType;  
  50.     private Context deserializerContext;  
  51.     private String deletePolicy;  
  52.     private String inputCharset;  
  53.     private DecodeErrorPolicy decodeErrorPolicy;  
  54.     private volatile boolean hasFatalError = false;  
  55.   
  56.     private SourceCounter sourceCounter;  
  57.     ReliableSpoolingFileEventExtReader reader;  
  58.     private ScheduledExecutorService executor;  
  59.     private boolean backoff = true;  
  60.     private boolean hitChannelException = false;  
  61.     private int maxBackoff;  
  62.   
  63.     // 增加代码开始  
  64.   
  65.     private Boolean annotateFileNameExtractor;  
  66.     private String fileNameExtractorHeader;  
  67.     private String fileNameExtractorPattern;  
  68.     private Boolean convertToTimestamp;  
  69.   
  70.     private String dateTimeFormat;  
  71.       
  72.     private boolean splitFileName;  
  73.     private  String splitBy;  
  74.     private  String splitBaseNameHeader;  
  75.   
  76.     // 增加代码结束  
  77.   
  78.     @Override  
  79.     public synchronized void start() {  
  80.         logger.info("SpoolDirectorySource source starting with directory: {}",  
  81.                 spoolDirectory);  
  82.   
  83.         executor = Executors.newSingleThreadScheduledExecutor();  
  84.   
  85.         File directory = new File(spoolDirectory);  
  86.         try {  
  87.             reader = new ReliableSpoolingFileEventExtReader.Builder()  
  88.                     .spoolDirectory(directory).completedSuffix(completedSuffix)  
  89.                     .ignorePattern(ignorePattern)  
  90.                     .trackerDirPath(trackerDirPath)  
  91.                     .annotateFileName(fileHeader).fileNameHeader(fileHeaderKey)  
  92.                     .annotateBaseName(basenameHeader)  
  93.                     .baseNameHeader(basenameHeaderKey)  
  94.                     .deserializerType(deserializerType)  
  95.                     .deserializerContext(deserializerContext)  
  96.                     .deletePolicy(deletePolicy).inputCharset(inputCharset)  
  97.                     .decodeErrorPolicy(decodeErrorPolicy)  
  98.                     .annotateFileNameExtractor(annotateFileNameExtractor)  
  99.                     .fileNameExtractorHeader(fileNameExtractorHeader)  
  100.                     .fileNameExtractorPattern(fileNameExtractorPattern)  
  101.                     .convertToTimestamp(convertToTimestamp)  
  102.                     .dateTimeFormat(dateTimeFormat)  
  103.                     .splitFileName(splitFileName).splitBy(splitBy)  
  104.                     .splitBaseNameHeader(splitBaseNameHeader).build();  
  105.         } catch (IOException ioe) {  
  106.             throw new FlumeException(  
  107.                     "Error instantiating spooling event parser", ioe);  
  108.         }  
  109.   
  110.         Runnable runner = new SpoolDirectoryRunnable(reader, sourceCounter);  
  111.         executor.scheduleWithFixedDelay(runner, 0, POLL_DELAY_MS,  
  112.                 TimeUnit.MILLISECONDS);  
  113.   
  114.         super.start();  
  115.         logger.debug("SpoolDirectorySource source started");  
  116.         sourceCounter.start();  
  117.     }  
  118.   
  119.     @Override  
  120.     public synchronized void stop() {  
  121.         executor.shutdown();  
  122.         try {  
  123.             executor.awaitTermination(10L, TimeUnit.SECONDS);  
  124.         } catch (InterruptedException ex) {  
  125.             logger.info("Interrupted while awaiting termination", ex);  
  126.         }  
  127.         executor.shutdownNow();  
  128.   
  129.         super.stop();  
  130.         sourceCounter.stop();  
  131.         logger.info("SpoolDir source {} stopped. Metrics: {}", getName(),  
  132.                 sourceCounter);  
  133.     }  
  134.   
  135.     @Override  
  136.     public String toString() {  
  137.         return "Spool Directory source " + getName() + ": { spoolDir: "  
  138.                 + spoolDirectory + " }";  
  139.     }  
  140.   
  141.     @Override  
  142.     public synchronized void configure(Context context) {  
  143.         spoolDirectory = context.getString(SPOOL_DIRECTORY);  
  144.         Preconditions.checkState(spoolDirectory != null,  
  145.                 "Configuration must specify a spooling directory");  
  146.   
  147.         completedSuffix = context.getString(SPOOLED_FILE_SUFFIX,  
  148.                 DEFAULT_SPOOLED_FILE_SUFFIX);  
  149.         deletePolicy = context.getString(DELETE_POLICY, DEFAULT_DELETE_POLICY);  
  150.         fileHeader = context.getBoolean(FILENAME_HEADER, DEFAULT_FILE_HEADER);  
  151.         fileHeaderKey = context.getString(FILENAME_HEADER_KEY,  
  152.                 DEFAULT_FILENAME_HEADER_KEY);  
  153.         basenameHeader = context.getBoolean(BASENAME_HEADER,  
  154.                 DEFAULT_BASENAME_HEADER);  
  155.         basenameHeaderKey = context.getString(BASENAME_HEADER_KEY,  
  156.                 DEFAULT_BASENAME_HEADER_KEY);  
  157.         batchSize = context.getInteger(BATCH_SIZE, DEFAULT_BATCH_SIZE);  
  158.         inputCharset = context.getString(INPUT_CHARSET, DEFAULT_INPUT_CHARSET);  
  159.         decodeErrorPolicy = DecodeErrorPolicy  
  160.                 .valueOf(context.getString(DECODE_ERROR_POLICY,  
  161.                         DEFAULT_DECODE_ERROR_POLICY).toUpperCase());  
  162.   
  163.         ignorePattern = context.getString(IGNORE_PAT, DEFAULT_IGNORE_PAT);  
  164.         trackerDirPath = context.getString(TRACKER_DIR, DEFAULT_TRACKER_DIR);  
  165.   
  166.         deserializerType = context  
  167.                 .getString(DESERIALIZER, DEFAULT_DESERIALIZER);  
  168.         deserializerContext = new Context(context.getSubProperties(DESERIALIZER  
  169.                 + "."));  
  170.   
  171.         // "Hack" to support backwards compatibility with previous generation of  
  172.         // spooling directory source, which did not support deserializers  
  173.         Integer bufferMaxLineLength = context  
  174.                 .getInteger(BUFFER_MAX_LINE_LENGTH);  
  175.         if (bufferMaxLineLength != null && deserializerType != null  
  176.                 && deserializerType.equalsIgnoreCase(DEFAULT_DESERIALIZER)) {  
  177.             deserializerContext.put(LineDeserializer.MAXLINE_KEY,  
  178.                     bufferMaxLineLength.toString());  
  179.         }  
  180.   
  181.         maxBackoff = context.getInteger(MAX_BACKOFF, DEFAULT_MAX_BACKOFF);  
  182.         if (sourceCounter == null) {  
  183.             sourceCounter = new SourceCounter(getName());  
  184.         }  
  185.           
  186.         //增加代码开始  
  187.   
  188.         annotateFileNameExtractor=context.getBoolean(FILENAME_EXTRACTOR, DEFAULT_FILENAME_EXTRACTOR);  
  189.         fileNameExtractorHeader=context.getString(FILENAME_EXTRACTOR_HEADER_KEY, DEFAULT_FILENAME_EXTRACTOR_HEADER_KEY);  
  190.         fileNameExtractorPattern=context.getString(FILENAME_EXTRACTOR_PATTERN,DEFAULT_FILENAME_EXTRACTOR_PATTERN);  
  191.         convertToTimestamp=context.getBoolean(FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP, DEFAULT_FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP);  
  192.         dateTimeFormat=context.getString(FILENAME_EXTRACTOR_DATETIME_FORMAT, DEFAULT_FILENAME_EXTRACTOR_DATETIME_FORMAT);  
  193.           
  194.         splitFileName=context.getBoolean(SPLIT_FILENAME, DEFAULT_SPLIT_FILENAME);  
  195.         splitBy=context.getString(SPLITY_BY, DEFAULT_SPLITY_BY);  
  196.         splitBaseNameHeader=context.getString(SPLIT_BASENAME_HEADER, DEFAULT_SPLIT_BASENAME_HEADER);  
  197.           
  198.           
  199.           
  200.         //增加代码结束   
  201.     }  
  202.   
  203.     @VisibleForTesting  
  204.     protected boolean hasFatalError() {  
  205.         return hasFatalError;  
  206.     }  
  207.   
  208.     /** 
  209.      * The class always backs off, this exists only so that we can test without 
  210.      * taking a really long time. 
  211.      *  
  212.      * @param backoff 
  213.      *            - whether the source should backoff if the channel is full 
  214.      */  
  215.     @VisibleForTesting  
  216.     protected void setBackOff(boolean backoff) {  
  217.         this.backoff = backoff;  
  218.     }  
  219.   
  220.     @VisibleForTesting  
  221.     protected boolean hitChannelException() {  
  222.         return hitChannelException;  
  223.     }  
  224.   
  225.     @VisibleForTesting  
  226.     protected SourceCounter getSourceCounter() {  
  227.         return sourceCounter;  
  228.     }  
  229.   
  230.     private class SpoolDirectoryRunnable implements Runnable {  
  231.         private ReliableSpoolingFileEventExtReader reader;  
  232.         private SourceCounter sourceCounter;  
  233.   
  234.         public SpoolDirectoryRunnable(  
  235.                 ReliableSpoolingFileEventExtReader reader,  
  236.                 SourceCounter sourceCounter) {  
  237.             this.reader = reader;  
  238.             this.sourceCounter = sourceCounter;  
  239.         }  
  240.   
  241.         @Override  
  242.         public void run() {  
  243.             int backoffInterval = 250;  
  244.             try {  
  245.                 while (!Thread.interrupted()) {  
  246.                     List<Event> events = reader.readEvents(batchSize);  
  247.                     if (events.isEmpty()) {  
  248.                         break;  
  249.                     }  
  250.                     sourceCounter.addToEventReceivedCount(events.size());  
  251.                     sourceCounter.incrementAppendBatchReceivedCount();  
  252.   
  253.                     try {  
  254.                         getChannelProcessor().processEventBatch(events);  
  255.                         reader.commit();  
  256.                     } catch (ChannelException ex) {  
  257.                         logger.warn("The channel is full, and cannot write data now. The "  
  258.                                 + "source will try again after "  
  259.                                 + String.valueOf(backoffInterval)  
  260.                                 + " milliseconds");  
  261.                         hitChannelException = true;  
  262.                         if (backoff) {  
  263.                             TimeUnit.MILLISECONDS.sleep(backoffInterval);  
  264.                             backoffInterval = backoffInterval << 1;  
  265.                             backoffInterval = backoffInterval >= maxBackoff ? maxBackoff  
  266.                                     : backoffInterval;  
  267.                         }  
  268.                         continue;  
  269.                     }  
  270.                     backoffInterval = 250;  
  271.                     sourceCounter.addToEventAcceptedCount(events.size());  
  272.                     sourceCounter.incrementAppendBatchAcceptedCount();  
  273.                 }  
  274.                 logger.info("Spooling Directory Source runner has shutdown.");  
  275.             } catch (Throwable t) {  
  276.                 logger.error(  
  277.                         "FATAL: "  
  278.                                 + SpoolDirectoryExtSource.this.toString()  
  279.                                 + ": "  
  280.                                 + "Uncaught exception in SpoolDirectorySource thread. "  
  281.                                 + "Restart or reconfigure Flume to continue processing.",  
  282.                         t);  
  283.                 hasFatalError = true;  
  284.                 Throwables.propagate(t);  
  285.             }  
  286.         }  
  287.     }  
  288. }  

主要提供了如下几个设置参数:

tier1.sources.source1.type=com.besttone.flume.SpoolDirectoryExtSource   #写类的全路径名
tier1.sources.source1.spoolDir=/opt/logs   #监控的目录
tier1.sources.source1.splitFileName=true   #是否分隔文件名,并把分割后的内容添加到header中,默认false
tier1.sources.source1.splitBy=\\.                   #以什么符号分隔,默认是"."分隔
tier1.sources.source1.splitBaseNameHeader=fileNameSplit  #分割后写入header的key的前缀,比如a.log.2014-07-31,按“."分隔,

则header中有fileNameSplit0=a,fileNameSplit1=log,fileNameSplit2=2014-07-31


(其中还有扩展一个通过正则表达式抽取文件名的功能也在里面,我们这里不用到,就不介绍了)

扩展了这个source之后,前面的那个需求就很容易实现了,只需要:

tier1.sinks.sink1.hdfs.path=hdfs://master68:8020/flume/events/%{fileNameSplit0}/%{fileNameSplit2}

a.log.2014-07-31这个文件的内容就会保存到hdfs://master68:8020/flume/events/a/2014-07-31目录下面去了。


接下来我们说说如何部署这个我们扩展的自定义的spooling directory source(基于CM的设置)。

首先,我们把上面三个类打成JAR包:SpoolDirectoryExtSource.jar
CM的flume插件目录为:/var/lib/flume-ng/plugins.d

然后再你需要使用这个source的agent上的/var/lib/flume-ng/plugins.d目录下面创建SpoolDirectoryExtSource目录以及子目录lib,libext,native,lib是放插件JAR的目录,libext是放插件的依赖JAR的目录,native放使用到的原生库(如果有用到的话)。

我们这里没有使用到其他的依赖,于是就把SpoolDirectoryExtSource.jar放到lib目录下就好了,最终的目录结构:

plugins.d/
plugins.d/SpoolDirectoryExtSource/
plugins.d/SpoolDirectoryExtSource/lib/SpoolDirectoryExtSource.jar
plugins.d/SpoolDirectoryExtSource/libext/
plugins.d/SpoolDirectoryExtSource/native/
重新启动flume agent,flume就会自动装载我们的插件,这样在flume.conf中就可以使用全路径类名配置type属性了。

最终flume.conf配置如下:

[plain]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. tier1.sources=source1  
  2. tier1.channels=channel1  
  3. tier1.sinks=sink1  
  4. tier1.sources.source1.type=com.bbaiggey.flume.SpoolDirectoryExtSource  
  5. tier1.sources.source1.spoolDir=/opt/logs  
  6. tier1.sources.source1.splitFileName=true  
  7. tier1.sources.source1.splitBy=\\.  
  8. tier1.sources.source1.splitBaseNameHeader=fileNameSplit  
  9. tier1.sources.source1.channels=channel1  
  10. tier1.sinks.sink1.type=hdfs  
  11. tier1.sinks.sink1.channel=channel1  
  12. tier1.sinks.sink1.hdfs.path=hdfs://ns1:8020/flume/events/%{fileNameSplit0}/%{fileNameSplit2}  
  13. tier1.sinks.sink1.hdfs.round=true  
  14. tier1.sinks.sink1.hdfs.roundValue=10  
  15. tier1.sinks.sink1.hdfs.roundUnit=minute  
  16. tier1.sinks.sink1.hdfs.fileType=DataStream  
  17. tier1.sinks.sink1.hdfs.writeFormat=Text  
  18. tier1.sinks.sink1.hdfs.rollInterval=0  
  19. tier1.sinks.sink1.hdfs.rollSize=10240  
  20. tier1.sinks.sink1.hdfs.rollCount=0  
  21. tier1.sinks.sink1.hdfs.idleTimeout=60  
  22. tier1.channels.channel1.type=memory  
  23. tier1.channels.channel1.capacity=10000  
  24. tier1.channels.channel1.transactionCapacity=1000  
  25. tier1.channels.channel1.keep-alive=30  

附上一张用logger作为sink的查看日志文件的截图:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值