Skip to content

Commit

Permalink
added debug port forwarder
Browse files Browse the repository at this point in the history
  • Loading branch information
vpalmisano committed May 15, 2024
1 parent efdc869 commit 6e9ff1a
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 17 deletions.
3 changes: 1 addition & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,8 +525,7 @@ will listen on the provided port + the start-session-id value.`,
arg: 'debugging-port',
},
debuggingAddress: {
doc: `The chrome debugging listen address. Valid only if \`debugging-port\` \
is provided.`,
doc: `The chrome debugging listening address. If unset, the network default interface address will be used.`,
format: String,
nullable: true,
default: '127.0.0.1',
Expand Down
21 changes: 17 additions & 4 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
logger,
PeerConnectionExternal,
PeerConnectionExternalMethod,
portForwarder,
resolveIP,
resolvePackagePath,
sha256,
Expand Down Expand Up @@ -238,6 +239,7 @@ export class Session extends EventEmitter {
private running = false
private browser?: Browser
private context?: BrowserContext
private stopPortForwarder?: () => void

/** The numeric id assigned to the session. */
readonly id: number
Expand Down Expand Up @@ -359,7 +361,7 @@ export class Session extends EventEmitter {
this.windowHeight = windowHeight || 1080
this.deviceScaleFactor = deviceScaleFactor || 1
this.debuggingPort = debuggingPort || 0
this.debuggingAddress = debuggingAddress || '127.0.0.1'
this.debuggingAddress = debuggingAddress || ''
this.display = display
/* this.audioRedForOpus = !!audioRedForOpus */
this.url = url
Expand Down Expand Up @@ -536,7 +538,6 @@ export class Session extends EventEmitter {
`--remote-debugging-port=${
this.debuggingPort ? this.debuggingPort + this.id : 0
}`,
`--remote-debugging-address=${this.debuggingAddress}`,
]

// 'WebRTC-VP8ConferenceTemporalLayers/2',
Expand Down Expand Up @@ -680,7 +681,7 @@ exec sg ${group} -c /tmp/webrtcperf-launcher-${mark}-browser`,

try {
// log.debug('defaultArgs:', puppeteer.defaultArgs());
this.browser = (await puppeteer.launch({
this.browser = await puppeteer.launch({
headless: this.display ? false : 'new',
executablePath,
handleSIGINT: false,
Expand All @@ -698,7 +699,7 @@ exec sg ${group} -c /tmp/webrtcperf-launcher-${mark}-browser`,
},
ignoreDefaultArgs,
args,
})) as Browser
})
// const version = await this.browser.version();
// console.log(`[session ${this.id}] Using chrome version: ${version}`);
} catch (err) {
Expand All @@ -710,6 +711,14 @@ exec sg ${group} -c /tmp/webrtcperf-launcher-${mark}-browser`,
}

assert(this.browser, 'BrowserNotCreated')

if (this.debuggingPort && this.debuggingAddress !== '127.0.0.1') {
this.stopPortForwarder = await portForwarder(
this.debuggingPort + this.id,
this.debuggingAddress,
)
}

this.browser.once('disconnected', () => {
log.warn('browser disconnected')
return this.stop()
Expand Down Expand Up @@ -1709,6 +1718,10 @@ window.SERVER_USE_HTTPS = ${this.serverUseHttps};
this.running = false
log.info(`${this.id} stop`)

if (this.stopPortForwarder) {
this.stopPortForwarder()
}

if (this.browser) {
// close the opened tabs
log.debug(`${this.id} closing ${this.pages.size} pages`)
Expand Down
18 changes: 8 additions & 10 deletions src/throttle.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import JSON5 from 'json5'
import os from 'os'

import { logger, runShellCommand, toPrecision } from './utils'
import {
getDefaultNetworkInterface,
logger,
runShellCommand,
toPrecision,
} from './utils'

const log = logger('webrtcperf:throttle')

Expand Down Expand Up @@ -35,21 +40,14 @@ const throttleCurrentValues = {
>(),
}

async function getDefaultInterface(): Promise<string> {
const { stdout } = await runShellCommand(
`ip route | awk '/default/ {print $5; exit}' | tr -d ''`,
)
return stdout.trim()
}

async function cleanup(): Promise<void> {
ruleTimeouts.forEach(timeoutId => clearTimeout(timeoutId))
ruleTimeouts.clear()
throttleCurrentValues.up.clear()
throttleCurrentValues.down.clear()
let device = throttleConfig?.length ? throttleConfig[0].device : ''
if (!device) {
device = await getDefaultInterface()
device = await getDefaultNetworkInterface()
}
await runShellCommand(`\
sudo -n tc qdisc del dev ${device} root || true;
Expand Down Expand Up @@ -253,7 +251,7 @@ async function start(): Promise<void> {

let device = throttleConfig[0].device
if (!device) {
device = await getDefaultInterface()
device = await getDefaultNetworkInterface()
}

await runShellCommand(
Expand Down
53 changes: 52 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import FormData from 'form-data'
import fs, { createWriteStream, WriteStream } from 'fs'
import { Agent } from 'https'
import * as ipaddrJs from 'ipaddr.js'
import net from 'net'
import NodeCache from 'node-cache'
import * as OSUtils from 'node-os-utils'
import os from 'os'
import os, { networkInterfaces } from 'os'
import path, { dirname } from 'path'
import pidtree from 'pidtree'
import pidusage from 'pidusage'
Expand Down Expand Up @@ -1008,3 +1009,53 @@ export function toPrecision(value: number, precision = 3): string {
precision,
)
}

export async function getDefaultNetworkInterface(): Promise<string> {
const { stdout } = await runShellCommand(
`ip route | awk '/default/ {print $5; exit}' | tr -d ''`,
)
return stdout.trim()
}

export async function portForwarder(port: number, listenInterface?: string) {
if (!listenInterface) {
listenInterface = await getDefaultNetworkInterface()
}
const controller = new AbortController()
Object.entries(networkInterfaces()).forEach(([iface, nets]) => {
if (listenInterface !== '0.0.0.0' && iface !== listenInterface) return
if (!nets) return
for (const n of nets) {
if (n.internal || n.address === '127.0.0.1' || n.family !== 'IPv4') {
continue
}
const msg = `portForwarder on ${iface} (${n.address}:${port})`
const server = net
.createServer(from => {
const to = net.createConnection({ host: '127.0.0.1', port })
from.once('error', err => {
log.error(`${msg} error: ${(err as Error).stack}`)
to.destroy()
})
to.once('error', err => {
log.error(`${msg} error: ${(err as Error).stack}`)
from.destroy()
})
from.pipe(to)
to.pipe(from)
})
.listen({ port, host: n.address, signal: controller.signal })
server.on('listening', () => {
log.debug(`${msg} listening`)
})
server.once('error', err => {
log.error(`${msg} error: ${(err as Error).stack}`)
})
}
})

return () => {
log.debug(`portForwarder on port ${port} stop`)
controller.abort()
}
}

0 comments on commit 6e9ff1a

Please sign in to comment.