FileWatcher.java 13 KB

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