Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 13 · 55 minutes

Find the failing layer and measure a network

After this lesson you can
  • Apply a fixed method to a network fault, one layer at a time
  • Use the tools of the course in order and read what each result proves
  • Measure latency, loss, throughput and availability from a probe log
Lab files of this lesson (54)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

On Monday at 08:50 four people write that "the intranet app is broken". Each one runs the first commands of the ladder (link, address, gateway, name, URL), adds one or two more, and sends you the output. You must name the first failing layer for each person, and say what to change. Then your manager asks a second question: "Is the app slow, or only down?" You get the log of one hour of probes (small tests on a timer) and you must give four numbers.

Recall

Which command shows which programs listen on which port, and on which address they are bound?

ss -tlnp (lesson 5). The address matters: 127.0.0.1:8443 accepts only local clients and 0.0.0.0:8443 accepts every network (lesson 11).

A laptop clock is 350 seconds behind, and the server certificate was issued five minutes ago. Which check of a TLS connection can fail?

The check of the dates. A certificate is valid only from its start date, so a clock that is behind the start date gives "certificate is not yet valid" (lesson 6).

The idea

A fault hunt needs a method, because a hurried guess breaks a second thing. Use five steps:

  1. Define. Say what fails, for whom, since when, and what changed. "From krbox, curl https://app.lab.test:8443/ ends with an error. Since 08:30. The switch was replaced on Sunday."
  2. Scope. Is it one user, one room or everyone? Which layer (lesson 1)? Start at the bottom and go up, or split the path in half and test the middle.
  3. Test. Run one test for one layer and keep the output as evidence.
  4. Change one thing. Change one setting, so that you know what fixed it. Note how to undo it.
  5. Verify. Run the failing test again, and then do what the user did. If it still fails, go back to step 1 with what you learned.
The troubleshooting loop
DefineScopeTestChangeVerifywhat fails, for whompick a layer, run its testchange one thing onlyrepeat the failing teststill broken?learn, start againDefineScopeTestChangeVerify12345
  1. Define → Scope: what fails, for whom
  2. Scope → Test: pick a layer, run its test
  3. Test → Change: change one thing only
  4. Change → Verify: repeat the failing test
  5. Verify → Define: still broken? learn, start again

The tools of the course make a ladder of seven rungs. Each rung proves one layer, and a rung that works proves every layer below it, for that path. Go up until one fails.

RungQuestionTestLesson
linkIs the card up?ip -br link1
addressIs there a good address?ip -br addr (not 169.254)2, 6
gatewayCan I reach my router?ping, ip neigh2, 3
dnsDoes the name resolve?getent hosts, dig7
tcpDoes the port answer?curl, ss5
tlsDoes the certificate pass?curl, openssl9
httpDoes the application answer?curl status code8

curl tells the rung by its exit code: 6 is "could not resolve the name", 7 is "could not connect" (refused), 28 is "timed out", 35 and 60 are TLS failures, and 0 is success. A failed ping alone is not a verdict, because many networks block ICMP, the protocol of ping.

Monitoring is the same tests on a timer. A probe is one small test. Four numbers describe a network, and each needs a baseline: what normal looks like for you.

  • Latency: the round-trip time of a probe, in milliseconds. Use the median and the 95th percentile (p95), not the mean. A few slow probes move the mean and hide the typical case.
  • Loss: the share of probes that got no answer.
  • Throughput: how much data a transfer moves in a second, in Mbit/s.
  • Availability: the share of probes that got the right answer (a 200, not only a reply).

An alert should need a pattern, such as three failed probes in a row.

Worked example

1. Climb the ladder on your own machine

Start the web server of lesson 5 in a second terminal (python3 -m http.server 8000 --bind 127.0.0.1). Then test your loopback, rung by rung. -w tells curl to print a value after the transfer, here the status code, and tail -2 keeps the last two lines. The loopback card says UNKNOWN, not UP, and that is normal for it.

cd ~/krlab/networking
ip -br link show lo
ip -br addr show lo
ping -c 1 127.0.0.1 | tail -2
getent hosts localhost
curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/
lo               UNKNOWN        00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
lo               UNKNOWN        127.0.0.1/8 ::1/128
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.078/0.078/0.078/0.000 ms
::1             localhost
200

Every rung works, so every layer works for this path. Keep the server running for step 5.

2. Read a recorded case

cases.txt holds the output that a user sent for case a. A line that starts with $ is the command, and [exit N] is its exit code (no line means 0). The app is app.lab.test on port 8443.

cat > cases.txt <<'EOT'
== a
$ ip -br link show eth0
eth0             UP             02:00:00:00:00:50 <BROADCAST,MULTICAST,UP,LOWER_UP>
$ ip -br addr show eth0
eth0             UP             10.20.0.20/22
$ ping -c 2 10.20.0.1
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
$ getent hosts app.lab.test
[exit 2]
$ curl -sS -o /dev/null -w '%{http_code}' --max-time 5 https://app.lab.test:8443/
curl: (6) Could not resolve host: app.lab.test
[exit 6]
$ grep nameserver /etc/resolv.conf
nameserver 10.20.0.99
$ ping -c 2 10.20.0.99
2 packets transmitted, 0 received, 100% packet loss, time 1010ms
[exit 1]
EOT
Case a, where the ladder stops
LaptopOffice networkLaptop 10.20.0.20GatewayDNS server 10.20.0.9912LaptopOffice networkLaptop 10.20.0.20GatewayDNS server 10.20.0.9912
  1. Laptop 10.20.0.20 → Gateway: ping answers: link, address, gateway ok
  2. Laptop 10.20.0.20 → DNS server 10.20.0.99: no answer: the dns rung fails

Read it by hand: the card is up, the address is good and the gateway answers, but the name does not resolve (getent exits 2, curl exits 6). The user's DNS server 10.20.0.99 does not answer ping. The first failing rung is the name, and the evidence points to a dead resolver.

3. Let a program climb the ladder

ladder.py reads the cases, tests each rung with the rules of the table, and marks the rungs above the first failure with -, because they prove nothing until the failure is fixed. Two library calls need a note. re.search finds a text pattern in a string: here, an IPv4 address followed by a slash. next(...) takes the first item that the loop inside it produces.

ladder.py

import re
import sys


def load(path):
    cases, cmds = {}, None
    for line in open(path):
        line = line.rstrip("\n")
        if line.startswith("== "):
            cmds = cases.setdefault(line[3:], {})
        elif line.startswith("$ "):
            cmd = cmds.setdefault(line[2:], {"out": "", "exit": 0})
        elif line.startswith("[exit "):
            cmd["exit"] = int(line[6:-1])
        else:
            cmd["out"] += line + "\n"
    return cases


def find(cmds, start):
    return next(v for k, v in cmds.items() if k.startswith(start))


def ladder(cmds):
    curl = find(cmds, "curl")
    ip = re.search(r"(\d+\.\d+\.\d+\.\d+)/", find(cmds, "ip -br addr")["out"])
    return [
        ("link", " UP " in find(cmds, "ip -br link")["out"]),
        ("address", bool(ip) and not ip.group(1).startswith("169.254.")),
        ("gateway", find(cmds, "ping")["exit"] == 0),
        ("dns", find(cmds, "getent")["exit"] == 0),
        ("tcp", curl["exit"] not in (7, 28)),
        ("tls", curl["exit"] not in (35, 60)),
        ("http", curl["exit"] == 0 and curl["out"].startswith("2")),
    ]


for name, cmds in load(sys.argv[1]).items():
    parts, failed = [], None
    for rung, good in ladder(cmds):
        parts.append(f"{rung} -" if failed else f"{rung} {'ok' if good else 'FAIL'}")
        failed = failed or (None if good else rung)
    print(f"{name}: " + ", ".join(parts))
    print(f"   first failing rung: {failed or 'none'}")
python3 ladder.py cases.txt
a: link ok, address ok, gateway ok, dns FAIL, tcp -, tls -, http -
   first failing rung: dns

The program gives the rung. You give the cause and the fix: here, the resolver 10.20.0.99 is down, so you change one thing (the resolver setting, or start the resolver) and run getent again.

4. Generate a probe log

probes.py writes a log of 60 probes with a fixed seed, so that everyone gets the same file. The three numbers are the seed, the share of timeouts and the share of 503 answers. About one probe in 20 is slow.

probes.py

import random
import sys

seed, timeouts, errors = int(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3])
rng = random.Random(seed)
print("n,status,rtt_ms,bytes,secs")
for n in range(1, 61):
    roll = rng.random()
    if roll < timeouts:
        print(f"{n},timeout,,0,0")  # no answer at all
        continue
    rtt = round(20 + rng.random() * 10 + (150 if rng.random() < 0.05 else 0), 1)  # one probe in 20 is slow
    if roll < timeouts + errors:
        print(f"{n},503,{rtt},0,0")  # an answer, but an error
    else:
        secs = round(500000 * 8 / (rng.uniform(40, 60) * 1e6), 3)  # a 500 kB download at 40 to 60 Mbit/s
        print(f"{n},200,{rtt},500000,{secs}")
python3 probes.py 3 0.05 0.03 > probes.csv
head -4 probes.csv
n,status,rtt_ms,bytes,secs
1,200,25.4,500000,0.077
2,200,170.7,500000,0.07
3,200,22.3,500000,0.081

5. Measure it

stats.py computes the four numbers. A percentile (here by the nearest-rank rule) is the value below which that share of the probes lie: sort the times, then take the value at position ceil(p/100 × count).

stats.py

import csv
import math
import sys

rows = list(csv.DictReader(open(sys.argv[1])))
answered = [r for r in rows if r["status"] != "timeout"]
good = [r for r in rows if r["status"] == "200"]
rtts = sorted(float(r["rtt_ms"]) for r in answered)


def percentile(values, p):  # nearest rank: the smallest value with p percent of the values at or below it
    return values[math.ceil(p / 100 * len(values)) - 1]


mbit = sum(int(r["bytes"]) for r in good) * 8 / sum(float(r["secs"]) for r in good) / 1e6
print(f"probes {len(rows)}  loss {100 * (len(rows) - len(answered)) / len(rows):.1f} %  "
      f"availability {100 * len(good) / len(rows):.1f} %")
print(f"latency ms  mean {sum(rtts) / len(rtts):.1f}  median {percentile(rtts, 50)}  p95 {percentile(rtts, 95)}  max {rtts[-1]}")
print(f"throughput {mbit:.1f} Mbit/s")
python3 stats.py probes.csv
probes 60  loss 6.7 %  availability 91.7 %
latency ms  mean 32.5  median 24.3  p95 170.7  max 175.8
throughput 49.5 Mbit/s
Latency of the 60 probes, in ms
Median24.3Mean32.5p95170.7Max175.8Median24.3Mean32.5p95170.7Max175.8

The median is the typical probe (probe 2 above is one of the slow ones). The p95 shows that about one probe in 20 is slow, and the mean describes neither. Loss and availability differ because a 503 is an answer but not a good one. To see a real probe from your machine, with the server of step 1 running:

curl -s -o /dev/null -w 'code=%{http_code} connect=%{time_connect}s total=%{time_total}s size=%{size_download} bytes\n' http://127.0.0.1:8000/
code=200 connect=0.000667s total=0.001801s size=17 bytes

Stop the server with Ctrl+C.

Your turn

Three more users sent their output, and a second probe log came in. Save the data.

cat > cases2.txt <<'EOT'
== b
$ ip -br link show eth0
eth0             UP             02:00:00:00:00:51 <BROADCAST,MULTICAST,UP,LOWER_UP>
$ ip -br addr show eth0
eth0             UP             10.20.0.21/22
$ ping -c 2 10.20.0.1
From 10.20.0.21 icmp_seq=1 Destination Host Unreachable
2 packets transmitted, 0 received, +2 errors, 100% packet loss, time 1030ms
[exit 1]
$ ip neigh show 10.20.0.1
10.20.0.1 dev eth0  FAILED
$ getent hosts app.lab.test
[exit 2]
$ curl -sS -o /dev/null -w '%{http_code}' --max-time 5 https://app.lab.test:8443/
curl: (6) Could not resolve host: app.lab.test
[exit 6]
== c
$ ip -br link show eth0
eth0             UP             02:00:00:00:00:52 <BROADCAST,MULTICAST,UP,LOWER_UP>
$ ip -br addr show eth0
eth0             UP             10.20.0.22/22
$ ping -c 2 10.20.0.1
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
$ getent hosts app.lab.test
10.20.1.10      app.lab.test
$ ping -c 2 10.20.1.10
2 packets transmitted, 0 received, 100% packet loss, time 1012ms
[exit 1]
$ curl -sS -o /dev/null -w '%{http_code}' --max-time 5 https://app.lab.test:8443/
curl: (60) SSL certificate problem: certificate is not yet valid
[exit 60]
$ date -u
Mon Mar  4 09:15:00 UTC 2019
== d
$ ip -br link show eth0
eth0             UP             02:00:00:00:00:53 <BROADCAST,MULTICAST,UP,LOWER_UP>
$ ip -br addr show eth0
eth0             UP             10.20.0.23/22
$ ping -c 2 10.20.0.1
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
$ getent hosts app.lab.test
10.20.1.10      app.lab.test
$ curl -sS -o /dev/null -w '%{http_code}' --max-time 5 https://app.lab.test:8443/
curl: (7) Failed to connect to app.lab.test port 8443 after 3 ms: Could not connect to server
[exit 7]
$ ss -tln   (run on app.lab.test by the server team)
LISTEN 0      128        127.0.0.1:8443       0.0.0.0:*
EOT
python3 probes.py 11 0.10 0.10 > probes2.csv
  1. Run ladder.py on cases2.txt. For each case write four lines: the first failing rung, the evidence (the line of output), the likely cause and the one change that you would make. In case c, the ping to the server fails too: say why that is not the fault. In case b, name the line of ip neigh that tells the layer.
  2. Run stats.py on probes2.csv. Then extend stats.py so that it prints the longest run of probes in a row that were not 200. Say if the alert "three failures in a row" would have fired.
A model extension for stats.py

Add these lines at the end of stats.py:

longest = run = 0
for r in rows:
    run = run + 1 if r["status"] != "200" else 0  # count up on a failure, start again on a 200
    longest = max(longest, run)
print("longest run of probes that were not 200:", longest)

It prints 3, so the alert "three failures in a row" would have fired once.

Check yourself

Why do you change only one thing at a time?

If you change three things and the fault goes away, you do not know which one fixed it. One change, then one test, gives a cause that you can undo.

A ping to the server fails, but its web page loads. Is the network broken?

No. The page loading proves layers 1 to 7 for that path. The server or a firewall in between does not answer ICMP. A success at a higher layer overrules a failure of a test that may be blocked on purpose.

Why report the p95 and not only the mean latency?

The mean mixes the typical probes with a few very slow ones, and it describes neither. The median shows the typical case and the p95 shows how bad the slow ones are.

An alert fires every time one probe is lost, and the team ignores it. What is the fix?

Alert on a pattern: for example three failed probes in a row, or a p95 over a limit for five minutes. One lost packet is normal on any network.

Field notes

  • Write the evidence as you go: the command, the line of output and the time, so that another person can repeat your test.
  • Test from where the user is. A probe on the server proves that the server works, not the path. Run probes from each network that has users.
  • A baseline is a measurement taken on a good day. Save ip route, ss -tlnp and the four numbers, to compare in an incident.
  • Time every record in UTC and keep the clocks in sync (lesson 6).
  • When the ladder passes and a user still has a problem, check the logs of the server and run the tool of lesson 14, which times each stage of a request.