-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathnode.js
376 lines (330 loc) · 8.79 KB
/
node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
'use strict'
const fs = require('fs')
const async = require('async')
const ipfs = require('ipfs-api')
const multiaddr = require('multiaddr')
const rimraf = require('rimraf')
const shutdown = require('shutdown')
const path = require('path')
const join = path.join
const once = require('once')
const exec = require('./exec')
const ipfsDefaultPath = findIpfsExecutable()
const GRACE_PERIOD = 7500 // amount of ms to wait before sigkill
function findIpfsExecutable () {
const rootPath = process.env.testpath ? process.env.testpath : __dirname
let appRoot = path.join(rootPath, '..')
// If inside <appname>.asar try to load from .asar.unpacked
// this only works if asar was built with
// asar --unpack-dir=node_modules/go-ipfs-dep/* (not tested)
// or
// electron-packager ./ --asar.unpackDir=node_modules/go-ipfs-dep
if (appRoot.includes(`.asar${path.sep}`)) {
appRoot = appRoot.replace(`.asar${path.sep}`, `.asar.unpacked${path.sep}`)
}
const depPath = path.join('go-ipfs-dep', 'go-ipfs', 'ipfs')
const npm3Path = path.join(appRoot, '../', depPath)
const npm2Path = path.join(appRoot, 'node_modules', depPath)
try {
fs.statSync(npm3Path)
return npm3Path
} catch (e) {
return npm2Path
}
}
function setConfigValue (node, key, value, callback) {
exec(
node.exec,
['config', key, value, '--json'],
{env: node.env},
callback
)
}
function configureNode (node, conf, callback) {
async.eachOfSeries(conf, (value, key, cb) => {
setConfigValue(node, key, JSON.stringify(value), cb)
}, callback)
}
function tryJsonParse (input, callback) {
let res
try {
res = JSON.parse(input)
} catch (err) {
return callback(err)
}
callback(null, res)
}
// Consistent error handling
function parseConfig (path, callback) {
async.waterfall([
(cb) => fs.readFile(join(path, 'config'), cb),
(file, cb) => tryJsonParse(file.toString(), cb)
], callback)
}
/**
* Controll a go-ipfs node.
*/
class Node {
/**
* Create a new node.
*
* @param {string} path
* @param {Object} [opts]
* @param {Object} [opts.env={}] - Additional environment settings, passed to executing shell.
* @param {boolean} [disposable=false] - Should this be a temporary node.
* @returns {Node}
*/
constructor (path, opts, disposable) {
this.path = path
this.opts = opts || {}
this.exec = process.env.IPFS_EXEC || ipfsDefaultPath
this.subprocess = null
this.initialized = fs.existsSync(path)
this.clean = true
this.env = Object.assign({}, process.env, {IPFS_PATH: path})
this.disposable = disposable
this._apiAddr = null
this._gatewayAddr = null
if (this.opts.env) {
Object.assign(this.env, this.opts.env)
}
}
/**
* Get the address of connected IPFS API.
*
* @returns {Multiaddr}
*/
get apiAddr () {
return this._apiAddr
}
/**
* Get the address of connected IPFS HTTP Gateway.
*
* @returns {Multiaddr}
*/
get gatewayAddr () {
return this._gatewayAddr
}
_run (args, opts, callback) {
return exec(this.exec, args, opts, callback)
}
/**
* Initialize a repo.
*
* @param {Object} [initOpts={}]
* @param {number} [initOpts.keysize=2048] - The bit size of the identiy key.
* @param {string} [initOpts.directory=IPFS_PATH] - The location of the repo.
* @param {function (Error, Node)} callback
* @returns {undefined}
*/
init (initOpts, callback) {
if (!callback) {
callback = initOpts
initOpts = {}
}
const keySize = initOpts.keysize || 2048
if (initOpts.directory && initOpts.directory !== this.path) {
this.path = initOpts.directory
this.env.IPFS_PATH = this.path
}
this._run(['init', '-b', keySize], {env: this.env}, (err, result) => {
if (err) {
return callback(err)
}
configureNode(this, this.opts, (err) => {
if (err) {
return callback(err)
}
this.clean = false
this.initialized = true
callback(null, this)
})
})
if (this.disposable) {
shutdown.addHandler('disposable', 1, this.shutdown.bind(this))
}
}
/**
* Delete the repo that was being used.
* If the node was marked as `disposable` this will be called
* automatically when the process is exited.
*
* @param {function(Error)} callback
* @returns {undefined}
*/
shutdown (callback) {
if (this.clean || !this.disposable) {
return callback()
}
rimraf(this.path, callback)
}
/**
* Start the daemon.
*
* @param {Array<string>} [flags=[]] - Flags to be passed to the `ipfs daemon` command.
* @param {function(Error, IpfsApi)} callback
* @returns {undefined}
*/
startDaemon (flags, callback) {
if (typeof flags === 'function') {
callback = flags
flags = []
}
const args = ['daemon'].concat(flags)
callback = once(callback)
parseConfig(this.path, (err, conf) => {
if (err) {
return callback(err)
}
this.subprocess = this._run(args, {env: this.env}, {
error: (err) => {
// Only look at the last error
const input = String(err)
.split('\n')
.map((l) => l.trim())
.filter(Boolean)
.slice(-1)[0] || ''
if (input.match('daemon is running')) {
// we're good
return callback(null, this.api)
}
// ignore when kill -9'd
if (!input.match('non-zero exit code')) {
callback(err)
}
},
data: (data) => {
const str = String(data).trim()
const match = str.match(/API server listening on (.*)/)
const gwmatch = str.match(/Gateway (.*) listening on (.*)/)
if (match) {
this._apiAddr = multiaddr(match[1])
this.api = ipfs(match[1])
this.api.apiHost = this.apiAddr.nodeAddress().address
this.api.apiPort = this.apiAddr.nodeAddress().port
if (gwmatch) {
this._gatewayAddr = multiaddr(gwmatch[2])
this.api.gatewayHost = this.gatewayAddr.nodeAddress().address
this.api.gatewayPort = this.gatewayAddr.nodeAddress().port
}
callback(null, this.api)
}
}
})
})
}
/**
* Stop the daemon.
*
* @param {function(Error)} callback
* @returns {undefined}
*/
stopDaemon (callback) {
if (!callback) {
callback = () => {}
}
if (!this.subprocess) {
return callback()
}
this.killProcess(callback)
}
/**
* Kill the `ipfs daemon` process.
*
* First `SIGTERM` is sent, after 7.5 seconds `SIGKILL` is sent
* if the process hasn't exited yet.
*
* @param {function()} callback - Called when the process was killed.
* @returns {undefined}
*/
killProcess (callback) {
// need a local var for the closure, as we clear the var.
const subprocess = this.subprocess
const timeout = setTimeout(() => {
subprocess.kill('SIGKILL')
callback()
}, GRACE_PERIOD)
subprocess.once('close', () => {
clearTimeout(timeout)
this.subprocess = null
callback()
})
subprocess.kill('SIGTERM')
this.subprocess = null
}
/**
* Get the pid of the `ipfs daemon` process.
*
* @returns {number}
*/
daemonPid () {
return this.subprocess && this.subprocess.pid
}
/**
* Call `ipfs config`
*
* If no `key` is passed, the whole config is returned as an object.
*
* @param {string} [key] - A specific config to retrieve.
* @param {function(Error, (Object|string))} callback
* @returns {undefined}
*/
getConfig (key, callback) {
if (typeof key === 'function') {
callback = key
key = 'show'
}
async.waterfall([
(cb) => this._run(
['config', key],
{env: this.env},
cb
),
(config, cb) => {
if (!key) {
return tryJsonParse(config, cb)
}
cb(null, config.trim())
}
], callback)
}
/**
* Set a config value.
*
* @param {string} key
* @param {string} value
* @param {function(Error)} callback
* @returns {undefined}
*/
setConfig (key, value, callback) {
this._run(
['config', key, value, '--json'],
{env: this.env},
callback
)
}
/**
* Replace the configuration with a given file
*
* @param {string} file - path to the new config file
* @param {function(Error)} callback
* @returns {undefined}
*/
replaceConf (file, callback) {
this._run(
['config', 'replace', file],
{env: this.env},
callback
)
}
/**
* Get the version of ipfs
*
* @param {function(Error, string)} callback
* @returns {undefined}
*/
version (callback) {
this._run(['version'], {env: this.env}, callback)
}
}
module.exports = Node