diff --git a/routes/api.js b/routes/api.js index 942c4ee..ddb4a66 100644 --- a/routes/api.js +++ b/routes/api.js @@ -8,26 +8,34 @@ var client = redis.createClient(); var request = require('request'); var lxc = require('../lxc'); +var runner = function(res, req, ip){ + return request.post({url:'http://'+ip, form: req.body}, function(error, response, body){ + body = JSON.parse(body); + body['ip'] = ip.replace('10.0.', '') + return res.json(body) + }); +}; +var addToRedis = function(){ + lxc.info(req.params.name, null, function(data){ + var domain = req.query.domain || 'vm42.us'; + domain = req.params.name+'.'+domain; + client.SADD("hosts", domain, function(){}); + + var ip = data.ip + ':5000'; + client.HSET(domain, "ip", ip, redis.print); + client.HSET(domain, "updated", (new Date).getTime(), redis.print); + client.hset(domain, "include", "proxy.include"); + return res.json({status: 200, info: data}); + }); +}; + router.get('/start/:name', function(req, res, next){ - lxc.start(req.params.name, function(data){ + return lxc.start(req.params.name, function(data){ console.log('start', arguments); if(!data){ - res.json({status: 500, name: req.params.name, message: data}); + return res.json({status: 500, name: req.params.name, message: data}); }else{ - setTimeout(function() { - lxc.info(req.params.name, null, function(data){ - var domain = req.query.domain || 'vm42.us'; - domain = req.params.name+'.'+domain; - client.SADD("hosts", domain, function(){}); - - var ip = data.ip + ':5000'; - client.HSET(domain, "ip", ip, redis.print); - client.HSET(domain, "updated", (new Date).getTime(), redis.print); - client.hset(domain, "include", "proxy.include"); - res.json({status: 200, info: data}); - }); - }, 5000); - + res.json({}) } }); }); @@ -85,29 +93,15 @@ router.get('/list', function(req, res, next) { }); router.post('/run/:ip?', function(req, res, next){ - - var runner = function(res, req, ip){ - console.log('runner on', ip,'with body:\n', JSON.stringify(req.body)); - return request.post({url:'http://'+ip, form: req.body}, function(error, response, body){ - console.log('request args:', arguments) - body = JSON.parse(body); - body['ip'] = ip.replace('10.0.', '') - return res.json(body) - }); - }; - - if(req.params.ip){ var ip = '10.0.'+ req.params.ip; return runner(res, req, ip); }else{ var name = 'u1-'+(Math.random()*100).toString().replace('.',''); - console.log('new VM', name); return lxc.startEphemeral(name, 'u1', function(data){ return runner(res, req, data.ip); }); } - }); module.exports = router;