mod_gridfs / gridfs / mod_gridfs.cpp

  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
/*
	mod_gridfs.c -- Apache 2.2+ module that supports serving of files from MongoDB GridFS.

	See http://www.mongodb.org/ and http://www.mongodb.org/display/DOCS/GridFS for more information.

	See LICENSE file for licensing details.
*/

#include <unistd.h>

#include "client/dbclient.h"
#include "client/gridfs.h"

#include "apr_strings.h"

#include "httpd.h"
#include "http_log.h"
#include "http_config.h"
#include "http_protocol.h"
#include "http_request.h"

//	Declare module
extern "C"
{
	extern module AP_MODULE_DECLARE_DATA gridfs_module;
}

//	Default cache max age in seconds
const int DEFAULT_CACHE_MAX_AGE = 604800;

//	Default connect timeout in seconds
const int DEFAULT_CONNECT_TIMEOUT = 30;

//	Maximum cache age in seconds
const int MAX_CACHE_MAX_AGE = 86400 * 365 * 10;

//	Maximum connect timeout in seconds
const int MAX_CONNECT_TIMEOUT = 300;

//	Retry delay in milliseconds
const int RETRY_DELAY = 300;

//	Module configuration
struct gridfs_config
{
	const std::string *connection_string;
	const std::string *database;
	const std::string *username;
	const std::string *password;
	int cache_max_age;
	bool cache_max_age_set;
	int connect_timeout;
	bool connect_timeout_set;
	bool slave_ok;
	bool slave_ok_set;
	const std::string *context;
};

//	Creates module configuration
static void *gridfs_create_config(apr_pool_t *const pool, char *const location)
{
	gridfs_config *const config = static_cast<gridfs_config *>(apr_pcalloc(pool, sizeof(gridfs_config)));
	if (config == 0)
		return 0;
	config->cache_max_age = DEFAULT_CACHE_MAX_AGE;
	config->connect_timeout = DEFAULT_CONNECT_TIMEOUT;
	if (location != 0 && location[0] == '/' && location[1] != '\0')
	{
	  	void *const context_data = apr_palloc(pool, sizeof(std::string));
	  	if (context_data == 0)
	    	return config;
		std::string *context;
		try
		{
			context = new (context_data) std::string(location + 1);
			if (*context->rbegin() != '/')
				context->append(1, '/');
		}
		catch (...)
		{
			return config;
		}
		config->context = context;
	}
	return config;
}

//	Merges module configuration
static void *gridfs_merge_config(apr_pool_t *const pool, void *const basev, void *const addv)
{
	gridfs_config *const config = static_cast<gridfs_config *>(apr_palloc(pool, sizeof(gridfs_config)));
	if (config == 0)
		return 0;
	const gridfs_config *const base = static_cast<const gridfs_config *>(basev);
	const gridfs_config *const add = static_cast<const gridfs_config *>(addv);
	config->connection_string = add->connection_string != 0 ? add->connection_string : base->connection_string;
	config->database = add->database != 0 ? add->database : base->database;
	config->username = add->username != 0 ? add->username : base->username;
	config->password = add->password != 0 ? add->password : base->password;
	config->cache_max_age = add->cache_max_age_set ? add->cache_max_age : base->cache_max_age;
	config->cache_max_age_set = add->cache_max_age_set || base->cache_max_age_set;
	config->connect_timeout = add->connect_timeout_set ? add->connect_timeout : base->connect_timeout;
	config->connect_timeout_set = add->connect_timeout_set || base->connect_timeout_set;
	config->slave_ok = add->slave_ok_set ? add->slave_ok : base->slave_ok;
	config->slave_ok_set = add->slave_ok_set || base->slave_ok_set;
	config->context = add->context != 0 ? add->context : base->context;
	return config;
}

//	Handles "GridFSConnection <connection string>" command
static const char *gridfs_connection_command(cmd_parms *const command, void *const module_config, const char *const argument)
{
	gridfs_config *const config = static_cast<gridfs_config *>(module_config);
	void *const connection_string_data = apr_palloc(command->pool, sizeof(std::string));
	if (connection_string_data == 0)
		return "GridFSConnection failed to allocate data.";
	std::string *connection_string;
	try
	{
		connection_string = new (connection_string_data) std::string(argument);
	}
	catch (...)
	{
		return "GridFSConnection exception.";
	}
	config->connection_string = connection_string;
	return 0;
}

//	Handles "GridFSDatabase <database name>" command
static const char *gridfs_database_command(cmd_parms *const command, void *const module_config, const char *const argument)
{
	gridfs_config *const config = static_cast<gridfs_config *>(module_config);
	void *const database_data = apr_palloc(command->pool, sizeof(std::string));
	if (database_data == 0)
		return "GridFSDatabase failed to allocate data.";
	std::string *database;
	try
	{
		database = new (database_data) std::string(argument);
	}
	catch (...)
	{
		return "GridFSDatabase exception.";
	}
	config->database = database;
	return 0;
}

//	Handles "GridFSUsername <username>" command
static const char *gridfs_username_command(cmd_parms *const command, void *const module_config, const char *const argument)
{
	gridfs_config *const config = static_cast<gridfs_config *>(module_config);
	void *const username_data = apr_palloc(command->pool, sizeof(std::string));
	if (username_data == 0)
		return "GridFSUsername failed to allocate data.";
	std::string *username;
	try
	{
		username = new (username_data) std::string(argument);
	}
	catch (...)
	{
		return "GridFSUsername exception.";
	}
	config->username = username;
	return 0;
}

//	Handles "GridFSPassword <password>" command
static const char *gridfs_password_command(cmd_parms *const command, void *const module_config, const char *const argument)
{
	gridfs_config *const config = static_cast<gridfs_config *>(module_config);
	void *const password_data = apr_palloc(command->pool, sizeof(std::string));
	if (password_data == 0)
		return "GridFSPassword failed to allocate data.";
	std::string *password;
	try
	{
		password = new (password_data) std::string(argument);
	}
	catch (...)
	{
		return "GridFSPassword exception.";
	}
	config->password = password;
	return 0;
}

//	Handles "GridFSCacheMaxAge <cache max age>" command
static const char *gridfs_cache_max_age_command(cmd_parms *const command, void *const module_config, const char *const argument)
{
	gridfs_config *const config = static_cast<gridfs_config *>(module_config);
	const int cache_max_age = std::atoi(argument);
	if (cache_max_age < 0 || cache_max_age > MAX_CACHE_MAX_AGE)
		return "GridFSCacheMaxAge out of range.";
	config->cache_max_age = cache_max_age;
	config->cache_max_age_set = true;
	return 0;
}

//	Handles "GridFSConnectTimeout <connect timeout>" command
static const char *gridfs_connect_timeout_command(cmd_parms *const command, void *const module_config, const char *const argument)
{
	gridfs_config *const config = static_cast<gridfs_config *>(module_config);
	int connect_timeout = atoi(argument);
	if (connect_timeout < 0 || connect_timeout > MAX_CONNECT_TIMEOUT)
		return "GridFSConnectTimeout out of range.";
	config->connect_timeout = connect_timeout;
	config->connect_timeout_set = true;
	return 0;
}

//	Handles "GridFSSlaveOk <On|Off>" command
static const char *gridfs_slave_ok_command(cmd_parms *const command, void *const module_config, int flag)
{
	gridfs_config *const config = static_cast<gridfs_config *>(module_config);
	config->slave_ok = flag != 0;
	config->slave_ok_set = true;
	return 0;
}

//	Handles request
static int gridfs_handler(request_rec *const request)
{
	const gridfs_config *const config = static_cast<gridfs_config *>(ap_get_module_config(request->per_dir_config, &gridfs_module));
	if (config->connection_string == 0 || config->database == 0)
		return DECLINED;
   	request->allowed |= AP_METHOD_BIT << M_GET;
	if (request->method_number != M_GET)
		return HTTP_NOT_IMPLEMENTED;
	if (*request->uri != '/' || request->uri[1] == '\0')
		return HTTP_NOT_FOUND;
	const char * filename = request->uri + 1;
	if (config->context != 0)
	{
	  	const std::string& context = *config->context;
	  	const size_t context_length = context.length();
	  	if (context.compare(0, context_length, filename, context_length) == 0)
		  	filename += context_length;
	}
	filename = apr_pstrdup(request->pool, filename);
	if (filename == 0)
	{
		ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, request, "mod_gridfs: Failed to allocate filename memory."); 
		return HTTP_INTERNAL_SERVER_ERROR;
	}
	request->filename = const_cast<char *>(filename);
	int result;
	apr_bucket_brigade *brigade = 0;
	try
	{
		apr_off_t content_length = 0;
		std::string content_type;
		const apr_time_t retry_threshold = request->request_time + apr_time_from_sec(config->connect_timeout);
		while (true)
		{
			try
			{
				std::auto_ptr<mongo::ScopedDbConnection> connection(mongo::ScopedDbConnection::getScopedDbConnection(*config->connection_string, config->connect_timeout));
				const std::string& database = *config->database;

				mongo::DBClientBase& client = connection->conn();
				if (config->username != 0 && config->password != 0)
				{
					const std::string& username = *config->username;
					std::string errmsg;
					if (!client.auth(database, username, *config->password, errmsg))
					{
						connection->done();
						ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, request, "mod_gridfs: Failed to authenticate user '%s' with database '%s': %s.", 
							username.c_str(), database.c_str(), errmsg.c_str());
						return HTTP_INTERNAL_SERVER_ERROR;
					}
				}

				const mongo::GridFS gridfs(client, database);
				mongo::GridFile gridfile = gridfs.findFile(filename, config->slave_ok);
				if (!gridfile.exists())
				{
					if (config->slave_ok)
					{
						gridfile = gridfs.findFile(filename, false);
						if (!gridfile.exists())
						{
							connection->done();
							return HTTP_NOT_FOUND;
						}
					}
					else
					{
						connection->done();
						return HTTP_NOT_FOUND;
					}
				}
				const mongo::Date_t upload_date = gridfile.getUploadDate();
				request->mtime = apr_time_from_sec(upload_date.toTimeT());
				ap_set_last_modified(request);
				const std::string& md5 = gridfile.getMD5();
				if (!md5.empty())
					apr_table_setn(request->headers_out, "ETag", md5.c_str());
				if (ap_meets_conditions(request) == HTTP_NOT_MODIFIED)
				{
					connection->done();
					if (!md5.empty())
						apr_table_unset(request->headers_out, "ETag");
					return HTTP_NOT_MODIFIED;
				}
				const mongo::gridfs_offset file_length = gridfile.getContentLength();
				content_length = 0;
				content_type = gridfile.getContentType();
				if (file_length != 0 && request->header_only == 0)
				{
					const int num_chunks = gridfile.getNumChunks();
					if (num_chunks == 0)
					{
						connection->done();
						ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, request, "mod_gridfs: No chunks available for file '%s'.", filename); 
						return HTTP_INTERNAL_SERVER_ERROR;
					}
					if (brigade == 0)
					{
						brigade = apr_brigade_create(request->pool, request->connection->bucket_alloc);
						if (brigade == 0)
						{
							connection->done();
							ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, request, "mod_gridfs: Failed to create brigade."); 
							return HTTP_INTERNAL_SERVER_ERROR;
						}
					}
					for (int chunk_index = 0;chunk_index < num_chunks;chunk_index++) 
					{
						const mongo::GridFSChunk& chunk = gridfile.getChunk(chunk_index);
						int chunk_length;
						const char *chunk_data = chunk.data(chunk_length);
						if (chunk_length == 0)
							continue;
						if ((result = apr_brigade_write(brigade, 0, 0, chunk_data, chunk_length)) != APR_SUCCESS)
						{
							connection->done();
							ap_log_rerror(APLOG_MARK, APLOG_ERR, result, request, "mod_gridfs: Failed to write chunk %d for file '%s' to brigade (length: %d).", chunk_index, filename, chunk_length); 
							return HTTP_INTERNAL_SERVER_ERROR;
						}
						content_length += chunk_length;
					}
					if (content_length != file_length)
					{
						connection->done();
						ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, result, request, "mod_gridfs: Mismatching files/chunks length for file '%s' (difference: %d).", filename, static_cast<int>(file_length - content_length));
						return HTTP_INTERNAL_SERVER_ERROR;
					}
				}
				connection->done();
				break;
			}
			catch (const mongo::DBException& exception)
			{
				if (apr_time_now() >= retry_threshold)
					throw;
				const int code = exception.getCode();
				switch (code)
				{
				case 9001:	//	default socket exception
				case 10009:	//	ReplicaSetMonitor no master found for set
				case 10276:	//	DBClientBase::findN: transport error
				case 11002:	//	pool socket exception
					ap_log_rerror(APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, result, request, "mod_gridfs: Retrying after MongoDB exception for file '%s' (code: %d): %s.", filename, code, exception.what()); 
					break;

				default:
					throw;
				}
			}
			if (brigade != 0)
				apr_brigade_cleanup(brigade);
			apr_sleep(RETRY_DELAY * 1000);
		}
		if (content_length != 0)
			ap_set_content_length(request, content_length);
		if (content_type.empty())
		{
			request->finfo.filetype = APR_REG;
			if ((result = ap_run_type_checker(request)) != APR_SUCCESS)
				ap_log_rerror(APLOG_MARK, APLOG_WARNING, result, request, "mod_gridfs: Failed to run type checker for file '%s'.", filename); 
		}
		else
			ap_set_content_type(request, content_type.c_str());
		if (config->cache_max_age != 0)
		{
			char cache_control[32];
			snprintf(cache_control, sizeof(cache_control) - 1, "public, max-age=%d", config->cache_max_age);
			apr_table_setn(request->headers_out, "Cache-Control", cache_control);
			apr_time_t expires_time = request->request_time + apr_time_from_sec(config->cache_max_age);
			char expires[APR_RFC822_DATE_LEN];
			apr_rfc822_date(expires, expires_time);
			apr_table_setn(request->headers_out, "Expires", expires);
		}
	}
	catch (const mongo::DBException& exception)
	{
		ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, request, "mod_gridfs: Unhandled MongoDB exception occured for file '%s' (code: %d): %s.", filename, exception.getCode(), exception.what()); 
		return HTTP_INTERNAL_SERVER_ERROR;
	}
	catch (const std::exception& exception)
	{
		ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, request, "mod_gridfs: Unhandled exception occured for file '%s': %s.", filename, exception.what()); 
		return HTTP_INTERNAL_SERVER_ERROR;
	}
	catch (...)
	{
		ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, request, "mod_gridfs: Unknown unhandled exception occured for file '%s'.", filename); 
		return HTTP_INTERNAL_SERVER_ERROR;
	}
	if (brigade != 0)
	    return ap_pass_brigade(request->output_filters, brigade);
	return OK;
}

//	Registers hooks
static void gridfs_register_hooks(apr_pool_t *const pool)
{
	ap_hook_handler(gridfs_handler, 0, 0, APR_HOOK_MIDDLE);
}

//	Describes module configuration commands
static const command_rec gridfs_commands[] =
{
	AP_INIT_TAKE1("GridFSConnection", reinterpret_cast<cmd_func>(gridfs_connection_command), 0, OR_FILEINFO, "GridFS connection string."),
	AP_INIT_TAKE1("GridFSDatabase", reinterpret_cast<cmd_func>(gridfs_database_command), 0, OR_FILEINFO, "GridFS database name."),
	AP_INIT_TAKE1("GridFSUsername", reinterpret_cast<cmd_func>(gridfs_username_command), 0, OR_FILEINFO, "GridFS database authentication username."),
	AP_INIT_TAKE1("GridFSPassword", reinterpret_cast<cmd_func>(gridfs_password_command), 0, OR_FILEINFO, "GridFS database authentication password."),	
	AP_INIT_TAKE1("GridFSCacheMaxAge", reinterpret_cast<cmd_func>(gridfs_cache_max_age_command), 0, OR_FILEINFO, "GridFS cache max age (seconds, 0 to disable expiration)."),
	AP_INIT_TAKE1("GridFSConnectTimeout", reinterpret_cast<cmd_func>(gridfs_connect_timeout_command), 0, OR_FILEINFO, "GridFS connect timeout (seconds, 0 for infinite)."),
	AP_INIT_FLAG("GridFSSlaveOk", reinterpret_cast<cmd_func>(gridfs_slave_ok_command), 0, OR_FILEINFO, "GridFS slaveOk flag."),
	{0}
};

//	Defines module
extern "C"
{
	module AP_MODULE_DECLARE_DATA gridfs_module =
	{
		STANDARD20_MODULE_STUFF,
		gridfs_create_config,
		gridfs_merge_config,
		0,
		0,
		gridfs_commands,
		gridfs_register_hooks
	};
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.