Skip to content
Browse files

Lets have 2 space indentation..

  • Loading branch information...
1 parent e2c392c commit b7f6da497ea73cc3c63198302ca3bc2ea385af8e @DanBUK DanBUK committed Jul 26, 2011
Showing with 1,017 additions and 766 deletions.
  1. +13 −11 app.js
  2. +28 −22 bin/install.js
  3. +5 −5 bin/node-config.js
  4. +513 −375 lib/app.js
  5. +4 −4 lib/apps.js
  6. +13 −16 lib/chroot.js
  7. +29 −11 lib/coupon.js
  8. +99 −76 lib/domains.js
  9. +91 −108 lib/lib.js
  10. +19 −10 lib/logger.js
  11. +38 −20 lib/middle.js
  12. +8 −9 lib/npm.js
  13. +10 −5 lib/status.js
  14. +19 −23 lib/unionfs.js
  15. +98 −48 lib/user.js
  16. +30 −23 proxy/proxy.js
View
24 app.js 100755 → 100644
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+
/*
Nodester opensource Node.js hosting service
@@ -14,36 +15,35 @@ var express = require('express'),
config = require('./config'),
middle = require('./lib/middle');
-process.on('uncaughtException', function (err) {
- console.log(err.stack);
+process.on('uncaughtException', function(err) {
+ console.log(err.stack);
});
var daemon = require('daemon');
// daemon.setreuid(config.opt.userid);
-
var myapp = express.createServer();
-myapp.configure(function(){
+myapp.configure(function() {
myapp.use(express.bodyParser());
myapp.use(express.static(config.opt.public_html_dir));
myapp.use(middle.error());
});
// Routes
// Homepage
-myapp.get('/', function(req, res, next){
+myapp.get('/', function(req, res, next) {
res.render('index.html');
});
-myapp.get('/api', function(req, res, next){
+myapp.get('/api', function(req, res, next) {
res.redirect('/api.html');
});
-myapp.get('/admin', function(req, res, next){
+myapp.get('/admin', function(req, res, next) {
res.redirect('http://admin.nodester.com');
});
-myapp.get('/irc', function(req, res, next){
+myapp.get('/irc', function(req, res, next) {
res.redirect('http://irc.nodester.com');
});
@@ -149,6 +149,8 @@ myapp.delete('/appdomains', middle.authenticate, middle.authenticate_app, domain
myapp.get('/appdomains', middle.authenticate, domains.get);
-myapp.use(express.errorHandler({ showStack: true }));
-myapp.listen(4001);
-console.log('Nodester app started on port 4001');
+myapp.use(express.errorHandler({
+ showStack: true
+}));
+myapp.listen(4001);
+console.log('Nodester app started on port 4001');
View
50 bin/install.js 100755 → 100644
@@ -5,7 +5,9 @@ var nodeControl = require('../deps/node-control/index.js');
var util = require('util');
var ins = util.inspect;
-var args = process.argv; args.shift(); args.shift();
+var args = process.argv;
+args.shift();
+args.shift();
if (args.length < 13) {
console.error('Invalid usage!');
console.log('install.js <username> <hostname> <top level domain> <couch db user> <couch db pass> <couch db ip> <couch db port> <couch db prefix> <tenant apps dir> <install app username> <app home dir> <install git username> <git home dir>');
@@ -26,38 +28,42 @@ var app_homedir = args.shift();
var git_username = args.shift();
var git_homedir = args.shift();
-var deps = new Array ('pool', 'express', 'npm-wrapper', 'request', 'daemon', 'forever', 'cradle', 'colored');
+var deps = new Array('pool', 'express', 'npm-wrapper', 'request', 'daemon', 'forever', 'cradle', 'colored');
-var ssh_config_base = { user: username };
+var ssh_config_base = {
+ user: username
+};
var ssh_hosts_base = nodeControl.hosts(ssh_config_base, [hostname]);
var host_base = ssh_hosts_base[0]; // TODO - This is for a single host install, need to create multi host install.
-
-var ssh_config_app = { user: app_username };
+var ssh_config_app = {
+ user: app_username
+};
var ssh_hosts_app = nodeControl.hosts(ssh_config_app, [hostname]);
var host_app = ssh_hosts_app[0];
-var random_string = function (L) {
- var s = '';
- var randomchar = function() {
- var n = Math.floor(Math.random() * 62);
- if(n < 10) return n; // 1-10
- if(n < 36) return String.fromCharCode(n + 55); // A-Z
- return String.fromCharCode(n + 61); // a-z
- };
- while (s.length < L) s += randomchar();
- return s;
+var random_string = function(L) {
+ var s = '';
+ var randomchar = function() {
+ var n = Math.floor(Math.random() * 62);
+ if (n < 10) return n; // 1-10
+ if (n < 36) return String.fromCharCode(n + 55); // A-Z
+ return String.fromCharCode(n + 61); // a-z
+ };
+ while (s.length < L) s += randomchar();
+ return s;
};
-var print_lines_prefix = function (prefix, lines) {
- var i = 0, l = lines.length;
- for(i = 0; i < l; i++) {
+var print_lines_prefix = function(prefix, lines) {
+ var i = 0,
+ l = lines.length;
+ for (i = 0; i < l; i++) {
if (i < (l - 1) || lines[i].length > 0) console.log('%s: %s', prefix, lines[i]);
}
};
var commands = [];
-var add_c = function (host, cmd, exp, need) {
+var add_c = function(host, cmd, exp, need) {
commands.push([host, cmd, exp, need]);
};
@@ -100,7 +106,7 @@ add_c(host_app, 'cp ./nodester/scripts/example_gitrepoclone.sh ./nodester/script
add_c(host_app, 'sed -i -e "s/KeepThisSecret/' + restart_key + '/" ./nodester/config.js', '', false);
add_c(host_app, 'sed -i -e "s/KeepThisSecret/' + restart_key + '/" ./nodester/scripts/gitrepoclone.sh', '', false);
add_c(host_app, 'sed -i -e "s/CouponCode/' + coupon_code + '/" ./nodester/config.js', '', false);
-for(var i in deps) {
+for (var i in deps) {
add_c(host_app, 'npm install ' + deps[i], '', true);
}
@@ -120,9 +126,9 @@ add_c(host_base, 'rm -f /tmp/my_file_1', '', false);
add_c(host_base, 'sudo chown root:root /etc/sudoers', '', false);
add_c(host_base, 'sudo chmod 0440 /etc/sudoers', '', false);
-var run_command = function (cmds) {
+var run_command = function(cmds) {
var cmd = cmds.shift();
- cmd[0].ssh(cmd[1], cmd[2], function (err, stdout, stderr) {
+ cmd[0].ssh(cmd[1], cmd[2], function(err, stdout, stderr) {
if (cmd[3] === false && err > 0) {
console.error('failed command: %s', cmd[1]);
console.error('response expected: "%s"', cmd[2]);
View
10 bin/node-config.js 100755 → 100644
@@ -8,10 +8,10 @@ var fs = require('fs');
var data = [];
for (var i in config) {
- if (typeof config[i] == 'string') {
- data.push('export ' + i.toUpperCase() + '=' + config[i]);
- }
+ if (typeof config[i] == 'string') {
+ data.push('export ' + i.toUpperCase() + '=' + config[i]);
+ }
}
-fs.writeFileSync('./.nodester.config', data.join('\n'), encoding='utf8');
-fs.chmodSync('./.nodester.config', '0777');
+fs.writeFileSync('./.nodester.config', data.join('\n'), encoding = 'utf8');
+fs.chmodSync('./.nodester.config', '0777');
View
888 lib/app.js
@@ -7,25 +7,34 @@ var config = require('../config'),
chroot = require('./chroot').chroot,
spawn = require('child_process').spawn,
exec = require('child_process').exec;
-
+
module.exports = {
logs: function(req, res, next) {
var appname = req.appname;
var user = req.user;
var app = req.app;
var app_error_log = path.join(config.opt.apps_home_dir, user._id, app.repo_id + '_rw', 'app', 'error.log');
- fs.readFile(app_error_log, function (err, body) {
- var code = 200, resp;
+ fs.readFile(app_error_log, function(err, body) {
+ var code = 200,
+ resp;
if (err) {
code = 500;
- resp = {success: false, error: "Failed to read error log."};
+ resp = {
+ success: false,
+ error: "Failed to read error log."
+ };
} else {
var lines = body.toString().split("\n");
lines = lines.slice(-100);
- resp = {success: true, lines: lines};
+ resp = {
+ success: true,
+ lines: lines
+ };
}
- res.writeHead(code, {'Content-Type': 'application/json'});
+ res.writeHead(code, {
+ 'Content-Type': 'application/json'
+ });
res.write(JSON.stringify(resp) + '\n');
res.end();
});
@@ -35,68 +44,93 @@ module.exports = {
var user = req.user;
var app = req.app;
var apps = lib.get_couchdb_database('apps');
- apps.get(appname, function (err, doc) {
- if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- } else {
- console.log('Resetting repo from git: ', app.repo_id);
- var app_user_home = path.join(config.opt.git_home_dir, user._id, app.repo_id);
- exec(config.opt.app_dir + '/scripts/gitreset.js ' + app_user_home, function () {
- app_restart(app.repo_id, function() {
- res.send({
- status: "success"
- });
- });
+ apps.get(appname, function(err, doc) {
+ if (err) {
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ } else {
+ console.log('Resetting repo from git: ', app.repo_id);
+ var app_user_home = path.join(config.opt.git_home_dir, user._id, app.repo_id);
+ exec(config.opt.app_dir + '/scripts/gitreset.js ' + app_user_home, function() {
+ app_restart(app.repo_id, function() {
+ res.send({
+ status: "success"
});
- }
+ });
+ });
+ }
});
},
delete: function(req, res, next) {
var appname = req.param("appname").toLowerCase();
var user = req.user;
var app = req.app;
var apps = lib.get_couchdb_database('apps');
- apps.get(appname, function (err, doc) {
- var app_user_home = path.join(config.opt.git_home_dir, user._id, app.repo_id);
- if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- } else {
- apps.remove(appname, doc._rev, function (err, resp) {
- if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- } else {
- lib.update_proxytable_map(function (err) {
- app_stop(app.repo_id, function() {
- exec(config.opt.app_dir + '/scripts/removeapp.js ' + app_user_home, function () {
- res.send({ "status" : "success" });
- });
- });
- });
- }
+ apps.get(appname, function(err, doc) {
+ var app_user_home = path.join(config.opt.git_home_dir, user._id, app.repo_id);
+ if (err) {
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ } else {
+ apps.remove(appname, doc._rev, function(err, resp) {
+ if (err) {
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
});
- }
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ } else {
+ lib.update_proxytable_map(function(err) {
+ app_stop(app.repo_id, function() {
+ exec(config.opt.app_dir + '/scripts/removeapp.js ' + app_user_home, function() {
+ res.send({
+ "status": "success"
+ });
+ });
+ });
+ });
+ }
+ });
+ }
});
},
put: function(req, res, next) {
var appname = req.body.appname.toLowerCase();
var user = req.user;
var app = req.app;
var db = lib.get_couchdb_database('apps');
- db.get(appname, function (err, appdoc) {
+ db.get(appname, function(err, appdoc) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
var start = req.body.start;
var app_user_home = path.join(config.opt.apps_home_dir, appdoc.username);
var app_home = path.join(app_user_home, appdoc.repo_id);
var app_repo = config.opt.git_user + '@' + config.opt.git_dom + ':' + path.join(config.opt.git_home_dir, appdoc.username, appdoc.repo_id + '.git');
if (typeof start != 'undefined' && start.length > 0) {
- db.merge(appname, {start: start}, function (err, resp) {
- res.send({ status: success,
+ db.merge(appname, {
+ start: start
+ }, function(err, resp) {
+ res.send({
+ status: success,
port: appdoc.port,
gitrepo: app_repo,
start: start,
@@ -107,42 +141,24 @@ module.exports = {
} else {
var running = req.body.running;
switch (running) {
- case "true":
- if (appdoc.running == "true") {
- res.error(res, 408, "failure - application already running.");
- } else {
- app_start(appdoc.repo_id, function (rv, pid) {
- var success = "false",
- running = "failed-to-start";
- if (rv === true) {
- success = "success";
- running = "true";
- lib.update_proxytable_map(function (err) {
- // Not sure if the user needs to be made aware in case of these errors. Admins should be though.
- });
- }
- db.merge(appname, {running: running, pid: pid }, function (err, resp) {
- res.send({
- status: success,
- port: appdoc.port,
- gitrepo: app_repo,
- start: appdoc.start,
- running: running,
- pid: pid
- });
- });
- });
- }
- break;
- case "restart":
- app_restart(app.repo_id, function (rv, pid) {
+ case "true":
+ if (appdoc.running == "true") {
+ res.error(res, 408, "failure - application already running.");
+ } else {
+ app_start(appdoc.repo_id, function(rv, pid) {
var success = "false",
- running = "failed-to-restart";
+ running = "failed-to-start";
if (rv === true) {
success = "success";
running = "true";
+ lib.update_proxytable_map(function(err) {
+ // Not sure if the user needs to be made aware in case of these errors. Admins should be though.
+ });
}
- db.merge(appname, {running: running, pid: pid }, function (err, resp) {
+ db.merge(appname, {
+ running: running,
+ pid: pid
+ }, function(err, resp) {
res.send({
status: success,
port: appdoc.port,
@@ -153,39 +169,71 @@ module.exports = {
});
});
});
- break;
- case "false":
- if (app.running == 'false') {
- res.error(res, 408, "failure - application already stopped.");
- } else {
- app_stop(app.repo_id, function (rv) {
- var success = "false",
- running = "failed-to-stop";
- if (rv === true) {
- success = "success";
- running = "false";
- lib.update_proxytable_map(function (err) {
- // Not sure if the user needs to be made aware in case of these errors. Admins should be though.
- });
- }
- db.merge(appname, {running: running, pid: 'unknown' }, function (err, resp) {
- res.send({
- status: success,
- port: appdoc.port,
- gitrepo: app_repo,
- start: appdoc.start,
- running: running,
- pid: 'unknown'
- });
+ }
+ break;
+ case "restart":
+ app_restart(app.repo_id, function(rv, pid) {
+ var success = "false",
+ running = "failed-to-restart";
+ if (rv === true) {
+ success = "success";
+ running = "true";
+ }
+ db.merge(appname, {
+ running: running,
+ pid: pid
+ }, function(err, resp) {
+ res.send({
+ status: success,
+ port: appdoc.port,
+ gitrepo: app_repo,
+ start: appdoc.start,
+ running: running,
+ pid: pid
+ });
+ });
+ });
+ break;
+ case "false":
+ if (app.running == 'false') {
+ res.error(res, 408, "failure - application already stopped.");
+ } else {
+ app_stop(app.repo_id, function(rv) {
+ var success = "false",
+ running = "failed-to-stop";
+ if (rv === true) {
+ success = "success";
+ running = "false";
+ lib.update_proxytable_map(function(err) {
+ // Not sure if the user needs to be made aware in case of these errors. Admins should be though.
+ });
+ }
+ db.merge(appname, {
+ running: running,
+ pid: 'unknown'
+ }, function(err, resp) {
+ res.send({
+ status: success,
+ port: appdoc.port,
+ gitrepo: app_repo,
+ start: appdoc.start,
+ running: running,
+ pid: 'unknown'
});
});
- }
- break;
- default:
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.write(JSON.stringify({status: "false", message: "Invalid action."}) + "\n");
- res.end();
- break;
+ });
+ }
+ break;
+ default:
+ res.writeHead(400, {
+ 'Content-Type': 'application/json'
+ });
+ res.write(JSON.stringify({
+ status: "false",
+ message: "Invalid action."
+ }) + "\n");
+ res.end();
+ break;
}
}
}
@@ -200,9 +248,13 @@ module.exports = {
} else {
app_start(repo_id, function(rv) {
if (rv === false) {
- res.send({ status: "failed to start" });
+ res.send({
+ status: "failed to start"
+ });
} else {
- res.send({ status: "started" });
+ res.send({
+ status: "started"
+ });
}
}, true);
}
@@ -216,9 +268,13 @@ module.exports = {
} else {
app_stop(repo_id, function(rv) {
if (rv === false) {
- res.send({ status: "failed to stop" });
+ res.send({
+ status: "failed to stop"
+ });
} else {
- res.send({ status: "stop" });
+ res.send({
+ status: "stop"
+ });
}
});
}
@@ -232,9 +288,13 @@ module.exports = {
} else {
app_restart(repo_id, function(rv) {
if (rv === false) {
- res.send({ status: "failed to restart" });
+ res.send({
+ status: "failed to restart"
+ });
} else {
- res.send({ status: "restarted" });
+ res.send({
+ status: "restarted"
+ });
}
}, true);
}
@@ -250,119 +310,164 @@ module.exports = {
});
},
post: function(req, res, next) {
- var appname = req.body.appname;
- var start = req.body.start;
- if (!appname) {
- res.send({
- status: "failure",
- message: "Appname Required"
- });
- return;
- }
- if (!start) {
- res.send({
+ var appname = req.body.appname;
+ var start = req.body.start;
+ if (!appname) {
+ res.send({
+ status: "failure",
+ message: "Appname Required"
+ });
+ return;
+ }
+ if (!start) {
+ res.send({
+ status: "failure",
+ message: "Start File Required"
+ });
+ return;
+ }
+ var user = req.user;
+ var apps = lib.get_couchdb_database('apps');
+ apps.get(appname, function(err, doc) {
+ if (err) {
+ if (err.error == 'not_found') {
+ var nextport = lib.get_couchdb_database('nextport');
+ nextport.get('port', function(err, next_port) {
+ if (err) {
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
status: "failure",
- message: "Start File Required"
- });
- return;
- }
- var user = req.user;
- var apps = lib.get_couchdb_database('apps');
- apps.get(appname, function (err, doc) {
- if (err) {
- if (err.error == 'not_found') {
- var nextport = lib.get_couchdb_database('nextport');
- nextport.get('port', function (err, next_port) {
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ } else {
+ var appport = next_port.address;
+ var repo_id = next_port._rev;
+ nextport.merge('port', {
+ address: appport + 1
+ }, function(err, resp) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
- var appport = next_port.address;
- var repo_id = next_port._rev;
- nextport.merge('port', {address: appport + 1}, function (err, resp) {
+ apps.save(appname, {
+ start: start,
+ port: appport,
+ username: user._id,
+ repo_id: repo_id,
+ running: false,
+ pid: 'unknown',
+ env: {}
+ }, function(err, resp) {
+ if (err) {
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ } else {
+ var repos = lib.get_couchdb_database('repos');
+ repos.save(repo_id, {
+ appname: appname,
+ username: user._id
+ }, function(err, resp) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
- apps.save(appname, {
- start: start,
- port: appport,
- username: user._id,
- repo_id: repo_id,
- running: false,
- pid: 'unknown',
- env: {}
- }, function (err, resp) {
- if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- } else {
- var repos = lib.get_couchdb_database('repos');
- repos.save(repo_id, {appname: appname, username: user._id}, function (err, resp) {
- if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- } else {
- var cmd = 'sudo ' + config.opt.app_dir + '/scripts/gitreposetup.sh ' + [config.opt.app_dir, config.opt.git_home_dir, user._id, repo_id, start, config.opt.userid, config.opt.git_user, config.opt.apps_home_dir].join(' ');
- console.log('gitsetup cmd: %s', cmd);
- exec(cmd, function (err, stdout, stderr) {
- if (err) console.error('gitsetup error: %s', err);
- if (stdout.length > 0) console.log('gitsetup stdout: %s', stdout);
- if (stderr.length > 0) console.error('gitsetup stderr: %s', stderr);
- });
- // var gitsetup = spawn('/usr/bin/env sudo ' + config.opt.app_dir + '/scripts/gitreposetup.sh', [config.opt.app_dir, config.opt.git_home_dir, user._id, repo_id, start, config.opt.userid, config.opt.git_user]);
- //Added logging to the reposetup script
- // gitsetup.stdout.on('data', function (data) {
- // console.log('git setup stdout: ' + data);
- //});
-
- // gitsetup.stderr.on('data', function (data) {
- // console.error('git setup stderr: ' + data);
- //});
-
- // Respond to API request
- res.send({ status: "success",
- port: appport,
- gitrepo: config.opt.git_user + '@' + config.opt.git_dom + ':' + path.join(config.opt.git_home_dir, user._id, repo_id + '.git'),
- start: start,
- running: false,
- pid: "unknown"
- });
- lib.update_proxytable_map(function (err) {
- // Not sure if the user needs to be made aware in case of these errors. Admins should be though.
- });
- }
- });
- }
- });
+ var cmd = 'sudo ' + config.opt.app_dir + '/scripts/gitreposetup.sh ' + [config.opt.app_dir, config.opt.git_home_dir, user._id, repo_id, start, config.opt.userid, config.opt.git_user, config.opt.apps_home_dir].join(' ');
+ console.log('gitsetup cmd: %s', cmd);
+ exec(cmd, function(err, stdout, stderr) {
+ if (err) console.error('gitsetup error: %s', err);
+ if (stdout.length > 0) console.log('gitsetup stdout: %s', stdout);
+ if (stderr.length > 0) console.error('gitsetup stderr: %s', stderr);
+ });
+ // var gitsetup = spawn('/usr/bin/env sudo ' + config.opt.app_dir + '/scripts/gitreposetup.sh', [config.opt.app_dir, config.opt.git_home_dir, user._id, repo_id, start, config.opt.userid, config.opt.git_user]);
+ //Added logging to the reposetup script
+ // gitsetup.stdout.on('data', function (data) {
+ // console.log('git setup stdout: ' + data);
+ //});
+ // gitsetup.stderr.on('data', function (data) {
+ // console.error('git setup stderr: ' + data);
+ //});
+ // Respond to API request
+ res.send({
+ status: "success",
+ port: appport,
+ gitrepo: config.opt.git_user + '@' + config.opt.git_dom + ':' + path.join(config.opt.git_home_dir, user._id, repo_id + '.git'),
+ start: start,
+ running: false,
+ pid: "unknown"
+ });
+ lib.update_proxytable_map(function(err) {
+ // Not sure if the user needs to be made aware in case of these errors. Admins should be though.
+ });
}
- });
+ });
+ }
+ });
}
- });
- } else {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- }
+ });
+ }
+ });
} else {
- res.send({status: "failure", message: "app exists"});
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
}
- });
+ } else {
+ res.send({
+ status: "failure",
+ message: "app exists"
+ });
+ }
+ });
},
env_get: function(req, res, next) {
var appname = req.body.appname.toLowerCase();
var db = lib.get_couchdb_database('apps');
- db.get(appname, function (err, appdoc) {
+ db.get(appname, function(err, appdoc) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
var start = req.body.start;
- db.get(appname, function (err, doc) {
+ db.get(appname, function(err, doc) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
- res.send({status: "success", message: doc.env || {}});
+ res.send({
+ status: "success",
+ message: doc.env || {}
+ });
}
});
}
@@ -374,15 +479,25 @@ module.exports = {
var key = req.body.key,
value = req.body.value;
if (!key || !value) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.write(JSON.stringify({status: "false", message: "Must specify both key and value."}) + "\n");
+ res.writeHead(400, {
+ 'Content-Type': 'application/json'
+ });
+ res.write(JSON.stringify({
+ status: "false",
+ message: "Must specify both key and value."
+ }) + "\n");
res.end();
return;
}
- db.get(appname, function (err, appdoc) {
+ db.get(appname, function(err, appdoc) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
env_update(res, db, appname, appdoc, key, value);
}
@@ -393,15 +508,25 @@ module.exports = {
var db = lib.get_couchdb_database('apps');
var key = req.body.key;
if (!key) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.write(JSON.stringify({status: "false", message: "Must specify key."}) + "\n");
+ res.writeHead(400, {
+ 'Content-Type': 'application/json'
+ });
+ res.write(JSON.stringify({
+ status: "false",
+ message: "Must specify key."
+ }) + "\n");
res.end();
return;
}
- db.get(appname, function (err, appdoc) {
+ db.get(appname, function(err, appdoc) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
env_update(res, db, appname, appdoc, key, undefined);
}
@@ -412,7 +537,7 @@ module.exports = {
var env_update = function(res, db, appname, appdoc, key, value) {
var env = {};
if (appdoc.env) {
- Object.keys(appdoc.env).forEach(function (k) {
+ Object.keys(appdoc.env).forEach(function(k) {
env[k] = appdoc.env[k];
});
}
@@ -421,179 +546,192 @@ var env_update = function(res, db, appname, appdoc, key, value) {
} else {
delete env[key];
}
- db.merge(appname, {env: env}, function(err, resp) {
+ db.merge(appname, {
+ env: env
+ }, function(err, resp) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
- res.send({status: "success", message: value === undefined ? ("DELETE " + key) : (key + "=" + value)});
+ res.send({
+ status: "success",
+ message: value === undefined ? ("DELETE " + key) : (key + "=" + value)
+ });
}
});
};
var force_stop = function(repo_id, callback) {
- console.log('Forcing stop for: ', repo_id);
- console.log("ps aux | awk '/" + repo_id + "/ && !/awk |curl / {print $2}'");
- exec("ps aux | awk '/" + repo_id + "/ && !/awk |curl / {print $2}'", function(err, pid) {
- if (err) {
- callback(false);
- return;
- }
- try {
- console.log('PID: "' + pid + '"');
- if (pid.length > 0) {
- var pids = pid.split('\n'),
- k = false;
-
- var p = typeof pids[0] != 'undefined' ? parseInt(pids[0], 10) : 0;
- console.log('p: "' + p + '"');
- if (p > 0) {
- console.log('Sending SIGKILL to ', p);
- process.kill(p, 'SIGKILL');
- k = true;
- }
- callback(k);
- } else {
- callback(true);
- }
-
- } catch (e) {
- callback(false);
+ console.log('Forcing stop for: ', repo_id);
+ console.log("ps aux | awk '/" + repo_id + "/ && !/awk |curl / {print $2}'");
+ exec("ps aux | awk '/" + repo_id + "/ && !/awk |curl / {print $2}'", function(err, pid) {
+ if (err) {
+ callback(false);
+ return;
+ }
+ try {
+ console.log('PID: "' + pid + '"');
+ if (pid.length > 0) {
+ var pids = pid.split('\n'),
+ k = false;
+
+ var p = typeof pids[0] != 'undefined' ? parseInt(pids[0], 10) : 0;
+ console.log('p: "' + p + '"');
+ if (p > 0) {
+ console.log('Sending SIGKILL to ', p);
+ process.kill(p, 'SIGKILL');
+ k = true;
}
- });
+ callback(k);
+ } else {
+ callback(true);
+ }
+
+ } catch (e) {
+ callback(false);
+ }
+ });
};
-var app_stop = function (repo_id, callback, skip_unmount) {
- var db = lib.get_couchdb_database('repos');
- db.get(repo_id, function (err, doc) {
- if (err) {
- callback(false);
- } else {
- var app_home = path.join(config.opt.apps_home_dir, doc.username, doc._id);
- fs.readFile(path.join(app_home + '_rw', '.nodester', 'pids', 'runner.pid'), function (err, data) {
- if (err) {
- callback(false);
- } else {
- var pid = parseInt(data.toString(), 10);
- if (pid > 0) {
- try {
- process.kill(pid, 'SIGINT');
- var app_home = path.join(config.opt.apps_home_dir, doc.username, repo_id);
- var app_rw = app_home + '_rw';
- var app_chroot = app_home + '_chroot';
- if (typeof skip_unmount == 'undefined' || skip_unmount !== true) lib.tear_down_unionfs_chroot(config.opt.node_base_folder, app_home, app_rw, app_chroot, function () {});
- } catch (e) {
- // Blah
- }
- callback(true);
- } else {
- callback(false);
+var app_stop = function(repo_id, callback, skip_unmount) {
+ var db = lib.get_couchdb_database('repos');
+ db.get(repo_id, function(err, doc) {
+ if (err) {
+ callback(false);
+ } else {
+ var app_home = path.join(config.opt.apps_home_dir, doc.username, doc._id);
+ fs.readFile(path.join(app_home + '_rw', '.nodester', 'pids', 'runner.pid'), function(err, data) {
+ if (err) {
+ callback(false);
+ } else {
+ var pid = parseInt(data.toString(), 10);
+ if (pid > 0) {
+ try {
+ process.kill(pid, 'SIGINT');
+ var app_home = path.join(config.opt.apps_home_dir, doc.username, repo_id);
+ var app_rw = app_home + '_rw';
+ var app_chroot = app_home + '_chroot';
+ if (typeof skip_unmount == 'undefined' || skip_unmount !== true) lib.tear_down_unionfs_chroot(config.opt.node_base_folder, app_home, app_rw, app_chroot, function() {});
+ } catch (e) {
+ // Blah
}
+ callback(true);
+ } else {
+ callback(false);
}
- });
- }
- });
+ }
+ });
+ }
+ });
};
-var app_start = function (repo_id, callback) {
- var db = lib.get_couchdb_database('repos');
- db.get(repo_id, function (err, doc) {
- if (err) {
- callback(false);
- } else {
- var user_home = path.join(config.opt.apps_home_dir, doc.username);
- var app_home = user_home + '/' + repo_id;
- var apps = lib.get_couchdb_database('apps');
- apps.get(doc.appname, function (err, app) {
- if (err) {
+var app_start = function(repo_id, callback) {
+ var db = lib.get_couchdb_database('repos');
+ db.get(repo_id, function(err, doc) {
+ if (err) {
+ callback(false);
+ } else {
+ var user_home = path.join(config.opt.apps_home_dir, doc.username);
+ var app_home = user_home + '/' + repo_id;
+ var apps = lib.get_couchdb_database('apps');
+ apps.get(doc.appname, function(err, app) {
+ if (err) {
+ callback(false);
+ } else {
+ var configData = {
+ appdir: config.opt.app_dir,
+ userid: config.opt.app_uid,
+ chroot_base: config.opt.node_base_folder,
+ apphome: app_home,
+ apprwfolder: path.join(app_home, '..', repo_id + '_rw'),
+ appchroot: path.join(app_home, '..', repo_id + '_chroot'),
+ start: app.start,
+ port: app.port,
+ ip: '127.0.0.1',
+ name: doc.appname,
+ env: app.env || {}
+ };
+ console.log('Checking: ', configData.apphome);
+ if (!path.existsSync(configData.apphome)) {
+ //Bad install??
+ console.log('App directory does not exist: ', apphome);
callback(false);
- } else {
- var configData = {
- appdir: config.opt.app_dir,
- userid: config.opt.app_uid,
- chroot_base: config.opt.node_base_folder,
- apphome: app_home,
- apprwfolder: path.join(app_home, '..', repo_id + '_rw'),
- appchroot: path.join(app_home, '..', repo_id + '_chroot'),
- start: app.start,
- port: app.port,
- ip: '127.0.0.1',
- name: doc.appname,
- env: app.env || {}
- };
- console.log('Checking: ', configData.apphome);
- if (!path.existsSync(configData.apphome)) {
- //Bad install??
- console.log('App directory does not exist: ', apphome);
- callback(false);
- return;
- }
- console.log('Checking: ', path.join(configData.apphome, app.start));
- if (!path.existsSync(path.join(configData.apphome, app.start))) {
- //Bad install??
- console.log('App start file does not exist: ', path.join(configData.apphome, app.start));
- callback(false);
- return;
- }
-
- console.log('Checking: ', path.join(configData.apprwfolder, '.nodester'));
- if (!path.existsSync(path.join(configData.apprwfolder, '.nodester'))) {
- console.log('Making Directories..');
- if (!path.existsSync(configData.apprwfolder)) fs.mkdirSync(configData.apprwfolder, '0777');
- fs.mkdirSync(path.join(configData.apprwfolder, 'app'), '0777');
- fs.mkdirSync(path.join(configData.apprwfolder, '.nodester'), '0777');
- fs.mkdirSync(path.join(configData.apprwfolder, '.nodester', 'logs'), '0777');
- fs.mkdirSync(path.join(configData.apprwfolder, '.nodester', 'pids'), '0777');
- }
- fs.chmodSync(path.join(configData.apprwfolder, 'app'), '0777');
- console.log('Writing config data: ', path.join(configData.apprwfolder, '.nodester', 'config.json'));
- fs.writeFileSync(path.join(configData.apprwfolder, '.nodester', 'config.json'), JSON.stringify(configData), encoding='utf8'); // TODO Change to ASYNC
- lib.tear_down_unionfs_chroot(configData.chroot_base, configData.apphome, configData.apprwfolder, configData.appchroot, function (resp) {
- lib.setup_unionfs_chroot(configData.chroot_base, configData.apphome, configData.apprwfolder, configData.appchroot, function (resp) {
- if (resp === true) {
- var cmd = 'cd ' + configData.appchroot + ' && ulimit -c unlimited -n 65000 -u 100000 -i 1000000 -l 10240 -s 102400 && sudo ' + path.join(config.opt.app_dir, 'scripts', 'chroot_runner.js');
- console.log(cmd);
- exec(cmd, function (error, stdout, stderr) {
- if (stdout) {
- console.log(stdout);
- }
- if (stderr) {
- console.log(stderr);
- }
- setTimeout(function () {
- var tapp = {pid: 'unknown', running: 'failed-to-start'};
- fs.readFile(path.join(configData.apprwfolder, '.nodester', 'pids', 'runner.pid'), function (err, pids) {
- var pid = parseInt(pids, 10);
- if (pid > 0) {
- tapp.pid = pid;
- tapp.running = 'true';
- }
- apps.merge(doc.appname, tapp, function() {
- callback(true, pid);
- });
- });
- }, 1000);
- });
- }
- });
- });
+ return;
+ }
+ console.log('Checking: ', path.join(configData.apphome, app.start));
+ if (!path.existsSync(path.join(configData.apphome, app.start))) {
+ //Bad install??
+ console.log('App start file does not exist: ', path.join(configData.apphome, app.start));
+ callback(false);
+ return;
}
- });
- }
- });
-};
-var app_restart = function (repo_id, callback) {
- app_stop(repo_id, function (rv) {
- setTimeout(function () {
- app_start(repo_id, function (rv, pid) {
- if (rv === false) {
- callback(false);
- } else {
- callback(true, pid);
- }
+ console.log('Checking: ', path.join(configData.apprwfolder, '.nodester'));
+ if (!path.existsSync(path.join(configData.apprwfolder, '.nodester'))) {
+ console.log('Making Directories..');
+ if (!path.existsSync(configData.apprwfolder)) fs.mkdirSync(configData.apprwfolder, '0777');
+ fs.mkdirSync(path.join(configData.apprwfolder, 'app'), '0777');
+ fs.mkdirSync(path.join(configData.apprwfolder, '.nodester'), '0777');
+ fs.mkdirSync(path.join(configData.apprwfolder, '.nodester', 'logs'), '0777');
+ fs.mkdirSync(path.join(configData.apprwfolder, '.nodester', 'pids'), '0777');
+ }
+ fs.chmodSync(path.join(configData.apprwfolder, 'app'), '0777');
+ console.log('Writing config data: ', path.join(configData.apprwfolder, '.nodester', 'config.json'));
+ fs.writeFileSync(path.join(configData.apprwfolder, '.nodester', 'config.json'), JSON.stringify(configData), encoding = 'utf8'); // TODO Change to ASYNC
+ lib.tear_down_unionfs_chroot(configData.chroot_base, configData.apphome, configData.apprwfolder, configData.appchroot, function(resp) {
+ lib.setup_unionfs_chroot(configData.chroot_base, configData.apphome, configData.apprwfolder, configData.appchroot, function(resp) {
+ if (resp === true) {
+ var cmd = 'cd ' + configData.appchroot + ' && ulimit -c unlimited -n 65000 -u 100000 -i 1000000 -l 10240 -s 102400 && sudo ' + path.join(config.opt.app_dir, 'scripts', 'chroot_runner.js');
+ console.log(cmd);
+ exec(cmd, function(error, stdout, stderr) {
+ if (stdout) {
+ console.log(stdout);
+ }
+ if (stderr) {
+ console.log(stderr);
+ }
+ setTimeout(function() {
+ var tapp = {
+ pid: 'unknown',
+ running: 'failed-to-start'
+ };
+ fs.readFile(path.join(configData.apprwfolder, '.nodester', 'pids', 'runner.pid'), function(err, pids) {
+ var pid = parseInt(pids, 10);
+ if (pid > 0) {
+ tapp.pid = pid;
+ tapp.running = 'true';
+ }
+ apps.merge(doc.appname, tapp, function() {
+ callback(true, pid);
+ });
+ });
+ }, 1000);
+ });
+ }
});
- }, 1000);
- }, true);
+ });
+ }
+ });
+ }
+ });
};
+
+var app_restart = function(repo_id, callback) {
+ app_stop(repo_id, function(rv) {
+ setTimeout(function() {
+ app_start(repo_id, function(rv, pid) {
+ if (rv === false) {
+ callback(false);
+ } else {
+ callback(true, pid);
+ }
+ });
+ }, 1000);
+ }, true);
+};
View
8 lib/apps.js
@@ -7,9 +7,9 @@ module.exports = {
var user = req.user;
var db = lib.get_couchdb_database('apps');
- db.view('nodeapps/all', function (err, resp) {
+ db.view('nodeapps/all', function(err, resp) {
var apps = [];
- resp.forEach(function (row) {
+ resp.forEach(function(row) {
if (row.username == user._id) {
apps.push({
name: row._id,
@@ -21,6 +21,6 @@ module.exports = {
}
});
res.send(apps);
- });
+ });
}
-};
+};
View
29 lib/chroot.js
@@ -1,25 +1,25 @@
-(function () {
+(function() {
var lib = require('./lib.js');
var path = require('path');
var fs = require('fs');
- var chroot = function (target) {
+ var chroot = function(target) {
this._setup(target);
};
-
- chroot.prototype._setup = function (target_path) {
+
+ chroot.prototype._setup = function(target_path) {
this.errors = [];
this.target_path = target_path;
this.mounted = false;
this.proc_path = path.join(this.target_path, 'proc');
this.dev_path = path.join(this.target_path, 'dev');
};
- chroot.prototype.start = function (cb) {
+ chroot.prototype.start = function(cb) {
if (!path.existsSync(this.proc_path)) fs.mkdirSync(this.proc_path, '0777');
if (!path.existsSync(this.dev_path)) fs.mkdirSync(this.dev_path, '0777');
- lib.ensure_mounted('/dev', this.dev_path, '--bind', function (respA) {
+ lib.ensure_mounted('/dev', this.dev_path, '--bind', function(respA) {
if (respA === true) {
- lib.ensure_mounted('proc', this.proc_path, '-t proc', function (respB) {
+ lib.ensure_mounted('proc', this.proc_path, '-t proc', function(respB) {
if (respB === true) {
this.mounted = true;
cb(undefined, true);
@@ -34,19 +34,16 @@
}
}.bind(this));
};
- chroot.prototype.stop = function (cb) {
+ chroot.prototype.stop = function(cb) {
if (this.mounted === true) {
- var arr = [
- 'sudo umount ' + this.dev_path,
- 'sudo umount ' + this.proc_path
- ];
- lib.exec_array(arr, function () {
- lib.is_mounted(this.dev_path, function (respA) {
+ var arr = ['sudo umount ' + this.dev_path, 'sudo umount ' + this.proc_path];
+ lib.exec_array(arr, function() {
+ lib.is_mounted(this.dev_path, function(respA) {
if (respA !== false) {
this.errors.push(this.dev_path + ' is still mounted');
cb(this.errors, undefined);
} else {
- lib.is_mounted(this.proc_path, function (respB) {
+ lib.is_mounted(this.proc_path, function(respB) {
if (respB !== false) {
this.errors.push(this.proc_path + ' is still mounted');
cb(this.errors, undefined);
@@ -63,4 +60,4 @@
}
};
exports.chroot = chroot;
-})();
+})();
View
40 lib/coupon.js
@@ -7,34 +7,52 @@ module.exports = {
var email = req.body.email;
if (typeof email != 'undefined') {
var coupons = lib.get_couchdb_database('coupons');
- coupons.save(email, {sent: false}, function (err, resp) {
+ coupons.save(email, {
+ sent: false
+ }, function(err, resp) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
- res.send({ status: "success - you are now in queue to receive an invite on our next batch!" });
+ res.send({
+ status: "success - you are now in queue to receive an invite on our next batch!"
+ });
}
});
} else {
- res.send({ status: "failure - please try again shortly!" });
+ res.send({
+ status: "failure - please try again shortly!"
+ });
}
},
//I don't have this view, so I can't test it..
// Convert to use Cradle
unsent: function(req, res, next) {
var coupons = lib.get_couchdb_database('coupons');
- coupons.view('coupons/unsent', function (err, resp) {
+ coupons.view('coupons/unsent', function(err, resp) {
if (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
+ res.writeHead(500, {
+ 'Content-Type': 'application/json'
+ });
+ res.end(JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
} else {
var buff = "";
- resp.forEach(function (row) {
+ resp.forEach(function(row) {
buff += row._id + '\n';
});
- res.writeHead(200, {'Content-Type': 'text/plain'});
+ res.writeHead(200, {
+ 'Content-Type': 'text/plain'
+ });
res.end(buff);
}
});
}
-};
+};
View
175 lib/domains.js
@@ -4,87 +4,110 @@ var request = require('request'),
lib = require('./lib');
module.exports = {
- post: function(req, res, next) {
- var appname = req.appname,
- domain = req.param("domain"),
- user = req.user,
- app = req.app;
+ post: function(req, res, next) {
+ var appname = req.appname,
+ domain = req.param("domain"),
+ user = req.user,
+ app = req.app;
- var gooddomain = lib.checkDomain(domain);
- if (gooddomain === true) {
- var aliasdomains = lib.get_couchdb_database('aliasdomains');
- aliasdomains.get(domain, function (err, doc) {
- if (err) {
- if (err.error == 'not_found') {
- aliasdomains.save(domain, {appname: app._id, host: '127.0.0.1', port: app.port, username: user._id}, function (err, resp) {
- if (err) {
- res.error(400, JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- } else {
- res.send({ "status": "success", "message": "Domain added." });
- }
- });
- } else {
- res.error(400, JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- }
- } else {
- res.error(400, '{"status": "failure - domain already exists"}\n');
- }
+ var gooddomain = lib.checkDomain(domain);
+ if (gooddomain === true) {
+ var aliasdomains = lib.get_couchdb_database('aliasdomains');
+ aliasdomains.get(domain, function(err, doc) {
+ if (err) {
+ if (err.error == 'not_found') {
+ aliasdomains.save(domain, {
+ appname: app._id,
+ host: '127.0.0.1',
+ port: app.port,
+ username: user._id
+ }, function(err, resp) {
+ if (err) {
+ res.error(400, JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ } else {
+ res.send({
+ "status": "success",
+ "message": "Domain added."
+ });
+ }
});
+ } else {
+ res.error(400, JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ }
} else {
- res.error(400, '{"status": "failure - ' + gooddomain + '"}\n');
+ res.error(400, '{"status": "failure - domain already exists"}\n');
}
- },
- delete: function(req, res, next) {
- var appname = req.appname,
- domain = req.param("domain"),
- user = req.user,
- app = req.app;
+ });
+ } else {
+ res.error(400, '{"status": "failure - ' + gooddomain + '"}\n');
+ }
+ },
+ delete: function(req, res, next) {
+ var appname = req.appname,
+ domain = req.param("domain"),
+ user = req.user,
+ app = req.app;
- var gooddomain = lib.checkDomain(domain);
- if (gooddomain === true) {
- var aliasdomains = lib.get_couchdb_database('aliasdomains');
- aliasdomains.get(domain, function (err, doc) {
- if (err) {
- if (err.error == 'not_found') {
- res.error(400, '{"status": "failure - domain not found."}\n');
- } else {
- res.error(400, JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- }
- } else {
- if (doc.appname == appname) {
- aliasdomains.remove(domain, function (err, resp) {
- if (err) {
- res.error(400, JSON.stringify({status: "failure", message: err.error + ' - ' + err.reason}) + '\n');
- } else {
- res.send({ "status": "success", "message": "Domain deleted." });
- }
- });
- } else {
- res.error(400, '{"status": "failure - domain is not for this app."}\n');
- }
- }
- });
+ var gooddomain = lib.checkDomain(domain);
+ if (gooddomain === true) {
+ var aliasdomains = lib.get_couchdb_database('aliasdomains');
+ aliasdomains.get(domain, function(err, doc) {
+ if (err) {
+ if (err.error == 'not_found') {
+ res.error(400, '{"status": "failure - domain not found."}\n');
+ } else {
+ res.error(400, JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ }
} else {
- res.error(400, '{"status": "failure - ' + gooddomain + '"}\n');
+ if (doc.appname == appname) {
+ aliasdomains.remove(domain, function(err, resp) {
+ if (err) {
+ res.error(400, JSON.stringify({
+ status: "failure",
+ message: err.error + ' - ' + err.reason
+ }) + '\n');
+ } else {
+ res.send({
+ "status": "success",
+ "message": "Domain deleted."
+ });
+ }
+ });
+ } else {
+ res.error(400, '{"status": "failure - domain is not for this app."}\n');
+ }
}
- },
- get: function(req, res, next) {
- var user = req.user;
- var db = lib.get_couchdb_database('aliasdomains');
- // db.view('aliasdomains/all', {key: req.user._id}, function (err, resp) {
- db.view('aliasdomains/all', function (err, resp) {
- var domains = [];
- resp.forEach(function (row) {
- if(row.username == user._id){
- domains.push({
- domain: row._id,
- appname: row.appname,
- host: row.host,
- port: row.port
- });
- }
- });
- res.send(domains);
- });
+ });
+ } else {
+ res.error(400, '{"status": "failure - ' + gooddomain + '"}\n');
}
-};
+ },
+ get: function(req, res, next) {
+ var user = req.user;
+ var db = lib.get_couchdb_database('aliasdomains');
+ // db.view('aliasdomains/all', {key: req.user._id}, function (err, resp) {
+ db.view('aliasdomains/all', function(err, resp) {
+ var domains = [];
+ resp.forEach(function(row) {
+ if (row.username == user._id) {
+ domains.push({
+ domain: row._id,
+ appname: row.appname,
+ host: row.host,
+ port: row.port
+ });
+ }
+ });
+ res.send(domains);
+ });
+ }
+};
View
199 lib/lib.js
@@ -1,5 +1,3 @@
-
-
var cradle = require('cradle');
var crypto = require('crypto');
var exec = require('child_process').exec;
@@ -16,17 +14,20 @@ if (config.opt.couch_prefix.length > 0) {
exports.couch_prefix = "";
}
exports.couch_loc = couch_loc;
-exports.h = {accept: 'application/json', 'content-type': 'application/json'};
+exports.h = {
+ accept: 'application/json',
+ 'content-type': 'application/json'
+};
-var couchdb_parse = function (err, body, cb) {
+var couchdb_parse = function(err, body, cb) {
if (err !== null) {
cb(err, null);
} else {
var doc = {};
try {
doc = JSON.parse(body);
} catch (e) {}
-
+
if (doc.hasOwnProperty('error')) {
cb(doc.error, doc);
} else {
@@ -36,18 +37,23 @@ var couchdb_parse = function (err, body, cb) {
};
exports.couchdb_parse = couchdb_parse;
-
-var get_couchdb_connection = function () {
+var get_couchdb_connection = function() {
return new cradle.Connection({
host: config.opt.couch_host,
port: config.opt.couch_port,
- auth: {username: config.opt.couch_user, password: config.opt.couch_pass},
- options: {cache: true, raw: false}
+ auth: {
+ username: config.opt.couch_user,
+ password: config.opt.couch_pass
+ },
+ options: {
+ cache: true,
+ raw: false
+ }
});
};
exports.get_couchdb_connection = get_couchdb_connection;
-var get_couchdb_database = function (database) {
+var get_couchdb_database = function(database) {
var conn = get_couchdb_connection();
return conn.database(exports.couch_prefix + database);
};
@@ -56,46 +62,48 @@ exports.get_couchdb_database = get_couchdb_database;
var www_dom = "www." + config.opt.tl_dom;
var tl_dom = config.opt.tl_dom;
var api_dom = config.opt.api_dom;
-var default_routes = {router: {}};
+var default_routes = {
+ router: {}
+};
default_routes.router["127.0.0.1"] = "127.0.0.1:4001";
default_routes.router[www_dom] = "127.0.0.1:4001";
default_routes.router[tl_dom] = "127.0.0.1:4001";
default_routes.router[api_dom] = "127.0.0.1:4001";
exports.default_routes = default_routes;
-var build_proxytable_map = function (cb) {
+var build_proxytable_map = function(cb) {
var conn = get_couchdb_connection();
var apps = conn.database(exports.couch_prefix + "apps");
var aliasdomains = conn.database(exports.couch_prefix + "aliasdomains");
var proxy_map = default_routes;
- apps.view('nodeapps/all', function (err, resp) {
- if (err) {
-
- } else {
- resp.forEach(function (row) {
- proxy_map.router[row._id + "." + config.opt.tl_dom] = "127.0.0.1:" + row.port;
- });
- aliasdomains.view('aliasdomains/all', function (err, resp) {
- if (resp && resp.length) {
- resp.forEach(function (row) {
- proxy_map.router[row._id] = row.host + ":" + row.port;
- });
- }
- cb(proxy_map);
- });
- }
+ apps.view('nodeapps/all', function(err, resp) {
+ if (err) {
+
+ } else {
+ resp.forEach(function(row) {
+ proxy_map.router[row._id + "." + config.opt.tl_dom] = "127.0.0.1:" + row.port;
+ });
+ aliasdomains.view('aliasdomains/all', function(err, resp) {
+ if (resp && resp.length) {
+ resp.forEach(function(row) {
+ proxy_map.router[row._id] = row.host + ":" + row.port;
+ });
+ }
+ cb(proxy_map);
+ });
+ }
});
};
exports.build_proxytable_map = build_proxytable_map;
-var update_proxytable_map = function (cb) {
+var update_proxytable_map = function(cb) {
var fs = require('fs');
- build_proxytable_map(function (proxy_map) {
- fs.writeFile(config.opt.proxy_table_file, JSON.stringify(proxy_map), function (err) {
+ build_proxytable_map(function(proxy_map) {
+ fs.writeFile(config.opt.proxy_table_file, JSON.stringify(proxy_map), function(err) {
if (err) {
cb(err);
} else {
- fs.chmod(config.opt.proxy_table_file, '0666', function (err) {
+ fs.chmod(config.opt.proxy_table_file, '0666', function(err) {
if (err) {
cb(err);
} else {
@@ -108,61 +116,36 @@ var update_proxytable_map = function (cb) {
};
exports.update_proxytable_map = update_proxytable_map;
-function checkDomain(nname) {
- var arr = new Array(
- '.com','.net','.org','.biz','.coop','.info','.museum','.name',
- '.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
- '.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
- '.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
- '.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
- '.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
- '.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
- '.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
- '.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
- '.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
- '.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
- '.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
- '.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
- '.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
- '.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
- '.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
- '.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
- '.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
- '.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
- '.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
- '.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
- '.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
- '.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
- '.wf','.ye','.yt','.yu','.za','.zm','.zw','.me'
- );
+var checkDomain = function(nname) {
+ var arr = new Array('.com', '.net', '.org', '.biz', '.coop', '.info', '.museum', '.name', '.pro', '.edu', '.gov', '.int', '.mil', '.ac', '.ad', '.ae', '.af', '.ag', '.ai', '.al', '.am', '.an', '.ao', '.aq', '.ar', '.as', '.at', '.au', '.aw', '.az', '.ba', '.bb', '.bd', '.be', '.bf', '.bg', '.bh', '.bi', '.bj', '.bm', '.bn', '.bo', '.br', '.bs', '.bt', '.bv', '.bw', '.by', '.bz', '.ca', '.cc', '.cd', '.cf', '.cg', '.ch', '.ci', '.ck', '.cl', '.cm', '.cn', '.co', '.cr', '.cu', '.cv', '.cx', '.cy', '.cz', '.de', '.dj', '.dk', '.dm', '.do', '.dz', '.ec', '.ee', '.eg', '.eh', '.er', '.es', '.et', '.fi', '.fj', '.fk', '.fm', '.fo', '.fr', '.ga', '.gd', '.ge', '.gf', '.gg', '.gh', '.gi', '.gl', '.gm', '.gn', '.gp', '.gq', '.gr', '.gs', '.gt', '.gu', '.gv', '.gy', '.hk', '.hm', '.hn', '.hr', '.ht', '.hu', '.id', '.ie', '.il', '.im', '.in', '.io', '.iq', '.ir', '.is', '.it', '.je', '.jm', '.jo', '.jp', '.ke', '.kg', '.kh', '.ki', '.km', '.kn', '.kp', '.kr', '.kw', '.ky', '.kz', '.la', '.lb', '.lc', '.li', '.lk', '.lr', '.ls', '.lt', '.lu', '.lv', '.ly', '.ma', '.mc', '.md', '.mg', '.mh', '.mk', '.ml', '.mm', '.mn', '.mo', '.mp', '.mq', '.mr', '.ms', '.mt', '.mu', '.mv', '.mw', '.mx', '.my', '.mz', '.na', '.nc', '.ne', '.nf', '.ng', '.ni', '.nl', '.no', '.np', '.nr', '.nu', '.nz', '.om', '.pa', '.pe', '.pf', '.pg', '.ph', '.pk', '.pl', '.pm', '.pn', '.pr', '.ps', '.pt', '.pw', '.py', '.qa', '.re', '.ro', '.rw', '.ru', '.sa', '.sb', '.sc', '.sd', '.se', '.sg', '.sh', '.si', '.sj', '.sk', '.sl', '.sm', '.sn', '.so', '.sr', '.st', '.sv', '.sy', '.sz', '.tc', '.td', '.tf', '.tg', '.th', '.tj', '.tk', '.tm', '.tn', '.to', '.tp', '.tr', '.tt', '.tv', '.tw', '.tz', '.ua', '.ug', '.uk', '.um', '.us', '.uy', '.uz', '.va', '.vc', '.ve', '.vg', '.vi', '.vn', '.vu', '.ws', '.wf', '.ye', '.yt', '.yu', '.za', '.zm', '.zw', '.me');
var mai = nname;
var val = true;
var dot = mai.lastIndexOf(".");
- var dname = mai.substring(0,dot);
- var ext = mai.substring(dot,mai.length);
+ var dname = mai.substring(0, dot);
+ var ext = mai.substring(dot, mai.length);
- if(dot > 2 && dot < 57) {
- for(var i = 0; i < arr.length; i++) {
- if(ext == arr[i]) {
+ if (dot > 2 && dot < 57) {
+ for (var i = 0; i < arr.length; i++) {
+ if (ext == arr[i]) {
val = true;
break;
} else {
val = false;
}
}
- if(val === false) {
- return "Invalid domain extesion " + ext + ", please tell support to add it to allowed extensions.";
+ if (val === false) {
+ return "Invalid domain extesion " + ext + ", please tell support to add it to allowed extensions.";
} else {
- for(var j = 0; j < dname.length; j++) {
+ for (var j = 0; j < dname.length; j++) {
var dh = dname.charAt(j);
var hh = dh.charCodeAt(0);
- if((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46) {
- if((j === 0 || j == dname.length - 1) && hh == 45) {
+ if ((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46) {
+ if ((j === 0 || j == dname.length - 1) && hh == 45) {
return "Domain names should not start or end with a '-'.";
}
- } else {
+ } else {
return "Your domain name should not have special characters";
}
}
@@ -171,23 +154,23 @@ function checkDomain(nname) {
return "Your domain name is too short/long.";
}
return true;
-}
+};
exports.checkDomain = checkDomain;
-var escape_packages = function (str) {
- return str.replace(/[^a-zA-Z0-9 \.\-_=<>@]+/g,'');
+var escape_packages = function(str) {
+ return str.replace(/[^a-zA-Z0-9 \.\-_=<>@]+/g, '');
};
exports.escape_packages = escape_packages;
-var md5 = function (str) {
+var md5 = function(str) {
return crypto.createHash('md5').update(str).digest('hex');
};
exports.md5 = md5;
-var rand_string = function (n) {
+var rand_string = function(n) {
var cs = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var cslen = cs.length;
var rtv = '';
- var rand_char = function () {
+ var rand_char = function() {
return cs.substr(Math.floor(Math.random() * cslen), 1);
};
for (var i = 0; i < n; i++) {
@@ -197,22 +180,22 @@ var rand_string = function (n) {
};
exports.rand_string = rand_string;
-var exec_array = function (arr, my_cb) {
+var exec_array = function(arr, my_cb) {
var running = false;
var timer = null;
- var do_job = function () {
- running = true;
- var v = arr.shift();
- exec(v, function (err, stdout, stderr) {
- if (err) {
- console.error('Error: Command %s Failed. Exit Val: %d - %s', v, err.code, err.toString());
- }
- console.log('%s stdout: %s', v, stdout); // Ugly output atm.
- console.log('%s stderr: %s', v, stderr); // Ditto
- running = false;
- });
- };
- timer = setInterval(function () {
+ var do_job = function() {
+ running = true;
+ var v = arr.shift();
+ exec(v, function(err, stdout, stderr) {
+ if (err) {
+ console.error('Error: Command %s Failed. Exit Val: %d - %s', v, err.code, err.toString());
+ }
+ console.log('%s stdout: %s', v, stdout); // Ugly output atm.
+ console.log('%s stderr: %s', v, stderr); // Ditto
+ running = false;
+ });
+ };
+ timer = setInterval(function() {
if (arr.length > 0) {
if (running === false) {
do_job();
@@ -225,8 +208,8 @@ var exec_array = function (arr, my_cb) {
};
exports.exec_array = exec_array;
-var is_mounted = function (pat, cb) {
- exec('mount | grep \'' + pat + '\'', function (err, stdout, stderr) {
+var is_mounted = function(pat, cb) {
+ exec('mount | grep \'' + pat + '\'', function(err, stdout, stderr) {
var pos = stdout.indexOf(pat);
if (pos > -1) {
cb(true);
@@ -237,14 +220,14 @@ var is_mounted = function (pat, cb) {
};
exports.is_mounted = is_mounted;
-var ensure_mounted = function (src, tgt, opts, cb) {
- is_mounted(tgt, function (resp) {
+var ensure_mounted = function(src, tgt, opts, cb) {
+ is_mounted(tgt, function(resp) {
if (resp === true) {
cb(true);
} else {
var cmd = 'sudo mount ' + opts + ' ' + src + ' ' + tgt;
- exec(cmd, function (err, stdout, stderr) {
- is_mounted(tgt, function (resp) {
+ exec(cmd, function(err, stdout, stderr) {
+ is_mounted(tgt, function(resp) {
if (resp === true) {
cb(true);
} else {
@@ -257,30 +240,30 @@ var ensure_mounted = function (src, tgt, opts, cb) {
};
exports.ensure_mounted = ensure_mounted;
-var tear_down_unionfs_chroot = function (chroot_base, git_home, rw_folder, final_chroot, callback) {
- var chr = new chroot (final_chroot);
+var tear_down_unionfs_chroot = function(chroot_base, git_home, rw_folder, final_chroot, callback) {
+ var chr = new chroot(final_chroot);
chr.mounted = true;
- chr.stop(function (err, resp) {
+ chr.stop(function(err, resp) {
// Ignore output...
// BAD need to fix this...
- var ufs = new unionfs (chroot_base, git_home, rw_folder, final_chroot);
+ var ufs = new unionfs(chroot_base, git_home, rw_folder, final_chroot);
ufs.mounted = true;
- ufs.stop(function (err, resp) {
+ ufs.stop(function(err, resp) {
callback();
- });
+ });
});
};
exports.tear_down_unionfs_chroot = tear_down_unionfs_chroot;
-var setup_unionfs_chroot = function (chroot_base, git_home, rw_folder, final_chroot, callback) {
- var ufs = new unionfs (chroot_base, git_home, rw_folder, final_chroot);
- ufs.start(function (err, resp) {
+var setup_unionfs_chroot = function(chroot_base, git_home, rw_folder, final_chroot,