Module 22 · Lesson 51 of 64

Serving dashboards and the data pipeline

Serve a Streamlit dashboard safely with localhost binding, SSH tunnels and basic auth, and wire capture, parsing and SQLite storage into one pipeline the dashboard reads.

  • Beginner to advanced
  • 10 min read
  • 55 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM; Python 3 with streamlit, scapy and pandas; nginx and apache2-utils; a Raspberry Pi 4 or 5 for the serving and replay exercises

Your place in the module
By the end you can 4 objectives
  • Bind a Streamlit server to 127.0.0.1 and reach it from another machine through an SSH local forward
  • Put nginx with basic auth in front of a dashboard, including the WebSocket proxy headers
  • Store parsed capture results in SQLite and read them from the dashboard in read-only mode
  • Replay a pcap against a device, record per-request latency and timeouts, and chart the results
Video coming soonServing dashboards and the data pipeline
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Dashboards with Streamlit
  • A Streamlit script reruns top to bottom on every widget interaction; widget calls return the reader's current selection
  • st.cache_data caches a function's return value across reruns and sessions, keyed by its arguments; st.session_state is per-browser-session storage
  • streamlit run app.py serves the app on http://localhost:8501 by default
01

Serving the dashboard safely

5 min read

In the previous lesson you built a Streamlit dashboard locally. This lesson serves it safely on the Pi with localhost binding and basic auth, and connects capture, parsing and storage into one data pipeline.

Start with the default, because the default is the unsafe case. streamlit run app.py starts a web server on port 8501 and, with no address configured, accepts connections on every interface: your laptop, the Pi, and anyone else on the lab network can open it. There is no login. For a dashboard that shows test results that is tolerable; for one that can trigger actions or expose device data it is not. The first fix costs one flag:

bash
streamlit run app.py --server.address 127.0.0.1 --server.port 8501

changes who can reach the port at the kernel level, not by a firewall rule you might forget. Verify it with ss -ltn. In a real test on Ubuntu 24.04 with Streamlit 1.67.0, a plain streamlit run app.py --server.headless true showed LISTEN 0 2048 *:8501 *:*, and with --server.address 127.0.0.1 the same line read LISTEN 0 2048 127.0.0.1:8501 0.0.0.0:* (the exact column layout on your machine will differ). From another machine the connection is now refused, which is exactly what you want.

But you still need to see the dashboard from your laptop. The safe answer is an :

bash
ssh -N -L 8501:127.0.0.1:8501 pi@raspberrypi.local

-N means "no remote command, just forward". Now http://localhost:8501 in your laptop's browser reaches the Pi's dashboard, the traffic is encrypted by SSH, and the dashboard's port stays invisible to the rest of the network. Authentication is your SSH login, which you already have. On an untrusted or shared network, this is the whole solution: bind to localhost, tunnel in, done.

Sometimes you want the whole lab team to open the dashboard without SSH accounts. Then you need a in front of Streamlit. Streamlit has no username-and-password login of its own, so basic auth lives in nginx:

bash
sudo apt install nginx apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd viewer

htpasswd prompts for a password and writes a hashed entry (the -b option takes the password on the command line instead, which is handy in a test but leaves it in your shell history). A site file in /etc/nginx/sites-available/, symlinked into sites-enabled/, then sudo nginx -t && sudo systemctl reload nginx:

text
server {
    listen 80;
    server_name raspberrypi.local;

    auth_basic "Lab dashboard";
    auth_basic_user_file /etc/nginx/.htpasswd;

    location / {
        proxy_pass http://127.0.0.1:8501;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}

The two Upgrade and Connection headers are not optional decoration: Streamlit pushes every update over a WebSocket, and without those headers the proxy breaks the WebSocket handshake and the page loads but never updates. This configuration was run for real with nginx 1.24.0 and Streamlit bound to 127.0.0.1: a request with no credentials got 401, a wrong password got 401, and the right one got 200. A WebSocket connection to /_stcore/stream through nginx succeeded with the two headers, and after deleting the two proxy_set_header lines for Upgrade and Connection it was rejected (server rejected WebSocket connection: HTTP 200, where a handshake needs 101). Two practical notes: a fresh Ubuntu nginx also ships a default site that answers on port 80, so remove its link from sites-enabled/ or request the server name you configured; and the base64 of viewer:s3cret is dmlld2VyOnMzY3JldA==, which decodes back to the password with one call, as the next box explains.

Basic auth is not encryption

HTTP basic auth sends the username and password Base64-encoded on every request. Base64 is an encoding, not encryption: anyone capturing traffic on the network can decode it. Use basic auth only on a trusted lab LAN, or put TLS in front of it. On anything else, prefer the SSH tunnel.

Two safe serving pathsSSH tunnelnginx + basicauthWho can connectSSH accountholdersanyone withpasswordEncryptionSSH, alwaysnone withoutTLSDashboard bindsto127.0.0.1127.0.0.1Extra softwarenonenginx,apache2-utilsBest foruntrustednetworkstrusted labLAN
Two safe ways to reach a dashboard on the Pi: an SSH tunnel for one user, or nginx with basic auth for the lab LAN.
Keep it running after logout

A dashboard started in an SSH session dies when the session closes. On the Pi, put the same command in a systemd service with --server.headless true (which stops Streamlit trying to open a browser), for example ExecStart=/home/pi/venv/bin/streamlit run /home/pi/dash/app.py --server.address 127.0.0.1 --server.headless true, so it restarts on boot and survives logout.

02

Capture, parse, store: one pipeline

3 min read

You now have two halves of a system: lessons S03A and S03B taught you to parse logs and frames into typed records and analyse them, and the previous lesson taught you to display dataframes. The missing piece is the contract between them. The rule that makes a lab tool trustworthy: the dashboard never captures, and the capture never renders. They meet only at the .

Capture, parse, store, renderCapturepcap,serial logParseregex, dataclasses,scapyStoreSQLite runsand rowsDashboardread-only,cachedCapturepcap,serial logParseregex, dataclasses,scapyStoreSQLite runsand rowsDashboardread-only,cached
The four stages. Each stage writes an artifact the next stage reads; the dashboard only ever reads the store.

Each stage has one job and one output:

Step by stepWhat each stage owns
  1. Capture: scapy's sniff() or rdpcap() writes a .pcap; pyserial writes a raw boot log. Raw bytes, timestamped, never edited.

  2. Parse: the regex-and-dataclass parsers from S03A (or scapy's dissectors from S06B2) turn raw artifacts into typed rows: sequence number, latency in milliseconds, boot milestone, seconds since reset.

  3. Store: rows go into SQLite via the standard-library sqlite3 module, tagged with a run id so repeated experiments stay separate.

  4. Dashboard: Streamlit opens the database read-only and renders charts. A rerun re-reads the store; it never sends a packet.

Why files and a database instead of function calls? Because the stages run at different times and different rates. Capture runs once per experiment, maybe for ten minutes with the device attached. The dashboard reruns its whole script on every widget click. If the dashboard captured on rerun, every slider move would poke the hardware. With a store in between, you can also re-plot yesterday's run, diff two runs, or parse the same pcap twice with a fixed parser without touching the device again.

A schema for latency runs is two tables:

sql
CREATE TABLE IF NOT EXISTS runs (
    run_id  INTEGER PRIMARY KEY,
    started TEXT NOT NULL,
    target  TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS latency (
    run_id    INTEGER NOT NULL REFERENCES runs(run_id),
    seq       INTEGER NOT NULL,
    rtt_ms    REAL,
    timed_out INTEGER NOT NULL DEFAULT 0
);

rtt_ms is nullable on purpose: a request that timed out is still a result, stored as a row with timed_out = 1 and no latency. Dropping timeouts silently would make a flaky device look fast, because only the successes would remain in the statistics.

The writer side is plain sqlite3:

python
import sqlite3

def save_run(con, rows, target, started):
    cur = con.execute(
        "INSERT INTO runs(started, target) VALUES (?, ?)",
        (started, target))
    run_id = cur.lastrowid
    con.executemany(
        "INSERT INTO latency(run_id, seq, rtt_ms, timed_out) "
        "VALUES (?, ?, ?, ?)",
        [(run_id, seq, rtt, int(rtt is None)) for seq, rtt in rows])
    con.commit()

The reader side opens the same file with a read-only URI, so a bug in the dashboard cannot corrupt an experiment, and caches the query so ten widget clicks do not mean ten full table scans:

python
import sqlite3
import pandas as pd
import streamlit as st

@st.cache_data(ttl=10)
def load_latency():
    con = sqlite3.connect("file:lab.db?mode=ro", uri=True)
    df = pd.read_sql_query(
        "SELECT seq, rtt_ms FROM latency ORDER BY seq", con)
    con.close()
    return df
One writer, many readers

SQLite handles this pattern well: one capture process writes a run, and any number of dashboard sessions read. Keep writes in the capture stage only. If you later need a live writer and reader at the same moment, enable WAL mode (PRAGMA journal_mode=WAL) so readers are not blocked during a commit.

03

Replay a capture and chart the latency

4 min read

The practical that ties the module together: take a capture of requests, replay it against a device, measure how long each response takes, and watch the result in the dashboard. Replaying a known capture instead of generating fresh traffic makes runs comparable: same requests, same order, so a latency change points at the device or the network, not at your stimulus.

scapy reads the capture with rdpcap() and sr1() sends one packet and waits for its answer. Wrap each send in time.perf_counter() and you have a per-request round trip:

python
from scapy.all import IP, rdpcap, sr

rows = []
for seq, pkt in enumerate(rdpcap("requests.pcap")):
    answered, _ = sr(pkt[IP], timeout=2, verbose=0)
    if answered:
        sent, reply = answered[0]
        rtt = float((reply.time - sent.sent_time) * 1000.0)
    else:
        rtt = None
    rows.append((seq, rtt))

Run it with sudo (scapy needs raw sockets), feed rows to save_run() from the previous section, and the run is in the store. Without a reply sr() returns an empty answered list after the two-second timeout, which becomes a timed_out row rather than a missing measurement.

Two details come from failures in a real test, and both matter for the numbers. First, sr and sr1 send at layer 3, so give them the IP part: a pcap captured with tcpdump stores whole Ethernet frames, and in the test sr1(pkt) on such a frame timed out for all five requests, so every row would have been stored as a timeout. pkt[IP] fixed it (a pcap that you wrote yourself from IP()/ICMP() packets has no Ethernet layer, and pkt[IP] still works). Second, do not time the call with time.perf_counter() around sr1: on the loopback interface, where the real echo round trip is a few hundredths of a millisecond, that stopwatch read 12.5 to 19.4 ms per request, because it also counts everything scapy does to set up the socket and route the packet. The reply.time - sent.sent_time difference read 0.043 to 0.058 ms for the same requests. The float() turns scapy's decimal timestamp type into a plain number that sqlite3 can store.

Timing one replayed requestHarnessDeviceStoresr1(pkt), starttimerreply or timeoutrow: seq, rtt_msor timed_out row1. Harness → Devicesr1(pkt), start timer2. Device → Harnessreply or timeout3. Harness → Storerow: seq, rtt_ms4. Harness → Storeor timed_out row
One replayed request: the harness timestamps the send, waits for the reply or the timeout, and writes one row either way.
Replay only into your own lab

A replayed capture contains real addresses and real payloads. Point it only at devices you own, on a network you control. Replaying captured traffic at someone else's device or network is indistinguishable from an attack. If you just want to blast packets at wire speed without measuring answers, tcpreplay --intf1=eth0 requests.pcap exists for that, but it reports nothing about responses, which is why the sr1() loop above is the right tool here.

The dashboard over the store is a few lines on top of load_latency():

python
df = load_latency()
st.line_chart(df, x="seq", y="rtt_ms")
st.metric("p95 latency (ms)", round(df["rtt_ms"].quantile(0.95), 2))
st.metric("timeouts", int(df["rtt_ms"].isna().sum()))

The line chart shows the shape of the run (a device that warms up, a periodic stall), the p95 metric summarises the tail using the percentile tools from S03B4, and the timeout count keeps the failures visible. Null latencies simply do not plot, while the metric still counts them. Run against a test database with four rows (0.5, NULL, 0.7 and 0.6 ms), Streamlit's headless test runner showed a p95 latency (ms) metric of 0.69 and timeouts of 1, and opening the database with mode=ro made an INSERT fail with OperationalError: attempt to write a readonly database.

The same pipeline serves boot data with no new machinery. The capture stage saves the serial boot log; the parse stage uses the S03A regex-and-dataclass approach to extract milestone rows (boot id, milestone name, seconds since reset); the store gets a milestones table next to latency. The dashboard then charts each milestone's duration across boots, so a kernel change that adds time to driver probe shows up as one bar growing while the others hold still. Capture, parse, store, render: you built the pattern once, and every future measurement in this course plugs into it.

That pattern is also the seed of the capstone. The next lesson, "The devkit brief and architecture", takes these pieces (protocol tooling, parsers, a store and a dashboard) and asks you to assemble them into one deliverable tool with a defined scope.

Key takeaways

  • Streamlit listens on port 8501 and, left unconfigured, on every interface; --server.address 127.0.0.1 makes it reachable only from the same machine
  • Basic auth belongs in a reverse proxy in front of Streamlit, and over plain HTTP its Base64 credentials are readable by anyone sniffing the network
  • A pipeline of capture, parse, store and dashboard stages communicates through files and a database, so dashboard reruns never touch the hardware
  • Timeouts must be stored as rows, not dropped, or the latency statistics only describe the requests that succeeded
Reflect
  1. Explain to a colleague, in two sentences: bind a Streamlit server to 127.0.0.1 and reach it from another machine through an SSH local forward
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close