资讯专栏INFORMATION COLUMN

修改Flume源码使taildir source支持递归(可配置)

fuyi501 / 1836人阅读

摘要:的选哪个首选断点还原可以记录偏移量可配置文件组,里面使用正则表达式配置多个要监控的文件就凭第一点其他的都被比下去了这么好的有一点不完美,不能支持递归监控文件夹。

Flume的source选哪个?
taildir source首选!
1.断点还原 positionFile可以记录偏移量
2.可配置文件组,里面使用正则表达式配置多个要监控的文件
就凭第一点其他的source都被比下去了!
这么好的taildir source有一点不完美,不能支持递归监控文件夹。
所以就只能修改源代码了……好玩,我喜欢~

改源码,先读源码

Flume的taildir source启动会调用start()方法作初始化,里面创建一个ReliableTaildirEventReader,这里用到了建造者模式

</>复制代码

  1. @Override
  2. public synchronized void start() {
  3. logger.info("{} TaildirSource source starting with directory: {}", getName(), filePaths);
  4. try {
  5. reader = new ReliableTaildirEventReader.Builder()
  6. .filePaths(filePaths)
  7. .headerTable(headerTable)
  8. .positionFilePath(positionFilePath)
  9. .skipToEnd(skipToEnd)
  10. .addByteOffset(byteOffsetHeader)
  11. .cachePatternMatching(cachePatternMatching)
  12. .recursive(isRecursive)
  13. .annotateFileName(fileHeader)
  14. .fileNameHeader(fileHeaderKey)
  15. .build();
  16. } catch (IOException e) {
  17. throw new FlumeException("Error instantiating ReliableTaildirEventReader", e);
  18. }
  19. idleFileChecker = Executors.newSingleThreadScheduledExecutor(
  20. new ThreadFactoryBuilder().setNameFormat("idleFileChecker").build());
  21. idleFileChecker.scheduleWithFixedDelay(new idleFileCheckerRunnable(),
  22. idleTimeout, checkIdleInterval, TimeUnit.MILLISECONDS);
  23. positionWriter = Executors.newSingleThreadScheduledExecutor(
  24. new ThreadFactoryBuilder().setNameFormat("positionWriter").build());
  25. positionWriter.scheduleWithFixedDelay(new PositionWriterRunnable(),
  26. writePosInitDelay, writePosInterval, TimeUnit.MILLISECONDS);
  27. super.start();
  28. logger.debug("TaildirSource started");
  29. sourceCounter.start();
  30. }

taildir source属于PollableSource

</>复制代码

  1. /**
  2. * A {@link Source} that requires an external driver to poll to determine
  3. * whether there are {@linkplain Event events} that are available to ingest
  4. * from the source.
  5. *
  6. * @see org.apache.flume.source.EventDrivenSourceRunner
  7. */
  8. public interface PollableSource extends Source {
  9. ...

这段注释的意思是PollableSource是需要一个外部驱动去查看有没有需要消费的事件,从而拉取事件,讲白了就是定时拉取。所以flume也不一定是真正实时的,只是隔一会儿不停地来查看事件而已。(与之相应的是另一种EventDrivenSourceRunner)
那么taildir source在定时拉取事件的时候是调用的process方法

</>复制代码

  1. @Override
  2. public Status process() {
  3. Status status = Status.READY;
  4. try {
  5. existingInodes.clear();
  6. existingInodes.addAll(reader.updateTailFiles());
  7. for (long inode : existingInodes) {
  8. TailFile tf = reader.getTailFiles().get(inode);
  9. if (tf.needTail()) {
  10. tailFileProcess(tf, true);
  11. }
  12. }
  13. closeTailFiles();
  14. try {
  15. TimeUnit.MILLISECONDS.sleep(retryInterval);
  16. } catch (InterruptedException e) {
  17. logger.info("Interrupted while sleeping");
  18. }
  19. } catch (Throwable t) {
  20. logger.error("Unable to tail files", t);
  21. status = Status.BACKOFF;
  22. }
  23. return status;
  24. }

重点就是下面这几行

</>复制代码

  1. existingInodes.addAll(reader.updateTailFiles());
    for (long inode : existingInodes) {
    TailFile tf = reader.getTailFiles().get(inode);
    if (tf.needTail()) {
    tailFileProcess(tf, true);
    } }
    reader.updateTailFiles()获取需要监控的文件,然后对每一个进行处理,查看最后修改时间,判定是否需要tail,需要tailtail
    那么进入reader.updateTailFiles()

</>复制代码

  1. for (TaildirMatcher taildir : taildirCache) {
  2. Map headers = headerTable.row(taildir.getFileGroup());
  3. for (File f : taildir.getMatchingFiles()) {
  4. long inode = getInode(f);
  5. TailFile tf = tailFiles.get(inode);
  6. if (tf == null || !tf.getPath().equals(f.getAbsolutePath())) {
  7. long startPos = skipToEnd ? f.length() : 0;
  8. tf = openFile(f, headers, inode, startPos);

遍历每一个正则表达式匹配对应的匹配器,每个匹配器去获取匹配的文件!taildir.getMatchingFiles()

</>复制代码

  1. List getMatchingFiles() {
  2. long now = TimeUnit.SECONDS.toMillis(
  3. TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
  4. long currentParentDirMTime = parentDir.lastModified();
  5. List result;
  6. // calculate matched files if
  7. // - we don"t want to use cache (recalculate every time) OR
  8. // - directory was clearly updated after the last check OR
  9. // - last mtime change wasn"t already checked for sure
  10. // (system clock hasn"t passed that second yet)
  11. if (!cachePatternMatching ||
  12. lastSeenParentDirMTime < currentParentDirMTime ||
  13. !(currentParentDirMTime < lastCheckedTime)) {
  14. lastMatchedFiles = sortByLastModifiedTime(getMatchingFilesNoCache(isRecursive));
  15. lastSeenParentDirMTime = currentParentDirMTime;
  16. lastCheckedTime = now;
  17. }
  18. return lastMatchedFiles;
  19. }

可以看到getMatchingFilesNoCache(isRecursive)就是获取匹配的文件的方法,也就是需要修改的方法了!
ps:这里的isRecursive是我加的~
点进去:

</>复制代码

  1. private List getMatchingFilesNoCache() {
  2. List result = Lists.newArrayList();
  3. try (DirectoryStream stream = Files.newDirectoryStream(parentDir.toPath(), fileFilter)) {
  4. for (Path entry : stream) {
  5. result.add(entry.toFile());
  6. }
  7. } catch (IOException e) {
  8. logger.error("I/O exception occurred while listing parent directory. " +
  9. "Files already matched will be returned. " + parentDir.toPath(), e);
  10. }
  11. return result;
  12. }

源码是用了Files.newDirectoryStream(parentDir.toPath(), fileFilter)),将父目录下符合正则表达式的文件都添加到一个迭代器里。(这里还用了try (...)的语法糖)


找到地方了,开始改!

我在这个getMatchingFilesNoCache()方法下面下了一个重载的方法, 可增加扩展性:

</>复制代码

  1. private List getMatchingFilesNoCache(boolean recursion) {
  2. if (!recursion) {
  3. return getMatchingFilesNoCache();
  4. }
  5. List result = Lists.newArrayList();
  6. // 使用非递归的方式遍历文件夹
  7. Queue dirs = new ArrayBlockingQueue<>(10);
  8. dirs.offer(parentDir);
  9. while (dirs.size() > 0) {
  10. File dir = dirs.poll();
  11. try {
  12. DirectoryStream stream = Files.newDirectoryStream(dir.toPath(), fileFilter);
  13. stream.forEach(path -> result.add(path.toFile()));
  14. } catch (IOException e) {
  15. logger.error("I/O exception occurred while listing parent directory. " +
  16. "Files already matched will be returned. (recursion)" + parentDir.toPath(), e);
  17. }
  18. File[] dirList = dir.listFiles();
  19. assert dirList != null;
  20. for (File f : dirList) {
  21. if (f.isDirectory()) {
  22. dirs.add(f);
  23. }
  24. }
  25. }
  26. return result;
  27. }

我使用了非递归的方式遍历文件夹,就是树到队列的转换。
到这里,核心部分就改完了。接下来要处理这个recursion的参数


华丽的分割线后,顺腾摸瓜!

一路改构造方法,添加这个参数,最终参数从哪来呢?
flume的source启动时会调用configure方法,将Context中的内容配置进reader等对象中。
isRecursive = context.getBoolean(RECURSIVE, DEFAULT_RECURSIVE);
contextTaildirSourceConfigurationConstants中获取配置名和默认值

</>复制代码

  1. /**
  2. * Whether to support recursion. */
  3. public static final String RECURSIVE = "recursive";
  4. public static final boolean DEFAULT_RECURSIVE = false;

这里的recursive也就是flume配置文件里配置项了

</>复制代码

  1. # Whether to support recusion
  2. a1.sources.r1.recursive = true
大功告成,打包试试!

用maven只对这一个module打包。我把这个module的pom改了下artifactId,加上了自己名字作个纪念,哈哈
可惜pom里面不能写中文……

</>复制代码

  1. org.apache.flume.flume-ng-sources
  2. flume-taildir-source-recursive-by-Wish000
  3. Flume Taildir Source

执行package将其放在flume的lib下,替换原来的flume-taildir-source***.jar
启动,测试,成功!

具体代码见GitHub地址:https://github.com/Wish000/me...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/36029.html

相关文章

  • 修改Flume源码使taildir source支持递归配置

    摘要:的选哪个首选断点还原可以记录偏移量可配置文件组,里面使用正则表达式配置多个要监控的文件就凭第一点其他的都被比下去了这么好的有一点不完美,不能支持递归监控文件夹。 Flume的source选哪个?taildir source首选!1.断点还原 positionFile可以记录偏移量2.可配置文件组,里面使用正则表达式配置多个要监控的文件就凭第一点其他的source都被比下去了!这么好的t...

    tylin 评论0 收藏0
  • 微服务之分布式文件系统

    摘要:于是便诞生了随行付分布式文件系统简称,提供的海量安全低成本高可靠的云存储服务。子系统相关流程图如下核心实现主要为随行付各个业务系统提供文件共享和访问服务,并且可以按应用统计流量命中率空间等指标。 背景 传统Web应用中所有的功能部署在一起,图片、文件也在一台服务器;应用微服务架构后,服务之间的图片共享通过FTP+Nginx静态资源的方式进行访问,文件共享通过nfs磁盘挂载的方式进行访问...

    stormjun 评论0 收藏0
  • Flume日志采集框架的使

    摘要:对于一般的采集需求,通过对的简单配置即可实现。针对特殊场景也具备良好的自定义扩展能力,因此,可以适用于大部分的日常数据采集场景。 文章作者:foochane  原文链接:https://foochane.cn/article/2019062701.html Flume日志采集框架 安装和部署 Flume运行机制 采集静态文件到hdfs 采集动态日志文件到hdfs 两个agent级联 F...

    laznrbfe 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<