blob: cfb7f5522477f4ce78fdb65cbbf93c64eb79b4ee [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"
Zhenkai Zhud1756272013-02-01 17:02:18 -080024#include "db-helper.h"
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080025#include "logging.h"
26
27#include <boost/bind.hpp>
28
29#include <QDirIterator>
30#include <QRegExp>
31
32using namespace std;
33using namespace boost;
34
35INIT_LOGGER ("FsWatcher");
36
Alexander Afanasyev9ca444e2013-01-25 16:29:35 -080037FsWatcher::FsWatcher (QString dirPath,
38 LocalFile_Change_Callback onChange, LocalFile_Change_Callback onDelete,
39 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 Afanasyev9e5a4702013-01-24 13:15:23 -080046{
47 _LOG_DEBUG ("Monitor dir: " << m_dirPath.toStdString ());
48 // add main directory to monitor
Alexander Afanasyev69e13172013-01-25 17:16:27 -080049
Zhenkai Zhud1756272013-02-01 17:02:18 -080050 initFileStateDb();
51
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080052 m_watcher->addPath (m_dirPath);
53
54 // register signals (callback functions)
55 connect (m_watcher, SIGNAL (directoryChanged (QString)), this, SLOT (DidDirectoryChanged (QString)));
56 connect (m_watcher, SIGNAL (fileChanged (QString)), this, SLOT (DidFileChanged (QString)));
57
Alexander Afanasyev583449a2013-01-28 17:04:06 -080058 m_scheduler->start ();
59
Alexander Afanasyev7943c6b2013-01-29 18:43:24 -080060 Scheduler::scheduleOneTimeTask (m_scheduler, 0,
Zhenkai Zhud1756272013-02-01 17:02:18 -080061 bind (&FsWatcher::ScanDirectory_NotifyRemovals_Execute, this, m_dirPath),
Alexander Afanasyev7a647002013-01-30 11:54:52 -080062 "rescan-r-" + m_dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080063
Alexander Afanasyev7943c6b2013-01-29 18:43:24 -080064 Scheduler::scheduleOneTimeTask (m_scheduler, 0,
Zhenkai Zhud1756272013-02-01 17:02:18 -080065 bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, m_dirPath),
Alexander Afanasyev7a647002013-01-30 11:54:52 -080066 "rescan-" +m_dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080067}
68
69FsWatcher::~FsWatcher()
70{
Alexander Afanasyev583449a2013-01-28 17:04:06 -080071 m_scheduler->shutdown ();
Zhenkai Zhud1756272013-02-01 17:02:18 -080072 sqlite3_close(m_db);
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080073}
74
75void
76FsWatcher::DidDirectoryChanged (QString dirPath)
77{
Alexander Afanasyev583449a2013-01-28 17:04:06 -080078 _LOG_DEBUG ("Triggered DirPath: " << dirPath.toStdString ());
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -080079
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080080 filesystem::path absPathTriggeredDir (dirPath.toStdString ());
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080081 if (!filesystem::exists (filesystem::path (absPathTriggeredDir)))
82 {
83 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
Zhenkai Zhud1756272013-02-01 17:02:18 -080084 bind (&FsWatcher::ScanDirectory_NotifyRemovals_Execute, this, dirPath),
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080085 "r-" + dirPath.toStdString ()); // only one task will be scheduled per directory
86 }
87 else
88 {
89 // m_executor.execute (bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath));
90 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
Zhenkai Zhud1756272013-02-01 17:02:18 -080091 bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath),
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -080092 dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyevc80207d2013-01-29 20:07:39 -080093
94 // m_executor.execute (bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath));
95 Scheduler::scheduleOneTimeTask (m_scheduler, 300,
Zhenkai Zhud1756272013-02-01 17:02:18 -080096 bind (&FsWatcher::ScanDirectory_NotifyUpdates_Execute, this, dirPath),
Alexander Afanasyevc80207d2013-01-29 20:07:39 -080097 "rescan-"+dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyev7a647002013-01-30 11:54:52 -080098
99 Scheduler::scheduleOneTimeTask (m_scheduler, 300,
Zhenkai Zhud1756272013-02-01 17:02:18 -0800100 bind (&FsWatcher::ScanDirectory_NotifyRemovals_Execute, this, m_dirPath),
Alexander Afanasyev7a647002013-01-30 11:54:52 -0800101 "rescan-r-" + m_dirPath.toStdString ()); // only one task will be scheduled per directory
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800102 }
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800103}
104
105void
106FsWatcher::DidFileChanged (QString filePath)
107{
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800108 if (!filePath.startsWith (m_dirPath))
109 {
Zhenkai Zhud1756272013-02-01 17:02:18 -0800110 _LOG_ERROR ("Got notification about a file not from the monitored directory: " << filePath.toStdString());
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800111 return;
112 }
113 filesystem::path absPathTriggeredFile (filePath.toStdString ());
114 filePath.remove (0, m_dirPath.size ());
115
116 filesystem::path triggeredFile (filePath.toStdString ());
117 if (filesystem::exists (filesystem::path (absPathTriggeredFile)))
118 {
119 _LOG_DEBUG ("Triggered UPDATE of file: " << triggeredFile.relative_path ().generic_string ());
Alexander Afanasyev583449a2013-01-28 17:04:06 -0800120 // m_onChange (triggeredFile.relative_path ());
121
122 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
123 bind (m_onChange, triggeredFile.relative_path ()),
124 triggeredFile.relative_path ().string());
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800125 }
126 else
127 {
128 _LOG_DEBUG ("Triggered DELETE of file: " << triggeredFile.relative_path ().generic_string ());
Alexander Afanasyev583449a2013-01-28 17:04:06 -0800129 // m_onDelete (triggeredFile.relative_path ());
130
131 Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
132 bind (m_onDelete, triggeredFile.relative_path ()),
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800133 "r-" + triggeredFile.relative_path ().string());
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800134 }
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800135}
136
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800137void
Zhenkai Zhud1756272013-02-01 17:02:18 -0800138FsWatcher::ScanDirectory_NotifyUpdates_Execute (QString dirPath)
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800139{
Alexander Afanasyev4a8781c2013-01-29 17:59:44 -0800140 _LOG_TRACE (" >> ScanDirectory_NotifyUpdates_Execute");
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800141
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800142 // exclude working only on last component, not the full path; iterating through all directories, even excluded from monitoring
143 QRegExp exclude ("^(\\.|\\.\\.|\\.chronoshare|.*~|.*\\.swp)$");
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800144
145 QDirIterator dirIterator (dirPath,
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800146 QDir::Dirs | QDir::Files | /*QDir::Hidden |*/ QDir::NoSymLinks | QDir::NoDotAndDotDot,
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800147 QDirIterator::Subdirectories); // directory iterator (recursive)
148
149 // iterate through directory recursively
150 while (dirIterator.hasNext ())
151 {
152 dirIterator.next ();
153
154 // Get FileInfo
155 QFileInfo fileInfo = dirIterator.fileInfo ();
156
157 QString name = fileInfo.fileName ();
Alexander Afanasyev4a8781c2013-01-29 17:59:44 -0800158 _LOG_DEBUG ("+++ Scanning: " << name.toStdString ());
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800159
160 if (!exclude.exactMatch (name))
161 {
Alexander Afanasyev69e13172013-01-25 17:16:27 -0800162 _LOG_DEBUG ("Not excluded file/dir: " << fileInfo.absoluteFilePath ().toStdString ());
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800163 QString absFilePath = fileInfo.absoluteFilePath ();
164
165 // _LOG_DEBUG ("Attempt to add path to watcher: " << absFilePath.toStdString ());
Alexander Afanasyevc4942042013-02-19 13:54:25 -0800166 m_watcher->removePath (absFilePath);
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800167 m_watcher->addPath (absFilePath);
168
Alexander Afanasyevf695aed2013-01-30 13:28:42 -0800169 if (fileInfo.isFile ())
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800170 {
Alexander Afanasyevf695aed2013-01-30 13:28:42 -0800171 QString relFile = absFilePath;
172 relFile.remove (0, m_dirPath.size ());
173 filesystem::path aFile (relFile.toStdString ());
174
Zhenkai Zhud1756272013-02-01 17:02:18 -0800175 if (
176 //!m_fileState->LookupFile (aFile.relative_path ().generic_string ()) /* file does not exist there, but exists locally: added */)
Alexander Afanasyev89024ac2013-02-14 09:38:10 -0800177 !fileExists(aFile.relative_path()) /*file does not exist in db, but exists in fs: add */)
Alexander Afanasyevf695aed2013-01-30 13:28:42 -0800178 {
Alexander Afanasyev89024ac2013-02-14 09:38:10 -0800179 addFile(aFile.relative_path());
Alexander Afanasyevf695aed2013-01-30 13:28:42 -0800180 DidFileChanged (absFilePath);
181 }
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800182 }
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800183 }
184 else
185 {
186 // _LOG_DEBUG ("Excluded file/dir: " << fileInfo.filePath ().toStdString ());
187 }
188 }
189}
190
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800191
192void
Zhenkai Zhud1756272013-02-01 17:02:18 -0800193FsWatcher::ScanDirectory_NotifyRemovals_Execute (QString dirPath)
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800194{
195 _LOG_DEBUG ("Triggered DirPath: " << dirPath.toStdString ());
196
197 filesystem::path absPathTriggeredDir (dirPath.toStdString ());
198 dirPath.remove (0, m_dirPath.size ());
199
200 filesystem::path triggeredDir (dirPath.toStdString ());
201
Zhenkai Zhud1756272013-02-01 17:02:18 -0800202 /*
Alexander Afanasyev506ff222013-01-29 18:12:55 -0800203 FileItemsPtr files = m_fileState->LookupFilesInFolderRecursively (triggeredDir.relative_path ().generic_string ());
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800204 for (std::list<FileItem>::iterator file = files->begin (); file != files->end (); file ++)
205 {
206 filesystem::path testFile = filesystem::path (m_dirPath.toStdString ()) / file->filename ();
207 _LOG_DEBUG ("Check file for deletion [" << testFile.generic_string () << "]");
208
209 if (!filesystem::exists (testFile))
210 {
Alexander Afanasyev7a647002013-01-30 11:54:52 -0800211 if (removeIncomplete || file->is_complete ())
212 {
213 _LOG_DEBUG ("Notifying about removed file [" << file->filename () << "]");
214 m_onDelete (file->filename ());
215 }
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800216 }
217 }
Zhenkai Zhud1756272013-02-01 17:02:18 -0800218 */
219
220 vector<string> files;
Alexander Afanasyev89024ac2013-02-14 09:38:10 -0800221 getFilesInDir(triggeredDir.relative_path(), files);
Zhenkai Zhud1756272013-02-01 17:02:18 -0800222 for (vector<string>::iterator file = files.begin(); file != files.end(); file++)
223 {
Alexander Afanasyev89024ac2013-02-14 09:38:10 -0800224 filesystem::path targetFile = filesystem::path (m_dirPath.toStdString()) / *file;
Zhenkai Zhud1756272013-02-01 17:02:18 -0800225 if (!filesystem::exists (targetFile))
226 {
Alexander Afanasyev89024ac2013-02-14 09:38:10 -0800227 deleteFile(*file);
228 m_onDelete(*file);
Zhenkai Zhud1756272013-02-01 17:02:18 -0800229 }
230 }
Alexander Afanasyev0a30a0c2013-01-29 17:25:42 -0800231}
232
Zhenkai Zhud1756272013-02-01 17:02:18 -0800233const string INIT_DATABASE = "\
234CREATE TABLE IF NOT EXISTS \n\
235 Files( \n\
236 filename TEXT NOT NULL, \n\
237 PRIMARY KEY (filename) \n\
238); \n\
239CREATE INDEX filename_index ON Files (filename); \n\
240";
241
242void
243FsWatcher::initFileStateDb()
244{
Alexander Afanasyev89024ac2013-02-14 09:38:10 -0800245 filesystem::path dbFolder = filesystem::path (m_dirPath.toStdString()) / ".chronoshare" / "fs_watcher";
Zhenkai Zhud1756272013-02-01 17:02:18 -0800246 filesystem::create_directories(dbFolder);
247
Alexander Afanasyev89024ac2013-02-14 09:38:10 -0800248 int res = sqlite3_open((dbFolder / "filestate.db").string ().c_str (), &m_db);
Zhenkai Zhud1756272013-02-01 17:02:18 -0800249 if (res != SQLITE_OK)
250 {
251 BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot open database: " + (dbFolder / "filestate.db").string()));
252 }
253
254 char *errmsg = 0;
255 res = sqlite3_exec(m_db, INIT_DATABASE.c_str(), NULL, NULL, &errmsg);
256 if (res != SQLITE_OK && errmsg != 0)
257 {
258 // _LOG_TRACE ("Init \"error\": " << errmsg);
259 cout << "FS-Watcher DB error: " << errmsg << endl;
260 sqlite3_free (errmsg);
261 }
262}
263
264bool
265FsWatcher::fileExists(const filesystem::path &filename)
266{
267 sqlite3_stmt *stmt;
268 sqlite3_prepare_v2(m_db, "SELECT * FROM Files WHERE filename = ?;", -1, &stmt, 0);
269 sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
270 bool retval = false;
271 if (sqlite3_step (stmt) == SQLITE_ROW)
272 {
273 retval = true;
274 }
275 sqlite3_finalize(stmt);
276
277 return retval;
278}
279
280void
281FsWatcher::addFile(const filesystem::path &filename)
282{
283 sqlite3_stmt *stmt;
284 sqlite3_prepare_v2(m_db, "INSERT OR IGNORE INTO Files (filename) VALUES (?);", -1, &stmt, 0);
285 sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
286 sqlite3_step(stmt);
287 sqlite3_finalize(stmt);
288}
289
290void
291FsWatcher::deleteFile(const filesystem::path &filename)
292{
293 sqlite3_stmt *stmt;
294 sqlite3_prepare_v2(m_db, "DELETE FROM Files WHERE filename = ?;", -1, &stmt, 0);
295 sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
296 sqlite3_step(stmt);
297 sqlite3_finalize(stmt);
298}
299
300void
301FsWatcher::getFilesInDir(const filesystem::path &dir, vector<string> &files)
302{
303 sqlite3_stmt *stmt;
304 sqlite3_prepare_v2(m_db, "SELECT * FROM Files WHERE filename LIKE ?;", -1, &stmt, 0);
305
306 string dirStr = dir.string();
307 ostringstream escapedDir;
308 for (string::const_iterator ch = dirStr.begin (); ch != dirStr.end (); ch ++)
309 {
310 if (*ch == '%')
311 escapedDir << "\\%";
312 else
313 escapedDir << *ch;
314 }
315 escapedDir << "/" << "%";
316 string escapedDirStr = escapedDir.str ();
317 sqlite3_bind_text (stmt, 1, escapedDirStr.c_str (), escapedDirStr.size (), SQLITE_STATIC);
318
319 while(sqlite3_step(stmt) == SQLITE_ROW)
320 {
321 string filename(reinterpret_cast<const char *>(sqlite3_column_text (stmt, 0)), sqlite3_column_bytes(stmt, 0));
322 files.push_back(filename);
323 }
324
325 sqlite3_finalize (stmt);
326
327}
Alexander Afanasyev9e5a4702013-01-24 13:15:23 -0800328
329#if WAF
330#include "fs-watcher.moc"
331#include "fs-watcher.cc.moc"
332#endif