-
Notifications
You must be signed in to change notification settings - Fork 62
/
ipfsd-daemon.js
407 lines (346 loc) · 9.64 KB
/
ipfsd-daemon.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
'use strict'
const { Multiaddr } = require('multiaddr')
const fs = require('fs').promises
const merge = require('merge-options').bind({ ignoreUndefined: true })
const debug = require('debug')
const execa = require('execa')
const { nanoid } = require('nanoid')
const path = require('path')
const os = require('os')
const { checkForRunningApi, repoExists, tmpDir, defaultRepo, buildInitArgs, buildStartArgs } = require('./utils')
const waitFor = require('p-wait-for')
const daemonLog = {
info: debug('ipfsd-ctl:daemon:stdout'),
err: debug('ipfsd-ctl:daemon:stderr')
}
/**
* @param {Error & { stdout: string, stderr: string }} err
*/
function translateError (err) {
// get the actual error message to be the err.message
err.message = `${err.stdout} \n\n ${err.stderr} \n\n ${err.message} \n\n`
return err
}
/** @typedef {import("./types").ControllerOptions} ControllerOptions */
/**
* Controller for daemon nodes
*
* @class
*
*/
class Daemon {
/**
* @class
* @param {Required<ControllerOptions>} opts
*/
constructor (opts) {
this.opts = opts
this.path = this.opts.ipfsOptions.repo || (opts.disposable ? tmpDir(opts.type) : defaultRepo(opts.type))
this.exec = this.opts.ipfsBin
this.env = merge({ IPFS_PATH: this.path }, this.opts.env)
this.disposable = this.opts.disposable
this.subprocess = null
this.initialized = false
this.started = false
this.clean = true
this.apiAddr = null
this.grpcAddr = null
this.gatewayAddr = null
this.api = null
}
/**
* @private
* @param {string} addr
*/
_setApi (addr) {
this.apiAddr = new Multiaddr(addr)
}
/**
* @private
* @param {string} addr
*/
_setGrpc (addr) {
this.grpcAddr = new Multiaddr(addr)
}
/**
* @private
* @param {string} addr
*/
_setGateway (addr) {
this.gatewayAddr = new Multiaddr(addr)
}
_createApi () {
if (this.opts.ipfsClientModule && this.grpcAddr) {
this.api = this.opts.ipfsClientModule.create({
grpc: this.grpcAddr,
http: this.apiAddr
})
} else if (this.apiAddr) {
this.api = this.opts.ipfsHttpModule.create(this.apiAddr)
}
if (!this.api) {
throw new Error(`Could not create API from http '${this.apiAddr}' and/or gRPC '${this.grpcAddr}'`)
}
if (this.apiAddr) {
this.api.apiHost = this.apiAddr.nodeAddress().address
this.api.apiPort = this.apiAddr.nodeAddress().port
}
if (this.gatewayAddr) {
this.api.gatewayHost = this.gatewayAddr.nodeAddress().address
this.api.gatewayPort = this.gatewayAddr.nodeAddress().port
}
if (this.grpcAddr) {
this.api.grpcHost = this.grpcAddr.nodeAddress().address
this.api.grpcPort = this.grpcAddr.nodeAddress().port
}
}
/**
* Initialize a repo.
*
* @param {import('./types').InitOptions} [initOptions={}]
* @returns {Promise<Daemon>}
*/
async init (initOptions = {}) {
this.initialized = await repoExists(this.path)
if (this.initialized) {
this.clean = false
return this
}
initOptions = merge({
emptyRepo: false,
profiles: this.opts.test ? ['test'] : []
},
typeof this.opts.ipfsOptions.init === 'boolean' ? {} : this.opts.ipfsOptions.init,
typeof initOptions === 'boolean' ? {} : initOptions
)
const opts = merge(
this.opts, {
ipfsOptions: {
init: initOptions
}
}
)
const args = buildInitArgs(opts)
const { stdout, stderr } = await execa(this.exec, args, {
env: this.env
})
.catch(translateError)
daemonLog.info(stdout)
daemonLog.err(stderr)
// default-config only for Go
if (this.opts.type === 'go') {
await this._replaceConfig(merge(
await this._getConfig(),
this.opts.ipfsOptions.config
))
}
this.clean = false
this.initialized = true
return 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.
*
* @returns {Promise<Daemon>}
*/
async cleanup () {
if (!this.clean) {
await fs.rmdir(this.path, {
recursive: true
})
this.clean = true
}
return this
}
/**
* Start the daemon.
*
* @returns {Promise<Daemon>}
*/
async start () {
// Check if a daemon is already running
const api = checkForRunningApi(this.path)
if (api) {
this._setApi(api)
this._createApi()
} else if (!this.exec) {
throw new Error('No executable specified')
} else {
const args = buildStartArgs(this.opts)
let output = ''
const ready = new Promise((resolve, reject) => {
this.subprocess = execa(this.exec, args, {
env: this.env
})
const { stdout, stderr } = this.subprocess
if (!stderr) {
throw new Error('stderr was not defined on subprocess')
}
if (!stdout) {
throw new Error('stderr was not defined on subprocess')
}
stderr.on('data', data => daemonLog.err(data.toString()))
stdout.on('data', data => daemonLog.info(data.toString()))
/**
* @param {Buffer} data
*/
const readyHandler = data => {
output += data.toString()
const apiMatch = output.trim().match(/API .*listening on:? (.*)/)
const gwMatch = output.trim().match(/Gateway .*listening on:? (.*)/)
const grpcMatch = output.trim().match(/gRPC .*listening on:? (.*)/)
if (apiMatch && apiMatch.length > 0) {
this._setApi(apiMatch[1])
}
if (gwMatch && gwMatch.length > 0) {
this._setGateway(gwMatch[1])
}
if (grpcMatch && grpcMatch.length > 0) {
this._setGrpc(grpcMatch[1])
}
if (output.match(/(?:daemon is running|Daemon is ready)/)) {
// we're good
this._createApi()
this.started = true
stdout.off('data', readyHandler)
resolve(this.api)
}
}
stdout.on('data', readyHandler)
this.subprocess.catch(err => reject(translateError(err)))
this.subprocess.on('exit', () => {
this.started = false
stderr.removeAllListeners()
stdout.removeAllListeners()
if (this.disposable) {
this.cleanup().catch(() => {})
}
})
})
await ready
}
this.started = true
// Add `peerId`
const id = await this.api.id()
this.api.peerId = id
return this
}
/**
* Stop the daemon.
*
* @param {object} [options]
* @param {number} [options.timeout=60000] - How long to wait for the daemon to stop
* @returns {Promise<Daemon>}
*/
async stop (options = {}) {
const timeout = options.timeout || 60000
if (!this.started) {
return this
}
if (this.subprocess) {
/** @type {ReturnType<setTimeout> | undefined} */
let killTimeout
const subprocess = this.subprocess
if (this.disposable) {
// we're done with this node and will remove it's repo when we are done
// so don't wait for graceful exit, just terminate the process
this.subprocess.kill('SIGKILL')
} else {
if (this.opts.forceKill !== false) {
killTimeout = setTimeout(() => {
// eslint-disable-next-line no-console
console.error(new Error(`Timeout stopping ${this.opts.type} node after ${this.opts.forceKillTimeout}ms. Process ${subprocess.pid} will be force killed now.`))
this.subprocess && this.subprocess.kill('SIGKILL')
}, this.opts.forceKillTimeout)
}
this.subprocess.cancel()
}
// wait for the subprocess to exit and declare ourselves stopped
await waitFor(() => !this.started, {
timeout
})
if (killTimeout) {
clearTimeout(killTimeout)
}
if (this.disposable) {
// wait for the cleanup routine to run after the subprocess has exited
await waitFor(() => this.clean, {
timeout
})
}
} else {
await this.api.stop()
this.started = false
}
return this
}
/**
* Get the pid of the `ipfs daemon` process.
*
* @returns {Promise<number>}
*/
pid () {
if (this.subprocess && this.subprocess.pid != null) {
return Promise.resolve(this.subprocess.pid)
}
throw new Error('Daemon process is not running.')
}
/**
* Call `ipfs config`
*
* If no `key` is passed, the whole config is returned as an object.
*
* @private
* @param {string} [key] - A specific config to retrieve.
* @returns {Promise<Object | string>}
*/
async _getConfig (key = 'show') {
const {
stdout
} = await execa(
this.exec,
['config', key],
{
env: this.env
})
.catch(translateError)
if (key === 'show') {
return JSON.parse(stdout)
}
return stdout.trim()
}
/**
* Replace the current config with the provided one
*
* @private
* @param {object} config
* @returns {Promise<Daemon>}
*/
async _replaceConfig (config) {
const tmpFile = path.join(os.tmpdir(), nanoid())
await fs.writeFile(tmpFile, JSON.stringify(config))
await execa(
this.exec,
['config', 'replace', `${tmpFile}`],
{ env: this.env }
)
.catch(translateError)
await fs.unlink(tmpFile)
return this
}
/**
* Get the version of ipfs
*
* @returns {Promise<string>}
*/
async version () {
const {
stdout
} = await execa(this.exec, ['version'], {
env: this.env
})
.catch(translateError)
return stdout.trim()
}
}
module.exports = Daemon