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

Commit 4961b26

Browse files
author
Gordon Hall
committed
replace byte convert utils with bytes package, change config to use a single property for allocation, some cleanup, add tests for utils
1 parent fa4b0a2 commit 4961b26

9 files changed

+305
-134
lines changed

bin/storjshare-logs.js

+17-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const utils = require('../lib/utils');
88
const {Tail} = require('tail');
99
const colors = require('colors/safe');
1010
const storjshare_logs = require('commander');
11+
const fs = require('fs');
1112

1213
storjshare_logs
1314
.description('tails the logs for the given share id')
@@ -45,6 +46,21 @@ sock.on('remote', function(rpc) {
4546

4647
let logTail = new Tail(logFilePath);
4748

49+
function getLastLines(filename, lines, callback) {
50+
let chunk = '';
51+
let size = Math.max(0, fs.statSync(filename).size - (lines * 200));
52+
53+
fs.createReadStream(filename, { start: size })
54+
.on('data', function(data) {
55+
chunk += data.toString();
56+
})
57+
.on('end', function() {
58+
chunk = chunk.split('\n').slice(-(lines + 1));
59+
chunk.pop();
60+
callback(chunk);
61+
});
62+
}
63+
4864
function prettyLog(line) {
4965
var output = ' ';
5066

@@ -80,7 +96,7 @@ sock.on('remote', function(rpc) {
8096
parseInt(storjshare_logs.lines) :
8197
20;
8298

83-
utils.getLastLines(logFilePath, numLines, (lines) => {
99+
getLastLines(logFilePath, numLines, (lines) => {
84100
lines.forEach((line) => prettyLog(line));
85101
logTail.on('line', (line) => prettyLog(line));
86102
});

bin/storjshare-start.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ if (!storjshare_start.config) {
1818
process.exit(1);
1919
}
2020

21-
const configPath = path.join(process.cwd(), storjshare_start.config);
21+
const configPath = storjshare_start.config[0] === '/' ?
22+
storjshare_start.config :
23+
path.join(process.cwd(), storjshare_start.config);
2224
const sock = dnode.connect(config.daemonRpcPort);
2325

2426
sock.on('remote', function(rpc) {

example/farmer.config.json

+3-4
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,9 @@
5656
"loggerOutputFile": "",
5757
// Directory path to store contracts and shards
5858
"storagePath": "",
59-
// Amount of space to lease to the network, measured by storageAllocationUnit
60-
"storageAllocationSize": 2,
61-
// Valid options are B, KB, MB, GB, TB
62-
"storageAllocationUnit": "GB",
59+
// Amount of space to lease to the network, as human readable string
60+
// Valid units are B, KB, MB, GB, TB
61+
"storageAllocation": "2GB",
6362
// Periodically report your used and free capacity to Storj Labs to improve
6463
// the network - no personally identifiable information is sent
6564
"enableTelemetryReporting": true

lib/config/farmer.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,7 @@ const config = require('rc')('storjfarmer', {
3939
loggerVerbosity: 3,
4040
loggerOutputFile: null,
4141
storagePath: null,
42-
storageAllocationUnit: 'GB',
43-
storageAllocationSize: 2,
42+
storageAllocation: '2GB',
4443
enableTelemetryReporting: true
4544
});
4645

lib/utils.js

+30-122
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@
44

55
'use strict';
66

7-
var fs = require('fs');
8-
var storj = require('storj-lib');
9-
var bitcore = storj.deps.bitcore;
10-
var du = require('du');
11-
var diskspace = require('fd-diskspace').diskSpace;
12-
var assert = require('assert');
7+
const fs = require('fs');
8+
const storj = require('storj-lib');
9+
const {bitcore} = storj.deps;
10+
const du = require('du');
11+
const diskspace = require('fd-diskspace').diskSpace;
12+
const assert = require('assert');
13+
const bytes = require('bytes');
1314

1415
/**
1516
* Validate the given payout address
1617
* @param {String} address
1718
*/
18-
module.exports._isValidPayoutAddress = function(address) {
19+
exports._isValidPayoutAddress = function(address) {
1920
return bitcore.Address.isValid(address) ||
2021
bitcore.Address.isValid(address, bitcore.Networks.testnet);
2122
};
@@ -24,33 +25,28 @@ module.exports._isValidPayoutAddress = function(address) {
2425
* Validate the given dataserv directory
2526
* @param {String} directory
2627
*/
27-
module.exports._isValidDirectory = function(directory) {
28+
exports._isValidDirectory = function(directory) {
2829
return this.existsSync(directory);
2930
};
3031

3132
/**
3233
* Validate the given size
3334
* @param {String} size
3435
*/
35-
module.exports._isValidSize = function(size) {
36+
exports._isValidSize = function(size) {
3637
return Number(size) > 0 && typeof size !== 'undefined';
3738
};
3839

3940
/**
4041
* Validates a given tab config
4142
* @param {Object} config
4243
*/
43-
module.exports.validate = function(config) {
44+
exports.validate = function(config) {
4445
assert(this._isValidPayoutAddress(config.paymentAddress),
4546
'Invalid payout address');
4647
assert(this._isValidDirectory(config.storagePath), 'Invalid directory');
47-
assert(this._isValidSize(config.storageAllocationSize),
48+
assert(this._isValidSize(bytes.parse(config.storageAllocation)),
4849
'Invalid storage size');
49-
50-
if (!this.existsSync(config.storagePath)) {
51-
fs.mkdirSync(config.storagePath);
52-
}
53-
5450
assert(this._isValidDirectory(config.storagePath),
5551
'Could not create Shard Directory');
5652
};
@@ -59,21 +55,18 @@ module.exports.validate = function(config) {
5955
* Validates the space being allocated exists
6056
* @param {Object} config
6157
*/
62-
module.exports.validateAllocation = function(conf, callback) {
58+
exports.validateAllocation = function(conf, callback) {
6359
const self = this;
6460

6561
self.getFreeSpace(conf.storagePath, function(err, free) {
66-
var allocatedSpace = self.manualConvert({
67-
size: conf.storageAllocationSize,
68-
unit: conf.storageAllocationUnit
69-
}, 'B', 0);
62+
var allocatedSpace = bytes.parse(conf.storageAllocation);
7063

7164
self.getDirectorySize(conf.storagePath, function(err, usedSpaceBytes) {
7265
if (err) {
7366
return callback(err);
7467
}
7568

76-
if (allocatedSpace.size > free + usedSpaceBytes) {
69+
if (allocatedSpace > free + usedSpaceBytes) {
7770
return callback(new Error('Invalid storage size'));
7871
}
7972

@@ -86,7 +79,7 @@ module.exports.validateAllocation = function(conf, callback) {
8679
* Check if file exists
8780
* @param {String} file - Path to file
8881
*/
89-
module.exports.existsSync = function(file) {
82+
exports.existsSync = function(file) {
9083
try {
9184
fs.statSync(file);
9285
} catch(err) {
@@ -96,84 +89,13 @@ module.exports.existsSync = function(file) {
9689
return true;
9790
};
9891

99-
/**
100-
* Converts to a reasonable unit of bytes
101-
* @param {Object} bytes
102-
* @param {Number} precision
103-
*/
104-
module.exports.autoConvert = function(object, precision) {
105-
/*jshint maxcomplexity:10 */
106-
var kilobyte = 1000;
107-
var megabyte = kilobyte * 1000;
108-
var gigabyte = megabyte * 1000;
109-
var terabyte = gigabyte * 1000;
110-
111-
var byteobject = (this.manualConvert(object, 'B'));
112-
var bytes = byteobject.size;
113-
114-
if ((bytes >= kilobyte) && (bytes < megabyte)) {
115-
return this.manualConvert(byteobject, 'KB', (precision || 1));
116-
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
117-
return this.manualConvert(byteobject, 'MB', (precision || 2));
118-
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
119-
return this.manualConvert(byteobject, 'GB', (precision || 3));
120-
} else if (bytes >= terabyte) {
121-
return this.manualConvert(byteobject, 'TB', (precision || 4));
122-
}
123-
124-
return byteobject;
125-
};
126-
127-
/**
128-
* Converts units of bytes to other units
129-
* @param {Object} object to be converted
130-
* @param {String} Unit Object will be converted to
131-
*/
132-
module.exports.manualConvert = function(object, unit, precision) {
133-
const table = {
134-
'B': 0,
135-
'KB': 1,
136-
'MB': 2,
137-
'GB': 3,
138-
'TB': 4
139-
};
140-
141-
precision = (!precision) ? (table[unit] ? table[unit] : 6) : precision;
142-
let diff = table[object.unit] - table[unit];
143-
144-
if (diff < 0) {
145-
return {
146-
size: (object.size / Math.pow(1000, Math.abs(diff))).toFixed(precision),
147-
unit: unit
148-
};
149-
} else if (diff > 0) {
150-
return {
151-
size: (object.size * Math.pow(1000, Math.abs(diff))).toFixed(precision),
152-
unit: unit
153-
};
154-
} else {
155-
return object;
156-
}
157-
};
158-
159-
/**
160-
* find the difference between two file sizes
161-
* @param {Object} object
162-
* @param {Object} object
163-
*/
164-
module.exports.subtract = function(object1, object2) {
165-
const bytes1 = this.manualConvert(object1, 'B');
166-
const bytes2 = this.manualConvert(object2, 'B');
167-
let difference = bytes1.size - bytes2.size;
168-
return this.autoConvert({ size: difference, unit: 'B' });
169-
};
170-
17192
/**
17293
* Recursively determines the size of a directory
17394
* @param {String} dir - Directory to traverse
17495
* @param {Function} callback
17596
*/
176-
module.exports.getDirectorySize = function(dir, callback) {
97+
exports.getDirectorySize = function(dir, callback) {
98+
/* istanbul ignore next */
17799
du(dir, {
178100
filter: function(f) {
179101
return f.indexOf('contracts.db') !== -1 ||
@@ -183,35 +105,35 @@ module.exports.getDirectorySize = function(dir, callback) {
183105
};
184106

185107
/**
186-
* get free space on disk of path
108+
* Get free space on disk of path
187109
* @param {String} path
188110
*/
189-
module.exports.getFreeSpace = function(path, callback) {
190-
var self = this;
191-
192-
if (!this.existsSync(path)) {
111+
/* istanbul ignore next */
112+
exports.getFreeSpace = function(path, callback) {
113+
if (!exports.existsSync(path)) {
193114
return callback(null, 0);
194115
}
195116

196117
diskspace(function(err, result) {
197-
/*jshint maxcomplexity:10 */
118+
/* jshint maxcomplexity:10 */
198119
if (err) {
199120
return callback(err);
200121
}
201122

202-
var free = 0;
123+
let free = 0;
203124

204-
for (var disk in result.disks) {
205-
var diskDrive = disk;
125+
for (let disk in result.disks) {
126+
let diskDrive = disk;
206127

128+
/* istanbul ignore if */
207129
if (process.platform === 'win32') {
208130
diskDrive += ':\\';
209131
}
210132

211-
if (self.existsSync(diskDrive)) {
133+
if (exports.existsSync(diskDrive)) {
212134
if (fs.statSync(path).dev === fs.statSync(diskDrive).dev) {
213-
// The `df` command on linux returns KB by default, so we need to
214-
// convert to bytes.
135+
// NB: The `df` command on gnu+linux returns KB by default
136+
// NB: so we need to convert to bytes.
215137
free = process.platform === 'win32' ?
216138
result.disks[disk].free :
217139
result.disks[disk].free * 1000;
@@ -223,17 +145,3 @@ module.exports.getFreeSpace = function(path, callback) {
223145
});
224146
};
225147

226-
exports.getLastLines = function(filename, lines, callback) {
227-
let chunk = '';
228-
let size = Math.max(0, fs.statSync(filename).size - (lines * 200));
229-
230-
fs.createReadStream(filename, { start: size })
231-
.on('data', function(data) {
232-
chunk += data.toString();
233-
})
234-
.on('end', function() {
235-
chunk = chunk.split('\n').slice(-(lines + 1));
236-
chunk.pop();
237-
callback(chunk);
238-
});
239-
};

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
},
4141
"homepage": "https://github.com/storj/storjshare-daemon#readme",
4242
"dependencies": {
43+
"bytes": "^2.4.0",
4344
"cli-table": "^0.3.1",
4445
"colors": "^1.1.2",
4546
"commander": "^2.9.0",

script/farmer.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,9 @@ const utils = require('../lib/utils');
66
const storj = require('storj-lib');
77
const Logger = require('kad-logger-json');
88
const config = JSON.parse(JSON.stringify(require('../lib/config/farmer')));
9+
const bytes = require('bytes');
910

10-
let spaceAllocation = storj.utils.toNumberBytes(
11-
config.storageAllocationSize,
12-
config.storageAllocationUnit
13-
);
11+
let spaceAllocation = bytes.parse(config.storageAllocation);
1412
let farmerState = {
1513
percentUsed: '...',
1614
totalPeers: 0,

0 commit comments

Comments
 (0)