Skip to content
This repository has been archived by the owner on Oct 30, 2018. It is now read-only.

Commit

Permalink
Merge pull request #62 from bookchin/master
Browse files Browse the repository at this point in the history
v2.3.0
  • Loading branch information
bookchin authored Feb 6, 2017
2 parents 784182f + e260383 commit b2bbb46
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 72 deletions.
1 change: 1 addition & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"laxbreak": true,
"bitwise": false,
"browser": true,
"camelcase": false,
Expand Down
25 changes: 21 additions & 4 deletions bin/storjshare-daemon.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,39 @@ const daemonize = require('daemon');
const dnode = require('dnode');
const config = require('../lib/config/daemon');
const RPC = require('../lib/api');
const utils = require('../lib/utils');
const api = new RPC({ logVerbosity: config.daemonLogVerbosity });
const {createWriteStream} = require('fs');
const logFile = createWriteStream(config.daemonLogFilePath, { flags: 'a' });
const storjshare_daemon = require('commander');

storjshare_daemon
.option('--status', 'print the status of the daemon and exit')
.option('-F, --foreground', 'keeps the process in the foreground')
.parse(process.argv);

if (!storjshare_daemon.foreground) {
function startDaemonRpcServer() {
dnode(api.methods)
.on('error', (err) => api.logger.warn(err.message))
.listen(config.daemonRpcPort, config.daemonRpcAddress);
}

function checkDaemonRpcStatus() {
utils.checkDaemonRpcStatus(config.daemonRpcPort, (isRunning) => {
console.info(`\n * daemon ${isRunning ? 'is' : 'is not'} running`);
process.exitCode = isRunning ? 0 : 3;
});
}

if (storjshare_daemon.status) {
checkDaemonRpcStatus();
} else if (!storjshare_daemon.foreground) {
daemonize();
api.logger.pipe(logFile);
startDaemonRpcServer();
} else {
api.logger.pipe(process.stdout);
startDaemonRpcServer();
}

dnode(api.methods)
.on('error', (err) => api.logger.warn(err.message))
.listen(config.daemonRpcPort, config.daemonRpcAddress);

99 changes: 49 additions & 50 deletions bin/storjshare-logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,52 @@ if (!storjshare_logs.nodeid) {
process.exit(1);
}

function getLastLines(filename, lines, callback) {
let chunk = '';
let size = Math.max(0, fs.statSync(filename).size - (lines * 200));

fs.createReadStream(filename, { start: size })
.on('data', function(data) {
chunk += data.toString();
})
.on('end', function() {
chunk = chunk.split('\n').slice(-(lines + 1));
chunk.pop();
callback(chunk);
});
}

function prettyLog(line) {
var output = ' ';

try {
line = JSON.parse(line);
} catch (err) {
return;
}

switch (line.level) {
case 'debug':
output += colors.magenta('[ debug ] ');
break;
case 'info':
output += colors.cyan('[ info ] ');
break;
case 'warn':
output += colors.yellow('[ warn ] ');
break;
case 'error':
output += colors.red('[ error ] ');
break;
default:
// noop
}

output += colors.gray( `[ ${line.timestamp} ]\n [ `);
output += `${line.message}`;
console.log(output);
}

const sock = dnode.connect(config.daemonRpcPort);

process.on('exit', () => {
Expand Down Expand Up @@ -50,56 +96,9 @@ sock.on('remote', function(rpc) {
}

let logTail = new Tail(logFilePath);

function getLastLines(filename, lines, callback) {
let chunk = '';
let size = Math.max(0, fs.statSync(filename).size - (lines * 200));

fs.createReadStream(filename, { start: size })
.on('data', function(data) {
chunk += data.toString();
})
.on('end', function() {
chunk = chunk.split('\n').slice(-(lines + 1));
chunk.pop();
callback(chunk);
});
}

function prettyLog(line) {
var output = ' ';

try {
line = JSON.parse(line);
} catch (err) {
return;
}

switch (line.level) {
case 'debug':
output += colors.magenta('[ debug ] ');
break;
case 'info':
output += colors.cyan('[ info ] ');
break;
case 'warn':
output += colors.yellow('[ warn ] ');
break;
case 'error':
output += colors.red('[ error ] ');
break;
default:
// noop
}

output += colors.gray( `[ ${line.timestamp} ]\n [ `)
output += `${line.message}`;
console.log(output);
}

let numLines = storjshare_logs.lines ?
parseInt(storjshare_logs.lines) :
20;
let numLines = storjshare_logs.lines
? parseInt(storjshare_logs.lines)
: 20;

getLastLines(logFilePath, numLines, (lines) => {
lines.forEach((line) => prettyLog(line));
Expand Down
1 change: 0 additions & 1 deletion bin/storjshare-start.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

'use strict';

const storj = require('storj-lib');
const dnode = require('dnode');
const path = require('path');
const config = require('../lib/config/daemon');
Expand Down
24 changes: 12 additions & 12 deletions bin/storjshare.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

'use strict';

const net = require('net');
const config = require('../lib/config/daemon');
const storjshare = require('commander');
const {fork} = require('child_process');
const path = require('path');
const utils = require('../lib/utils');
const {version} = require('../package');
const {software: core, protocol} = require('storj-lib').version;

const TIME_WAIT_IF_STARTED = 1000;
const TIME_WAIT_AFTER_START = 6000;

storjshare
.version(`\n * daemon: ${version}, core: ${core}, protocol: ${protocol}`)
.command('start', 'start a farming node')
Expand All @@ -25,17 +28,14 @@ storjshare
.command('daemon', 'starts the daemon');

if (!['daemon'].includes(process.argv[2])) {
const sock = net.connect(config.daemonRpcPort);

sock.once('error', function() {
console.info('\n * daemon is not running, starting...');
fork(path.join(__dirname, 'storjshare-daemon.js'), []);
setTimeout(() => storjshare.parse(process.argv), 4000);
});

sock.once('connect', function() {
sock.end();
setTimeout(() => storjshare.parse(process.argv), 1000);
utils.checkDaemonRpcStatus(config.daemonRpcPort, (isRunning) => {
if (isRunning) {
setTimeout(() => storjshare.parse(process.argv), TIME_WAIT_IF_STARTED);
} else {
console.info('\n * daemon is not running, starting...');
fork(path.join(__dirname, 'storjshare-daemon.js'), []);
setTimeout(() => storjshare.parse(process.argv), TIME_WAIT_AFTER_START);
}
});
} else {
storjshare.parse(process.argv);
Expand Down
19 changes: 18 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

'use strict';

const net = require('net');
const fs = require('fs');
const storj = require('storj-lib');
const {bitcore} = storj.deps;
Expand Down Expand Up @@ -34,7 +35,7 @@ exports._isValidDirectory = function(directory) {
* @param {String} size
*/
exports._isValidSize = function(size) {
return Number(size) > 0 && typeof size !== 'undefined';
return Number(size) >= 0 && typeof size !== 'undefined';
};

/**
Expand Down Expand Up @@ -145,3 +146,19 @@ exports.getFreeSpace = function(path, callback) {
});
};

/**
* Checks the status of the daemon RPC server
* @param {Number} port
*/
exports.checkDaemonRpcStatus = function(port, callback) {
const sock = net.connect(port);

sock.once('error', function() {
callback(false);
});

sock.once('connect', () => {
sock.end();
callback(true);
});
};
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "storjshare-daemon",
"version": "2.2.0",
"version": "2.3.0",
"description": "daemon + process manager for sharing space on the storj network",
"main": "index.js",
"bin": {
Expand All @@ -25,7 +25,7 @@
"test": "npm run testsuite && npm run linter",
"testsuite": "STORJ_ALLOW_LOOPBACK=1 ./node_modules/.bin/mocha test/** --recursive",
"coverage": "STORJ_ALLOW_LOOPBACK=1 ./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --recursive",
"linter": "./node_modules/.bin/jshint --config .jshintrc ./index.js ./lib ./test"
"linter": "./node_modules/.bin/jshint --config .jshintrc ./index.js ./lib ./test ./bin"
},
"preferGlobal": true,
"repository": {
Expand Down
44 changes: 42 additions & 2 deletions test/utils.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const utils = require('../lib/utils');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const {expect} = require('chai');
const {EventEmitter} = require('events');

describe('module:utils', function() {

Expand Down Expand Up @@ -51,8 +52,8 @@ describe('module:utils', function() {
expect(utils._isValidSize(1)).to.equal(true);
});

it('should return false for 0 or less', function() {
expect(utils._isValidSize(0)).to.equal(false);
it('should return false for less than 0', function() {
expect(utils._isValidSize(0)).to.equal(true);
expect(utils._isValidSize(-1)).to.equal(false);
});

Expand Down Expand Up @@ -182,4 +183,43 @@ describe('module:utils', function() {

});

describe('#checkDaemonRpcStatus', function() {

it('should callback true if connect', function(done) {
let sock = new EventEmitter();
sock.end = sinon.stub();
let _utils = proxyquire('../lib/utils', {
net: {
connect: () => {
setTimeout(() => sock.emit('connect'), 50);
return sock;
}
}
});
_utils.checkDaemonRpcStatus(45015, (isRunning) => {
expect(isRunning).to.equal(true);
done();
});
});

it('should callback false if error', function(done) {
let sock = new EventEmitter();
sock.end = sinon.stub();
let _utils = proxyquire('../lib/utils', {
net: {
connect: () => {
setTimeout(() => sock.emit('error',
new Error('ECONNREFUSED')), 50);
return sock;
}
}
});
_utils.checkDaemonRpcStatus(45015, (isRunning) => {
expect(isRunning).to.equal(false);
done();
});
});

});

});

0 comments on commit b2bbb46

Please sign in to comment.