File: INotifyMonitor.cpp

package info (click to toggle)
pinot 0.85-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 5,524 kB
  • ctags: 3,868
  • sloc: cpp: 33,107; sh: 8,801; ansic: 3,049; makefile: 557; xml: 366; python: 250
file content (451 lines) | stat: -rw-r--r-- 11,319 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
 *  Copyright 2005,2006 Fabrice Colin
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "config.h"
#include <sys/ioctl.h>
#ifdef HAVE_LINUX_INOTIFY_H
#include <stdint.h>
#include <linux/inotify.h>
#include "linux-inotify-syscalls.h"
#else
#ifdef HAVE_SYS_INOTIFY_H
#include <sys/inotify.h>
#endif
#endif
#include <string.h>
#include <errno.h>
#include <iostream>
#include <set>

#include "INotifyMonitor.h"

using std::string;
using std::map;
using std::set;
using std::queue;
using std::pair;
using std::cout;
using std::cerr;
using std::endl;

INotifyMonitor::INotifyMonitor() :
	MonitorInterface(),
	m_noWatchesLeft(false)
{
	pthread_mutex_init(&m_mutex, NULL);
	m_monitorFd = inotify_init();
	if (m_monitorFd < 0)
	{
		char errBuffer[1024];

		strerror_r(errno, errBuffer, 1024);
		cerr << "Couldn't initialize inotify: " << errBuffer << endl;
	}
}

INotifyMonitor::~INotifyMonitor()
{
	if (m_monitorFd >= 0)
	{
		close(m_monitorFd);
	}
	pthread_mutex_destroy(&m_mutex);
}

bool INotifyMonitor::removeWatch(const string &location)
{
	map<string, int>::iterator locationIter = m_locations.find(location);
	if (locationIter != m_locations.end())
	{
		inotify_rm_watch(m_monitorFd, locationIter->second);
		m_noWatchesLeft = false;

		map<int, string>::iterator watchIter = m_watches.find(locationIter->second);
		if (watchIter != m_watches.end())
		{
			m_watches.erase(watchIter);
		}
		m_locations.erase(locationIter);

		return true;
	}
	else
	{
		cerr << location << " is not being monitored" << endl;
	}

	return false;
}

/// Starts monitoring a location.
bool INotifyMonitor::addLocation(const string &location, bool isDirectory)
{
	uint32_t eventsMask = IN_CLOSE_WRITE|IN_MOVE|IN_CREATE|IN_DELETE|IN_UNMOUNT|IN_MOVE_SELF|IN_DELETE_SELF;
	bool addedLocation = false;

	if ((location.empty() == true) ||
		(location == "/") ||
		(m_monitorFd < 0) ||
		(m_noWatchesLeft == true))
	{
		return false;
	}

	if (pthread_mutex_lock(&m_mutex) != 0)
	{
		return false;
	}

	map<string, int>::iterator locationIter = m_locations.find(location);
	if (locationIter != m_locations.end())
	{
		// This is already being monitored
		addedLocation = true;
	}
	else
	{
		// FIXME: check the maximum number of watches hasn't been reached (MAX_FILE_WATCHES ?)
		int watchNum = inotify_add_watch(m_monitorFd, location.c_str(), eventsMask);
		if (watchNum >= 0)
		{
			// Generate an event to signal the file exists and is being monitored
			if (isDirectory == false)
			{
				MonitorEvent monEvent;
				monEvent.m_location = location;
				monEvent.m_isWatch = true;
				monEvent.m_type = MonitorEvent::EXISTS;
				monEvent.m_isDirectory = false;
				m_internalEvents.push(monEvent);
			}

			m_watches.insert(pair<int, string>(watchNum, location));
			m_locations.insert(pair<string, int>(location, watchNum));
#ifdef DEBUG
			cout << "INotifyMonitor::addLocation: added watch "
				<< watchNum << " for " << location << endl;
#endif
			addedLocation = true;
		}
		else
		{
			if (errno == ENOSPC)
			{
				m_noWatchesLeft = true;
			}
			cerr << "Couldn't monitor " << location << endl;
		}
	}
	pthread_mutex_unlock(&m_mutex);

	return addedLocation;
}

/// Stops monitoring a location.
bool INotifyMonitor::removeLocation(const string &location)
{
	bool removedLocation = false;

	if ((location.empty() == true) ||
		(m_monitorFd < 0))
	{
		return false;
	}

	if (pthread_mutex_lock(&m_mutex) != 0)
	{
		return false;
	}

	removedLocation = removeWatch(location);
	pthread_mutex_unlock(&m_mutex);

	return removedLocation;
}

/// Retrieves pending events.
bool INotifyMonitor::retrievePendingEvents(queue<MonitorEvent> &events)
{
	set<string> removedLocations;
	char buffer[1024];
	unsigned int queueLen = 0;
	size_t offset = 0;

	if (m_monitorFd < 0)
	{
		return false;
	}

	if (pthread_mutex_lock(&m_mutex) != 0)
	{
		return false;
	}

	// Copy internal events
	while (m_internalEvents.empty() == false)
	{
		MonitorEvent &internalEvent = m_internalEvents.front();
		events.push(internalEvent);

		// Next
		m_internalEvents.pop();
	}

	if (ioctl(m_monitorFd, FIONREAD, &queueLen) == 0)
	{
#ifdef DEBUG
		cout << "INotifyMonitor::retrievePendingEvents: "
			<< queueLen << " bytes to read" << endl;
#endif
	}
	if (queueLen == 0)
	{
		// Nothing to read
		pthread_mutex_unlock(&m_mutex);
		return true;
	}

	int bytesRead = read(m_monitorFd, buffer, 1024);
	while ((bytesRead > 0) &&
		(bytesRead - offset > 0))
	{
		struct inotify_event *pEvent = (struct inotify_event *)&buffer[offset];
		size_t eventSize = sizeof(struct inotify_event) + pEvent->len;

#ifdef DEBUG
		cout << "INotifyMonitor::retrievePendingEvents: read "
			<< bytesRead << " bytes at offset " << offset << endl;
#endif

		// What location is this event for ?
		map<int, string>::iterator watchIter = m_watches.find(pEvent->wd);
		if (watchIter == m_watches.end())
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: unknown watch "
				<< pEvent->wd << endl;
#endif
			offset += eventSize;
			continue;
		}

		MonitorEvent monEvent;

		monEvent.m_isWatch = true;
		if (pEvent->mask & IN_ISDIR)
		{
			monEvent.m_isDirectory = true;
		}

		monEvent.m_location = watchIter->second;
		// A name is provided if the target is below a location we match
		if (pEvent->len >= 1)
		{
			monEvent.m_location += "/";
			monEvent.m_location += pEvent->name;
			monEvent.m_isWatch = false;
		}

		// What type of event ?
		if (pEvent->mask & IN_CREATE)
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: created "
				<< monEvent.m_location << endl;
#endif
			monEvent.m_type = MonitorEvent::CREATED;
		}
		else if (pEvent->mask & IN_CLOSE_WRITE)
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: written and closed "
				<< monEvent.m_location << endl;
#endif
			monEvent.m_type = MonitorEvent::WRITE_CLOSED;
		}
		else if (pEvent->mask & IN_MOVED_FROM)
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: moved from on "
				<< monEvent.m_location << " " << pEvent->cookie << endl;
#endif
			// Store this until we receive a IN_MOVED_TO event
			m_movedFrom.insert(pair<uint32_t, MonitorEvent>(pEvent->cookie, monEvent));
		}
		else if (pEvent->mask & IN_MOVED_TO)
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: moved to on "
				<< monEvent.m_location << " " << pEvent->cookie << endl;
#endif
			// What was the previous location ?
			map<uint32_t, MonitorEvent>::iterator movedIter = m_movedFrom.find(pEvent->cookie);
			if (movedIter != m_movedFrom.end())
			{
				monEvent.m_previousLocation = movedIter->second.m_location;
				monEvent.m_type = MonitorEvent::MOVED;
#ifdef DEBUG
				cout << "INotifyMonitor::retrievePendingEvents: moved from "
					<< monEvent.m_previousLocation << endl;
#endif
				m_movedFrom.erase(movedIter);

				// Has a watch moved ?
				if ((monEvent.m_isWatch == true) &&
					(monEvent.m_previousLocation == watchIter->second))
				{
					// Update the location for this watch
					map<string, int>::iterator locationIter = m_locations.find(watchIter->second);
					if (locationIter != m_locations.end())
					{
						m_locations.erase(locationIter);
						m_locations[monEvent.m_location] = pEvent->wd;
					}
					watchIter->second = monEvent.m_location;
				}
			}
			else
			{
				// The previous location is unknown because it's from somewhere not being monitored
				monEvent.m_type = MonitorEvent::CREATED;
#ifdef DEBUG
				cout << "INotifyMonitor::retrievePendingEvents: don't know where file was moved from" << endl;
#endif
			}
		}
		else if (pEvent->mask & IN_MOVE_SELF)
		{
			map<uint32_t, MonitorEvent>::iterator movedIter = m_movedFrom.end();

#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: moved self on "
				<< monEvent.m_location << " " << pEvent->cookie << endl;
#endif
			// It was moved somewhere not being monitored
			if (pEvent->cookie == 0)
			{
				for (movedIter = m_movedFrom.begin(); movedIter != m_movedFrom.end(); ++movedIter)
				{
					if (movedIter->second.m_location == monEvent.m_location)
					{
						// For some reason, IN_ISDIR is not set when the cookie is 0
						if (movedIter->second.m_isDirectory == true)
						{
							monEvent.m_isDirectory = true;
						}
						break;
					}
				}
			}
			else
			{
				movedIter = m_movedFrom.find(pEvent->cookie);
			}

			if (movedIter != m_movedFrom.end())
			{
				monEvent.m_type = MonitorEvent::DELETED;

				m_movedFrom.erase(movedIter);
			}
		}
		else if (pEvent->mask & IN_DELETE)
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: deleted "
				<< monEvent.m_location << endl;
#endif
			monEvent.m_type = MonitorEvent::DELETED;
		}
		else if (pEvent->mask & IN_DELETE_SELF)
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: deleted self on "
				<< monEvent.m_location << endl;
#endif
			if (monEvent.m_isWatch == true)
			{
				removedLocations.insert(monEvent.m_location);
			}
		}
		else if (pEvent->mask & IN_UNMOUNT)
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: unmounted on "
				<< monEvent.m_location << endl;
#endif
			if (monEvent.m_isWatch == true)
			{
				// Watches are removed silently if the backing filesystem is unmounted
				removedLocations.insert(monEvent.m_location);
			}
		}
		else
		{
#ifdef DEBUG
			cout << "INotifyMonitor::retrievePendingEvents: ignoring event "
				<< pEvent->mask << " on " << monEvent.m_location << endl;
#endif
		}

		// Return event ?
		if (monEvent.m_type != MonitorEvent::UNKNOWN)
		{
			events.push(monEvent);
		}

		// Any IN_MOVED_FROM event for which we didn't get a IN_MOVED_TO ?
		time_t now = time(NULL);
		map<uint32_t, MonitorEvent>::iterator movedIter = m_movedFrom.begin();
		while (movedIter != m_movedFrom.end())
		{
			// The file was probably moved to an unmonitored location on the same filesystem
			if (movedIter->second.m_time + 60 < now)
			{
				// It's as good as if it was deleted
				movedIter->second.m_type = MonitorEvent::DELETED;
				events.push(movedIter->second);
#ifdef DEBUG
				cout << "INotifyMonitor::retrievePendingEvents: don't know where "
					<< movedIter->second.m_location << " was moved to" << endl;
#endif

				map<uint32_t, MonitorEvent>::iterator nextMovedIter = movedIter;
				++nextMovedIter;
				m_movedFrom.erase(movedIter);
				movedIter = nextMovedIter;
			}
			else
			{
				++movedIter;
			}
		}

		offset += eventSize;
	}
	// Any location to remove ?
	for (set<string>::const_iterator removalIter = removedLocations.begin();
		removalIter != removedLocations.end(); ++removalIter)
	{
		removeWatch(*removalIter);
	}
	pthread_mutex_unlock(&m_mutex);

	return true;
}