-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
331 lines (278 loc) · 7.38 KB
/
index.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
/* eslint no-await-in-loop: 0 */
import path from 'node:path';
import fs from 'node:fs/promises';
import {createWriteStream} from 'node:fs';
import {once, EventEmitter} from 'node:events';
import childProcess from 'node:child_process';
import {pipeline} from 'node:stream/promises';
import {promisify} from 'node:util';
import {fileURLToPath} from 'node:url';
import {createServer} from 'node:net';
import {setTimeout} from 'node:timers/promises';
import AMI from 'ami';
import pMap from 'p-map';
import which from 'which';
import vinylFS from 'vinyl-fs';
import {FixtureRunDirectory} from '@cfware/fixture-run-directory';
const execFile = promisify(childProcess.execFile);
const __dirname = fileURLToPath(path.dirname(import.meta.url));
const findAddressOctets = [127, 0, 0, 0];
let addressesDepleted = false;
function nextAddress() {
let octet = 3;
if (!addressesDepleted) {
while (octet > 0) {
findAddressOctets[octet]++;
if (findAddressOctets[octet] < 255) {
return findAddressOctets.join('.');
}
findAddressOctets[octet] = 0;
octet--;
}
}
addressesDepleted = true;
throw new Error('Out of addresses');
}
async function copyFiles(source, destination) {
await pipeline(vinylFS.src(source), vinylFS.dest(destination));
}
export class AsteriskInstance extends FixtureRunDirectory {
#serverHold = createServer();
#astdirs = {
astetcdir: 'etc/asterisk',
astvarlibdir: 'var/lib/asterisk',
astdbdir: 'var/spool',
astkeydir: 'var/lib/asterisk',
astdatadir: 'var/lib/asterisk',
astspooldir: 'var/spool',
astrundir: 'run',
astlogdir: 'var/log'
};
asteriskConf = this.astdir('astetcdir', 'asterisk.conf');
directories = Object.keys(this.#astdirs);
amiEvents = new EventEmitter();
collectEvents(name) {
const list = [];
const collectionCB = asObject => list.push(asObject);
this.amiEvents.on(name, collectionCB);
return {
list,
stop: () => this.amiEvents.off(name, collectionCB)
};
}
astdir(key, ...args) {
return this.runPath(this.#astdirs[key], ...args);
}
async installConfigs(id) {
await copyFiles(
this.fixturePath(`asterisk-${id}/**/*.conf`),
this.astdir('astetcdir')
);
}
assignAddress() {
if (this.serverAddress) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
let address;
const listen = () => {
address = nextAddress();
this.#serverHold.listen(29999, address);
};
this.#serverHold.on('error', error => {
if (error.code !== 'EADDRINUSE') {
return reject(error);
}
this.#serverHold.close();
listen();
});
this.#serverHold.on('listening', () => {
this.serverAddress = address;
resolve();
});
listen();
});
}
async build() {
await this.assignAddress();
this.ami = new AMI({
connect: {
host: this.serverAddress,
port: 5038
}
});
this.ami.on('event', ({asObject}) => {
this.amiEvents.emit(asObject.event.toLowerCase(), asObject);
});
this.bin = await which('asterisk');
const directories = Object.fromEntries(this.directories.map(id => [id, ['']]));
Object.assign(directories, {
astvarlibdir: [
'keys',
'moh',
'documentation',
'sounds/en/silence'
],
astetcdir: [
'acl.d',
'cli_permissions.d',
'confbridge.d',
'extensions.d',
'http.d',
'manager.d',
'musiconhold.d',
'pjsip.d',
'sorcery.d'
]
});
/* Make directories */
await pMap(
Object.entries(directories).flatMap(
([key, directories]) => directories.map(directory => this.astdir(key, directory))
),
directory => fs.mkdir(directory, {recursive: true})
);
await fs.writeFile(this.runPath('asterisk'), [
'#!/usr/bin/env sh',
`exec ${this.bin} -C "${this.asteriskConf}" "$@"`,
''
].join('\n'));
await fs.chmod(this.runPath('asterisk'), 0o775);
/* Copy documentation */
await copyFiles(
path.join(__dirname, 'documentation/**'),
this.astdir('astvarlibdir', 'documentation')
);
/* Copy audio */
await copyFiles(
path.join(__dirname, 'sounds/**'),
this.astdir('astvarlibdir', 'sounds/en')
);
/* Copy initial generic configs */
await copyFiles(
path.join(__dirname, 'configs/**'),
this.astdir('astetcdir')
);
/* Generate IP based configs */
await fs.writeFile(this.astdir('astetcdir', 'bindaddr.conf'), `bindaddr=${this.serverAddress}\n`);
await fs.writeFile(this.astdir('astetcdir', 'pjsip-bind.conf'), `bind=${this.serverAddress}:5060\n`);
/* Copy user provided configs */
await this.installConfigs(this.instanceID);
/* Generate basic asterisk.conf for directories */
await fs.writeFile(this.astdir('astetcdir', 'asterisk.conf'), [
'[directories]',
...this.directories.map(id => `${id}=${this.astdir(id)}`),
'',
`#include ${this.astdir('astetcdir', 'asterisk-options.conf')}`,
''
].join('\n'));
}
async start() {
this.asteriskProcess = execFile(this.bin, [
'-f',
'-C',
this.asteriskConf
]);
try {
await this.fullyBooted();
} catch (error) {
this.asteriskProcess.child.kill(9);
this.asteriskProcess = undefined;
throw error;
}
this.ami.on('event', packet => {
if (this.amiTracer) {
this.amiTracer.write(',\n\t');
} else {
this.amiTracer = createWriteStream(this.astdir('astlogdir', 'ami-events.json'));
this.amiTracer.write('[\n\t');
}
this.amiTracer.write(JSON.stringify(packet.asObject));
});
await this.ami.connect();
}
get _refdebugLog() {
return this.astdir('astlogdir', 'refs');
}
async _refdebugEnabled() {
try {
await fs.stat(this._refdebugLog);
return true;
} catch {
return false;
}
}
async stop() {
if (!this.asteriskProcess) {
return;
}
const {asteriskProcess} = this;
this.asteriskProcess = undefined;
if (await this._refdebugEnabled()) {
await setTimeout(6400);
}
await this.cliCommand('core stop gracefully').catch(() => {});
await asteriskProcess;
this.ami.removeAllListeners('event');
if (this.amiTracer) {
this.amiTracer.end('\n]');
await once(this.amiTracer, 'close');
}
this.#serverHold.unref();
}
async checkStopped() {
const python = await which('python3');
if (await this._refdebugEnabled()) {
await execFile(python, [
path.join(__dirname, 'scripts/refcounter.py'),
'-f',
this._refdebugLog,
'-n'
]);
}
}
cliCommand(command) {
if (!this.bin) {
throw new Error('Not started');
}
return execFile(this.bin, [
'-C',
this.asteriskConf,
'-rx',
command
]);
}
async fullyBooted() {
let attempt = 0;
while (attempt < 100) {
try {
await setTimeout(100);
await this.cliCommand('core waitfullybooted');
return;
} catch {
attempt++;
}
}
throw new Error('Failed to start asterisk');
}
}
export function setupIntegrationAMITesting(tap, integrationInstance) {
const {Test} = tap;
Test.addAssert('checkAMIEvents', 2, async function ({instanceID, watch, expect, execute}, message, extra) {
const {ami} = integrationInstance[instanceID ?? 'defaultInstance'];
watch = [].concat(watch).map(eventName => eventName.toLowerCase());
const events = [];
const listener = ({asObject}) => {
if (watch.includes(asObject.event.toLowerCase())) {
events.push(asObject);
}
};
ami.on('event', listener);
const result = await execute();
await setTimeout(50);
ami.off('event', listener);
this.equal(events.length, expect.length, 'events.length matches', extra);
this.match(events, expect, message || 'events match', extra);
return result;
});
}