blob: 04e761f493f0a59644216e05cb0384771e0a5fce [file] [log] [blame]
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -08001/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2012-2013 University of California, Los Angeles
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Jared Lindblom <lindblom@cs.ucla.edu>
19 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
20 * Zhenkai Zhu <zhenkai@cs.ucla.edu>
21 */
22
23#include "fs-watcher.h"
24#include "logging.h"
25
26#include <boost/bind.hpp>
27
28#include <QDirIterator>
29#include <QRegExp>
30
31using namespace std;
32using namespace boost;
33
34INIT_LOGGER ("FsWatcher");
35
Alexander Afanasyev9ca444e2013-01-25 16:29:35 -080036FsWatcher::FsWatcher (QString dirPath,
37 LocalFile_Change_Callback onChange, LocalFile_Change_Callback onDelete,
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080038 FileState *fileState,
Alexander Afanasyev9ca444e2013-01-25 16:29:35 -080039 QObject* parent)
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080040 : QObject(parent)
41 , m_watcher (new QFileSystemWatcher())
Alexander Afanasyev583449a2013-01-28 17:04:06 -080042 , m_scheduler (new Scheduler ())
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080043 , m_dirPath (dirPath)
Alexander Afanasyev9ca444e2013-01-25 16:29:35 -080044 , m_onChange (onChange)
45 , m_onDelete (onDelete)
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080046 , m_fileState (fileState)
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080047{
48 _LOG_DEBUG ("Monitor dir: " << m_dirPath.toStdString ());
49 // add main directory to monitor
Alexander Afanasyev69e13172013-01-25 17:16:27 -080050
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080051 m_watcher->addPath (m_dirPath);
52
53 // register signals (callback functions)
54 connect (m_watcher, SIGNAL (directoryChanged (QString)), this, SLOT (DidDirectoryChanged (QString)));
55 connect (m_watcher, SIGNAL (fileChanged (QString)), this, SLOT (DidFileChanged (QString)));
56
Alexander Afanasyev583449a2013-01-28 17:04:06 -080057 m_scheduler->start ();
58
Alexander Afanasyev7943c6b2013-01-29 18:43:24 -080059 Scheduler::scheduleOneTimeTask (m_scheduler, 0,
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080060 bind (&FsWatcher::ScanDirectory_NotifyRemovals_Execute, this, m_dirPath),
61 "r-" + m_dirPath.toStdString ()); // only one task will be scheduled per directory
62
Alexander Afanasyev7943c6b2013-01-29 18:43:24 -080063 Scheduler::scheduleOneTimeTask (m_scheduler, 0,
Alexander Afanasyevc80207d2013-01-29 20:07:39 -080064 bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, m_dirPath, true),
Alexander Afanasyev583449a2013-01-28 17:04:06 -080065 m_dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080066}
67
68FsWatcher::~FsWatcher()
69{
Alexander Afanasyev583449a2013-01-28 17:04:06 -080070 m_scheduler->shutdown ();
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080071}
72
73void
74FsWatcher::DidDirectoryChanged (QString dirPath)
75{
Alexander Afanasyev583449a2013-01-28 17:04:06 -080076 _LOG_DEBUG ("Triggered DirPath: " << dirPath.toStdString ());
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080077
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080078 filesystem::path absPathTriggeredDir (dirPath.toStdString ());
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080079 if (!filesystem::exists (filesystem::path (absPathTriggeredDir)))
80 {
81 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
82 bind (&FsWatcher::ScanDirectory_NotifyRemovals_Execute, this, dirPath),
83 "r-" + dirPath.toStdString ()); // only one task will be scheduled per directory
84 }
85 else
86 {
87 // m_executor.execute (bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath));
88 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
Alexander Afanasyevc80207d2013-01-29 20:07:39 -080089 bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath, false),
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080090 dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyevc80207d2013-01-29 20:07:39 -080091
92 // m_executor.execute (bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath));
93 Scheduler::scheduleOneTimeTask (m_scheduler, 300,
94 bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath, true),
95 "rescan-"+dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080096 }
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080097}
98
99void
100FsWatcher::DidFileChanged (QString filePath)
101{
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800102 if (!filePath.startsWith (m_dirPath))
103 {
104 _LOG_ERROR ("Got notification about a file not from the monitored directory");
105 return;
106 }
107 filesystem::path absPathTriggeredFile (filePath.toStdString ());
108 filePath.remove (0, m_dirPath.size ());
109
110 filesystem::path triggeredFile (filePath.toStdString ());
111 if (filesystem::exists (filesystem::path (absPathTriggeredFile)))
112 {
113 _LOG_DEBUG ("Triggered UPDATE of file: " << triggeredFile.relative_path ().generic_string ());
Alexander Afanasyev583449a2013-01-28 17:04:06 -0800114 // m_onChange (triggeredFile.relative_path ());
115
116 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
117 bind (m_onChange, triggeredFile.relative_path ()),
118 triggeredFile.relative_path ().string());
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800119 }
120 else
121 {
122 _LOG_DEBUG ("Triggered DELETE of file: " << triggeredFile.relative_path ().generic_string ());
Alexander Afanasyev583449a2013-01-28 17:04:06 -0800123 // m_onDelete (triggeredFile.relative_path ());
124
125 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
126 bind (m_onDelete, triggeredFile.relative_path ()),
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800127 "r-" + triggeredFile.relative_path ().string());
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800128 }
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800129}
130
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800131void
Alexander Afanasyevc80207d2013-01-29 20:07:39 -0800132FsWatcher::ScanDirectory_NotifyUpdates_Execute (QString dirPath, bool notifyCallbacks)
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800133{
Alexander Afanasyev4a8781c2013-01-29 17:59:44 -0800134 _LOG_TRACE (" >> ScanDirectory_NotifyUpdates_Execute");
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800135
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800136 // exclude working only on last component, not the full path; iterating through all directories, even excluded from monitoring
137 QRegExp exclude ("^(\\.|\\.\\.|\\.chronoshare|.*~|.*\\.swp)$");
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800138
139 QDirIterator dirIterator (dirPath,
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800140 QDir::Dirs | QDir::Files | /*QDir::Hidden |*/ QDir::NoSymLinks | QDir::NoDotAndDotDot,
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800141 QDirIterator::Subdirectories); // directory iterator (recursive)
142
143 // iterate through directory recursively
144 while (dirIterator.hasNext ())
145 {
146 dirIterator.next ();
147
148 // Get FileInfo
149 QFileInfo fileInfo = dirIterator.fileInfo ();
150
151 QString name = fileInfo.fileName ();
Alexander Afanasyev4a8781c2013-01-29 17:59:44 -0800152 _LOG_DEBUG ("+++ Scanning: " << name.toStdString ());
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800153
154 if (!exclude.exactMatch (name))
155 {
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800156 _LOG_DEBUG ("Not excluded file/dir: " << fileInfo.absoluteFilePath ().toStdString ());
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800157 QString absFilePath = fileInfo.absoluteFilePath ();
158
159 // _LOG_DEBUG ("Attempt to add path to watcher: " << absFilePath.toStdString ());
160 m_watcher->addPath (absFilePath);
161
Alexander Afanasyevc80207d2013-01-29 20:07:39 -0800162 if (notifyCallbacks && fileInfo.isFile ())
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800163 {
164 DidFileChanged (absFilePath);
165 }
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800166 }
167 else
168 {
169 // _LOG_DEBUG ("Excluded file/dir: " << fileInfo.filePath ().toStdString ());
170 }
171 }
172}
173
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800174
175void
176FsWatcher::ScanDirectory_NotifyRemovals_Execute (QString dirPath)
177{
178 _LOG_DEBUG ("Triggered DirPath: " << dirPath.toStdString ());
179
180 filesystem::path absPathTriggeredDir (dirPath.toStdString ());
181 dirPath.remove (0, m_dirPath.size ());
182
183 filesystem::path triggeredDir (dirPath.toStdString ());
184
Alexander Afanasyev506ff222013-01-29 18:12:55 -0800185 FileItemsPtr files = m_fileState->LookupFilesInFolderRecursively (triggeredDir.relative_path ().generic_string ());
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800186 for (std::list<FileItem>::iterator file = files->begin (); file != files->end (); file ++)
187 {
188 filesystem::path testFile = filesystem::path (m_dirPath.toStdString ()) / file->filename ();
189 _LOG_DEBUG ("Check file for deletion [" << testFile.generic_string () << "]");
190
191 if (!filesystem::exists (testFile))
192 {
193 _LOG_DEBUG ("Notifying about removed file [" << file->filename () << "]");
194 m_onDelete (file->filename ());
195 }
196 }
197}
198
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800199// std::vector<sEventInfo> FsWatcher::reconcileDirectory(QHash<QString, qint64> currentState, QString dirPath)
200// {
201// // list of files changed
202// std::vector<sEventInfo> dirChanges;
203
204// // compare result (database/stored snapshot) to fileList (current snapshot)
205// QMutableHashIterator<QString, qint64> i(m_storedState);
206
207// while(i.hasNext())
208// {
209// i.next();
210
211// QString absFilePath = i.key();
212// qint64 storedCreated = i.value();
213
214// // if this file is in a level higher than
215// // this directory, ignore
216// if(!absFilePath.startsWith(dirPath))
217// {
218// continue;
219// }
220
221// // check file existence
222// if(currentState.contains(absFilePath))
223// {
224// qint64 currentCreated = currentState.value(absFilePath);
225
226// if(storedCreated != currentCreated)
227// {
228// // update stored state
229// i.setValue(currentCreated);
230
231// // this file has been modified
232// sEventInfo eventInfo;
233// eventInfo.event = MODIFIED;
234// eventInfo.absFilePath = absFilePath.toStdString();
235// dirChanges.push_back(eventInfo);
236// }
237
238// // delete this file from fileList we have processed it
239// currentState.remove(absFilePath);
240// }
241// else
242// {
243// // delete from stored state
244// i.remove();
245
246// // this file has been deleted
247// sEventInfo eventInfo;
248// eventInfo.event = DELETED;
249// eventInfo.absFilePath = absFilePath.toStdString();
250// dirChanges.push_back(eventInfo);
251// }
252// }
253
254// // any files left in fileList have been added
255// for(QHash<QString, qint64>::iterator i = currentState.begin(); i != currentState.end(); ++i)
256// {
257// QString absFilePath = i.key();
258// qint64 currentCreated = i.value();
259
260// m_storedState.insert(absFilePath, currentCreated);
261
262// // this file has been added
263// sEventInfo eventInfo;
264// eventInfo.event = ADDED;
265// eventInfo.absFilePath = absFilePath.toStdString();
266// dirChanges.push_back(eventInfo);
267// }
268
269// return dirChanges;
270// }
271
272// QByteArray FsWatcher::calcChecksum(QString absFilePath)
273// {
274// // initialize checksum
275// QCryptographicHash crypto(QCryptographicHash::Md5);
276
277// // open file
278// QFile file(absFilePath);
279// file.open(QFile::ReadOnly);
280
281// // calculate checksum
282// while(!file.atEnd())
283// {
284// crypto.addData(file.read(8192));
285// }
286
287// return crypto.result();
288// }
289
290// void FsWatcher::printChanges(std::vector<sEventInfo> dirChanges)
291// {
292// if(!dirChanges.empty())
293// {
294// for(size_t i = 0; i < dirChanges.size(); i++)
295// {
296// QString tempString;
297
298// eEvent event = dirChanges[i].event;
299// QString absFilePath = QString::fromStdString(dirChanges[i].absFilePath);
300
301// switch(event)
302// {
303// case ADDED:
304// tempString.append("ADDED: ");
305// break;
306// case MODIFIED:
307// tempString.append("MODIFIED: ");
308// break;
309// case DELETED:
310// tempString.append("DELETED: ");
311// break;
312// }
313
314// tempString.append(absFilePath);
315
316// _LOG_DEBUG ("\t" << tempString.toStdString ());
317// }
318// }
319// else
320// {
321// _LOG_DEBUG ("\t[EMPTY]");
322// }
323// }
324
325#if WAF
326#include "fs-watcher.moc"
327#include "fs-watcher.cc.moc"
328#endif