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

我想实现一个功能,就在读一个文件的时候,将文件的名字和文件生成的日期作为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 plaincopy
  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. package com.bbaiggey.flume;
  20. import java.io.File;
  21. import java.io.FileFilter;
  22. import java.io.FileNotFoundException;
  23. import java.io.IOException;
  24. import java.nio.charset.Charset;
  25. import java.util.Arrays;
  26. import java.util.Collections;
  27. import java.util.Comparator;
  28. import java.util.List;
  29. import java.util.regex.Matcher;
  30. import java.util.regex.Pattern;
  31. import org.apache.flume.Context;
  32. import org.apache.flume.Event;
  33. import org.apache.flume.FlumeException;
  34. import org.apache.flume.annotations.InterfaceAudience;
  35. import org.apache.flume.annotations.InterfaceStability;
  36. import org.apache.flume.client.avro.ReliableEventReader;
  37. import org.apache.flume.serialization.DecodeErrorPolicy;
  38. import org.apache.flume.serialization.DurablePositionTracker;
  39. import org.apache.flume.serialization.EventDeserializer;
  40. import org.apache.flume.serialization.EventDeserializerFactory;
  41. import org.apache.flume.serialization.PositionTracker;
  42. import org.apache.flume.serialization.ResettableFileInputStream;
  43. import org.apache.flume.serialization.ResettableInputStream;
  44. import org.apache.flume.tools.PlatformDetect;
  45. import org.joda.time.DateTime;
  46. import org.joda.time.format.DateTimeFormat;
  47. import org.joda.time.format.DateTimeFormatter;
  48. import org.slf4j.Logger;
  49. import org.slf4j.LoggerFactory;
  50. import com.google.common.base.Charsets;
  51. import com.google.common.base.Optional;
  52. import com.google.common.base.Preconditions;
  53. import com.google.common.io.Files;
  54. /**
  55. * <p/>
  56. * A {@link ReliableEventReader} which reads log data from files stored in a
  57. * spooling directory and renames each file once all of its data has been read
  58. * (through {@link EventDeserializer#readEvent()} calls). The user must
  59. * {@link #commit()} each read, to indicate that the lines have been fully
  60. * processed.
  61. * <p/>
  62. * Read calls will return no data if there are no files left to read. This
  63. * class, in general, is not thread safe.
  64. *
  65. * <p/>
  66. * This reader assumes that files with unique file names are left in the
  67. * spooling directory and not modified once they are placed there. Any user
  68. * behavior which violates these assumptions, when detected, will result in a
  69. * FlumeException being thrown.
  70. *
  71. * <p/>
  72. * This class makes the following guarantees, if above assumptions are met:
  73. * <ul>
  74. * <li>Once a log file has been renamed with the {@link #completedSuffix}, all
  75. * of its records have been read through the
  76. * {@link EventDeserializer#readEvent()} function and {@link #commit()}ed at
  77. * least once.
  78. * <li>All files in the spooling directory will eventually be opened and
  79. * delivered to a {@link #readEvents(int)} caller.
  80. * </ul>
  81. */
  82. @InterfaceAudience.Private
  83. @InterfaceStability.Evolving
  84. public class ReliableSpoolingFileEventExtReader implements ReliableEventReader {
  85. private static final Logger logger = LoggerFactory
  86. .getLogger(ReliableSpoolingFileEventExtReader.class);
  87. static final String metaFileName = ".flumespool-main.meta";
  88. private final File spoolDirectory;
  89. private final String completedSuffix;
  90. private final String deserializerType;
  91. private final Context deserializerContext;
  92. private final Pattern ignorePattern;
  93. private final File metaFile;
  94. private final boolean annotateFileName;
  95. private final boolean annotateBaseName;
  96. private final String fileNameHeader;
  97. private final String baseNameHeader;
  98. // 添加参数开始
  99. private final boolean annotateFileNameExtractor;
  100. private final String fileNameExtractorHeader;
  101. private final Pattern fileNameExtractorPattern;
  102. private final boolean convertToTimestamp;
  103. private final String dateTimeFormat;
  104. private final boolean splitFileName;
  105. private final String splitBy;
  106. private final String splitBaseNameHeader;
  107. // 添加参数结束
  108. private final String deletePolicy;
  109. private final Charset inputCharset;
  110. private final DecodeErrorPolicy decodeErrorPolicy;
  111. private Optional<FileInfo> currentFile = Optional.absent();
  112. /** Always contains the last file from which lines have been read. **/
  113. private Optional<FileInfo> lastFileRead = Optional.absent();
  114. private boolean committed = true;
  115. /**
  116. * Create a ReliableSpoolingFileEventReader to watch the given directory.
  117. */
  118. private ReliableSpoolingFileEventExtReader(File spoolDirectory,
  119. String completedSuffix, String ignorePattern,
  120. String trackerDirPath, boolean annotateFileName,
  121. String fileNameHeader, boolean annotateBaseName,
  122. String baseNameHeader, String deserializerType,
  123. Context deserializerContext, String deletePolicy,
  124. String inputCharset, DecodeErrorPolicy decodeErrorPolicy,
  125. boolean annotateFileNameExtractor, String fileNameExtractorHeader,
  126. String fileNameExtractorPattern, boolean convertToTimestamp,
  127. String dateTimeFormat, boolean splitFileName, String splitBy,
  128. String splitBaseNameHeader) throws IOException {
  129. // Sanity checks
  130. Preconditions.checkNotNull(spoolDirectory);
  131. Preconditions.checkNotNull(completedSuffix);
  132. Preconditions.checkNotNull(ignorePattern);
  133. Preconditions.checkNotNull(trackerDirPath);
  134. Preconditions.checkNotNull(deserializerType);
  135. Preconditions.checkNotNull(deserializerContext);
  136. Preconditions.checkNotNull(deletePolicy);
  137. Preconditions.checkNotNull(inputCharset);
  138. // validate delete policy
  139. if (!deletePolicy.equalsIgnoreCase(DeletePolicy.NEVER.name())
  140. && !deletePolicy
  141. .equalsIgnoreCase(DeletePolicy.IMMEDIATE.name())) {
  142. throw new IllegalArgumentException("Delete policies other than "
  143. + "NEVER and IMMEDIATE are not yet supported");
  144. }
  145. if (logger.isDebugEnabled()) {
  146. logger.debug("Initializing {} with directory={}, metaDir={}, "
  147. + "deserializer={}", new Object[] {
  148. ReliableSpoolingFileEventExtReader.class.getSimpleName(),
  149. spoolDirectory, trackerDirPath, deserializerType });
  150. }
  151. // Verify directory exists and is readable/writable
  152. Preconditions
  153. .checkState(
  154. spoolDirectory.exists(),
  155. "Directory does not exist: "
  156. + spoolDirectory.getAbsolutePath());
  157. Preconditions.checkState(spoolDirectory.isDirectory(),
  158. "Path is not a directory: " + spoolDirectory.getAbsolutePath());
  159. // Do a canary test to make sure we have access to spooling directory
  160. try {
  161. File canary = File.createTempFile("flume-spooldir-perm-check-",
  162. ".canary", spoolDirectory);
  163. Files.write("testing flume file permissions\n", canary,
  164. Charsets.UTF_8);
  165. List<String> lines = Files.readLines(canary, Charsets.UTF_8);
  166. Preconditions.checkState(!lines.isEmpty(), "Empty canary file %s",
  167. canary);
  168. if (!canary.delete()) {
  169. throw new IOException("Unable to delete canary file " + canary);
  170. }
  171. logger.debug("Successfully created and deleted canary file: {}",
  172. canary);
  173. } catch (IOException e) {
  174. throw new FlumeException("Unable to read and modify files"
  175. + " in the spooling directory: " + spoolDirectory, e);
  176. }
  177. this.spoolDirectory = spoolDirectory;
  178. this.completedSuffix = completedSuffix;
  179. this.deserializerType = deserializerType;
  180. this.deserializerContext = deserializerContext;
  181. this.annotateFileName = annotateFileName;
  182. this.fileNameHeader = fileNameHeader;
  183. this.annotateBaseName = annotateBaseName;
  184. this.baseNameHeader = baseNameHeader;
  185. this.ignorePattern = Pattern.compile(ignorePattern);
  186. this.deletePolicy = deletePolicy;
  187. this.inputCharset = Charset.forName(inputCharset);
  188. this.decodeErrorPolicy = Preconditions.checkNotNull(decodeErrorPolicy);
  189. // 增加代码开始
  190. this.annotateFileNameExtractor = annotateFileNameExtractor;
  191. this.fileNameExtractorHeader = fileNameExtractorHeader;
  192. this.fileNameExtractorPattern = Pattern
  193. .compile(fileNameExtractorPattern);
  194. this.convertToTimestamp = convertToTimestamp;
  195. this.dateTimeFormat = dateTimeFormat;
  196. this.splitFileName = splitFileName;
  197. this.splitBy = splitBy;
  198. this.splitBaseNameHeader = splitBaseNameHeader;
  199. // 增加代码结束
  200. File trackerDirectory = new File(trackerDirPath);
  201. // if relative path, treat as relative to spool directory
  202. if (!trackerDirectory.isAbsolute()) {
  203. trackerDirectory = new File(spoolDirectory, trackerDirPath);
  204. }
  205. // ensure that meta directory exists
  206. if (!trackerDirectory.exists()) {
  207. if (!trackerDirectory.mkdir()) {
  208. throw new IOException(
  209. "Unable to mkdir nonexistent meta directory "
  210. + trackerDirectory);
  211. }
  212. }
  213. // ensure that the meta directory is a directory
  214. if (!trackerDirectory.isDirectory()) {
  215. throw new IOException("Specified meta directory is not a directory"
  216. + trackerDirectory);
  217. }
  218. this.metaFile = new File(trackerDirectory, metaFileName);
  219. }
  220. /**
  221. * Return the filename which generated the data from the last successful
  222. * {@link #readEvents(int)} call. Returns null if called before any file
  223. * contents are read.
  224. */
  225. public String getLastFileRead() {
  226. if (!lastFileRead.isPresent()) {
  227. return null;
  228. }
  229. return lastFileRead.get().getFile().getAbsolutePath();
  230. }
  231. // public interface
  232. public Event readEvent() throws IOException {
  233. List<Event> events = readEvents(1);
  234. if (!events.isEmpty()) {
  235. return events.get(0);
  236. } else {
  237. return null;
  238. }
  239. }
  240. public List<Event> readEvents(int numEvents) throws IOException {
  241. if (!committed) {
  242. if (!currentFile.isPresent()) {
  243. throw new IllegalStateException("File should not roll when "
  244. + "commit is outstanding.");
  245. }
  246. logger.info("Last read was never committed - resetting mark position.");
  247. currentFile.get().getDeserializer().reset();
  248. } else {
  249. // Check if new files have arrived since last call
  250. if (!currentFile.isPresent()) {
  251. currentFile = getNextFile();
  252. }
  253. // Return empty list if no new files
  254. if (!currentFile.isPresent()) {
  255. return Collections.emptyList();
  256. }
  257. }
  258. EventDeserializer des = currentFile.get().getDeserializer();
  259. List<Event> events = des.readEvents(numEvents);
  260. /*
  261. * It's possible that the last read took us just up to a file boundary.
  262. * If so, try to roll to the next file, if there is one.
  263. */
  264. if (events.isEmpty()) {
  265. retireCurrentFile();
  266. currentFile = getNextFile();
  267. if (!currentFile.isPresent()) {
  268. return Collections.emptyList();
  269. }
  270. events = currentFile.get().getDeserializer().readEvents(numEvents);
  271. }
  272. if (annotateFileName) {
  273. String filename = currentFile.get().getFile().getAbsolutePath();
  274. for (Event event : events) {
  275. event.getHeaders().put(fileNameHeader, filename);
  276. }
  277. }
  278. if (annotateBaseName) {
  279. String basename = currentFile.get().getFile().getName();
  280. for (Event event : events) {
  281. event.getHeaders().put(baseNameHeader, basename);
  282. }
  283. }
  284. // 增加代码开始
  285. // 按正则抽取文件名的内容
  286. if (annotateFileNameExtractor) {
  287. Matcher matcher = fileNameExtractorPattern.matcher(currentFile
  288. .get().getFile().getName());
  289. if (matcher.find()) {
  290. String value = matcher.group();
  291. if (convertToTimestamp) {
  292. DateTimeFormatter formatter = DateTimeFormat
  293. .forPattern(dateTimeFormat);
  294. DateTime dateTime = formatter.parseDateTime(value);
  295. value = Long.toString(dateTime.getMillis());
  296. }
  297. for (Event event : events) {
  298. event.getHeaders().put(fileNameExtractorHeader, value);
  299. }
  300. }
  301. }
  302. // 按分隔符拆分文件名
  303. if (splitFileName) {
  304. String[] splits = currentFile.get().getFile().getName()
  305. .split(splitBy);
  306. for (Event event : events) {
  307. for (int i = 0; i < splits.length; i++) {
  308. event.getHeaders().put(splitBaseNameHeader + i, splits[i]);
  309. }
  310. }
  311. }
  312. // 增加代码结束
  313. committed = false;
  314. lastFileRead = currentFile;
  315. return events;
  316. }
  317. @Override
  318. public void close() throws IOException {
  319. if (currentFile.isPresent()) {
  320. currentFile.get().getDeserializer().close();
  321. currentFile = Optional.absent();
  322. }
  323. }
  324. /** Commit the last lines which were read. */
  325. @Override
  326. public void commit() throws IOException {
  327. if (!committed && currentFile.isPresent()) {
  328. currentFile.get().getDeserializer().mark();
  329. committed = true;
  330. }
  331. }
  332. /**
  333. * Closes currentFile and attempt to rename it.
  334. *
  335. * If these operations fail in a way that may cause duplicate log entries,
  336. * an error is logged but no exceptions are thrown. If these operations fail
  337. * in a way that indicates potential misuse of the spooling directory, a
  338. * FlumeException will be thrown.
  339. *
  340. * @throws FlumeException
  341. *             if files do not conform to spooling assumptions
  342. */
  343. private void retireCurrentFile() throws IOException {
  344. Preconditions.checkState(currentFile.isPresent());
  345. File fileToRoll = new File(currentFile.get().getFile()
  346. .getAbsolutePath());
  347. currentFile.get().getDeserializer().close();
  348. // Verify that spooling assumptions hold
  349. if (fileToRoll.lastModified() != currentFile.get().getLastModified()) {
  350. String message = "File has been modified since being read: "
  351. + fileToRoll;
  352. throw new IllegalStateException(message);
  353. }
  354. if (fileToRoll.length() != currentFile.get().getLength()) {
  355. String message = "File has changed size since being read: "
  356. + fileToRoll;
  357. throw new IllegalStateException(message);
  358. }
  359. if (deletePolicy.equalsIgnoreCase(DeletePolicy.NEVER.name())) {
  360. rollCurrentFile(fileToRoll);
  361. } else if (deletePolicy.equalsIgnoreCase(DeletePolicy.IMMEDIATE.name())) {
  362. deleteCurrentFile(fileToRoll);
  363. } else {
  364. // TODO: implement delay in the future
  365. throw new IllegalArgumentException("Unsupported delete policy: "
  366. + deletePolicy);
  367. }
  368. }
  369. /**
  370. * Rename the given spooled file
  371. *
  372. * @param fileToRoll
  373. * @throws IOException
  374. */
  375. private void rollCurrentFile(File fileToRoll) throws IOException {
  376. File dest = new File(fileToRoll.getPath() + completedSuffix);
  377. logger.info("Preparing to move file {} to {}", fileToRoll, dest);
  378. // Before renaming, check whether destination file name exists
  379. if (dest.exists() && PlatformDetect.isWindows()) {
  380. /*
  381. * If we are here, it means the completed file already exists. In
  382. * almost every case this means the user is violating an assumption
  383. * of Flume (that log files are placed in the spooling directory
  384. * with unique names). However, there is a corner case on Windows
  385. * systems where the file was already rolled but the rename was not
  386. * atomic. If that seems likely, we let it pass with only a warning.
  387. */
  388. if (Files.equal(currentFile.get().getFile(), dest)) {
  389. logger.warn("Completed file " + dest
  390. + " already exists, but files match, so continuing.");
  391. boolean deleted = fileToRoll.delete();
  392. if (!deleted) {
  393. logger.error("Unable to delete file "
  394. + fileToRoll.getAbsolutePath()
  395. + ". It will likely be ingested another time.");
  396. }
  397. } else {
  398. String message = "File name has been re-used with different"
  399. + " files. Spooling assumptions violated for " + dest;
  400. throw new IllegalStateException(message);
  401. }
  402. // Dest file exists and not on windows
  403. } else if (dest.exists()) {
  404. String message = "File name has been re-used with different"
  405. + " files. Spooling assumptions violated for " + dest;
  406. throw new IllegalStateException(message);
  407. // Destination file does not already exist. We are good to go!
  408. } else {
  409. boolean renamed = fileToRoll.renameTo(dest);
  410. if (renamed) {
  411. logger.debug("Successfully rolled file {} to {}", fileToRoll,
  412. dest);
  413. // now we no longer need the meta file
  414. deleteMetaFile();
  415. } else {
  416. /*
  417. * If we are here then the file cannot be renamed for a reason
  418. * other than that the destination file exists (actually, that
  419. * remains possible w/ small probability due to TOC-TOU
  420. * conditions).
  421. */
  422. String message = "Unable to move "
  423. + fileToRoll
  424. + " to "
  425. + dest
  426. + ". This will likely cause duplicate events. Please verify that "
  427. + "flume has sufficient permissions to perform these operations.";
  428. throw new FlumeException(message);
  429. }
  430. }
  431. }
  432. /**
  433. * Delete the given spooled file
  434. *
  435. * @param fileToDelete
  436. * @throws IOException
  437. */
  438. private void deleteCurrentFile(File fileToDelete) throws IOException {
  439. logger.info("Preparing to delete file {}", fileToDelete);
  440. if (!fileToDelete.exists()) {
  441. logger.warn("Unable to delete nonexistent file: {}", fileToDelete);
  442. return;
  443. }
  444. if (!fileToDelete.delete()) {
  445. throw new IOException("Unable to delete spool file: "
  446. + fileToDelete);
  447. }
  448. // now we no longer need the meta file
  449. deleteMetaFile();
  450. }
  451. /**
  452. * Find and open the oldest file in the chosen directory. If two or more
  453. * files are equally old, the file name with lower lexicographical value is
  454. * returned. If the directory is empty, this will return an absent option.
  455. */
  456. private Optional<FileInfo> getNextFile() {
  457. /* Filter to exclude finished or hidden files */
  458. FileFilter filter = new FileFilter() {
  459. public boolean accept(File candidate) {
  460. String fileName = candidate.getName();
  461. if ((candidate.isDirectory())
  462. || (fileName.endsWith(completedSuffix))
  463. || (fileName.startsWith("."))
  464. || ignorePattern.matcher(fileName).matches()) {
  465. return false;
  466. }
  467. return true;
  468. }
  469. };
  470. List<File> candidateFiles = Arrays.asList(spoolDirectory
  471. .listFiles(filter));
  472. if (candidateFiles.isEmpty()) {
  473. return Optional.absent();
  474. } else {
  475. Collections.sort(candidateFiles, new Comparator<File>() {
  476. public int compare(File a, File b) {
  477. int timeComparison = new Long(a.lastModified())
  478. .compareTo(new Long(b.lastModified()));
  479. if (timeComparison != 0) {
  480. return timeComparison;
  481. } else {
  482. return a.getName().compareTo(b.getName());
  483. }
  484. }
  485. });
  486. File nextFile = candidateFiles.get(0);
  487. try {
  488. // roll the meta file, if needed
  489. String nextPath = nextFile.getPath();
  490. PositionTracker tracker = DurablePositionTracker.getInstance(
  491. metaFile, nextPath);
  492. if (!tracker.getTarget().equals(nextPath)) {
  493. tracker.close();
  494. deleteMetaFile();
  495. tracker = DurablePositionTracker.getInstance(metaFile,
  496. nextPath);
  497. }
  498. // sanity check
  499. Preconditions
  500. .checkState(
  501. tracker.getTarget().equals(nextPath),
  502. "Tracker target %s does not equal expected filename %s",
  503. tracker.getTarget(), nextPath);
  504. ResettableInputStream in = new ResettableFileInputStream(
  505. nextFile, tracker,
  506. ResettableFileInputStream.DEFAULT_BUF_SIZE,
  507. inputCharset, decodeErrorPolicy);
  508. EventDeserializer deserializer = EventDeserializerFactory
  509. .getInstance(deserializerType, deserializerContext, in);
  510. return Optional.of(new FileInfo(nextFile, deserializer));
  511. } catch (FileNotFoundException e) {
  512. // File could have been deleted in the interim
  513. logger.warn("Could not find file: " + nextFile, e);
  514. return Optional.absent();
  515. } catch (IOException e) {
  516. logger.error("Exception opening file: " + nextFile, e);
  517. return Optional.absent();
  518. }
  519. }
  520. }
  521. private void deleteMetaFile() throws IOException {
  522. if (metaFile.exists() && !metaFile.delete()) {
  523. throw new IOException("Unable to delete old meta file " + metaFile);
  524. }
  525. }
  526. /** An immutable class with information about a file being processed. */
  527. private static class FileInfo {
  528. private final File file;
  529. private final long length;
  530. private final long lastModified;
  531. private final EventDeserializer deserializer;
  532. public FileInfo(File file, EventDeserializer deserializer) {
  533. this.file = file;
  534. this.length = file.length();
  535. this.lastModified = file.lastModified();
  536. this.deserializer = deserializer;
  537. }
  538. public long getLength() {
  539. return length;
  540. }
  541. public long getLastModified() {
  542. return lastModified;
  543. }
  544. public EventDeserializer getDeserializer() {
  545. return deserializer;
  546. }
  547. public File getFile() {
  548. return file;
  549. }
  550. }
  551. @InterfaceAudience.Private
  552. @InterfaceStability.Unstable
  553. static enum DeletePolicy {
  554. NEVER, IMMEDIATE, DELAY
  555. }
  556. /**
  557. * Special builder class for ReliableSpoolingFileEventReader
  558. */
  559. public static class Builder {
  560. private File spoolDirectory;
  561. private String completedSuffix = SpoolDirectorySourceConfigurationExtConstants.SPOOLED_FILE_SUFFIX;
  562. private String ignorePattern = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_IGNORE_PAT;
  563. private String trackerDirPath = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_TRACKER_DIR;
  564. private Boolean annotateFileName = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILE_HEADER;
  565. private String fileNameHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_HEADER_KEY;
  566. private Boolean annotateBaseName = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_BASENAME_HEADER;
  567. private String baseNameHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_BASENAME_HEADER_KEY;
  568. private String deserializerType = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_DESERIALIZER;
  569. private Context deserializerContext = new Context();
  570. private String deletePolicy = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_DELETE_POLICY;
  571. private String inputCharset = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_INPUT_CHARSET;
  572. private DecodeErrorPolicy decodeErrorPolicy = DecodeErrorPolicy
  573. .valueOf(SpoolDirectorySourceConfigurationExtConstants.DEFAULT_DECODE_ERROR_POLICY
  574. .toUpperCase());
  575. // 增加代码开始
  576. private Boolean annotateFileNameExtractor = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR;
  577. private String fileNameExtractorHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_HEADER_KEY;
  578. private String fileNameExtractorPattern = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_PATTERN;
  579. private Boolean convertToTimestamp = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP;
  580. private String dateTimeFormat = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_FILENAME_EXTRACTOR_DATETIME_FORMAT;
  581. private Boolean splitFileName = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_SPLIT_FILENAME;
  582. private String splitBy = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_SPLITY_BY;
  583. private String splitBaseNameHeader = SpoolDirectorySourceConfigurationExtConstants.DEFAULT_SPLIT_BASENAME_HEADER;
  584. public Builder annotateFileNameExtractor(
  585. Boolean annotateFileNameExtractor) {
  586. this.annotateFileNameExtractor = annotateFileNameExtractor;
  587. return this;
  588. }
  589. public Builder fileNameExtractorHeader(String fileNameExtractorHeader) {
  590. this.fileNameExtractorHeader = fileNameExtractorHeader;
  591. return this;
  592. }
  593. public Builder fileNameExtractorPattern(String fileNameExtractorPattern) {
  594. this.fileNameExtractorPattern = fileNameExtractorPattern;
  595. return this;
  596. }
  597. public Builder convertToTimestamp(Boolean convertToTimestamp) {
  598. this.convertToTimestamp = convertToTimestamp;
  599. return this;
  600. }
  601. public Builder dateTimeFormat(String dateTimeFormat) {
  602. this.dateTimeFormat = dateTimeFormat;
  603. return this;
  604. }
  605. public Builder splitFileName(Boolean splitFileName) {
  606. this.splitFileName = splitFileName;
  607. return this;
  608. }
  609. public Builder splitBy(String splitBy) {
  610. this.splitBy = splitBy;
  611. return this;
  612. }
  613. public Builder splitBaseNameHeader(String splitBaseNameHeader) {
  614. this.splitBaseNameHeader = splitBaseNameHeader;
  615. return this;
  616. }
  617. // 增加代码结束
  618. public Builder spoolDirectory(File directory) {
  619. this.spoolDirectory = directory;
  620. return this;
  621. }
  622. public Builder completedSuffix(String completedSuffix) {
  623. this.completedSuffix = completedSuffix;
  624. return this;
  625. }
  626. public Builder ignorePattern(String ignorePattern) {
  627. this.ignorePattern = ignorePattern;
  628. return this;
  629. }
  630. public Builder trackerDirPath(String trackerDirPath) {
  631. this.trackerDirPath = trackerDirPath;
  632. return this;
  633. }
  634. public Builder annotateFileName(Boolean annotateFileName) {
  635. this.annotateFileName = annotateFileName;
  636. return this;
  637. }
  638. public Builder fileNameHeader(String fileNameHeader) {
  639. this.fileNameHeader = fileNameHeader;
  640. return this;
  641. }
  642. public Builder annotateBaseName(Boolean annotateBaseName) {
  643. this.annotateBaseName = annotateBaseName;
  644. return this;
  645. }
  646. public Builder baseNameHeader(String baseNameHeader) {
  647. this.baseNameHeader = baseNameHeader;
  648. return this;
  649. }
  650. public Builder deserializerType(String deserializerType) {
  651. this.deserializerType = deserializerType;
  652. return this;
  653. }
  654. public Builder deserializerContext(Context deserializerContext) {
  655. this.deserializerContext = deserializerContext;
  656. return this;
  657. }
  658. public Builder deletePolicy(String deletePolicy) {
  659. this.deletePolicy = deletePolicy;
  660. return this;
  661. }
  662. public Builder inputCharset(String inputCharset) {
  663. this.inputCharset = inputCharset;
  664. return this;
  665. }
  666. public Builder decodeErrorPolicy(DecodeErrorPolicy decodeErrorPolicy) {
  667. this.decodeErrorPolicy = decodeErrorPolicy;
  668. return this;
  669. }
  670. public ReliableSpoolingFileEventExtReader build() throws IOException {
  671. return new ReliableSpoolingFileEventExtReader(spoolDirectory,
  672. completedSuffix, ignorePattern, trackerDirPath,
  673. annotateFileName, fileNameHeader, annotateBaseName,
  674. baseNameHeader, deserializerType, deserializerContext,
  675. deletePolicy, inputCharset, decodeErrorPolicy,
  676. annotateFileNameExtractor, fileNameExtractorHeader,
  677. fileNameExtractorPattern, convertToTimestamp,
  678. dateTimeFormat, splitFileName, splitBy, splitBaseNameHeader);
  679. }
  680. }
  681. }
[java] view plaincopy
  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. package com.bbaiggey.flume;
  18. import org.apache.flume.serialization.DecodeErrorPolicy;
  19. public class SpoolDirectorySourceConfigurationExtConstants {
  20. /** Directory where files are deposited. */
  21. public static final String SPOOL_DIRECTORY = "spoolDir";
  22. /** Suffix appended to files when they are finished being sent. */
  23. public static final String SPOOLED_FILE_SUFFIX = "fileSuffix";
  24. public static final String DEFAULT_SPOOLED_FILE_SUFFIX = ".COMPLETED";
  25. /** Header in which to put absolute path filename. */
  26. public static final String FILENAME_HEADER_KEY = "fileHeaderKey";
  27. public static final String DEFAULT_FILENAME_HEADER_KEY = "file";
  28. /** Whether to include absolute path filename in a header. */
  29. public static final String FILENAME_HEADER = "fileHeader";
  30. public static final boolean DEFAULT_FILE_HEADER = false;
  31. /** Header in which to put the basename of file. */
  32. public static final String BASENAME_HEADER_KEY = "basenameHeaderKey";
  33. public static final String DEFAULT_BASENAME_HEADER_KEY = "basename";
  34. /** Whether to include the basename of a file in a header. */
  35. public static final String BASENAME_HEADER = "basenameHeader";
  36. public static final boolean DEFAULT_BASENAME_HEADER = false;
  37. /** What size to batch with before sending to ChannelProcessor. */
  38. public static final String BATCH_SIZE = "batchSize";
  39. public static final int DEFAULT_BATCH_SIZE = 100;
  40. /** Maximum number of lines to buffer between commits. */
  41. @Deprecated
  42. public static final String BUFFER_MAX_LINES = "bufferMaxLines";
  43. @Deprecated
  44. public static final int DEFAULT_BUFFER_MAX_LINES = 100;
  45. /** Maximum length of line (in characters) in buffer between commits. */
  46. @Deprecated
  47. public static final String BUFFER_MAX_LINE_LENGTH = "bufferMaxLineLength";
  48. @Deprecated
  49. public static final int DEFAULT_BUFFER_MAX_LINE_LENGTH = 5000;
  50. /** Pattern of files to ignore */
  51. public static final String IGNORE_PAT = "ignorePattern";
  52. public static final String DEFAULT_IGNORE_PAT = "^$"; // no effect
  53. /** Directory to store metadata about files being processed */
  54. public static final String TRACKER_DIR = "trackerDir";
  55. public static final String DEFAULT_TRACKER_DIR = ".flumespool";
  56. /** Deserializer to use to parse the file data into Flume Events */
  57. public static final String DESERIALIZER = "deserializer";
  58. public static final String DEFAULT_DESERIALIZER = "LINE";
  59. public static final String DELETE_POLICY = "deletePolicy";
  60. public static final String DEFAULT_DELETE_POLICY = "never";
  61. /** Character set used when reading the input. */
  62. public static final String INPUT_CHARSET = "inputCharset";
  63. public static final String DEFAULT_INPUT_CHARSET = "UTF-8";
  64. /** What to do when there is a character set decoding error. */
  65. public static final String DECODE_ERROR_POLICY = "decodeErrorPolicy";
  66. public static final String DEFAULT_DECODE_ERROR_POLICY = DecodeErrorPolicy.FAIL
  67. .name();
  68. public static final String MAX_BACKOFF = "maxBackoff";
  69. public static final Integer DEFAULT_MAX_BACKOFF = 4000;
  70. // 增加代码开始
  71. public static final String FILENAME_EXTRACTOR = "fileExtractor";
  72. public static final boolean DEFAULT_FILENAME_EXTRACTOR = false;
  73. public static final String FILENAME_EXTRACTOR_HEADER_KEY = "fileExtractorHeaderKey";
  74. public static final String DEFAULT_FILENAME_EXTRACTOR_HEADER_KEY = "fileExtractorHeader";
  75. public static final String FILENAME_EXTRACTOR_PATTERN = "fileExtractorPattern";
  76. public static final String DEFAULT_FILENAME_EXTRACTOR_PATTERN = "(.)*";
  77. public static final String FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP = "convertToTimestamp";
  78. public static final boolean DEFAULT_FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP = false;
  79. public static final String FILENAME_EXTRACTOR_DATETIME_FORMAT = "dateTimeFormat";
  80. public static final String DEFAULT_FILENAME_EXTRACTOR_DATETIME_FORMAT = "yyyy-MM-dd";
  81. public static final String SPLIT_FILENAME = "splitFileName";
  82. public static final boolean DEFAULT_SPLIT_FILENAME = false;
  83. public static final String SPLITY_BY = "splitBy";
  84. public static final String DEFAULT_SPLITY_BY = "\\.";
  85. public static final String SPLIT_BASENAME_HEADER = "splitBaseNameHeader";
  86. public static final String DEFAULT_SPLIT_BASENAME_HEADER = "fileNameSplit";
  87. // 增加代码结束
  88. }
[java] view plaincopy
  1. package com.bbaiggey.flume;
  2. import static com.bbaiggey.flume.SpoolDirectorySourceConfigurationExtConstants.*;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.util.List;
  6. import java.util.concurrent.Executors;
  7. import java.util.concurrent.ScheduledExecutorService;
  8. import java.util.concurrent.TimeUnit;
  9. import org.apache.flume.ChannelException;
  10. import org.apache.flume.Context;
  11. import org.apache.flume.Event;
  12. import org.apache.flume.EventDrivenSource;
  13. import org.apache.flume.FlumeException;
  14. import org.apache.flume.conf.Configurable;
  15. import org.apache.flume.instrumentation.SourceCounter;
  16. import org.apache.flume.serialization.DecodeErrorPolicy;
  17. import org.apache.flume.serialization.LineDeserializer;
  18. import org.apache.flume.source.AbstractSource;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21. import com.google.common.annotations.VisibleForTesting;
  22. import com.google.common.base.Preconditions;
  23. import com.google.common.base.Throwables;
  24. public class SpoolDirectoryExtSource extends AbstractSource implements
  25. Configurable, EventDrivenSource {
  26. private static final Logger logger = LoggerFactory
  27. .getLogger(SpoolDirectoryExtSource.class);
  28. // Delay used when polling for new files
  29. private static final int POLL_DELAY_MS = 500;
  30. /* Config options */
  31. private String completedSuffix;
  32. private String spoolDirectory;
  33. private boolean fileHeader;
  34. private String fileHeaderKey;
  35. private boolean basenameHeader;
  36. private String basenameHeaderKey;
  37. private int batchSize;
  38. private String ignorePattern;
  39. private String trackerDirPath;
  40. private String deserializerType;
  41. private Context deserializerContext;
  42. private String deletePolicy;
  43. private String inputCharset;
  44. private DecodeErrorPolicy decodeErrorPolicy;
  45. private volatile boolean hasFatalError = false;
  46. private SourceCounter sourceCounter;
  47. ReliableSpoolingFileEventExtReader reader;
  48. private ScheduledExecutorService executor;
  49. private boolean backoff = true;
  50. private boolean hitChannelException = false;
  51. private int maxBackoff;
  52. // 增加代码开始
  53. private Boolean annotateFileNameExtractor;
  54. private String fileNameExtractorHeader;
  55. private String fileNameExtractorPattern;
  56. private Boolean convertToTimestamp;
  57. private String dateTimeFormat;
  58. private boolean splitFileName;
  59. private  String splitBy;
  60. private  String splitBaseNameHeader;
  61. // 增加代码结束
  62. @Override
  63. public synchronized void start() {
  64. logger.info("SpoolDirectorySource source starting with directory: {}",
  65. spoolDirectory);
  66. executor = Executors.newSingleThreadScheduledExecutor();
  67. File directory = new File(spoolDirectory);
  68. try {
  69. reader = new ReliableSpoolingFileEventExtReader.Builder()
  70. .spoolDirectory(directory).completedSuffix(completedSuffix)
  71. .ignorePattern(ignorePattern)
  72. .trackerDirPath(trackerDirPath)
  73. .annotateFileName(fileHeader).fileNameHeader(fileHeaderKey)
  74. .annotateBaseName(basenameHeader)
  75. .baseNameHeader(basenameHeaderKey)
  76. .deserializerType(deserializerType)
  77. .deserializerContext(deserializerContext)
  78. .deletePolicy(deletePolicy).inputCharset(inputCharset)
  79. .decodeErrorPolicy(decodeErrorPolicy)
  80. .annotateFileNameExtractor(annotateFileNameExtractor)
  81. .fileNameExtractorHeader(fileNameExtractorHeader)
  82. .fileNameExtractorPattern(fileNameExtractorPattern)
  83. .convertToTimestamp(convertToTimestamp)
  84. .dateTimeFormat(dateTimeFormat)
  85. .splitFileName(splitFileName).splitBy(splitBy)
  86. .splitBaseNameHeader(splitBaseNameHeader).build();
  87. } catch (IOException ioe) {
  88. throw new FlumeException(
  89. "Error instantiating spooling event parser", ioe);
  90. }
  91. Runnable runner = new SpoolDirectoryRunnable(reader, sourceCounter);
  92. executor.scheduleWithFixedDelay(runner, 0, POLL_DELAY_MS,
  93. TimeUnit.MILLISECONDS);
  94. super.start();
  95. logger.debug("SpoolDirectorySource source started");
  96. sourceCounter.start();
  97. }
  98. @Override
  99. public synchronized void stop() {
  100. executor.shutdown();
  101. try {
  102. executor.awaitTermination(10L, TimeUnit.SECONDS);
  103. } catch (InterruptedException ex) {
  104. logger.info("Interrupted while awaiting termination", ex);
  105. }
  106. executor.shutdownNow();
  107. super.stop();
  108. sourceCounter.stop();
  109. logger.info("SpoolDir source {} stopped. Metrics: {}", getName(),
  110. sourceCounter);
  111. }
  112. @Override
  113. public String toString() {
  114. return "Spool Directory source " + getName() + ": { spoolDir: "
  115. + spoolDirectory + " }";
  116. }
  117. @Override
  118. public synchronized void configure(Context context) {
  119. spoolDirectory = context.getString(SPOOL_DIRECTORY);
  120. Preconditions.checkState(spoolDirectory != null,
  121. "Configuration must specify a spooling directory");
  122. completedSuffix = context.getString(SPOOLED_FILE_SUFFIX,
  123. DEFAULT_SPOOLED_FILE_SUFFIX);
  124. deletePolicy = context.getString(DELETE_POLICY, DEFAULT_DELETE_POLICY);
  125. fileHeader = context.getBoolean(FILENAME_HEADER, DEFAULT_FILE_HEADER);
  126. fileHeaderKey = context.getString(FILENAME_HEADER_KEY,
  127. DEFAULT_FILENAME_HEADER_KEY);
  128. basenameHeader = context.getBoolean(BASENAME_HEADER,
  129. DEFAULT_BASENAME_HEADER);
  130. basenameHeaderKey = context.getString(BASENAME_HEADER_KEY,
  131. DEFAULT_BASENAME_HEADER_KEY);
  132. batchSize = context.getInteger(BATCH_SIZE, DEFAULT_BATCH_SIZE);
  133. inputCharset = context.getString(INPUT_CHARSET, DEFAULT_INPUT_CHARSET);
  134. decodeErrorPolicy = DecodeErrorPolicy
  135. .valueOf(context.getString(DECODE_ERROR_POLICY,
  136. DEFAULT_DECODE_ERROR_POLICY).toUpperCase());
  137. ignorePattern = context.getString(IGNORE_PAT, DEFAULT_IGNORE_PAT);
  138. trackerDirPath = context.getString(TRACKER_DIR, DEFAULT_TRACKER_DIR);
  139. deserializerType = context
  140. .getString(DESERIALIZER, DEFAULT_DESERIALIZER);
  141. deserializerContext = new Context(context.getSubProperties(DESERIALIZER
  142. + "."));
  143. // "Hack" to support backwards compatibility with previous generation of
  144. // spooling directory source, which did not support deserializers
  145. Integer bufferMaxLineLength = context
  146. .getInteger(BUFFER_MAX_LINE_LENGTH);
  147. if (bufferMaxLineLength != null && deserializerType != null
  148. && deserializerType.equalsIgnoreCase(DEFAULT_DESERIALIZER)) {
  149. deserializerContext.put(LineDeserializer.MAXLINE_KEY,
  150. bufferMaxLineLength.toString());
  151. }
  152. maxBackoff = context.getInteger(MAX_BACKOFF, DEFAULT_MAX_BACKOFF);
  153. if (sourceCounter == null) {
  154. sourceCounter = new SourceCounter(getName());
  155. }
  156. //增加代码开始
  157. annotateFileNameExtractor=context.getBoolean(FILENAME_EXTRACTOR, DEFAULT_FILENAME_EXTRACTOR);
  158. fileNameExtractorHeader=context.getString(FILENAME_EXTRACTOR_HEADER_KEY, DEFAULT_FILENAME_EXTRACTOR_HEADER_KEY);
  159. fileNameExtractorPattern=context.getString(FILENAME_EXTRACTOR_PATTERN,DEFAULT_FILENAME_EXTRACTOR_PATTERN);
  160. convertToTimestamp=context.getBoolean(FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP, DEFAULT_FILENAME_EXTRACTOR_CONVERT_TO_TIMESTAMP);
  161. dateTimeFormat=context.getString(FILENAME_EXTRACTOR_DATETIME_FORMAT, DEFAULT_FILENAME_EXTRACTOR_DATETIME_FORMAT);
  162. splitFileName=context.getBoolean(SPLIT_FILENAME, DEFAULT_SPLIT_FILENAME);
  163. splitBy=context.getString(SPLITY_BY, DEFAULT_SPLITY_BY);
  164. splitBaseNameHeader=context.getString(SPLIT_BASENAME_HEADER, DEFAULT_SPLIT_BASENAME_HEADER);
  165. //增加代码结束
  166. }
  167. @VisibleForTesting
  168. protected boolean hasFatalError() {
  169. return hasFatalError;
  170. }
  171. /**
  172. * The class always backs off, this exists only so that we can test without
  173. * taking a really long time.
  174. *
  175. * @param backoff
  176. *            - whether the source should backoff if the channel is full
  177. */
  178. @VisibleForTesting
  179. protected void setBackOff(boolean backoff) {
  180. this.backoff = backoff;
  181. }
  182. @VisibleForTesting
  183. protected boolean hitChannelException() {
  184. return hitChannelException;
  185. }
  186. @VisibleForTesting
  187. protected SourceCounter getSourceCounter() {
  188. return sourceCounter;
  189. }
  190. private class SpoolDirectoryRunnable implements Runnable {
  191. private ReliableSpoolingFileEventExtReader reader;
  192. private SourceCounter sourceCounter;
  193. public SpoolDirectoryRunnable(
  194. ReliableSpoolingFileEventExtReader reader,
  195. SourceCounter sourceCounter) {
  196. this.reader = reader;
  197. this.sourceCounter = sourceCounter;
  198. }
  199. @Override
  200. public void run() {
  201. int backoffInterval = 250;
  202. try {
  203. while (!Thread.interrupted()) {
  204. List<Event> events = reader.readEvents(batchSize);
  205. if (events.isEmpty()) {
  206. break;
  207. }
  208. sourceCounter.addToEventReceivedCount(events.size());
  209. sourceCounter.incrementAppendBatchReceivedCount();
  210. try {
  211. getChannelProcessor().processEventBatch(events);
  212. reader.commit();
  213. } catch (ChannelException ex) {
  214. logger.warn("The channel is full, and cannot write data now. The "
  215. + "source will try again after "
  216. + String.valueOf(backoffInterval)
  217. + " milliseconds");
  218. hitChannelException = true;
  219. if (backoff) {
  220. TimeUnit.MILLISECONDS.sleep(backoffInterval);
  221. backoffInterval = backoffInterval << 1;
  222. backoffInterval = backoffInterval >= maxBackoff ? maxBackoff
  223. : backoffInterval;
  224. }
  225. continue;
  226. }
  227. backoffInterval = 250;
  228. sourceCounter.addToEventAcceptedCount(events.size());
  229. sourceCounter.incrementAppendBatchAcceptedCount();
  230. }
  231. logger.info("Spooling Directory Source runner has shutdown.");
  232. } catch (Throwable t) {
  233. logger.error(
  234. "FATAL: "
  235. + SpoolDirectoryExtSource.this.toString()
  236. + ": "
  237. + "Uncaught exception in SpoolDirectorySource thread. "
  238. + "Restart or reconfigure Flume to continue processing.",
  239. t);
  240. hasFatalError = true;
  241. Throwables.propagate(t);
  242. }
  243. }
  244. }
  245. }

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

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 plaincopy
  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的查看日志文件的截图:

flume学习(七):自定义source相关推荐

  1. PyTorch框架学习七——自定义transforms方法

    PyTorch框架学习七--自定义transforms方法 一.自定义transforms注意要素 二.自定义transforms步骤 三.自定义transforms实例:椒盐噪声 虽然前面的笔记介绍 ...

  2. Flume的开发之 自定义 source 自定义 sink 自定义拦截器

    一:开发相关 加入 jar 包依赖: <dependency> <groupId>org.apache.flume</groupId> <artifactId ...

  3. 三十九、Flume自定义Source、Sink

    上篇文章咱们基于Flume举了几个例子,包括它的扇入扇出等等.这篇文章我们主要来看一下怎样通过自定义Source和Sink来实现Flume的数据采集.关注专栏<破茧成蝶--大数据篇>,查看 ...

  4. flume学习-含安装

    1.Flume是什么:Flume是Cloudera提供的一个高可用的,高可靠的,分布式的海量日志采集.聚合和传输的系统.Flume基于流式架构,灵活简单. Flume组成架构 下面我们来详细介绍一下F ...

  5. Docker学习七:使用docker搭建Hadoop集群

    本博客简单分享了如何在Docker上搭建Hadoop集群,我的电脑是Ubuntu20,听同学说wsl2有些命令不对,所以建议在虚拟机里按照Ubuntu或者直接安装双系统吧 Docker学习一:Dock ...

  6. (转)MyBatis框架的学习(七)——MyBatis逆向工程自动生成代码

    http://blog.csdn.net/yerenyuan_pku/article/details/71909325 什么是逆向工程 MyBatis的一个主要的特点就是需要程序员自己编写sql,那么 ...

  7. iOS学习笔记-自定义过渡动画

    代码地址如下: http://www.demodashi.com/demo/11678.html 这篇笔记翻译自raywenderlick网站的过渡动画的一篇文章,原文用的swift,由于考虑到swi ...

  8. Java虚拟机JVM学习06 自定义类加载器 父委托机制和命名空间的再讨论

    Java虚拟机JVM学习06 自定义类加载器 父委托机制和命名空间的再讨论 创建用户自定义的类加载器 要创建用户自定义的类加载器,只需要扩展java.lang.ClassLoader类,然后覆盖它的f ...

  9. STL源码剖析学习七:stack和queue

    STL源码剖析学习七:stack和queue stack是一种先进后出的数据结构,只有一个出口. 允许新增.删除.获取最顶端的元素,没有任何办法可以存取其他元素,不允许有遍历行为. 缺省情况下用deq ...

  10. OpenCV与图像处理学习七——传统图像分割之阈值法(固定阈值、自适应阈值、大津阈值)

    OpenCV与图像处理学习七--传统图像分割之阈值法(固定阈值.自适应阈值.大津阈值) 一.固定阈值图像分割 1.1 直方图双峰法 1.2 OpenCV中的固定阈值分割 二.自动阈值图像分割 2.1 ...

最新文章

  1. Zabbix5.0监控系统安装详解
  2. Python__面向对象思想
  3. OpenCV-图像特征harris角点检测/SIFT函数/特征匹配-05
  4. 一个系统中同时使用VC6.0+OpenCV1.0和VS2010+OpenCV2.4.6.0的方法
  5. 爱荷华大学计算机科学专业,爱荷华大学计算机科学专业好不好?专业设置详情一览...
  6. 【教程】把PPT转WORD形式的方法
  7. Open vSwitch 使用
  8. matlab2c使用c++实现matlab函数系列教程-trace函数
  9. RK3288_Android7.1增加自定义的红外遥控按键流程记录
  10. 二维字符数组转字符串c语言,[求助] 怎样转换一个字符二维数组到一维数组~~~...
  11. 1.封包(二)(雷电模拟器+ProxyDroid+CCProxy+WPE) 的使用
  12. [9i] stuff 和 things 在表示“东西”时的细微区别
  13. GitHub压缩包下载URL
  14. 安装DCOS,关于docker异常引发的调查
  15. qt中在QLabel上显示图像并画矩形框。
  16. div完成田字格布局
  17. Docker 容器技术(史上最强总结)
  18. ToxinPred – 多肽毒性预测、突变设计和理化性质预测
  19. C语言实现字符串在屏幕上滚动
  20. dsp 精准投放_招商加盟行业如何精准获客

热门文章

  1. 阶段3 1.Mybatis_05.使用Mybatis完成CRUD_7 Mybatis中参数的深入-使用实体类的包装对象作为查询条件...
  2. 阶段1 语言基础+高级_1-3-Java语言高级_09-基础加强_第2节 反射_8_反射_Class对象功能_获取Field...
  3. 【Leetcode_easy】724. Find Pivot Index
  4. nlogn 求最长上升子序列 LIS
  5. 【MyBean调试笔记】接口的使用和清理
  6. 《深入理解计算机网络》读后小记 8、IP地址和子网
  7. (转)asp.net c#如何采集需要登录的页面?
  8. 利用Flash XMLSocket实现”服务器推”技术
  9. Mysql常见的引擎
  10. sql select 0 字段 某字段是不在指定的表