FileWatcher.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package info.fetter.logstashforwarder;
  2. /*
  3. * Copyright 2015 Didier Fetter
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * 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,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. import info.fetter.logstashforwarder.util.AdapterException;
  19. import info.fetter.logstashforwarder.util.LastModifiedFileFilter;
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import org.apache.commons.io.FileUtils;
  27. import org.apache.commons.io.FilenameUtils;
  28. import org.apache.commons.io.filefilter.FileFilterUtils;
  29. import org.apache.commons.io.filefilter.IOFileFilter;
  30. import org.apache.commons.io.filefilter.WildcardFileFilter;
  31. import org.apache.commons.io.monitor.FileAlterationObserver;
  32. import org.apache.log4j.Logger;
  33. public class FileWatcher {
  34. private static final Logger logger = Logger.getLogger(FileWatcher.class);
  35. private List<FileAlterationObserver> observerList = new ArrayList<FileAlterationObserver>();
  36. public static final int ONE_DAY = 24 * 3600 * 1000;
  37. private Map<File,FileState> oldWatchMap = new HashMap<File,FileState>();
  38. private Map<File,FileState> newWatchMap = new HashMap<File,FileState>();
  39. private FileState[] savedStates;
  40. private int maxSignatureLength;
  41. private boolean tail = false;
  42. private Event stdinFields;
  43. private boolean stdinConfigured = false;
  44. private String sincedbFile = null;
  45. public FileWatcher() {
  46. }
  47. public void initialize() throws IOException {
  48. logger.debug("Initializing FileWatcher");
  49. if(savedStates != null) {
  50. for(FileState state : savedStates) {
  51. logger.info("Loading file state: " + state.getFile() + ":" + state.getPointer());
  52. oldWatchMap.put(state.getFile(), state);
  53. }
  54. }
  55. processModifications();
  56. if(tail) {
  57. for(FileState state : oldWatchMap.values()) {
  58. if(state.getPointer() == 0) {
  59. state.setPointer(state.getSize());
  60. }
  61. }
  62. }
  63. printWatchMap();
  64. }
  65. public void addFilesToWatch(String fileToWatch, Event fields, long deadTime, Multiline multiline) {
  66. try {
  67. if(fileToWatch.equals("-")) {
  68. addStdIn(fields);
  69. } else if(fileToWatch.contains("*")) {
  70. addWildCardFiles(fileToWatch, fields, deadTime, multiline);
  71. } else {
  72. addSingleFile(fileToWatch, fields, deadTime, multiline);
  73. }
  74. } catch(Exception e) {
  75. throw new RuntimeException(e);
  76. }
  77. }
  78. public void checkFiles() throws IOException {
  79. logger.trace("Checking files");
  80. logger.trace("==============");
  81. for(FileAlterationObserver observer : observerList) {
  82. observer.checkAndNotify();
  83. }
  84. processModifications();
  85. printWatchMap();
  86. }
  87. public int readFiles(FileReader reader) throws IOException, AdapterException {
  88. logger.trace("Reading files");
  89. logger.trace("==============");
  90. int numberOfLinesRead = reader.readFiles(oldWatchMap.values());
  91. Registrar.writeStateToJson(sincedbFile,oldWatchMap.values());
  92. return numberOfLinesRead;
  93. }
  94. public int readStdin(InputReader reader) throws AdapterException, IOException {
  95. if(stdinConfigured) {
  96. logger.debug("Reading stdin");
  97. reader.setFields(stdinFields);
  98. int numberOfLinesRead = reader.readInput();
  99. return numberOfLinesRead;
  100. } else {
  101. return 0;
  102. }
  103. }
  104. private void processModifications() throws IOException {
  105. for(File file : newWatchMap.keySet()) {
  106. FileState state = newWatchMap.get(file);
  107. if(logger.isTraceEnabled()) {
  108. logger.trace("Checking file : " + file.getCanonicalPath());
  109. logger.trace("-- Last modified : " + state.getLastModified());
  110. logger.trace("-- Size : " + state.getSize());
  111. logger.trace("-- Directory : " + state.getDirectory());
  112. logger.trace("-- Filename : " + state.getFileName());
  113. }
  114. logger.trace("Determine if file has just been written to");
  115. FileState oldState = oldWatchMap.get(file);
  116. if(oldState != null) {
  117. if(oldState.getSize() > state.getSize()) {
  118. logger.trace("File shorter : file can't be the same");
  119. } else {
  120. if(oldState.getSignatureLength() == state.getSignatureLength() && oldState.getSignature() == state.getSignature()) {
  121. state.setOldFileState(oldState);
  122. logger.trace("Same signature size and value : file is the same");
  123. continue;
  124. } else if(oldState.getSignatureLength() < state.getSignatureLength()){
  125. long signature = FileSigner.computeSignature(state.getRandomAccessFile(), oldState.getSignatureLength());
  126. if(signature == oldState.getSignature()) {
  127. state.setOldFileState(oldState);
  128. logger.trace("Same signature : file is the same");
  129. continue;
  130. } else {
  131. logger.trace("Signature different : file can't be the same");
  132. }
  133. } else if(oldState.getSignatureLength() > state.getSignatureLength()){
  134. logger.trace("Signature shorter : file can't be the same");
  135. }
  136. }
  137. }
  138. if(state.getOldFileState() == null) {
  139. logger.trace("Determine if file has been renamed and/or written to");
  140. for(File otherFile : oldWatchMap.keySet()) {
  141. FileState otherState = oldWatchMap.get(otherFile);
  142. if(otherState != null && state.getSize() >= otherState.getSize() && state.getDirectory().equals(otherState.getDirectory())) {
  143. if(logger.isTraceEnabled()) {
  144. logger.trace("Comparing to : " + otherFile.getCanonicalPath());
  145. }
  146. if(otherState.getSignatureLength() == state.getSignatureLength() && otherState.getSignature() == state.getSignature()) {
  147. state.setOldFileState(otherState);
  148. logger.trace("Same signature size and value : file is the same");
  149. break;
  150. } else if(otherState.getSignatureLength() < state.getSignatureLength()){
  151. long signature = FileSigner.computeSignature(state.getRandomAccessFile(), otherState.getSignatureLength());
  152. if(signature == otherState.getSignature()) {
  153. state.setOldFileState(otherState);
  154. logger.trace("Same signature : file is the same");
  155. break;
  156. } else {
  157. logger.trace("Signature different : file can't be the same");
  158. }
  159. } else if(otherState.getSignatureLength() > state.getSignatureLength()){
  160. logger.trace("Signature shorter : file can't be the same");
  161. }
  162. }
  163. }
  164. }
  165. }
  166. for(FileState state : newWatchMap.values()) {
  167. if(logger.isTraceEnabled()) {
  168. logger.trace("Refreshing file state: " + state.getFile());
  169. }
  170. FileState oldState = state.getOldFileState();
  171. if(oldState == null) {
  172. if(logger.isDebugEnabled()) {
  173. logger.debug("File " + state.getFile() + " has been truncated or created, not retrieving pointer");
  174. }
  175. oldState = oldWatchMap.get(state.getFile());
  176. if(oldState != null && ! oldState.isMatchedToNewFile()) {
  177. if(logger.isDebugEnabled()) {
  178. logger.debug("File " + state.getFile() + " has been replaced and not renamed, removing from watchMap");
  179. }
  180. try {
  181. oldState.getRandomAccessFile().close();
  182. } catch(Exception e) {}
  183. oldWatchMap.remove(state.getFile());
  184. }
  185. } else {
  186. if(logger.isInfoEnabled() && ! state.getFileName().equals(oldState.getFileName()))
  187. {
  188. logger.info("File rename was detected: " + oldState.getFile() + " -> " + state.getFile());
  189. }
  190. if(logger.isDebugEnabled()) {
  191. logger.debug("File " + state.getFile() + " has not been truncated or created, retrieving pointer: " + oldState.getPointer());
  192. }
  193. state.setPointer(oldState.getPointer());
  194. state.deleteOldFileState();
  195. }
  196. }
  197. logger.trace("Replacing old state");
  198. for(File file : newWatchMap.keySet()) {
  199. FileState state = newWatchMap.get(file);
  200. oldWatchMap.put(file, state);
  201. }
  202. // Truncating changedWatchMap
  203. newWatchMap.clear();
  204. removeMarkedFilesFromWatchMap();
  205. }
  206. private void addSingleFile(String fileToWatch, Event fields, long deadTime, Multiline multiline) throws Exception {
  207. logger.info("Watching file : " + new File(fileToWatch).getCanonicalPath());
  208. String directory = FilenameUtils.getFullPath(fileToWatch);
  209. String fileName = FilenameUtils.getName(fileToWatch);
  210. IOFileFilter fileFilter = FileFilterUtils.and(
  211. FileFilterUtils.fileFileFilter(),
  212. FileFilterUtils.nameFileFilter(fileName),
  213. new LastModifiedFileFilter(deadTime));
  214. initializeWatchMap(new File(directory), fileFilter, fields, multiline);
  215. }
  216. private void addWildCardFiles(String filesToWatch, Event fields, long deadTime, Multiline multiline) throws Exception {
  217. logger.info("Watching wildcard files : " + filesToWatch);
  218. String directory = FilenameUtils.getFullPath(filesToWatch);
  219. String wildcard = FilenameUtils.getName(filesToWatch);
  220. logger.trace("Directory : " + new File(directory).getCanonicalPath() + ", wildcard : " + wildcard);
  221. IOFileFilter fileFilter = FileFilterUtils.and(
  222. FileFilterUtils.fileFileFilter(),
  223. new WildcardFileFilter(wildcard),
  224. new LastModifiedFileFilter(deadTime));
  225. initializeWatchMap(new File(directory), fileFilter, fields, multiline);
  226. }
  227. private void addStdIn(Event fields) {
  228. logger.error("Watching stdin");
  229. stdinFields = fields;
  230. stdinConfigured = true;
  231. }
  232. private void initializeWatchMap(File directory, IOFileFilter fileFilter, Event fields, Multiline multiline) throws Exception {
  233. if(!directory.isDirectory()) {
  234. logger.warn("Directory " + directory + " does not exist");
  235. return;
  236. }
  237. FileAlterationObserver observer = new FileAlterationObserver(directory, fileFilter);
  238. FileModificationListener listener = new FileModificationListener(this, fields, multiline);
  239. observer.addListener(listener);
  240. observerList.add(observer);
  241. observer.initialize();
  242. for(File file : FileUtils.listFiles(directory, fileFilter, null)) {
  243. addFileToWatchMap(newWatchMap, file, fields, multiline);
  244. }
  245. }
  246. private void addFileToWatchMap(Map<File,FileState> map, File file, Event fields, Multiline multiline) {
  247. try {
  248. FileState state = new FileState(file);
  249. state.setFields(fields);
  250. int signatureLength = (int) (state.getSize() > maxSignatureLength ? maxSignatureLength : state.getSize());
  251. state.setSignatureLength(signatureLength);
  252. long signature = FileSigner.computeSignature(state.getRandomAccessFile(), signatureLength);
  253. state.setSignature(signature);
  254. logger.trace("Setting signature of size : " + signatureLength + " on file : " + file + " : " + signature);
  255. state.setMultiline(multiline);
  256. map.put(file, state);
  257. } catch(IOException e) {
  258. logger.error("Caught IOException : " + e.getMessage());
  259. }
  260. }
  261. public void onFileChange(File file, Event fields, Multiline multiline) {
  262. try {
  263. logger.debug("Change detected on file : " + file.getCanonicalPath());
  264. addFileToWatchMap(newWatchMap, file, fields, multiline);
  265. } catch (IOException e) {
  266. logger.error("Caught IOException : " + e.getMessage());
  267. }
  268. }
  269. public void onFileCreate(File file, Event fields, Multiline multiline) {
  270. try {
  271. logger.debug("Create detected on file : " + file.getCanonicalPath());
  272. addFileToWatchMap(newWatchMap, file, fields, multiline);
  273. } catch (IOException e) {
  274. logger.error("Caught IOException : " + e.getMessage());
  275. }
  276. }
  277. public void onFileDelete(File file) {
  278. try {
  279. logger.debug("Delete detected on file : " + file.getCanonicalPath());
  280. FileState state = oldWatchMap.get(file);
  281. if (state != null) state.setDeleted();
  282. } catch (IOException e) {
  283. logger.error("Caught IOException : " + e.getMessage());
  284. }
  285. }
  286. private void printWatchMap() throws IOException {
  287. if(logger.isTraceEnabled()) {
  288. logger.trace("WatchMap contents : ");
  289. for(File file : oldWatchMap.keySet()) {
  290. FileState state = oldWatchMap.get(file);
  291. logger.trace("\tFile : " + file.getCanonicalPath() + " marked for deletion : " + state.isDeleted());
  292. }
  293. }
  294. }
  295. private void removeMarkedFilesFromWatchMap() throws IOException {
  296. logger.trace("Removing deleted files from watchMap");
  297. List<File> markedList = null;
  298. for(File file : oldWatchMap.keySet()) {
  299. FileState state = oldWatchMap.get(file);
  300. if(state.getRandomAccessFile() == null) {
  301. state.setDeleted();
  302. }
  303. if(state.isDeleted()) {
  304. if(! file.exists()) {
  305. if(markedList == null) {
  306. markedList = new ArrayList<File>();
  307. }
  308. markedList.add(file);
  309. }
  310. try {
  311. state.getRandomAccessFile().close();
  312. } catch(Exception e) {}
  313. }
  314. }
  315. if(markedList != null) {
  316. for(File file : markedList) {
  317. oldWatchMap.remove(file);
  318. logger.debug("File " + file + " removed from watchMap");
  319. }
  320. }
  321. }
  322. public void close() throws IOException {
  323. logger.debug("Closing all files");
  324. for(File file : oldWatchMap.keySet()) {
  325. FileState state = oldWatchMap.get(file);
  326. state.getRandomAccessFile().close();
  327. }
  328. }
  329. public int getMaxSignatureLength() {
  330. return maxSignatureLength;
  331. }
  332. public void setMaxSignatureLength(int maxSignatureLength) {
  333. this.maxSignatureLength = maxSignatureLength;
  334. }
  335. public void setTail(boolean tail) {
  336. this.tail = tail;
  337. }
  338. public void setSincedb(String sincedbFile) {
  339. this.sincedbFile = sincedbFile;
  340. try {
  341. logger.debug("Loading saved states");
  342. savedStates = Registrar.readStateFromJson(sincedbFile);
  343. } catch(Exception e) {
  344. logger.warn("Could not load saved states : " + e.getMessage(), e);
  345. }
  346. }
  347. }