2011-08-24 04:42:27 +08:00
|
|
|
// CartoDB SQL API
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
|
|
|
// all requests expect the following URL args:
|
|
|
|
// - `sql` {String} SQL to execute
|
|
|
|
//
|
|
|
|
// for private (read/write) queries:
|
2011-08-24 04:42:27 +08:00
|
|
|
// - OAuth. Must have proper OAuth 1.1 headers. For OAuth 1.1 spec see Google
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
2011-08-24 04:42:27 +08:00
|
|
|
// eg. /api/v1/?sql=SELECT 1 as one (with a load of OAuth headers or URL arguments)
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
|
|
|
// for public (read only) queries:
|
2011-08-24 04:42:27 +08:00
|
|
|
// - sql only, provided the subdomain exists in CartoDB and the table's sharing options are public
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
2011-08-24 04:42:27 +08:00
|
|
|
// eg. vizzuality.cartodb.com/api/v1/?sql=SELECT * from my_table
|
2012-07-24 16:29:47 +08:00
|
|
|
//
|
|
|
|
//
|
2012-11-12 19:37:34 +08:00
|
|
|
|
2014-05-07 22:14:17 +08:00
|
|
|
if ( ! process.env['PGAPPNAME'] )
|
2014-05-07 22:15:46 +08:00
|
|
|
process.env['PGAPPNAME']='cartodb_sqlapi';
|
2014-05-07 22:14:17 +08:00
|
|
|
|
2014-01-31 17:55:30 +08:00
|
|
|
function App() {
|
|
|
|
|
2012-11-12 19:37:34 +08:00
|
|
|
var path = require('path');
|
|
|
|
|
2012-04-13 22:37:09 +08:00
|
|
|
var express = require('express')
|
2014-02-11 00:34:27 +08:00
|
|
|
, app = express.createServer()
|
2012-05-01 23:46:30 +08:00
|
|
|
, Step = require('step')
|
|
|
|
, crypto = require('crypto')
|
2012-10-15 16:13:39 +08:00
|
|
|
, fs = require('fs')
|
2014-03-20 18:22:13 +08:00
|
|
|
, os = require('os')
|
2012-10-15 16:13:39 +08:00
|
|
|
, zlib = require('zlib')
|
2012-10-25 18:38:45 +08:00
|
|
|
, util = require('util')
|
2014-03-20 01:34:21 +08:00
|
|
|
, Profiler = require('step-profiler')
|
2014-03-20 18:22:13 +08:00
|
|
|
, StatsD = require('node-statsd').StatsD
|
2014-08-05 08:29:07 +08:00
|
|
|
, MetadataDB = require('cartodb-redis')
|
2014-08-12 02:15:55 +08:00
|
|
|
, PSQL = require('cartodb-psql')
|
2013-12-18 18:57:46 +08:00
|
|
|
, CdbRequest = require(global.settings.app_root + '/app/models/cartodb_request')
|
2014-08-05 22:20:06 +08:00
|
|
|
, AuthApi = require(global.settings.app_root + '/app/auth/auth_api')
|
2012-05-01 23:46:30 +08:00
|
|
|
, _ = require('underscore')
|
2013-02-14 01:57:14 +08:00
|
|
|
, LRU = require('lru-cache')
|
2013-05-27 17:21:56 +08:00
|
|
|
, formats = require(global.settings.app_root + '/app/models/formats')
|
2014-08-27 00:40:58 +08:00
|
|
|
, HealthCheck = require(global.settings.app_root + '/app/monitoring/health_check')
|
2014-11-11 20:57:15 +08:00
|
|
|
, PgErrorHandler = require(global.settings.app_root + '/app/postgresql/error_handler')
|
2013-02-14 01:57:14 +08:00
|
|
|
;
|
|
|
|
|
2014-08-05 08:29:07 +08:00
|
|
|
var metadataBackend = MetadataDB({
|
|
|
|
host: global.settings.redis_host,
|
|
|
|
port: global.settings.redis_port,
|
|
|
|
max: global.settings.redisPool,
|
|
|
|
idleTimeoutMillis: global.settings.redisIdleTimeoutMillis,
|
|
|
|
reapIntervalMillis: global.settings.redisReapIntervalMillis
|
|
|
|
});
|
|
|
|
var cdbReq = new CdbRequest();
|
2013-12-18 18:57:46 +08:00
|
|
|
|
2013-11-06 00:49:10 +08:00
|
|
|
// Set default configuration
|
|
|
|
global.settings.db_pubuser = global.settings.db_pubuser || "publicuser";
|
2014-07-31 08:17:07 +08:00
|
|
|
global.settings.bufferedRows = global.settings.bufferedRows || 1000;
|
2013-11-06 00:49:10 +08:00
|
|
|
|
2013-02-14 01:57:14 +08:00
|
|
|
var tableCache = LRU({
|
|
|
|
// store no more than these many items in the cache
|
|
|
|
max: global.settings.tableCacheMax || 8192,
|
|
|
|
// consider entries expired after these many milliseconds (10 minutes by default)
|
|
|
|
maxAge: global.settings.tableCacheMaxAge || 1000*60*10
|
|
|
|
});
|
2011-08-24 04:42:27 +08:00
|
|
|
|
2013-06-19 18:24:04 +08:00
|
|
|
function pad(n) { return n < 10 ? '0' + n : n }
|
|
|
|
Date.prototype.toJSON = function() {
|
|
|
|
var s = this.getFullYear() + '-'
|
|
|
|
+ pad(this.getMonth() + 1) + '-'
|
|
|
|
+ pad(this.getDate()) + 'T'
|
|
|
|
+ pad(this.getHours()) + ':'
|
|
|
|
+ pad(this.getMinutes()) + ':'
|
|
|
|
+ pad(this.getSeconds());
|
|
|
|
var offset = this.getTimezoneOffset();
|
|
|
|
if (offset == 0) s += 'Z';
|
|
|
|
else {
|
|
|
|
s += ( offset < 0 ? '+' : '-' )
|
|
|
|
+ pad(Math.abs(offset / 60))
|
|
|
|
+ pad(Math.abs(offset % 60))
|
2014-04-11 18:03:43 +08:00
|
|
|
|
2013-06-19 18:24:04 +08:00
|
|
|
}
|
|
|
|
return s;
|
2014-07-04 22:47:43 +08:00
|
|
|
};
|
2013-06-19 18:24:04 +08:00
|
|
|
|
2014-03-13 18:52:40 +08:00
|
|
|
var loggerOpts = {
|
|
|
|
buffer: true,
|
|
|
|
format: global.settings.log_format ||
|
|
|
|
':req[X-Real-IP] :method :req[Host]:url :status :response-time ms -> :res[Content-Type]'
|
|
|
|
};
|
|
|
|
|
|
|
|
if ( global.log4js ) {
|
2014-03-14 00:13:53 +08:00
|
|
|
app.use(log4js.connectLogger(log4js.getLogger(), _.defaults(loggerOpts, {level:'info'})));
|
2014-03-13 18:52:40 +08:00
|
|
|
} else {
|
|
|
|
app.use(express.logger(loggerOpts));
|
|
|
|
}
|
2014-02-11 00:34:27 +08:00
|
|
|
|
2014-03-20 18:22:13 +08:00
|
|
|
// Initialize statsD client if requested
|
|
|
|
var statsd_client;
|
|
|
|
if ( global.settings.statsd ) {
|
|
|
|
|
|
|
|
// Perform keyword substitution in statsd
|
|
|
|
if ( global.settings.statsd.prefix ) {
|
|
|
|
var host_token = os.hostname().split('.').reverse().join('.');
|
|
|
|
global.settings.statsd.prefix = global.settings.statsd.prefix.replace(/:host/, host_token);
|
|
|
|
}
|
|
|
|
|
|
|
|
statsd_client = new StatsD(global.settings.statsd);
|
|
|
|
statsd_client.last_error = { msg:'', count:0 };
|
|
|
|
statsd_client.socket.on('error', function(err) {
|
|
|
|
var last_err = statsd_client.last_error;
|
|
|
|
var last_msg = last_err.msg;
|
|
|
|
var this_msg = ''+err;
|
|
|
|
if ( this_msg != last_msg ) {
|
|
|
|
console.error("statsd client socket error: " + err);
|
|
|
|
statsd_client.last_error.count = 1;
|
|
|
|
statsd_client.last_error.msg = this_msg;
|
|
|
|
} else {
|
|
|
|
++last_err.count;
|
|
|
|
if ( ! last_err.interval ) {
|
|
|
|
//console.log("Installing interval");
|
|
|
|
statsd_client.last_error.interval = setInterval(function() {
|
2014-07-04 22:47:43 +08:00
|
|
|
var count = statsd_client.last_error.count;
|
2014-03-20 18:22:13 +08:00
|
|
|
if ( count > 1 ) {
|
|
|
|
console.error("last statsd client socket error repeated " + count + " times");
|
|
|
|
statsd_client.last_error.count = 1;
|
|
|
|
//console.log("Clearing interval");
|
|
|
|
clearInterval(statsd_client.last_error.interval);
|
|
|
|
statsd_client.last_error.interval = null;
|
|
|
|
}
|
|
|
|
}, 1000);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2014-03-20 01:34:21 +08:00
|
|
|
// Use step-profiler
|
|
|
|
if ( global.settings.useProfiler ) {
|
|
|
|
app.use(function(req, res, next) {
|
2014-03-20 18:22:13 +08:00
|
|
|
req.profiler = new Profiler({statsd_client:statsd_client});
|
2014-03-20 01:34:21 +08:00
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2014-01-31 17:55:30 +08:00
|
|
|
// Set connection timeout
|
|
|
|
if ( global.settings.hasOwnProperty('node_socket_timeout') ) {
|
|
|
|
var timeout = parseInt(global.settings.node_socket_timeout);
|
|
|
|
app.use(function(req, res, next) {
|
|
|
|
req.connection.setTimeout(timeout);
|
|
|
|
next()
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2014-03-13 20:40:56 +08:00
|
|
|
// Version extracting function
|
|
|
|
function getVersion() {
|
|
|
|
var version = {};
|
|
|
|
version.cartodb_sql_api = require(__dirname + '/../../package.json').version;
|
|
|
|
return version;
|
|
|
|
}
|
|
|
|
|
2011-09-07 19:05:10 +08:00
|
|
|
app.use(express.bodyParser());
|
2011-08-24 04:42:27 +08:00
|
|
|
app.enable('jsonp callback');
|
2013-05-30 17:56:43 +08:00
|
|
|
app.set("trust proxy", true);
|
2011-09-07 19:05:10 +08:00
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
// basic routing
|
2013-05-24 20:21:13 +08:00
|
|
|
app.options('*', function(req,res) { setCrossDomain(res); res.end(); });
|
2015-01-30 18:37:29 +08:00
|
|
|
|
|
|
|
app.all(global.settings.base_url + '/sql', handleQuery);
|
|
|
|
app.all(global.settings.base_url + '/sql.:f', handleQuery);
|
|
|
|
app.get(global.settings.base_url + '/cachestatus', handleCacheStatus);
|
|
|
|
app.get(global.settings.base_url + '/health', handleHealthCheck);
|
|
|
|
app.get(global.settings.base_url + '/version', handleVersion);
|
2012-05-01 23:46:30 +08:00
|
|
|
|
2015-01-07 04:40:01 +08:00
|
|
|
var sqlQueryMayWriteRegex = new RegExp("\\b(alter|insert|update|delete|create|drop|reindex|truncate|refresh)\\b", "i");
|
2014-04-11 18:03:43 +08:00
|
|
|
/**
|
|
|
|
* This is a fuzzy check, the return could be true even if the query doesn't really write anything. But you can be
|
|
|
|
* pretty sure of a false return.
|
|
|
|
*
|
2014-04-11 18:13:44 +08:00
|
|
|
* @param sql The SQL statement to check against
|
2014-04-11 18:03:43 +08:00
|
|
|
* @returns {boolean} Return true of the given query may write to the database
|
|
|
|
*/
|
2012-10-15 19:20:37 +08:00
|
|
|
function queryMayWrite(sql) {
|
2014-04-11 18:03:43 +08:00
|
|
|
return sqlQueryMayWriteRegex.test(sql);
|
2012-10-15 19:20:37 +08:00
|
|
|
}
|
|
|
|
|
2012-11-12 19:37:34 +08:00
|
|
|
function sanitize_filename(filename) {
|
|
|
|
filename = path.basename(filename, path.extname(filename));
|
|
|
|
filename = filename.replace(/[;()\[\]<>'"\s]/g, '_');
|
|
|
|
//console.log("Sanitized: " + filename);
|
|
|
|
return filename;
|
|
|
|
}
|
2012-10-18 17:33:35 +08:00
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
// request handlers
|
2015-01-30 18:37:29 +08:00
|
|
|
function handleVersion(req, res) {
|
|
|
|
res.send(getVersion());
|
|
|
|
}
|
|
|
|
|
2012-06-30 07:54:53 +08:00
|
|
|
function handleQuery(req, res) {
|
2011-07-04 23:28:39 +08:00
|
|
|
|
2012-06-07 02:47:21 +08:00
|
|
|
// extract input
|
2011-09-07 19:05:10 +08:00
|
|
|
var body = (req.body) ? req.body : {};
|
2013-07-15 20:39:15 +08:00
|
|
|
var params = _.extend({}, req.query, body); // clone so don't modify req.params or req.body so oauth is not broken
|
|
|
|
var sql = params.q;
|
|
|
|
var limit = parseInt(params.rows_per_page);
|
|
|
|
var offset = parseInt(params.page);
|
2014-04-14 21:01:12 +08:00
|
|
|
var orderBy = params.order_by;
|
|
|
|
var sortOrder = params.sort_order;
|
2013-07-15 20:39:15 +08:00
|
|
|
var requestedFormat = params.format;
|
2012-11-13 23:47:04 +08:00
|
|
|
var format = _.isArray(requestedFormat) ? _.last(requestedFormat) : requestedFormat;
|
2013-07-15 20:39:15 +08:00
|
|
|
var requestedFilename = params.filename;
|
2012-11-13 23:47:04 +08:00
|
|
|
var filename = requestedFilename;
|
2013-07-15 20:39:15 +08:00
|
|
|
var requestedSkipfields = params.skipfields;
|
2015-02-02 19:09:34 +08:00
|
|
|
var cdbUsername = cdbReq.userByReq(req);
|
2013-05-06 18:30:32 +08:00
|
|
|
var skipfields;
|
2013-07-15 20:39:15 +08:00
|
|
|
var dp = params.dp; // decimal point digits (defaults to 6)
|
2012-11-13 23:47:04 +08:00
|
|
|
var gn = "the_geom"; // TODO: read from configuration file
|
2013-02-14 01:57:14 +08:00
|
|
|
var tableCacheItem;
|
2012-09-11 18:22:27 +08:00
|
|
|
|
2014-03-20 01:34:21 +08:00
|
|
|
if ( req.profiler ) req.profiler.start('sqlapi.query');
|
|
|
|
|
2014-03-19 20:30:29 +08:00
|
|
|
req.aborted = false;
|
|
|
|
req.on("close", function() {
|
2014-06-02 20:48:38 +08:00
|
|
|
if (req.formatter && _.isFunction(req.formatter.cancel)) {
|
|
|
|
req.formatter.cancel();
|
|
|
|
}
|
|
|
|
req.aborted = true; // TODO: there must be a builtin way to check this
|
2014-03-19 20:30:29 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
function checkAborted(step) {
|
|
|
|
if ( req.aborted ) {
|
|
|
|
var err = new Error("Request aborted during " + step);
|
|
|
|
// We'll use status 499, same as ngnix in these cases
|
|
|
|
// see http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error
|
|
|
|
err.http_status = 499;
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-08-24 04:42:27 +08:00
|
|
|
try {
|
2012-10-12 18:17:35 +08:00
|
|
|
|
2013-05-06 18:30:32 +08:00
|
|
|
// sanitize and apply defaults to input
|
|
|
|
dp = (dp === "" || _.isUndefined(dp)) ? '6' : dp;
|
|
|
|
format = (format === "" || _.isUndefined(format)) ? 'json' : format.toLowerCase();
|
|
|
|
filename = (filename === "" || _.isUndefined(filename)) ? 'cartodb-query' : sanitize_filename(filename);
|
|
|
|
sql = (sql === "" || _.isUndefined(sql)) ? null : sql;
|
2013-05-23 19:21:23 +08:00
|
|
|
limit = (!_.isNaN(limit)) ? limit : null;
|
|
|
|
offset = (!_.isNaN(offset)) ? offset * limit : null;
|
2013-05-06 18:30:32 +08:00
|
|
|
|
|
|
|
// Accept both comma-separated string or array of comma-separated strings
|
|
|
|
if ( requestedSkipfields ) {
|
|
|
|
if ( _.isString(requestedSkipfields) ) skipfields = requestedSkipfields.split(',');
|
|
|
|
else if ( _.isArray(requestedSkipfields) ) {
|
|
|
|
skipfields = [];
|
|
|
|
_.each(requestedSkipfields, function(ele) {
|
|
|
|
skipfields = skipfields.concat(ele.split(','));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
skipfields = [];
|
|
|
|
}
|
|
|
|
|
2013-05-17 17:44:50 +08:00
|
|
|
//if ( -1 === supportedFormats.indexOf(format) )
|
2014-07-04 22:47:59 +08:00
|
|
|
if ( ! formats.hasOwnProperty(format) ) {
|
|
|
|
throw new Error("Invalid format: " + format);
|
|
|
|
}
|
2012-10-12 18:17:35 +08:00
|
|
|
|
2014-07-04 22:47:59 +08:00
|
|
|
if (!_.isString(sql)) {
|
|
|
|
throw new Error("You must indicate a sql query");
|
|
|
|
}
|
2012-05-08 22:28:22 +08:00
|
|
|
|
|
|
|
// initialise MD5 key of sql for cache lookups
|
|
|
|
var sql_md5 = generateMD5(sql);
|
|
|
|
|
|
|
|
// placeholder for connection
|
2012-05-08 22:25:19 +08:00
|
|
|
var pg;
|
2011-08-24 04:42:27 +08:00
|
|
|
|
2013-11-18 18:42:43 +08:00
|
|
|
// Database options
|
2013-11-18 19:21:30 +08:00
|
|
|
var dbopts = {
|
2013-11-18 20:31:11 +08:00
|
|
|
port: global.settings.db_port,
|
|
|
|
pass: global.settings.db_pubuser_pass
|
2013-11-18 19:21:30 +08:00
|
|
|
};
|
2013-11-18 18:42:43 +08:00
|
|
|
|
2014-08-08 18:48:29 +08:00
|
|
|
var authenticated = false;
|
2012-10-15 19:20:37 +08:00
|
|
|
|
2013-05-27 17:21:56 +08:00
|
|
|
var formatter;
|
|
|
|
|
2015-01-30 18:37:29 +08:00
|
|
|
var authApi = new AuthApi(req, params),
|
2014-08-05 22:20:06 +08:00
|
|
|
dbParams;
|
2013-12-18 18:57:46 +08:00
|
|
|
|
2014-03-20 18:22:13 +08:00
|
|
|
if ( req.profiler ) req.profiler.done('init');
|
2014-03-20 01:34:21 +08:00
|
|
|
|
2011-08-24 04:42:27 +08:00
|
|
|
// 1. Get database from redis via the username stored in the host header subdomain
|
|
|
|
// 2. Run the request through OAuth to get R/W user id if signed
|
2012-04-21 02:34:18 +08:00
|
|
|
// 3. Get the list of tables affected by the query
|
2013-05-27 17:21:56 +08:00
|
|
|
// 4. Setup headers
|
|
|
|
// 5. Send formatted results back
|
2011-08-24 04:42:27 +08:00
|
|
|
Step(
|
2014-07-04 22:47:59 +08:00
|
|
|
function getDatabaseConnectionParams() {
|
|
|
|
checkAborted('getDatabaseConnectionParams');
|
2014-08-05 22:20:06 +08:00
|
|
|
// If the request is providing credentials it may require every DB parameters
|
|
|
|
if (authApi.hasCredentials()) {
|
|
|
|
metadataBackend.getAllUserDBParams(cdbUsername, this);
|
|
|
|
} else {
|
|
|
|
metadataBackend.getUserDBPublicConnectionParams(cdbUsername, this);
|
|
|
|
}
|
2011-08-24 04:42:27 +08:00
|
|
|
},
|
2014-08-05 08:29:07 +08:00
|
|
|
function authenticate(err, userDBParams) {
|
2013-11-16 01:36:49 +08:00
|
|
|
if (err) {
|
2012-06-07 02:47:21 +08:00
|
|
|
err.http_status = 404;
|
2014-08-05 22:20:06 +08:00
|
|
|
err.message = "Sorry, we can't find CartoDB user '" + cdbUsername
|
2014-07-04 22:47:59 +08:00
|
|
|
+ "'. Please check that you have entered the correct domain.";
|
|
|
|
throw err;
|
2012-05-12 04:46:45 +08:00
|
|
|
}
|
2014-08-05 08:29:07 +08:00
|
|
|
|
2014-08-19 01:45:17 +08:00
|
|
|
if ( req.profiler ) req.profiler.done('getDBParams');
|
|
|
|
|
2014-08-05 08:29:07 +08:00
|
|
|
dbParams = userDBParams;
|
|
|
|
|
2014-07-04 22:47:59 +08:00
|
|
|
dbopts.host = dbParams.dbhost;
|
|
|
|
dbopts.dbname = dbParams.dbname;
|
2014-08-05 08:29:07 +08:00
|
|
|
dbopts.user = (!!dbParams.dbpublicuser) ? dbParams.dbpublicuser : global.settings.db_pubuser;
|
2013-11-16 01:36:49 +08:00
|
|
|
|
2014-08-06 18:51:55 +08:00
|
|
|
authApi.verifyCredentials({
|
|
|
|
metadataBackend: metadataBackend,
|
|
|
|
apiKey: dbParams.apikey
|
|
|
|
}, this);
|
2011-08-24 04:42:27 +08:00
|
|
|
},
|
2014-08-05 08:29:07 +08:00
|
|
|
function setDBAuth(err, isAuthenticated) {
|
2014-07-04 22:47:59 +08:00
|
|
|
if (err) {
|
|
|
|
throw err;
|
|
|
|
}
|
2014-08-19 01:45:17 +08:00
|
|
|
|
|
|
|
if ( req.profiler ) req.profiler.done('authenticate');
|
|
|
|
|
2014-08-05 08:29:07 +08:00
|
|
|
if (_.isBoolean(isAuthenticated) && isAuthenticated) {
|
2014-08-08 18:48:29 +08:00
|
|
|
authenticated = isAuthenticated;
|
2014-08-05 08:29:07 +08:00
|
|
|
dbopts.user = _.template(global.settings.db_user, {user_id: dbParams.dbuser});
|
2014-07-04 22:47:59 +08:00
|
|
|
if ( global.settings.hasOwnProperty('db_user_pass') ) {
|
|
|
|
dbopts.pass = _.template(global.settings.db_user_pass, {
|
2014-08-05 08:29:07 +08:00
|
|
|
user_id: dbParams.dbuser,
|
|
|
|
user_password: dbParams.dbpass
|
2014-07-04 22:47:59 +08:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
delete dbopts.pass;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
2013-11-18 20:31:11 +08:00
|
|
|
},
|
2014-07-04 22:47:59 +08:00
|
|
|
function queryExplain(err){
|
2014-07-04 18:57:20 +08:00
|
|
|
var self = this;
|
|
|
|
|
2013-11-18 20:31:11 +08:00
|
|
|
if (err) throw err;
|
2014-08-19 01:45:17 +08:00
|
|
|
|
|
|
|
if ( req.profiler ) req.profiler.done('setDBAuth');
|
|
|
|
|
2014-03-19 20:30:29 +08:00
|
|
|
checkAborted('queryExplain');
|
2013-11-18 20:31:11 +08:00
|
|
|
|
|
|
|
pg = new PSQL(dbopts);
|
2012-05-01 23:46:30 +08:00
|
|
|
// get all the tables from Cache or SQL
|
2013-02-14 01:57:14 +08:00
|
|
|
tableCacheItem = tableCache.get(sql_md5);
|
|
|
|
if (tableCacheItem) {
|
|
|
|
tableCacheItem.hits++;
|
2013-02-13 23:43:04 +08:00
|
|
|
return false;
|
2012-10-15 19:20:37 +08:00
|
|
|
} else {
|
2014-06-26 15:22:51 +08:00
|
|
|
//TODO: sanitize cdbuser
|
|
|
|
pg.query("SELECT CDB_QueryTables($quotesql$" + sql + "$quotesql$)", function (err, result) {
|
2014-07-01 01:55:47 +08:00
|
|
|
if (err) {
|
|
|
|
self(err);
|
|
|
|
return;
|
|
|
|
}
|
2014-06-26 15:22:51 +08:00
|
|
|
if ( result.rowCount === 1 ) {
|
|
|
|
var raw_tables = result.rows[0].cdb_querytables;
|
|
|
|
var tables = raw_tables.split(/^\{(.*)\}$/)[1].split(',');
|
|
|
|
self(null, tables);
|
|
|
|
} else {
|
|
|
|
console.error("Unexpected result from CDB_QueryTables($quotesql$" + sql + "$quotesql$): " + result);
|
|
|
|
self(null, []);
|
|
|
|
}
|
|
|
|
});
|
2012-05-01 23:46:30 +08:00
|
|
|
}
|
2012-04-21 02:34:18 +08:00
|
|
|
},
|
2014-06-26 15:22:51 +08:00
|
|
|
function setHeaders(err, tables){
|
2012-04-21 02:34:18 +08:00
|
|
|
if (err) throw err;
|
2014-08-19 01:45:17 +08:00
|
|
|
|
2014-03-20 01:34:21 +08:00
|
|
|
if ( req.profiler ) req.profiler.done('queryExplain');
|
2014-08-19 01:45:17 +08:00
|
|
|
|
2014-03-19 20:30:29 +08:00
|
|
|
checkAborted('setHeaders');
|
2012-04-21 04:09:31 +08:00
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
// store explain result in local Cache
|
2014-06-26 15:22:51 +08:00
|
|
|
if ( ! tableCacheItem && tables.length ) {
|
|
|
|
tableCacheItem = {
|
|
|
|
affected_tables: tables,
|
|
|
|
// check if query may possibly write
|
|
|
|
may_write: queryMayWrite(sql),
|
|
|
|
// initialise hit counter
|
|
|
|
hits: 1
|
|
|
|
};
|
|
|
|
tableCache.set(sql_md5, tableCacheItem);
|
2012-05-01 23:46:30 +08:00
|
|
|
}
|
2012-04-21 02:34:18 +08:00
|
|
|
|
2014-08-08 18:48:29 +08:00
|
|
|
if ( !authenticated && tableCacheItem ) {
|
|
|
|
var affected_tables = tableCacheItem.affected_tables;
|
|
|
|
for ( var i = 0; i < affected_tables.length; ++i ) {
|
|
|
|
var t = affected_tables[i];
|
|
|
|
if ( t.match(/\bpg_/) ) {
|
|
|
|
var e = new SyntaxError("system tables are forbidden");
|
|
|
|
e.http_status = 403;
|
|
|
|
throw(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-06-02 20:48:38 +08:00
|
|
|
var fClass = formats[format];
|
2013-05-27 17:21:56 +08:00
|
|
|
formatter = new fClass();
|
2014-06-02 20:48:38 +08:00
|
|
|
req.formatter = formatter;
|
2011-10-28 19:11:18 +08:00
|
|
|
|
2012-04-13 22:37:09 +08:00
|
|
|
|
2012-10-25 19:40:21 +08:00
|
|
|
// configure headers for given format
|
2012-11-14 23:30:18 +08:00
|
|
|
var use_inline = !requestedFormat && !requestedFilename;
|
2013-09-05 23:07:11 +08:00
|
|
|
res.header("Content-Disposition", getContentDisposition(formatter, filename, use_inline));
|
2013-05-27 17:21:56 +08:00
|
|
|
res.header("Content-Type", formatter.getContentType());
|
2012-04-13 22:37:09 +08:00
|
|
|
|
|
|
|
// allow cross site post
|
|
|
|
setCrossDomain(res);
|
|
|
|
|
|
|
|
// set cache headers
|
2013-07-22 23:21:38 +08:00
|
|
|
var ttl = 31536000; // 1 year time to live by default
|
2012-11-13 02:14:20 +08:00
|
|
|
var cache_policy = req.query.cache_policy;
|
2013-07-15 20:39:15 +08:00
|
|
|
if ( cache_policy === 'persist' ) {
|
2014-07-04 22:47:59 +08:00
|
|
|
res.header('Cache-Control', 'public,max-age=' + ttl);
|
2012-11-13 02:14:20 +08:00
|
|
|
} else {
|
2013-07-23 00:20:26 +08:00
|
|
|
if ( ! tableCacheItem || tableCacheItem.may_write ) {
|
2013-10-18 19:29:06 +08:00
|
|
|
// Tell clients this response is already expired
|
|
|
|
// TODO: prevent cache_policy from overriding this ?
|
2013-07-22 23:21:38 +08:00
|
|
|
ttl = 0;
|
2014-07-04 22:47:59 +08:00
|
|
|
}
|
2013-07-10 13:58:35 +08:00
|
|
|
res.header('Cache-Control', 'no-cache,max-age='+ttl+',must-revalidate,public');
|
2012-11-13 02:14:20 +08:00
|
|
|
}
|
|
|
|
|
2013-10-18 19:29:06 +08:00
|
|
|
// Only set an X-Cache-Channel for responses we want Varnish to cache.
|
|
|
|
if ( tableCacheItem && ! tableCacheItem.may_write ) {
|
2014-07-04 22:47:59 +08:00
|
|
|
res.header('X-Cache-Channel', generateCacheKey(dbopts.dbname, tableCacheItem, authenticated));
|
2013-10-18 19:29:06 +08:00
|
|
|
}
|
|
|
|
|
2013-07-15 19:13:19 +08:00
|
|
|
// Set Last-Modified header
|
|
|
|
//
|
|
|
|
// Currently sets it to NOW
|
|
|
|
//
|
|
|
|
// TODO: use a real value, querying for most recent change in
|
|
|
|
// any of the source tables
|
|
|
|
//
|
|
|
|
res.header('Last-Modified', new Date().toUTCString());
|
|
|
|
|
2014-06-26 15:22:51 +08:00
|
|
|
return null;
|
2012-04-13 22:37:09 +08:00
|
|
|
},
|
2014-06-26 15:22:51 +08:00
|
|
|
function generateFormat(err){
|
2011-08-24 04:42:27 +08:00
|
|
|
if (err) throw err;
|
2014-03-19 20:30:29 +08:00
|
|
|
checkAborted('generateFormat');
|
2011-10-28 19:11:18 +08:00
|
|
|
|
2013-05-27 17:21:56 +08:00
|
|
|
// TODO: drop this, fix UI!
|
2014-08-12 02:15:55 +08:00
|
|
|
sql = new PSQL.QueryWrapper(sql).orderBy(orderBy, sortOrder).window(limit, offset).query();
|
2013-05-27 17:21:56 +08:00
|
|
|
|
|
|
|
var opts = {
|
2015-03-02 21:34:01 +08:00
|
|
|
username: cdbUsername,
|
2013-11-18 18:42:43 +08:00
|
|
|
dbopts: dbopts,
|
2013-05-27 17:21:56 +08:00
|
|
|
sink: res,
|
|
|
|
gn: gn,
|
|
|
|
dp: dp,
|
|
|
|
skipfields: skipfields,
|
|
|
|
sql: sql,
|
2014-03-19 20:30:29 +08:00
|
|
|
filename: filename,
|
2014-07-31 08:17:07 +08:00
|
|
|
bufferedRows: global.settings.bufferedRows,
|
|
|
|
callback: params.callback,
|
2014-07-04 22:47:43 +08:00
|
|
|
abortChecker: checkAborted
|
|
|
|
};
|
2014-03-20 01:34:21 +08:00
|
|
|
|
|
|
|
if ( req.profiler ) {
|
|
|
|
opts.profiler = req.profiler;
|
|
|
|
opts.beforeSink = function() {
|
2014-08-19 01:45:17 +08:00
|
|
|
req.profiler.done('beforeSink');
|
2014-07-30 01:29:16 +08:00
|
|
|
res.header('X-SQLAPI-Profiler', req.profiler.toJSONString());
|
2014-03-20 01:34:21 +08:00
|
|
|
};
|
2012-11-13 00:10:16 +08:00
|
|
|
}
|
|
|
|
|
2014-07-30 18:39:03 +08:00
|
|
|
if (global.settings.api_hostname) {
|
|
|
|
res.header('X-Served-By-Host', global.settings.api_hostname);
|
|
|
|
}
|
2014-08-22 18:29:27 +08:00
|
|
|
if (dbopts.host) {
|
|
|
|
res.header('X-Served-By-DB-Host', dbopts.host);
|
|
|
|
}
|
2013-05-27 17:21:56 +08:00
|
|
|
formatter.sendResponse(opts, this);
|
2011-08-24 04:42:27 +08:00
|
|
|
},
|
2013-05-27 17:21:56 +08:00
|
|
|
function errorHandle(err){
|
2014-11-12 18:36:59 +08:00
|
|
|
formatter = null;
|
|
|
|
|
2013-05-27 17:21:56 +08:00
|
|
|
if ( err ) handleException(err, res);
|
2014-03-20 01:34:21 +08:00
|
|
|
if ( req.profiler ) {
|
|
|
|
req.profiler.sendStats(); // TODO: do on nextTick ?
|
|
|
|
}
|
2014-03-20 18:22:13 +08:00
|
|
|
if (statsd_client) {
|
|
|
|
if ( err ) statsd_client.increment('sqlapi.query.error');
|
|
|
|
else statsd_client.increment('sqlapi.query.success');
|
|
|
|
}
|
2011-08-24 04:42:27 +08:00
|
|
|
}
|
|
|
|
);
|
|
|
|
} catch (err) {
|
2011-08-18 01:42:19 +08:00
|
|
|
handleException(err, res);
|
2014-03-20 18:22:13 +08:00
|
|
|
if (statsd_client) statsd_client.increment('sqlapi.query.error');
|
2011-08-24 04:42:27 +08:00
|
|
|
}
|
2011-09-07 19:05:10 +08:00
|
|
|
}
|
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
function handleCacheStatus(req, res){
|
2013-02-14 01:57:14 +08:00
|
|
|
var tableCacheValues = tableCache.values();
|
2012-05-01 23:46:30 +08:00
|
|
|
var totalExplainHits = _.reduce(tableCacheValues, function(memo, res) { return memo + res.hits}, 0);
|
|
|
|
var totalExplainKeys = tableCacheValues.length;
|
2013-02-13 23:43:04 +08:00
|
|
|
res.send({explain: {pid: process.pid, hits: totalExplainHits, keys : totalExplainKeys }});
|
2012-05-01 23:46:30 +08:00
|
|
|
}
|
|
|
|
|
2014-08-27 00:40:58 +08:00
|
|
|
var healthCheck = new HealthCheck(metadataBackend, PSQL);
|
|
|
|
function handleHealthCheck(req, res) {
|
|
|
|
var healthConfig = global.settings.health || {};
|
|
|
|
if (!!healthConfig.enabled) {
|
|
|
|
var startTime = Date.now();
|
|
|
|
healthCheck.check(healthConfig.username, healthConfig.query, function(err, result) {
|
|
|
|
var ok = !err;
|
|
|
|
var response = {
|
|
|
|
enabled: true,
|
|
|
|
ok: ok,
|
|
|
|
elapsed: Date.now() - startTime,
|
|
|
|
result: result
|
|
|
|
};
|
|
|
|
if (err) {
|
|
|
|
response.err = err.message;
|
|
|
|
}
|
|
|
|
res.send(response, ok ? 200 : 503);
|
|
|
|
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
res.send({enabled: false, ok: true}, 200);
|
|
|
|
}
|
|
|
|
}
|
2013-03-28 02:40:37 +08:00
|
|
|
|
2013-09-05 23:07:11 +08:00
|
|
|
function getContentDisposition(formatter, filename, inline) {
|
|
|
|
var ext = formatter.getFileExtension();
|
2011-10-28 19:11:18 +08:00
|
|
|
var time = new Date().toUTCString();
|
2012-11-13 02:44:16 +08:00
|
|
|
return ( inline ? 'inline' : 'attachment' ) +'; filename=' + filename + '.' + ext + '; modification-date="' + time + '";';
|
2011-10-28 19:11:18 +08:00
|
|
|
}
|
2011-09-07 19:05:10 +08:00
|
|
|
|
2012-04-13 07:30:45 +08:00
|
|
|
function setCrossDomain(res){
|
|
|
|
res.header("Access-Control-Allow-Origin", "*");
|
2012-11-01 20:16:46 +08:00
|
|
|
res.header("Access-Control-Allow-Headers", "X-Requested-With, X-Prototype-Version, X-CSRF-Token");
|
2012-04-13 07:30:45 +08:00
|
|
|
}
|
|
|
|
|
2013-02-13 23:43:04 +08:00
|
|
|
function generateCacheKey(database, query_info, is_authenticated){
|
2013-02-18 19:20:18 +08:00
|
|
|
if ( ! query_info || ( is_authenticated && query_info.may_write ) ) {
|
2012-10-15 19:20:37 +08:00
|
|
|
return "NONE";
|
|
|
|
} else {
|
2014-06-26 15:22:51 +08:00
|
|
|
return database + ":" + query_info.affected_tables.join(',');
|
2012-10-15 19:20:37 +08:00
|
|
|
}
|
2012-04-21 02:34:18 +08:00
|
|
|
}
|
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
function generateMD5(data){
|
|
|
|
var hash = crypto.createHash('md5');
|
|
|
|
hash.update(data);
|
|
|
|
return hash.digest('hex');
|
|
|
|
}
|
|
|
|
|
2013-05-16 17:24:52 +08:00
|
|
|
|
2014-11-11 20:57:15 +08:00
|
|
|
function handleException(err, res) {
|
|
|
|
var pgErrorHandler = new PgErrorHandler(err);
|
|
|
|
|
|
|
|
var msg = {
|
|
|
|
error: [pgErrorHandler.getMessage()]
|
|
|
|
};
|
|
|
|
|
2014-11-21 19:59:48 +08:00
|
|
|
_.defaults(msg, pgErrorHandler.getFields());
|
|
|
|
|
2014-11-11 20:57:15 +08:00
|
|
|
if (global.settings.environment == 'development') {
|
|
|
|
msg.stack = err.stack;
|
|
|
|
}
|
|
|
|
|
2011-08-25 03:47:10 +08:00
|
|
|
if (global.settings.environment !== 'test'){
|
|
|
|
// TODO: email this Exception report
|
2014-03-13 19:14:11 +08:00
|
|
|
console.error("EXCEPTION REPORT: " + err.stack)
|
2011-08-25 03:47:10 +08:00
|
|
|
}
|
2011-10-28 19:11:18 +08:00
|
|
|
|
2012-04-13 07:30:45 +08:00
|
|
|
// allow cross site post
|
|
|
|
setCrossDomain(res);
|
|
|
|
|
2013-02-13 20:32:34 +08:00
|
|
|
// Force inline content disposition
|
|
|
|
res.header("Content-Disposition", 'inline');
|
|
|
|
|
2014-03-20 01:34:21 +08:00
|
|
|
if ( res.req && res.req.profiler ) {
|
2014-07-04 22:47:43 +08:00
|
|
|
res.req.profiler.done('finish');
|
2014-07-30 01:29:16 +08:00
|
|
|
res.header('X-SQLAPI-Profiler', res.req.profiler.toJSONString());
|
2014-03-20 01:34:21 +08:00
|
|
|
}
|
|
|
|
|
2014-11-11 20:57:15 +08:00
|
|
|
res.send(msg, getStatusError(pgErrorHandler, res.req));
|
2014-03-20 01:34:21 +08:00
|
|
|
|
|
|
|
if ( res.req && res.req.profiler ) {
|
2014-07-04 22:47:43 +08:00
|
|
|
res.req.profiler.sendStats();
|
2014-03-20 01:34:21 +08:00
|
|
|
}
|
2011-06-13 20:07:21 +08:00
|
|
|
}
|
|
|
|
|
2014-11-11 20:57:15 +08:00
|
|
|
function getStatusError(pgErrorHandler, req) {
|
2014-08-04 21:56:43 +08:00
|
|
|
|
2014-11-11 20:57:15 +08:00
|
|
|
var statusError = pgErrorHandler.getStatus();
|
2014-09-02 21:00:04 +08:00
|
|
|
|
2014-08-04 21:56:43 +08:00
|
|
|
// JSONP has to return 200 status error
|
|
|
|
if (req && req.query && req.query.callback) {
|
|
|
|
statusError = 200;
|
|
|
|
}
|
|
|
|
|
|
|
|
return statusError;
|
|
|
|
}
|
|
|
|
|
2014-01-31 17:55:30 +08:00
|
|
|
return app;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = App;
|