File: CachedFileStat.hpp

package info (click to toggle)
ruby-passenger 4.0.53-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,668 kB
  • ctags: 70,512
  • sloc: cpp: 264,280; ruby: 25,606; sh: 22,815; ansic: 18,277; python: 767; makefile: 99; perl: 20
file content (246 lines) | stat: -rw-r--r-- 7,830 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
/*
 *  Phusion Passenger - https://www.phusionpassenger.com/
 *  Copyright (c) 2010-2013 Phusion
 *
 *  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
#ifndef _PASSENGER_CACHED_FILE_STAT_HPP_
#define _PASSENGER_CACHED_FILE_STAT_HPP_

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>

#include <cerrno>
#include <cassert>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <oxt/system_calls.hpp>

#include <StaticString.h>
 #include <Utils/SystemTime.h>
#include <Utils/StringMap.h>

namespace Passenger {

using namespace std;
using namespace oxt;
using namespace boost;

/**
 * CachedFileStat allows one to stat() files at a throttled rate, in order
 * to minimize stress on the filesystem. It does this by caching the old stat
 * data for a specified amount of time.
 *
 * The cache has a maximum size, which may be altered during runtime. If a
 * file that wasn't in the cache is being stat()ed, and the cache is full,
 * then the oldest cache entry will be removed.
 *
 * This class is fully thread-safe.
 */
class CachedFileStat {
public:
	/** Represents a cached file stat entry. */
	class Entry {
	private:
		/** The last return value of stat(). */
		int last_result;

		/** The errno set by the last stat() call. */
		int last_errno;

		/** The last time a stat() was performed. */
		time_t last_time;

		/**
		 * Checks whether `interval` seconds have elapsed since `begin`.
		 * The current time is returned via the `currentTime` argument,
		 * so that the caller doesn't have to call time() again if it needs the current
		 * time.
		 *
		 * @pre begin <= time(NULL)
		 * @return Whether `interval` seconds have elapsed since `begin`.
		 * @throws TimeRetrievalException Something went wrong while retrieving the time.
		 * @throws boost::thread_interrupted
		 */
		bool expired(time_t begin, unsigned int interval, time_t &currentTime) {
			currentTime = SystemTime::get();
			return (unsigned int) (currentTime - begin) >= interval;
		}

	public:
		/** The cached stat info. */
		struct stat info;

		/** This entry's filename. */
		string filename;

		/**
		 * Creates a new Entry object. The file will not be
		 * stat()ted until you call refresh().
		 *
		 * @param filename The file to stat.
		 */
		Entry(const string &_filename)
			: filename(_filename)
		{
			memset(&info, 0, sizeof(struct stat));
			last_result = -1;
			last_errno = 0;
			last_time = 0;
		}

		/**
		 * Re-stat() the file, if necessary. If <tt>throttleRate</tt> seconds have
		 * passed since the last time stat() was called, then the file will be
		 * re-stat()ted.
		 *
		 * The stat information, which may either be the result of a new stat() call
		 * or just the old cached information, is be available in the <tt>info</tt>
		 * member.
		 *
		 * @return 0 if the stat() call succeeded or if no stat() was performed,
		 *         -1 if something went wrong while statting the file. In the latter
		 *         case, <tt>errno</tt> will be populated with an appropriate error code.
		 * @throws TimeRetrievalException Something went wrong while retrieving the
		 *         system time.
		 * @throws boost::thread_interrupted
		 */
		int refresh(unsigned int throttleRate) {
			time_t currentTime;

			if (expired(last_time, throttleRate, currentTime)) {
				last_result = syscalls::stat(filename.c_str(), &info);
				last_errno = errno;
				last_time = currentTime;
				return last_result;
			} else {
				errno = last_errno;
				return last_result;
			}
		}
	};

	typedef boost::shared_ptr<Entry> EntryPtr;
	typedef list<EntryPtr> EntryList;
	typedef StringMap<EntryList::iterator> EntryMap;

	unsigned int maxSize;
	EntryList entries;
	EntryMap cache;
	mutable boost::mutex lock;

	/**
	 * Creates a new CachedFileStat object.
	 *
	 * @param maxSize The maximum cache size. A size of 0 means unlimited.
	 */
	CachedFileStat(unsigned int maxSize = 0) {
		this->maxSize = maxSize;
	}

	/**
	 * Stats the given file. If `throttleRate` seconds have passed since
	 * the last time stat() was called on this file, then the file will be
	 * re-stat()ted, otherwise the cached stat information will be returned.
	 *
	 * @param filename The file to stat.
	 * @param stat A pointer to a stat struct; the retrieved stat information
	 *             will be stored here.
	 * @param throttleRate Tells this CachedFileStat that the file may only
	 *        be statted at most every <tt>throttleRate</tt> seconds.
	 * @return 0 if the stat() call succeeded or if the cached stat information was used;
	 *         -1 if something went wrong while statting the file. In the latter
	 *         case, <tt>errno</tt> will be populated with an appropriate error code.
	 * @throws SystemException Something went wrong while retrieving the
	 *         system time. stat() errors will <em>not</em> result in
	 *         SystemException being thrown.
	 * @throws boost::thread_interrupted
	 */
	int stat(const StaticString &filename, struct stat *buf, unsigned int throttleRate = 0) {
		boost::unique_lock<boost::mutex> l(lock);
		EntryList::iterator it(cache.get(filename, entries.end()));
		EntryPtr entry;
		int ret;

		if (it == entries.end()) {
			// Filename not in cache.
			// If cache is full, remove the least recently used
			// cache entry.
			if (maxSize != 0 && cache.size() == maxSize) {
				EntryList::iterator listEnd(entries.end());
				listEnd--;
				string filename2((*listEnd)->filename);
				entries.pop_back();
				cache.remove(filename2);
			}

			// Add to cache as most recently used.
			entry = boost::make_shared<Entry>(filename);
			entries.push_front(entry);
			cache.set(filename, entries.begin());
		} else {
			// Cache hit.
			entry = *it;

			// Mark this cache item as most recently used.
			entries.splice(entries.begin(), entries, it);
			cache.set(filename, entries.begin());
		}
		ret = entry->refresh(throttleRate);
		*buf = entry->info;
		return ret;
	}

	/**
	 * Change the maximum size of the cache. If the new size is larger
	 * than the old size, then the oldest entries in the cache are
	 * removed.
	 *
	 * A size of 0 means unlimited.
	 */
	void setMaxSize(unsigned int maxSize) {
		boost::unique_lock<boost::mutex> l(lock);
		if (maxSize != 0) {
			int toRemove = cache.size() - maxSize;
			for (int i = 0; i < toRemove; i++) {
				string filename(entries.back()->filename);
				entries.pop_back();
				cache.remove(filename);
			}
		}
		this->maxSize = maxSize;
	}

	/**
	 * Returns whether `filename` is in the cache.
	 */
	bool knows(const StaticString &filename) const {
		boost::unique_lock<boost::mutex> l(lock);
		return cache.has(filename);
	}
};

} // namespace Passenger

#endif /* _PASSENGER_CACHED_FILE_STAT_HPP_ */