diff --git a/bin/index.js b/bin/index.js index 3f73044..de7d78d 100755 --- a/bin/index.js +++ b/bin/index.js @@ -150,7 +150,7 @@ async function run(argv) { try { await start(options); if (options.localhost) { - console.log(`Started throttler on localhost RTT:${options.rtt}ms `); + console.log(`Started throttler on localhost RTT:${options.rtt}ms PL:${options.packetLoss}%`); } else { let message = 'Started throttler:'; if (typeof options.down !== 'undefined') { diff --git a/lib/index.js b/lib/index.js index 062c49c..8574406 100644 --- a/lib/index.js +++ b/lib/index.js @@ -32,7 +32,7 @@ export async function start(options = {}) { switch (platform()) { case 'darwin': { if (options.localhost) { - return startPfctlLocalhost(options.rtt); + return startPfctlLocalhost(options.rtt, options.packetLoss); } return startPfctl( options.up, @@ -44,7 +44,7 @@ export async function start(options = {}) { case 'linux': { return options.localhost - ? startTcLocalhost(options.rtt) + ? startTcLocalhost(options.rtt, options.packetLoss) : startTc(options.up, options.down, options.rtt, options.packetLoss); } diff --git a/lib/localHostPfctl.js b/lib/localHostPfctl.js index 08daa81..b03fe09 100644 --- a/lib/localHostPfctl.js +++ b/lib/localHostPfctl.js @@ -1,7 +1,7 @@ import sudo from './sudo.js'; import shell from './shell.js'; -export async function start(rtt) { +export async function start(rtt, packetLoss=0) { const halfWayRTT = rtt / 2; await stop(); @@ -9,15 +9,18 @@ export async function start(rtt) { await sudo('dnctl', '-q', 'flush'); await sudo('dnctl', '-q', 'pipe', 'flush'); - await sudo( + const parameters = [ 'dnctl', 'pipe', 1, 'config', 'delay', - `${halfWayRTT}ms`, - 'noerror' - ); + `${halfWayRTT}ms` + ]; + if (packetLoss > 0) { + parameters.push('plr', packetLoss / 100, 'noerror'); + } + await sudo.apply(this, parameters); await shell( 'echo "dummynet out from any to 127.0.0.1 pipe 1" | sudo pfctl -f -' diff --git a/lib/localHostTc.js b/lib/localHostTc.js index 19d4d51..8302812 100644 --- a/lib/localHostTc.js +++ b/lib/localHostTc.js @@ -1,6 +1,6 @@ import sudo from './sudo.js'; -export async function start(delay) { +export async function start(delay, packetLoss=0) { const halfWayDelay = delay / 2; try { @@ -9,7 +9,7 @@ export async function start(delay) { // ignore } - await sudo( + const parameters = [ 'tc', 'qdisc', 'add', @@ -21,7 +21,13 @@ export async function start(delay) { 'netem', 'delay', `${halfWayDelay}ms` - ); + ]; + + if (packetLoss) { + parameters.push('loss', `${packetLoss}%`); + } + + await sudo.apply(this, parameters); } export async function stop() { await sudo('tc', 'qdisc', 'del', 'dev', 'lo', 'root');