Created
February 21, 2016 03:07
-
-
Save felixbuenemann/ce497195181d6cc09869 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// AWS Lamda Function to Test Dynamic VIPS Binary | |
var exec = require('child_process').exec; | |
var spawn = require('child_process').spawn; | |
var https = require('https'); | |
// Example Event: | |
// { | |
// "cmd": "/tmp/vips/bin/vips -v", | |
// "url": "https://www.dropbox.com/s/nba1piz7wfx2wb0/vips-8.3.0-0a4991c-dynamic.tar.bz2?dl=1" | |
// } | |
exports.handler = function(event, context) { | |
if (!event.url) { | |
context.fail('Please specify a vips tarball url as event.url'); | |
return; | |
} | |
if (!event.cmd) { | |
context.fail('Please specify a command to run as event.cmd'); | |
return; | |
} | |
var tar = spawn('/bin/tar', ['xjC', '/tmp']); | |
tar.stdout.on('data', console.log); | |
tar.stderr.on('data', console.error); | |
tar.on('exit', function(code) { | |
if (code === 0) { | |
console.log('Starting cmd ' + event.cmd); | |
var child = exec(event.cmd, function(error) { | |
// Resolve with result of process | |
context.done(error, 'Process complete!'); | |
}); | |
// Log process stdout and stderr | |
child.stdout.on('data', console.log); | |
child.stderr.on('data', console.error); | |
} else { | |
context.fail('tar exited with error ' + code); | |
} | |
}); | |
var numRedirects = 0; | |
var download = function(url) { | |
console.log('Loading ' + url); | |
https.get(url, function(resource) { | |
if (resource.statusCode === 302) { | |
var redirectUrl = resource.headers.location; | |
if (numRedirects++ < 10) { | |
console.log('Following redirect to ' + redirectUrl); | |
download(redirectUrl); | |
} else { | |
context.fail('Too many redirects: ' + numRedirects); | |
} | |
} else if (resource.statusCode === 200) { | |
// Extract tar on the fly | |
resource.pipe(tar.stdin); | |
resource.on('error', function(error) { | |
console.error('Download failed!'); | |
context.fail(error); | |
}); | |
resource.on('end', function() { | |
console.log('Download finished!'); | |
tar.stdin.end(); | |
}); | |
} else { | |
context.fail('Unhandled http status code ', resource.statusCode); | |
} | |
}).on('error', function(error) { | |
context.fail(error); | |
}); | |
}; | |
download(event.url); | |
}; | |
var context = {}; | |
context.done = function(error, result) { | |
if (error) { | |
context.fail(error); | |
} else { | |
context.succeed(result); | |
} | |
}; | |
context.fail = function(error) { | |
console.error(error); | |
process.exit(1); | |
}; | |
context.succeed = function(result) { | |
console.log(result); | |
process.exit(0); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment