exports.setscpDefault = function() { client.defaults({ 'port': _port, 'host': _host, 'username': _username, 'password': _password }); };
grunt.registerTask('ssh_deploy', 'Begin Deployment', function() { var done = this.async(); var Connection = require('ssh2'); var client = require('scp2'); var moment = require('moment'); var timestamp = moment().format('YYYYMMDDHHmmssSSS'); var async = require('async'); var extend = require('extend'); var defaults = { current_symlink: 'current', port: 22 }; var options = extend({}, defaults, grunt.config.get('environments').options, grunt.config.get('environments')[this.args]['options']); // scp defaults client.defaults({ port: options.port, host: options.host, username: options.username, privateKey: options.privateKey }); var c = new Connection(); c.on('connect', function() { grunt.log.subhead('Connecting :: ' + options.host); }); c.on('ready', function() { grunt.log.subhead('Connected :: ' + options.host); // execution of tasks execCommands(options,c); }); c.on('error', function(err) { grunt.log.subhead("Error :: " + options.host); grunt.log.errorlns(err); if (err) {throw err;} }); c.on('close', function(had_error) { grunt.log.subhead("Closed :: " + options.host); return true; }); c.connect(options); var execCommands = function(options, connection){ var childProcessExec = require('child_process').exec; var execLocal = function(cmd, next) { var nextFun = next; childProcessExec(cmd, function(err, stdout, stderr){ grunt.log.debug(cmd); grunt.log.debug('stdout: ' + stdout); grunt.log.debug('stderr: ' + stderr); if (err !== null) { grunt.log.errorlns('exec error: ' + err); grunt.log.subhead('Error deploying. Closing connection.'); deleteRelease(closeConnection); } else { next(); } }); }; // executes a remote command via ssh var execRemote = function(cmd, showLog, next){ connection.exec(cmd, function(err, stream) { if (err) { grunt.log.errorlns(err); grunt.log.subhead('ERROR DEPLOYING. CLOSING CONNECTION AND DELETING RELEASE.'); deleteRelease(closeConnection); } stream.on('data', function(data, extended) { grunt.log.debug((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ') + data); }); stream.on('end', function() { grunt.log.debug('REMOTE: ' + cmd); if(!err) { next(); } }); }); }; var onBeforeDeploy = function(callback){ if (typeof options.before_deploy == "undefined" || !options.before_deploy) { callback(); } else { var command = options.before_deploy; grunt.log.subhead("--------------- RUNNING PRE-DEPLOY COMMANDS"); if (command instanceof Array) { async.eachSeries(command, function (command, callback) { grunt.log.subhead('--- ' + command); execRemote(command, options.debug, callback); }, callback); } else { grunt.log.subhead('--- ' + command);; execRemote(command, options.debug, callback); } } }; var createReleases = function(callback) { var command = 'cd ' + options.deploy_path + ' && mkdir -p releases/' + timestamp; grunt.log.subhead('--------------- CREATING NEW RELEASE'); grunt.log.subhead('--- ' + command); execRemote(command, options.debug, callback); }; var scpBuild = function(callback) { grunt.log.subhead('--------------- UPLOADING NEW BUILD'); grunt.log.debug('SCP FROM LOCAL: ' + options.local_path + '\n TO REMOTE: ' + options.deploy_path + '/releases/' + timestamp + '/'); client.scp(options.local_path, { path: options.deploy_path + '/releases/' + timestamp + '/' }, function (err) { if (err) { grunt.log.errorlns(err); } else { grunt.log.subhead('--- DONE UPLOADING'); callback(); } }); }; var updateSymlink = function(callback) { var delete_symlink = 'rm -rf ' + options.deploy_path + '/' + options.current_symlink; var set_symlink = 'cd ' + options.deploy_path + ' && ln -s releases/' + timestamp + ' ' + options.current_symlink; var command = delete_symlink + ' && ' + set_symlink; grunt.log.subhead('--------------- UPDATING SYM LINK'); grunt.log.subhead('--- ' + command); execRemote(command, options.debug, callback); }; var deleteRelease = function(callback) { var command = 'rm -rf ' + options.deploy_path + '/releases/' + timestamp + '/'; grunt.log.subhead('--------------- DELETING RELEASE'); grunt.log.subhead('--- ' + command); execRemote(command, options.debug, callback); }; var onAfterDeploy = function(callback){ if (typeof options.after_deploy == "undefined" || !options.after_deploy) { callback(); } else { var command = options.after_deploy; grunt.log.subhead("--------------- RUNNING POST-DEPLOY COMMANDS"); if (command instanceof Array) { async.eachSeries(command, function (command, callback) { grunt.log.subhead('--- ' + command);; execRemote(command, options.debug, callback); }, callback); } else { grunt.log.subhead('--- ' + command);; execRemote(command, options.debug, callback); } } }; // closing connection to remote server var closeConnection = function(callback) { connection.end(); callback(); }; async.series([ onBeforeDeploy, createReleases, scpBuild, updateSymlink, onAfterDeploy, closeConnection ], function () { done(); }); }; });
/** * Created by prrathore on 1/13/15. */ var client = require('scp2'); var fs = require('fs'); client.defaults({ port: 22, host: 'hostname', username: '******', privateKey: fs.readFileSync('privateKeyPath') }); client.upload('/Users/prrathore/temp/DEVELOPMENT-application.properties', '/x/home/prrathore/temp/application-dev-scp.txt', function(err) { if(err) { console.log("File upload failed: " + err); client.close(); } console.log("file moved to server successfully!!"); client.close(); }); client.on('connect', function() { console.log("Connected!!"); }); client.on('ready', function() { console.log("Ready for file transfer!!");
.then(function(){ client.defaults(opts.auth); })
/** * Exports the scorecard passed via SCP or local saving according to * configuration settings * * @param scorecard * {object} Scorecard JSON object ot be exproted * @param doctor * {string} CPSCId of doctor scorecard is for * @param period * {object} Time period object that scorecard is for * @param callback * {function} Callback to call when complete. Call with no arguments * if successful, or pass error message */ function exportScorecard(scorecard, doctor, period, callback) { var docInfo = doctors.getDoctorInfo(doctor); // create filename for resulting scorecard // The date in the label should be the day after the end of the period var dateLabel = new moment(period.end).add(1, "days"); var filename = docInfo.exportAs + "_" + dateLabel.format("YYYY_MM_DD") + ".xml"; var scorecardContents = js2xmlparser('ScoreCard', scorecard); var privateKeyPath; if (!connectionsConfig.getUpload().saveLocal) { // SaveLocal is not defined or false. Use standard SCP upload. if ((typeof connectionsConfig.getUpload().keyPath === 'string' || connectionsConfig .getUpload().keyPath instanceof String) && (connectionsConfig.getUpload().keyPath.length > 0)) { // Keypath is explicitly defined in the config privateKeyPath = connectionsConfig.getUpload().keyPath; } else { // Keypath is not defined // Use user's keypath // Attempt to read user's home directory var homeDir; switch (process.platform) { case 'linux': homeDir = process.env['HOME']; break; case 'win32': homeDir = process.env['USERPROFILE']; break; default: console .log('Unrecognized OS. Treating current directory as HOMEDIR.'); homeDir = __dirname; } privateKeyPath = homeDir + '/.ssh/id_rsa' } // configure connection scpClient.defaults({ port : connectionsConfig.getUpload().port, host : connectionsConfig.getUpload().host, username : connectionsConfig.getUpload().username, privateKey : fs.readFileSync(privateKeyPath), readyTimeout : 99999 }); // Limit simultaneous uploads using semaphore sem.take(function() { // Send Scorecard text scpClient.write({ destination : filename, content : new Buffer(scorecardContents, "utf-8") }, function(error) { // Unlock sempahore sem.leave(); if (error) { console.log("Error sending scorecard: " + error); callback(error); } else { console.log("Successfully sent scoredard: " + filename); callback(); } }); }); } else { // Save file, using savePath from index.js var savePath = __dirname + '/../scorecards/'; var saveFile = savePath + filename; // Use debugging save to local filesystem method // fs.writeFileSync(saveFile, scorecardContents); fs.writeFile(saveFile, scorecardContents, function(error) { if (error) { console.log("Successfully saved scorecard locally to: " + saveFile + "\n" + error); callback(error); } else { console.log("Successfully saved scorecard locally to: " + saveFile); callback(); } }); } }