Skip to content

Instantly share code, notes, and snippets.

@howardjohn
Created July 7, 2023 21:36
Show Gist options
  • Save howardjohn/d8794e92bf4b901249d79b09b224a93a to your computer and use it in GitHub Desktop.
Save howardjohn/d8794e92bf4b901249d79b09b224a93a to your computer and use it in GitHub Desktop.
A CLI to upload a trace to perfetto. There must be a better way, but... here it is.
#!/bin/bash
t="$(mktemp -d)"
cp "${1:?file to trace}" "$t/trace"
cat <<'EOF' > "$t/index.html"
<!doctype html>
<html lang="en-us">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
<body>
<pre id="logs" cols="80" rows="20"></pre>
<script type="text/javascript">
const ORIGIN = 'https://ui.perfetto.dev';
const logs = document.getElementById('logs');
const btnFetch = document.getElementById('btn_fetch');
async function fetchAndOpen(traceUrl) {
logs.innerText += `Fetching trace from ${traceUrl}...\n`;
const resp = await fetch(traceUrl, {mode:"no-cors"});
// Error checcking is left as an exercise to the reader.
const blob = await resp.blob();
const arrayBuffer = await blob.arrayBuffer();
logs.innerText += `fetch() complete, now passing to ui.perfetto.dev\n`;
openTrace(arrayBuffer, traceUrl);
setTimeout(function () {
window.close();
}, 5000);
}
function openTrace(arrayBuffer, traceUrl) {
const win = window.open(ORIGIN);
if (!win) {
btnFetch.style.background = '#f3ca63';
btnFetch.onclick = () => openTrace(arrayBuffer);
logs.innerText += `Popups blocked, you need to manually click the button`;
btnFetch.innerText = 'Popups blocked, click here to open the trace file';
return;
}
const timer = setInterval(() => win.postMessage('PING', ORIGIN), 50);
const onMessageHandler = (evt) => {
if (evt.data !== 'PONG') return;
// We got a PONG, the UI is ready.
window.clearInterval(timer);
window.removeEventListener('message', onMessageHandler);
const reopenUrl = new URL(location.href);
reopenUrl.hash = `#reopen=${traceUrl}`;
win.postMessage({
perfetto: {
buffer: arrayBuffer,
title: 'Trace',
url: reopenUrl.toString(),
}}, ORIGIN);
};
window.addEventListener('message', onMessageHandler);
}
// This is triggered when following the link from the Perfetto UI's sidebar.
if (location.hash.startsWith('#reopen=')) {
const traceUrl = location.hash.substr(8);
fetchAndOpen(traceUrl);
}
fetchAndOpen("trace")
</script>
</body>
</html>
EOF
python -m http.server 63343 -d "$t" &
open http://localhost:63343
sleep 5
kill %1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment