ToFaRev sessions

ToFaRev review

srl-labs/containerlab · 1c9b3577d08f

completed · 18 messages · 26 tool calls

Last snapshot:

Download session JSON · Full transcript

Final review

# ToFaRev review

Review complete within the supplied scope.

Source inspection only; PR code, tests, and benchmarks were not executed.

| Finding | Location |
| --- | --- |
| **P4 - `emit` computes `interfaceAttributes` before checking `w.reported`, wasting a root-netns lookup on every `delete`** | [core/events/netlink.go:681-687](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink.go#L681-L687) |
| **P4 - Stitch-mark window is measured from the first report and the ceiling is not marked per the ponytail rule** | [core/events/netlink.go:650-670](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink.go#L650-L670) |
| **P4 - New `delete`+`create` re-report of stitched interfaces is undocumented in [`docs/cmd/events.md`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/docs/cmd/events.md#L1-L1)** | [docs/cmd/events.md:32-32](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/docs/cmd/events.md#L32-L32) |
| **P4 - Positive path of `reportStitchMarks` is untested** | [core/events/netlink_watch_test.go:511-511](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink_watch_test.go#L511-L511) |

## P4 - `emit` computes `interfaceAttributes` before checking `w.reported`, wasting a root-netns lookup on every `delete`

**Location:** [core/events/netlink.go:681-687](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink.go#L681-L687)

**Problem:** In the `delete` branch of `emit`, `attributes := interfaceAttributes(w.container, snapshot)` is computed before the code checks `w.reported`, and the freshly computed attributes are then discarded whenever a previous report exists. `interfaceAttributes` ends in `overlayToolsInterface` -> `clablinks.ToolsInterface` -> `netlink.LinkByName`, a root-netns `RTM_GETLINK` round trip.

**Trigger:** Every interface `delete` event for a previously reported interface, which is the common case for link teardown during `destroy` or `redeploy`.

**Impact:** One wasted netlink lookup per `delete` event. Small in absolute terms, but free to avoid.

**Suggested correction:** Look up `w.reported[snapshot.Index]` first and only call `interfaceAttributes` when no previous report exists, for example: `previous, ok := w.reported[snapshot.Index]; attributes := previous.attributes; if !ok { attributes = interfaceAttributes(w.container, snapshot) }`.


## P4 - Stitch-mark window is measured from the first report and the ceiling is not marked per the ponytail rule

**Location:** [core/events/netlink.go:650-670](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink.go#L650-L670)

**Problem:** `track` preserves the original `since` timestamp forever (`since = previous.since`), and `reportStitchMarks` skips any link where `time.Since(reported.since) > stitchMarkWindow`. The window therefore measures from the first time the watcher reported the link, not from the most recent poll. Refreshing `since` on every poll would instead keep every veth a polling candidate forever, so the one-minute bound is a deliberate cost ceiling.

**Trigger:** A veth-stitch link whose host-side altname is applied more than one minute after the node end was first reported, which happens when the opposite endpoint's container starts slowly (image pull) so stitching occurs in `PostDeploy` long after the first node's interface was reported, or after a subscription outage longer than the window.

**Impact:** Those interfaces remain reported under the node-side name (`eth1`) instead of the stitch name until the node-side link changes or the watcher resubscribes. This matches the base behavior, so it is a residual gap in an improvement rather than a regression, but the repository's ponytail rule asks that deliberate ceilings carry a `ponytail:` comment naming the ceiling and upgrade path, and the comment on `reportStitchMarks` explains only the mechanism.

**Suggested correction:** Add a `ponytail:` comment at `stitchMarkWindow` stating the ceiling, for example that links stitched more than one minute after first report are not renamed in the stream until the link changes or the watcher resubscribes, with a root-namespace altname monitor as the upgrade path. Optionally widen the window if deploy observations show it is tight.


## P4 - New `delete`+`create` re-report of stitched interfaces is undocumented in [`docs/cmd/events.md`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/docs/cmd/events.md#L1-L1)

**Location:** [docs/cmd/events.md:32-32](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/docs/cmd/events.md#L32-L32)

**Problem:** The events documentation `states` that interface notifications are emitted when a link appears, disappears, or when its relevant properties change. This PR adds a new class of emission: a link whose node-side properties did not change can be re-reported as a `delete` under its node-side name followed by a `create` under the host-side stitch interface name, both live via `track` and proactively via `reportStitchMarks` (introduced in [`core/events/netlink.go`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink.go#L1-L1) lines 672-699).

**Trigger:** Any consumer of `clab events` watching a lab with veth-stitch links, during deploy or link reconfiguration.

**Impact:** Consumers that key records on `ifname`, the documented contract, will observe teardown-plus-creation pairs for the same logical interface whenever a stitch is marked, which can surprise integrators into treating the rename as a link removal and re-add.

**Suggested correction:** Add one or two sentences to [`docs/cmd/events.md`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/docs/cmd/events.md#L1-L1) explaining that a stitched interface may be reported as `delete` under its node-side name and `create` under the stitch interface name when the host-side stitch is marked, and that `alias` carries the topology name throughout. Since release 0.83 is the current unreleased release, a short Miscellaneous bullet in [`docs/rn/0.83.md`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/docs/rn/0.83.md#L1-L1) would also fit.


## P4 - Positive path of `reportStitchMarks` is untested

**Location:** [core/events/netlink_watch_test.go:511-511](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink_watch_test.go#L511-L511)

**Problem:** `TestReportStitchMarksLeavesUnmarkedLinks` covers only the negative filtering cases (stitch already reflected, expired window, never reported). The core new behavior, a within-window link reported under its own name whose host-side stitch gets marked and which produces a `delete` of the old name and a `create` under the stitch name, has no direct test. The rename mechanics are covered indirectly by `TestEmitReportsRenamedLinkDeleted` and `TestEmitStatsReportsRenamedLinkFirst`, but the polling function's candidate filter and its interaction with `emit` are not exercised end to end.

**Trigger:** A future refactor of `reportStitchMarks`, such as reordering the window or type check, would not be caught by the test suite.

**Impact:** Low, but this polling logic is the headline behavior of the PR and the existing test harness already fakes stitch marks, so the missing case is cheap to add.

**Suggested correction:** Add one test in [`core/events/netlink_watch_test.go`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink_watch_test.go#L1-L1) modeled on `TestReportStitchMarksLeavesUnmarkedLinks`: pre-seed `watcher.reported` with a veth reported under its own name with a fresh `since`, fake a stitch mark in the harness, call `reportStitchMarks`, and assert the expected `delete` plus `create` sequence in the collected events.


## Coverage

- Source-only review: head and base snapshots, the full diff, both changed files, callers of the changed functions, the events documentation, release notes, and the repository review rules were inspected. Tests and formatters were not executed.
- All changed paths ([`core/events/netlink.go`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink.go#L1-L1), [`core/events/netlink_watch_test.go`](https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/core/events/netlink_watch_test.go#L1-L1)) and their surrounding code were reviewed; the base comparison confirmed the removed `container == nil` guard is preserved by guards inside `emit` and `emitStats`, and all `sendInterfaceEvent` call sites are within guarded paths.
- `w.reported` is accessed only from the watcher goroutine, and `track` stores `maps.Clone(attributes)`, so no race or aliasing issue was found in the new state tracking.
- Pre-existing behavior where links present at the first subscription are recorded in `states` but not `w.reported` with `includeSnapshot=false` was checked and is not worsened by this PR; it is noted as pre-existing rather than a finding.
- The ponytail ceiling-comment rule was applied to the `stitchMarkWindow` heuristic in finding 2; no other deliberate simplification in this PR appeared to warrant a ceiling marker.

---
Powered by <a href="https://tokenfactory.nebius.com/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/hellt/tofarev/11341daf301af9b89b711528df08d0a9e9139bca/assets/nebius-token-factory-dark.svg"><img src="https://raw.githubusercontent.com/hellt/tofarev/11341daf301af9b89b711528df08d0a9e9139bca/assets/nebius-token-factory-light.svg" alt="Nebius Token Factory" height="22" align="absmiddle"></picture></a>

```json
{
  "version": 1,
  "findings": [
    {
      "priority": "P4",
      "title": "`emit` computes `interfaceAttributes` before checking `w.reported`, wasting a root-netns lookup on every `delete`",
      "location": {
        "revision": "head",
        "path": "core/events/netlink.go",
        "start": 681,
        "end": 687
      },
      "problem": "In the `delete` branch of `emit`, `attributes := interfaceAttributes(w.container, snapshot)` is computed before the code checks `w.reported`, and the freshly computed attributes are then discarded whenever a previous report exists. `interfaceAttributes` ends in `overlayToolsInterface` -> `clablinks.ToolsInterface` -> `netlink.LinkByName`, a root-netns `RTM_GETLINK` round trip.",
      "trigger": "Every interface `delete` event for a previously reported interface, which is the common case for link teardown during `destroy` or `redeploy`.",
      "impact": "One wasted netlink lookup per `delete` event. Small in absolute terms, but free to avoid.",
      "suggestion": "Look up `w.reported[snapshot.Index]` first and only call `interfaceAttributes` when no previous report exists, for example: `previous, ok := w.reported[snapshot.Index]; attributes := previous.attributes; if !ok { attributes = interfaceAttributes(w.container, snapshot) }`."
    },
    {
      "priority": "P4",
      "title": "Stitch-mark window is measured from the first report and the ceiling is not marked per the ponytail rule",
      "location": {
        "revision": "head",
        "path": "core/events/netlink.go",
        "start": 650,
        "end": 670
      },
      "problem": "`track` preserves the original `since` timestamp forever (`since = previous.since`), and `reportStitchMarks` skips any link where `time.Since(reported.since) > stitchMarkWindow`. The window therefore measures from the first time the watcher reported the link, not from the most recent poll. Refreshing `since` on every poll would instead keep every veth a polling candidate forever, so the one-minute bound is a deliberate cost ceiling.",
      "trigger": "A veth-stitch link whose host-side altname is applied more than one minute after the node end was first reported, which happens when the opposite endpoint's container starts slowly (image pull) so stitching occurs in `PostDeploy` long after the first node's interface was reported, or after a subscription outage longer than the window.",
      "impact": "Those interfaces remain reported under the node-side name (`eth1`) instead of the stitch name until the node-side link changes or the watcher resubscribes. This matches the base behavior, so it is a residual gap in an improvement rather than a regression, but the repository's ponytail rule asks that deliberate ceilings carry a `ponytail:` comment naming the ceiling and upgrade path, and the comment on `reportStitchMarks` explains only the mechanism.",
      "suggestion": "Add a `ponytail:` comment at `stitchMarkWindow` stating the ceiling, for example that links stitched more than one minute after first report are not renamed in the stream until the link changes or the watcher resubscribes, with a root-namespace altname monitor as the upgrade path. Optionally widen the window if deploy observations show it is tight."
    },
    {
      "priority": "P4",
      "title": "New `delete`+`create` re-report of stitched interfaces is undocumented in `docs/cmd/events.md`",
      "location": {
        "revision": "head",
        "path": "docs/cmd/events.md",
        "start": 32,
        "end": 32
      },
      "problem": "The events documentation `states` that interface notifications are emitted when a link appears, disappears, or when its relevant properties change. This PR adds a new class of emission: a link whose node-side properties did not change can be re-reported as a `delete` under its node-side name followed by a `create` under the host-side stitch interface name, both live via `track` and proactively via `reportStitchMarks` (introduced in `core/events/netlink.go` lines 672-699).",
      "trigger": "Any consumer of `clab events` watching a lab with veth-stitch links, during deploy or link reconfiguration.",
      "impact": "Consumers that key records on `ifname`, the documented contract, will observe teardown-plus-creation pairs for the same logical interface whenever a stitch is marked, which can surprise integrators into treating the rename as a link removal and re-add.",
      "suggestion": "Add one or two sentences to `docs/cmd/events.md` explaining that a stitched interface may be reported as `delete` under its node-side name and `create` under the stitch interface name when the host-side stitch is marked, and that `alias` carries the topology name throughout. Since release 0.83 is the current unreleased release, a short Miscellaneous bullet in `docs/rn/0.83.md` would also fit."
    },
    {
      "priority": "P4",
      "title": "Positive path of `reportStitchMarks` is untested",
      "location": {
        "revision": "head",
        "path": "core/events/netlink_watch_test.go",
        "start": 511,
        "end": 511
      },
      "problem": "`TestReportStitchMarksLeavesUnmarkedLinks` covers only the negative filtering cases (stitch already reflected, expired window, never reported). The core new behavior, a within-window link reported under its own name whose host-side stitch gets marked and which produces a `delete` of the old name and a `create` under the stitch name, has no direct test. The rename mechanics are covered indirectly by `TestEmitReportsRenamedLinkDeleted` and `TestEmitStatsReportsRenamedLinkFirst`, but the polling function's candidate filter and its interaction with `emit` are not exercised end to end.",
      "trigger": "A future refactor of `reportStitchMarks`, such as reordering the window or type check, would not be caught by the test suite.",
      "impact": "Low, but this polling logic is the headline behavior of the PR and the existing test harness already fakes stitch marks, so the missing case is cheap to add.",
      "suggestion": "Add one test in `core/events/netlink_watch_test.go` modeled on `TestReportStitchMarksLeavesUnmarkedLinks`: pre-seed `watcher.reported` with a veth reported under its own name with a fresh `since`, fake a stitch mark in the harness, call `reportStitchMarks`, and assert the expected `delete` plus `create` sequence in the collected events."
    }
  ],
  "coverage": {
    "complete": true,
    "notes": [
      "Source-only review: head and base snapshots, the full diff, both changed files, callers of the changed functions, the events documentation, release notes, and the repository review rules were inspected. Tests and formatters were not executed.",
      "All changed paths (`core/events/netlink.go`, `core/events/netlink_watch_test.go`) and their surrounding code were reviewed; the base comparison confirmed the removed `container == nil` guard is preserved by guards inside `emit` and `emitStats`, and all `sendInterfaceEvent` call sites are within guarded paths.",
      "`w.reported` is accessed only from the watcher goroutine, and `track` stores `maps.Clone(attributes)`, so no race or aliasing issue was found in the new state tracking.",
      "Pre-existing behavior where links present at the first subscription are recorded in `states` but not `w.reported` with `includeSnapshot=false` was checked and is not worsened by this PR; it is noted as pre-existing rather than a finding.",
      "The ponytail ceiling-comment rule was applied to the `stitchMarkWindow` heuristic in finding 2; no other deliberate simplification in this PR appeared to warrant a ceiling marker."
    ]
  }
}
```
User · 1
Review the read-only PR snapshot at /source.
Read standards.json and its referenced rules, then diff.txt and relevant head/ and base/ files. Track all 2 changed paths from the diff. Complete checks for each changed path and relevant callers, tests, docs, and schema before finalizing. Source-only review can be complete without executing tests; disclose that limitation. Use read offsets for truncated output and group independent tool calls. Use glob/grep for surrounding code. Return the trusted result schema.
Head: 1c9b3577d08f7524fd228e5ab4df3dd3fc107f53. Comparison base: f57133d88d7f26767e78a9f4c0f81a9ed070fe8b. Target base: f57133d88d7f26767e78a9f4c0f81a9ed070fe8b.
GitHub permalink roots: head=https://github.com/srl-labs/containerlab/blob/1c9b3577d08f7524fd228e5ab4df3dd3fc107f53/; base=https://github.com/srl-labs/containerlab/blob/f57133d88d7f26767e78a9f4c0f81a9ed070fe8b/.
Snapshot incomplete: false. The full inventory and omission details are in manifest.json; consult it when needed. 
Message metadata
{
  "role": "user",
  "id": "msg_1d46a1f70001REibDVUjhvUdJT",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565087088
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 2
step-start
{
  "type": "step-start",
  "id": "prt_1d46a29c2001X3WufDGXZF2uz8",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a22890015Ez4XYfmUNSh7v"
}
Reasoning
Let me start by exploring the source directory.
read · error

Input

{
  "filePath": "/source"
}

Output

The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules [{"permission":"*","action":"allow","pattern":"*"},{"permission":"read","pattern":"*","action":"allow"},{"permission":"read","pattern":"*.env","action":"ask"},{"permission":"read","pattern":"*.env.*","action":"ask"},{"permission":"read","pattern":"*.env.example","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"}]
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46a2a61001e6YkAI7u3hiqLm",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a22890015Ez4XYfmUNSh7v",
  "callID": "call_0b864763503e4bd1b39f73c7",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source"
    },
    "error": "The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules [{\"permission\":\"*\",\"action\":\"allow\",\"pattern\":\"*\"},{\"permission\":\"read\",\"pattern\":\"*\",\"action\":\"allow\"},{\"permission\":\"read\",\"pattern\":\"*.env\",\"action\":\"ask\"},{\"permission\":\"read\",\"pattern\":\"*.env.*\",\"action\":\"ask\"},{\"permission\":\"read\",\"pattern\":\"*.env.example\",\"action\":\"allow\"},{\"permission\":\"*\",\"action\":\"deny\",\"pattern\":\"*\"},{\"permission\":\"read\",\"pattern\":\"*\",\"action\":\"deny\"},{\"permission\":\"read\",\"pattern\":\"source/*\",\"action\":\"allow\"},{\"permission\":\"*\",\"action\":\"deny\",\"pattern\":\"*\"},{\"permission\":\"read\",\"pattern\":\"*\",\"action\":\"deny\"},{\"permission\":\"read\",\"pattern\":\"source/*\",\"action\":\"allow\"}]",
    "time": {
      "start": 1794565089898,
      "end": 1794565089905
    }
  }
}
read · completed

Input

{
  "filePath": "/source/standards.json"
}

Output

<path>/source/standards.json</path>
<type>file</type>
<content>
1: [
2:   {
3:     "path": ".cursor/rules/karpathy-guidelines.mdc",
4:     "revision": "f57133d88d7f26767e78a9f4c0f81a9ed070fe8b",
5:     "file": "standards/karpathy-guidelines.mdc"
6:   },
7:   {
8:     "path": ".cursor/rules/ponytail.mdc",
9:     "revision": "f57133d88d7f26767e78a9f4c0f81a9ed070fe8b",
10:     "file": "standards/ponytail.mdc"
11:   }
12: ]

(End of file - total 12 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46a2aa3001EB9lq9iLcPsdQZ",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a22890015Ez4XYfmUNSh7v",
  "callID": "call_c5716e28e18a483e828b4880",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/standards.json"
    },
    "output": "<path>/source/standards.json</path>\n<type>file</type>\n<content>\n1: [\n2:   {\n3:     \"path\": \".cursor/rules/karpathy-guidelines.mdc\",\n4:     \"revision\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n5:     \"file\": \"standards/karpathy-guidelines.mdc\"\n6:   },\n7:   {\n8:     \"path\": \".cursor/rules/ponytail.mdc\",\n9:     \"revision\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n10:     \"file\": \"standards/ponytail.mdc\"\n11:   }\n12: ]\n\n(End of file - total 12 lines)\n</content>",
    "title": "source/standards.json",
    "metadata": {
      "preview": "[\n  {\n    \"path\": \".cursor/rules/karpathy-guidelines.mdc\",\n    \"revision\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n    \"file\": \"standards/karpathy-guidelines.mdc\"\n  },\n  {\n    \"path\": \".cursor/rules/ponytail.mdc\",\n    \"revision\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n    \"file\": \"standards/ponytail.mdc\"\n  }\n]",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/standards.json",
        "text": "[\n  {\n    \"path\": \".cursor/rules/karpathy-guidelines.mdc\",\n    \"revision\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n    \"file\": \"standards/karpathy-guidelines.mdc\"\n  },\n  {\n    \"path\": \".cursor/rules/ponytail.mdc\",\n    \"revision\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n    \"file\": \"standards/ponytail.mdc\"\n  }\n]",
        "lineStart": 1,
        "lineEnd": 12,
        "totalLines": 12,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565089961,
      "end": 1794565089984
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46a2ac6001f8cV3yKn2YmcSs",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a22890015Ez4XYfmUNSh7v",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3308,
    "input": 3275,
    "output": 23,
    "reasoning": 10,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46a22890015Ez4XYfmUNSh7v",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565087881,
    "completed": 1794565089999
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3308,
    "input": 3275,
    "output": 23,
    "reasoning": 10,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 3
step-start
{
  "type": "step-start",
  "id": "prt_1d46a3206001HJcs7Iwvza1wMN",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a2ad3001l3GJJWnrl3hJy5"
}
read · completed

Input

{
  "filePath": "/source/standards/karpathy-guidelines.mdc"
}

Output

<path>/source/standards/karpathy-guidelines.mdc</path>
<type>file</type>
<content>
1: ---
2: description: Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria.
3: alwaysApply: true
4: ---
5: 
6: # Karpathy behavioral guidelines
7: 
8: Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
9: 
10: **Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
11: 
12: ## 1. Think Before Coding
13: 
14: **Don't assume. Don't hide confusion. Surface tradeoffs.**
15: 
16: Before implementing:
17: 
18: - State your assumptions explicitly. If uncertain, ask.
19: - If multiple interpretations exist, present them - don't pick silently.
20: - If a simpler approach exists, say so. Push back when warranted.
21: - If something is unclear, stop. Name what's confusing. Ask.
22: 
23: ## 2. Simplicity First
24: 
25: **Minimum code that solves the problem. Nothing speculative.**
26: 
27: - No features beyond what was asked.
28: - No abstractions for single-use code.
29: - No "flexibility" or "configurability" that wasn't requested.
30: - No error handling for impossible scenarios.
31: - If you write 200 lines and it could be 50, rewrite it.
32: 
33: Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
34: 
35: ## 3. Surgical Changes
36: 
37: **Touch only what you must. Clean up only your own mess.**
38: 
39: When editing existing code:
40: 
41: - Don't "improve" adjacent code, comments, or formatting.
42: - Don't refactor things that aren't broken.
43: - Match existing style, even if you'd do it differently.
44: - If you notice unrelated dead code, mention it - don't delete it.
45: 
46: When your changes create orphans:
47: 
48: - Remove imports/variables/functions that YOUR changes made unused.
49: - Don't remove pre-existing dead code unless asked.
50: 
51: The test: Every changed line should trace directly to the user's request.
52: 
53: ## 4. Goal-Driven Execution
54: 
55: **Define success criteria. Loop until verified.**
56: 
57: Transform tasks into verifiable goals:
58: 
59: - "Add validation" → "Write tests for invalid inputs, then make them pass"
60: - "Fix the bug" → "Write a test that reproduces it, then make it pass"
61: - "Refactor X" → "Ensure tests pass before and after"
62: 
63: For multi-step tasks, state a brief plan:
64: 
65: ```
66: 1. [Step] → verify: [check]
67: 2. [Step] → verify: [check]
68: 3. [Step] → verify: [check]
69: ```
70: 
71: Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
72: 
73: ---
74: 
75: **These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.

(End of file - total 75 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46a3826001kRAkvPVotAJ3Rr",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a2ad3001l3GJJWnrl3hJy5",
  "callID": "call_e4c435a53eb34a03a173da31",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/standards/karpathy-guidelines.mdc"
    },
    "output": "<path>/source/standards/karpathy-guidelines.mdc</path>\n<type>file</type>\n<content>\n1: ---\n2: description: Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria.\n3: alwaysApply: true\n4: ---\n5: \n6: # Karpathy behavioral guidelines\n7: \n8: Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.\n9: \n10: **Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.\n11: \n12: ## 1. Think Before Coding\n13: \n14: **Don't assume. Don't hide confusion. Surface tradeoffs.**\n15: \n16: Before implementing:\n17: \n18: - State your assumptions explicitly. If uncertain, ask.\n19: - If multiple interpretations exist, present them - don't pick silently.\n20: - If a simpler approach exists, say so. Push back when warranted.\n21: - If something is unclear, stop. Name what's confusing. Ask.\n22: \n23: ## 2. Simplicity First\n24: \n25: **Minimum code that solves the problem. Nothing speculative.**\n26: \n27: - No features beyond what was asked.\n28: - No abstractions for single-use code.\n29: - No \"flexibility\" or \"configurability\" that wasn't requested.\n30: - No error handling for impossible scenarios.\n31: - If you write 200 lines and it could be 50, rewrite it.\n32: \n33: Ask yourself: \"Would a senior engineer say this is overcomplicated?\" If yes, simplify.\n34: \n35: ## 3. Surgical Changes\n36: \n37: **Touch only what you must. Clean up only your own mess.**\n38: \n39: When editing existing code:\n40: \n41: - Don't \"improve\" adjacent code, comments, or formatting.\n42: - Don't refactor things that aren't broken.\n43: - Match existing style, even if you'd do it differently.\n44: - If you notice unrelated dead code, mention it - don't delete it.\n45: \n46: When your changes create orphans:\n47: \n48: - Remove imports/variables/functions that YOUR changes made unused.\n49: - Don't remove pre-existing dead code unless asked.\n50: \n51: The test: Every changed line should trace directly to the user's request.\n52: \n53: ## 4. Goal-Driven Execution\n54: \n55: **Define success criteria. Loop until verified.**\n56: \n57: Transform tasks into verifiable goals:\n58: \n59: - \"Add validation\" → \"Write tests for invalid inputs, then make them pass\"\n60: - \"Fix the bug\" → \"Write a test that reproduces it, then make it pass\"\n61: - \"Refactor X\" → \"Ensure tests pass before and after\"\n62: \n63: For multi-step tasks, state a brief plan:\n64: \n65: ```\n66: 1. [Step] → verify: [check]\n67: 2. [Step] → verify: [check]\n68: 3. [Step] → verify: [check]\n69: ```\n70: \n71: Strong success criteria let you loop independently. Weak criteria (\"make it work\") require constant clarification.\n72: \n73: ---\n74: \n75: **These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.\n\n(End of file - total 75 lines)\n</content>",
    "title": "source/standards/karpathy-guidelines.mdc",
    "metadata": {
      "preview": "---\ndescription: Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria.\nalwaysApply: true\n---\n\n# Karpathy behavioral guidelines\n\nBehavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.\n\n**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.\n\n## 1. Think Before Coding\n\n**Don't assume. Don't hide confusion. Surface tradeoffs.**\n\nBefore implementing:\n\n- State your assumptions explicitly. If uncertain, ask.\n- If multiple interpretations exist, present them - don't pick silently.\n- If a simpler approach exists, say so. Push back when warranted.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/standards/karpathy-guidelines.mdc",
        "text": "---\ndescription: Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria.\nalwaysApply: true\n---\n\n# Karpathy behavioral guidelines\n\nBehavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.\n\n**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.\n\n## 1. Think Before Coding\n\n**Don't assume. Don't hide confusion. Surface tradeoffs.**\n\nBefore implementing:\n\n- State your assumptions explicitly. If uncertain, ask.\n- If multiple interpretations exist, present them - don't pick silently.\n- If a simpler approach exists, say so. Push back when warranted.\n- If something is unclear, stop. Name what's confusing. Ask.\n\n## 2. Simplicity First\n\n**Minimum code that solves the problem. Nothing speculative.**\n\n- No features beyond what was asked.\n- No abstractions for single-use code.\n- No \"flexibility\" or \"configurability\" that wasn't requested.\n- No error handling for impossible scenarios.\n- If you write 200 lines and it could be 50, rewrite it.\n\nAsk yourself: \"Would a senior engineer say this is overcomplicated?\" If yes, simplify.\n\n## 3. Surgical Changes\n\n**Touch only what you must. Clean up only your own mess.**\n\nWhen editing existing code:\n\n- Don't \"improve\" adjacent code, comments, or formatting.\n- Don't refactor things that aren't broken.\n- Match existing style, even if you'd do it differently.\n- If you notice unrelated dead code, mention it - don't delete it.\n\nWhen your changes create orphans:\n\n- Remove imports/variables/functions that YOUR changes made unused.\n- Don't remove pre-existing dead code unless asked.\n\nThe test: Every changed line should trace directly to the user's request.\n\n## 4. Goal-Driven Execution\n\n**Define success criteria. Loop until verified.**\n\nTransform tasks into verifiable goals:\n\n- \"Add validation\" → \"Write tests for invalid inputs, then make them pass\"\n- \"Fix the bug\" → \"Write a test that reproduces it, then make it pass\"\n- \"Refactor X\" → \"Ensure tests pass before and after\"\n\nFor multi-step tasks, state a brief plan:\n\n```\n1. [Step] → verify: [check]\n2. [Step] → verify: [check]\n3. [Step] → verify: [check]\n```\n\nStrong success criteria let you loop independently. Weak criteria (\"make it work\") require constant clarification.\n\n---\n\n**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.",
        "lineStart": 1,
        "lineEnd": 75,
        "totalLines": 75,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565093421,
      "end": 1794565093468
    }
  }
}
read · completed

Input

{
  "filePath": "/source/standards/ponytail.mdc"
}

Output

<path>/source/standards/ponytail.mdc</path>
<type>file</type>
<content>
1: ---
2: description: Ponytail, lazy senior dev mode. Always pick the simplest solution that works.
3: globs:
4: alwaysApply: true
5: ---
6: 
7: # Ponytail, lazy senior dev mode
8: 
9: You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.
10: 
11: Before writing any code, stop at the first rung that holds:
12: 
13: 1. Does this need to be built at all? (YAGNI)
14: 2. Does it already exist in this codebase? Reuse the helper, util, or pattern that's already here, don't re-write it.
15: 3. Does the standard library already do this? Use it.
16: 4. Does a native platform feature cover it? Use it.
17: 5. Does an already-installed dependency solve it? Use it.
18: 6. Can this be one line? Make it one line.
19: 7. Only then: write the minimum code that works.
20: 
21: The ladder runs after you understand the problem, not instead of it: read the task and the code it touches, trace the real flow end to end, then climb.
22: 
23: Bug fix = root cause, not symptom: a report names a symptom. Grep every caller of the function you touch and fix the shared function once — one guard there is a smaller diff than one per caller, and patching only the path the ticket names leaves a sibling caller still broken.
24: 
25: Rules:
26: 
27: - No abstractions that weren't explicitly requested.
28: - No new dependency if it can be avoided.
29: - No boilerplate nobody asked for.
30: - Deletion over addition. Boring over clever. Fewest files possible.
31: - Shortest working diff wins, but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.
32: - Question complex requests: "Do you actually need X, or does Y cover it?"
33: - Pick the edge-case-correct option when two stdlib approaches are the same size, lazy means less code, not the flimsier algorithm.
34: - Mark deliberate simplifications that cut a real corner with a known ceiling (global lock, O(n²) scan, naive heuristic) with a `ponytail:` comment naming the ceiling and upgrade path.
35: 
36: Not lazy about: understanding the problem (read it fully and trace the real flow before picking a rung, a small diff you don't understand is just laziness dressed up as efficiency), input validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs (the platform is never the spec ideal, a clock drifts, a sensor reads off), anything explicitly requested. Lazy code without its check is unfinished: non-trivial logic leaves ONE runnable check behind, the smallest thing that fails if the logic breaks (an assert-based demo/self-check or one small test file; no frameworks, no fixtures). Trivial one-liners need no test.

(End of file - total 36 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46a3830001z21AzeSp207eUC",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a2ad3001l3GJJWnrl3hJy5",
  "callID": "call_c6492934e2744f2281a2f34e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/standards/ponytail.mdc"
    },
    "output": "<path>/source/standards/ponytail.mdc</path>\n<type>file</type>\n<content>\n1: ---\n2: description: Ponytail, lazy senior dev mode. Always pick the simplest solution that works.\n3: globs:\n4: alwaysApply: true\n5: ---\n6: \n7: # Ponytail, lazy senior dev mode\n8: \n9: You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.\n10: \n11: Before writing any code, stop at the first rung that holds:\n12: \n13: 1. Does this need to be built at all? (YAGNI)\n14: 2. Does it already exist in this codebase? Reuse the helper, util, or pattern that's already here, don't re-write it.\n15: 3. Does the standard library already do this? Use it.\n16: 4. Does a native platform feature cover it? Use it.\n17: 5. Does an already-installed dependency solve it? Use it.\n18: 6. Can this be one line? Make it one line.\n19: 7. Only then: write the minimum code that works.\n20: \n21: The ladder runs after you understand the problem, not instead of it: read the task and the code it touches, trace the real flow end to end, then climb.\n22: \n23: Bug fix = root cause, not symptom: a report names a symptom. Grep every caller of the function you touch and fix the shared function once — one guard there is a smaller diff than one per caller, and patching only the path the ticket names leaves a sibling caller still broken.\n24: \n25: Rules:\n26: \n27: - No abstractions that weren't explicitly requested.\n28: - No new dependency if it can be avoided.\n29: - No boilerplate nobody asked for.\n30: - Deletion over addition. Boring over clever. Fewest files possible.\n31: - Shortest working diff wins, but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.\n32: - Question complex requests: \"Do you actually need X, or does Y cover it?\"\n33: - Pick the edge-case-correct option when two stdlib approaches are the same size, lazy means less code, not the flimsier algorithm.\n34: - Mark deliberate simplifications that cut a real corner with a known ceiling (global lock, O(n²) scan, naive heuristic) with a `ponytail:` comment naming the ceiling and upgrade path.\n35: \n36: Not lazy about: understanding the problem (read it fully and trace the real flow before picking a rung, a small diff you don't understand is just laziness dressed up as efficiency), input validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs (the platform is never the spec ideal, a clock drifts, a sensor reads off), anything explicitly requested. Lazy code without its check is unfinished: non-trivial logic leaves ONE runnable check behind, the smallest thing that fails if the logic breaks (an assert-based demo/self-check or one small test file; no frameworks, no fixtures). Trivial one-liners need no test.\n\n(End of file - total 36 lines)\n</content>",
    "title": "source/standards/ponytail.mdc",
    "metadata": {
      "preview": "---\ndescription: Ponytail, lazy senior dev mode. Always pick the simplest solution that works.\nglobs:\nalwaysApply: true\n---\n\n# Ponytail, lazy senior dev mode\n\nYou are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.\n\nBefore writing any code, stop at the first rung that holds:\n\n1. Does this need to be built at all? (YAGNI)\n2. Does it already exist in this codebase? Reuse the helper, util, or pattern that's already here, don't re-write it.\n3. Does the standard library already do this? Use it.\n4. Does a native platform feature cover it? Use it.\n5. Does an already-installed dependency solve it? Use it.\n6. Can this be one line? Make it one line.\n7. Only then: write the minimum code that works.\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/standards/ponytail.mdc",
        "text": "---\ndescription: Ponytail, lazy senior dev mode. Always pick the simplest solution that works.\nglobs:\nalwaysApply: true\n---\n\n# Ponytail, lazy senior dev mode\n\nYou are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.\n\nBefore writing any code, stop at the first rung that holds:\n\n1. Does this need to be built at all? (YAGNI)\n2. Does it already exist in this codebase? Reuse the helper, util, or pattern that's already here, don't re-write it.\n3. Does the standard library already do this? Use it.\n4. Does a native platform feature cover it? Use it.\n5. Does an already-installed dependency solve it? Use it.\n6. Can this be one line? Make it one line.\n7. Only then: write the minimum code that works.\n\nThe ladder runs after you understand the problem, not instead of it: read the task and the code it touches, trace the real flow end to end, then climb.\n\nBug fix = root cause, not symptom: a report names a symptom. Grep every caller of the function you touch and fix the shared function once — one guard there is a smaller diff than one per caller, and patching only the path the ticket names leaves a sibling caller still broken.\n\nRules:\n\n- No abstractions that weren't explicitly requested.\n- No new dependency if it can be avoided.\n- No boilerplate nobody asked for.\n- Deletion over addition. Boring over clever. Fewest files possible.\n- Shortest working diff wins, but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.\n- Question complex requests: \"Do you actually need X, or does Y cover it?\"\n- Pick the edge-case-correct option when two stdlib approaches are the same size, lazy means less code, not the flimsier algorithm.\n- Mark deliberate simplifications that cut a real corner with a known ceiling (global lock, O(n²) scan, naive heuristic) with a `ponytail:` comment naming the ceiling and upgrade path.\n\nNot lazy about: understanding the problem (read it fully and trace the real flow before picking a rung, a small diff you don't understand is just laziness dressed up as efficiency), input validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs (the platform is never the spec ideal, a clock drifts, a sensor reads off), anything explicitly requested. Lazy code without its check is unfinished: non-trivial logic leaves ONE runnable check behind, the smallest thing that fails if the logic breaks (an assert-based demo/self-check or one small test file; no frameworks, no fixtures). Trivial one-liners need no test.",
        "lineStart": 1,
        "lineEnd": 36,
        "totalLines": 36,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565093429,
      "end": 1794565093453
    }
  }
}
read · completed

Input

{
  "filePath": "/source/diff.txt"
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1: diff --git a/core/events/netlink.go b/core/events/netlink.go
2: index 1654a4a..d1ed517 100644
3: --- a/core/events/netlink.go
4: +++ b/core/events/netlink.go
5: @@ -2,10 +2,11 @@ package events
6:  
7:  import (
8:  	"context"
9:  	"errors"
10:  	"fmt"
11: +	"maps"
12:  	"math"
13:  	"strconv"
14:  	"strings"
15:  	"sync"
16:  	"time"
17: @@ -245,12 +246,28 @@ type netlinkWatcher struct {
18:  	done            chan struct{}
19:  	includeSnapshot bool
20:  	includeStats    bool
21:  	statsInterval   time.Duration
22:  	nsHandle        netns.NsHandle
23: +	// reported holds what each link was last reported as, by its index in the
24: +	// container's namespace.
25: +	reported map[int]reportedInterface
26:  }
27:  
28: +// reportedInterface is what a link was last reported as.
29: +type reportedInterface struct {
30: +	attributes map[string]string
31: +	// since is when the link was first reported.
32: +	since time.Time
33: +}
34: +
35: +// stitchMarkWindow is how long after a link is first reported its host-side
36: +// stitch interface is looked for while the link itself does not change.
37: +// Deploying a veth-stitch link marks that interface right after it creates the
38: +// link, without a change in the node's namespace.
39: +var stitchMarkWindow = time.Minute
40: +
41:  // Retry settings for a watcher that could not subscribe to link updates.
42:  var (
43:  	watchMaxAttempts   = 5
44:  	watchRetryDelay    = time.Second
45:  	watchMaxRetryDelay = 10 * time.Second
46: @@ -419,10 +436,11 @@ func (w *netlinkWatcher) watch(
47:  		select {
48:  		case <-tickerC:
49:  			w.collectAndEmitStats(netHandle, states, statsSamples, registry)
50:  		case <-netemTicker.C:
51:  			w.pollNetemChanges(states, registry, netemQuery)
52: +			w.reportStitchMarks(states, registry)
53:  		case <-ctx.Done():
54:  			return true, nil
55:  		case update, ok := <-updates:
56:  			if !ok {
57:  				errMu.Lock()
58: @@ -494,15 +512,15 @@ func (w *netlinkWatcher) processExisting(
59:  		}
60:  	}
61:  
62:  	switch {
63:  	case exists:
64: -		registry.emitInterfaceEvent(w.container, "update", snapshot)
65: +		w.emit(registry, "update", snapshot)
66:  	case !initial:
67: -		registry.emitInterfaceEvent(w.container, "create", snapshot)
68: +		w.emit(registry, "create", snapshot)
69:  	case w.includeSnapshot:
70: -		registry.emitInterfaceEvent(w.container, "snapshot", snapshot)
71: +		w.emit(registry, "snapshot", snapshot)
72:  	}
73:  }
74:  
75:  // removeVanishedLinks reports the links that were deleted while no
76:  // subscription was active and returns their indexes.
77: @@ -532,11 +550,11 @@ func (w *netlinkWatcher) removeVanishedLinks(
78:  
79:  		vanished[idx] = struct{}{}
80:  
81:  		delete(states, idx)
82:  		delete(statsSamples, idx)
83: -		registry.emitInterfaceEvent(w.container, "delete", snapshot)
84: +		w.emit(registry, "delete", snapshot)
85:  	}
86:  
87:  	return vanished
88:  }
89:  
90: @@ -567,11 +585,11 @@ func (w *netlinkWatcher) processUpdate(
91:  			return
92:  		}
93:  
94:  		delete(states, snapshot.Index)
95:  		delete(statsSamples, snapshot.Index)
96: -		registry.emitInterfaceEvent(w.container, "delete", previous)
97: +		w.emit(registry, "delete", previous)
98:  	case unix.RTM_NEWLINK:
99:  		// Query netem info for this interface
100:  		snapshot = withNetem(snapshot, netemQuery.Query())
101:  
102:  		if exists && snapshot.equal(previous) {
103: @@ -587,11 +605,11 @@ func (w *netlinkWatcher) processUpdate(
104:  		if w.includeStats && statsSamples != nil {
105:  			if sample, ok := newStatsSample(snapshot, time.Now()); ok {
106:  				statsSamples[snapshot.Index] = sample
107:  			}
108:  		}
109: -		registry.emitInterfaceEvent(w.container, action, snapshot)
110: +		w.emit(registry, action, snapshot)
111:  	}
112:  }
113:  
114:  // pollNetemChanges checks for netem changes and emits update events.
115:  func (w *netlinkWatcher) pollNetemChanges(
116: @@ -622,13 +640,117 @@ func (w *netlinkWatcher) pollNetemChanges(
117:  			snapshot.Corruption = 0
118:  		}
119:  
120:  		if !snapshot.equal(previous) {
121:  			states[idx] = snapshot
122: -			registry.emitInterfaceEvent(w.container, "update", snapshot)
123: +			w.emit(registry, "update", snapshot)
124: +		}
125: +	}
126: +}
127: +
128: +// reportStitchMarks reports the links whose host-side stitch interface got
129: +// marked after their last event. Only veths reported under their own name
130: +// shortly before are looked at: the node's end of a veth-stitch link is a veth
131: +// and is marked while its lab deploys.
132: +func (w *netlinkWatcher) reportStitchMarks(
133: +	states map[int]ifaceSnapshot,
134: +	registry *netlinkRegistry,
135: +) {
136: +	for idx, snapshot := range states {
137: +		reported, ok := w.reported[idx]
138: +		if !ok || snapshot.Type != "veth" ||
139: +			reported.attributes["ifname"] != snapshot.Name ||
140: +			time.Since(reported.since) > stitchMarkWindow {
141: +			continue
142: +		}
143: +
144: +		if interfaceAttributes(w.container, snapshot)["ifname"] != snapshot.Name {
145: +			w.emit(registry, "update", snapshot)
146: +		}
147: +	}
148: +}
149: +
150: +// emit reports an event of a link. A deletion names the link as it was last
151: +// reported. A link reported under another name before, such as the node's own
152: +// interface until its stitch interface got marked, is first reported deleted
153: +// under that name, so that clients do not keep both; it is then new to them.
154: +func (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {
155: +	if w.container == nil {
156: +		return
157: +	}
158: +
159: +	if action == "delete" {
160: +		attributes := interfaceAttributes(w.container, snapshot)
161: +		if previous, ok := w.reported[snapshot.Index]; ok {
162: +			attributes = previous.attributes
163:  		}
164: +
165: +		delete(w.reported, snapshot.Index)
166: +		registry.sendInterfaceEvent(w.container, action, attributes, time.Now())
167: +
168: +		return
169: +	}
170: +
171: +	attributes := interfaceAttributes(w.container, snapshot)
172: +	if w.track(registry, snapshot.Index, attributes) && action == "update" {
173: +		action = "create"
174: +	}
175: +
176: +	registry.sendInterfaceEvent(w.container, action, attributes, time.Now())
177: +}
178: +
179: +// emitStats reports the counters of a link, under the name emit reports it.
180: +func (w *netlinkWatcher) emitStats(
181: +	registry *netlinkRegistry,
182: +	snapshot ifaceSnapshot,
183: +	metrics ifaceStatsMetrics,
184: +) {
185: +	if !registry.includeStats || w.container == nil || !snapshot.HasStats {
186: +		return
187: +	}
188: +
189: +	attributes := interfaceAttributes(w.container, snapshot)
190: +	if w.track(registry, snapshot.Index, attributes) {
191: +		registry.sendInterfaceEvent(
192: +			w.container,
193: +			"create",
194: +			maps.Clone(attributes),
195: +			metrics.Timestamp,
196: +		)
197: +	}
198: +
199: +	interfaceStatsAttributes(attributes, metrics)
200: +	registry.sendInterfaceEvent(w.container, "stats", attributes, metrics.Timestamp)
201: +}
202: +
203: +// track records what the link at index is reported as. When it was reported
204: +// under another name before, it reports that name deleted and returns true.
205: +func (w *netlinkWatcher) track(
206: +	registry *netlinkRegistry,
207: +	index int,
208: +	attributes map[string]string,
209: +) bool {
210: +	if w.reported == nil {
211: +		w.reported = make(map[int]reportedInterface)
212:  	}
213: +
214: +	previous, known := w.reported[index]
215: +
216: +	since := time.Now()
217: +	if known {
218: +		since = previous.since
219: +	}
220: +
221: +	w.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}
222: +
223: +	if !known || previous.attributes["ifname"] == attributes["ifname"] {
224: +		return false
225: +	}
226: +
227: +	registry.sendInterfaceEvent(w.container, "delete", previous.attributes, time.Now())
228: +
229: +	return true
230:  }
231:  
232:  func firstContainerName(container *clabruntime.GenericContainer) string {
233:  	if container == nil || len(container.Names) == 0 {
234:  		return ""
235: @@ -807,23 +929,18 @@ func overlayToolsInterface(
236:  	if snapshot.MAC != "" {
237:  		attributes["mac"] = snapshot.MAC
238:  	}
239:  }
240:  
241: -func (r *netlinkRegistry) emitInterfaceEvent(
242: +func (r *netlinkRegistry) sendInterfaceEvent(
243:  	container *clabruntime.GenericContainer,
244:  	action string,
245: -	snapshot ifaceSnapshot,
246: +	attributes map[string]string,
247: +	timestamp time.Time,
248:  ) {
249: -	if container == nil {
250: -		return
251: -	}
252: -
253: -	attributes := interfaceAttributes(container, snapshot)
254: -
255:  	event := aggregatedEvent{
256: -		Timestamp:   time.Now(),
257: +		Timestamp:   timestamp,
258:  		Type:        "interface",
259:  		Action:      action,
260:  		ActorID:     container.ShortID,
261:  		ActorName:   firstContainerName(container),
262:  		ActorFullID: container.ID,
263: @@ -870,38 +987,10 @@ func waitForNamespacePath(
264:  	}
265:  
266:  	return "", fmt.Errorf("namespace path not ready for container %s", containerID)
267:  }
268:  
269: -func (r *netlinkRegistry) emitInterfaceStatsEvent(
270: -	container *clabruntime.GenericContainer,
271: -	snapshot ifaceSnapshot,
272: -	metrics ifaceStatsMetrics,
273: -) {
274: -	if !r.includeStats || container == nil || !snapshot.HasStats {
275: -		return
276: -	}
277: -
278: -	attributes := interfaceAttributes(container, snapshot)
279: -	interfaceStatsAttributes(attributes, metrics)
280: -
281: -	event := aggregatedEvent{
282: -		Timestamp:   metrics.Timestamp,
283: -		Type:        "interface",
284: -		Action:      "stats",
285: -		ActorID:     container.ShortID,
286: -		ActorName:   firstContainerName(container),
287: -		ActorFullID: container.ID,
288: -		Attributes:  attributes,
289: -	}
290: -
291: -	select {
292: -	case r.events <- event:
293: -	case <-r.ctx.Done():
294: -	}
295: -}
296: -
297:  func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {
298:  	if netHandle == nil {
299:  		return nil, fmt.Errorf("netlink handle is nil")
300:  	}
301:  
302: @@ -1138,11 +1227,11 @@ func (w *netlinkWatcher) collectAndEmitStats(
303:  			TxPps:     float64(txPacketsDelta) / seconds,
304:  			Interval:  interval,
305:  			Timestamp: now,
306:  		}
307:  
308: -		registry.emitInterfaceStatsEvent(w.container, state, metrics)
309: +		w.emitStats(registry, state, metrics)
310:  
311:  		statsSamples[idx] = ifaceStatsSample{
312:  			RxBytes:   state.RxBytes,
313:  			TxBytes:   state.TxBytes,
314:  			RxPackets: state.RxPackets,
315: diff --git a/core/events/netlink_watch_test.go b/core/events/netlink_watch_test.go
316: index 29fc7ee..b81b0e4 100644
317: --- a/core/events/netlink_watch_test.go
318: +++ b/core/events/netlink_watch_test.go
319: @@ -386,5 +386,149 @@ func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {
320:  
321:  	if _, ok := states[7]; ok {
322:  		t.Fatal("deleted link is still tracked")
323:  	}
324:  }
325: +
326: +// reportedEvent is the action and interface name of an emitted event.
327: +type reportedEvent struct {
328: +	action string
329: +	ifname string
330: +}
331: +
332: +// drainEvents closes events and returns what was emitted, in order.
333: +func drainEvents(events chan aggregatedEvent) []reportedEvent {
334: +	close(events)
335: +
336: +	var got []reportedEvent
337: +	for ev := range events {
338: +		got = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes["ifname"]})
339: +	}
340: +
341: +	return got
342: +}
343: +
344: +// stitchedWatcher returns a watcher that reported the link with index 7 as
345: +// the host-side stitch interface of its veth-stitch link.
346: +func stitchedWatcher() *netlinkWatcher {
347: +	return &netlinkWatcher{
348: +		container: &clabruntime.GenericContainer{Names: []string{"n1"}},
349: +		reported: map[int]reportedInterface{
350: +			7: {
351: +				attributes: map[string]string{"ifname": "clab-s-0011aabb", "alias": "e1-1"},
352: +				since:      time.Now(),
353: +			},
354: +		},
355: +	}
356: +}
357: +
358: +// TestEmitReportsRenamedLinkDeleted checks that a link reported under another
359: +// name than before is first reported deleted under the old name, so clients
360: +// do not keep both, and is then new to them.
361: +func TestEmitReportsRenamedLinkDeleted(t *testing.T) {
362: +	events := make(chan aggregatedEvent, 8)
363: +	registry := newNetlinkRegistry(t.Context(), events, false, false, 0)
364: +	watcher := stitchedWatcher()
365: +
366: +	link := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "e1-1", MTU: 1500}}
367: +	watcher.emit(registry, "update", snapshotFromLink(link))
368: +	watcher.emit(registry, "update", snapshotFromLink(link))
369: +
370: +	want := []reportedEvent{
371: +		{action: "delete", ifname: "clab-s-0011aabb"},
372: +		{action: "create", ifname: "e1-1"},
373: +		{action: "update", ifname: "e1-1"},
374: +	}
375: +	if got := drainEvents(events); !slices.Equal(got, want) {
376: +		t.Fatalf("events = %v, want %v", got, want)
377: +	}
378: +}
379: +
380: +// TestEmitDeletesLinkAsLastReported checks that a deletion names the link as
381: +// clients know it, also when its stitch interface is already gone.
382: +func TestEmitDeletesLinkAsLastReported(t *testing.T) {
383: +	events := make(chan aggregatedEvent, 8)
384: +	registry := newNetlinkRegistry(t.Context(), events, false, false, 0)
385: +	watcher := stitchedWatcher()
386: +
387: +	link := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "e1-1", MTU: 1500}}
388: +	watcher.emit(registry, "delete", snapshotFromLink(link))
389: +
390: +	want := []reportedEvent{{action: "delete", ifname: "clab-s-0011aabb"}}
391: +	if got := drainEvents(events); !slices.Equal(got, want) {
392: +		t.Fatalf("events = %v, want %v", got, want)
393: +	}
394: +
395: +	if _, ok := watcher.reported[7]; ok {
396: +		t.Fatal("deleted link is still tracked as reported")
397: +	}
398: +}
399: +
400: +// TestEmitStatsReportsRenamedLinkFirst checks that counters of a link reported
401: +// under another name before follow its deletion under that name and its
402: +// creation without counters.
403: +func TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {
404: +	events := make(chan aggregatedEvent, 8)
405: +	registry := newNetlinkRegistry(t.Context(), events, false, true, time.Second)
406: +	watcher := stitchedWatcher()
407: +
408: +	link := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{
409: +		Index:      7,
410: +		Name:       "e1-1",
411: +		MTU:        1500,
412: +		Statistics: &netlink.LinkStatistics{RxBytes: 10},
413: +	}}
414: +	watcher.emitStats(registry, snapshotFromLink(link), ifaceStatsMetrics{
415: +		Timestamp: time.Now(),
416: +	})
417: +	close(events)
418: +
419: +	var got []reportedEvent
420: +	for ev := range events {
421: +		got = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes["ifname"]})
422: +
423: +		_, hasCounters := ev.Attributes["rx_bytes"]
424: +		if hasCounters != (ev.Action == "stats") {
425: +			t.Fatalf("%s event has counters: %v", ev.Action, hasCounters)
426: +		}
427: +	}
428: +
429: +	want := []reportedEvent{
430: +		{action: "delete", ifname: "clab-s-0011aabb"},
431: +		{action: "create", ifname: "e1-1"},
432: +		{action: "stats", ifname: "e1-1"},
433: +	}
434: +	if !slices.Equal(got, want) {
435: +		t.Fatalf("events = %v, want %v", got, want)
436: +	}
437: +
438: +	if _, ok := watcher.reported[7].attributes["rx_bytes"]; ok {
439: +		t.Fatal("counters are kept as what the link was reported as")
440: +	}
441: +}
442: +
443: +// TestReportStitchMarksLeavesUnmarkedLinks checks that links without a marked
444: +// stitch interface, or reported too long ago, are not reported again.
445: +func TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {
446: +	events := make(chan aggregatedEvent, 8)
447: +	registry := newNetlinkRegistry(t.Context(), events, false, false, 0)
448: +	watcher := &netlinkWatcher{
449: +		container: &clabruntime.GenericContainer{Names: []string{"n1"}},
450: +	}
451: +
452: +	recent := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "e1-1", MTU: 1500}}
453: +	old := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 8, Name: "e1-2", MTU: 1500}}
454: +	states := map[int]ifaceSnapshot{7: snapshotFromLink(recent), 8: snapshotFromLink(old)}
455: +	watcher.emit(registry, "create", states[7])
456: +	watcher.emit(registry, "create", states[8])
457: +	watcher.reported[8] = reportedInterface{
458: +		attributes: watcher.reported[8].attributes,
459: +		since:      time.Now().Add(-2 * stitchMarkWindow),
460: +	}
461: +
462: +	watcher.reportStitchMarks(states, registry)
463: +
464: +	want := []reportedEvent{{action: "create", ifname: "e1-1"}, {action: "create", ifname: "e1-2"}}
465: +	if got := drainEvents(events); !slices.Equal(got, want) {
466: +		t.Fatalf("events = %v, want %v", got, want)
467: +	}
468: +}

(End of file - total 468 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46a383800106rzH1PoyjpOns",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a2ad3001l3GJJWnrl3hJy5",
  "callID": "call_082aea23eed74abe9cae87c7",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt"
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1: diff --git a/core/events/netlink.go b/core/events/netlink.go\n2: index 1654a4a..d1ed517 100644\n3: --- a/core/events/netlink.go\n4: +++ b/core/events/netlink.go\n5: @@ -2,10 +2,11 @@ package events\n6:  \n7:  import (\n8:  \t\"context\"\n9:  \t\"errors\"\n10:  \t\"fmt\"\n11: +\t\"maps\"\n12:  \t\"math\"\n13:  \t\"strconv\"\n14:  \t\"strings\"\n15:  \t\"sync\"\n16:  \t\"time\"\n17: @@ -245,12 +246,28 @@ type netlinkWatcher struct {\n18:  \tdone            chan struct{}\n19:  \tincludeSnapshot bool\n20:  \tincludeStats    bool\n21:  \tstatsInterval   time.Duration\n22:  \tnsHandle        netns.NsHandle\n23: +\t// reported holds what each link was last reported as, by its index in the\n24: +\t// container's namespace.\n25: +\treported map[int]reportedInterface\n26:  }\n27:  \n28: +// reportedInterface is what a link was last reported as.\n29: +type reportedInterface struct {\n30: +\tattributes map[string]string\n31: +\t// since is when the link was first reported.\n32: +\tsince time.Time\n33: +}\n34: +\n35: +// stitchMarkWindow is how long after a link is first reported its host-side\n36: +// stitch interface is looked for while the link itself does not change.\n37: +// Deploying a veth-stitch link marks that interface right after it creates the\n38: +// link, without a change in the node's namespace.\n39: +var stitchMarkWindow = time.Minute\n40: +\n41:  // Retry settings for a watcher that could not subscribe to link updates.\n42:  var (\n43:  \twatchMaxAttempts   = 5\n44:  \twatchRetryDelay    = time.Second\n45:  \twatchMaxRetryDelay = 10 * time.Second\n46: @@ -419,10 +436,11 @@ func (w *netlinkWatcher) watch(\n47:  \t\tselect {\n48:  \t\tcase <-tickerC:\n49:  \t\t\tw.collectAndEmitStats(netHandle, states, statsSamples, registry)\n50:  \t\tcase <-netemTicker.C:\n51:  \t\t\tw.pollNetemChanges(states, registry, netemQuery)\n52: +\t\t\tw.reportStitchMarks(states, registry)\n53:  \t\tcase <-ctx.Done():\n54:  \t\t\treturn true, nil\n55:  \t\tcase update, ok := <-updates:\n56:  \t\t\tif !ok {\n57:  \t\t\t\terrMu.Lock()\n58: @@ -494,15 +512,15 @@ func (w *netlinkWatcher) processExisting(\n59:  \t\t}\n60:  \t}\n61:  \n62:  \tswitch {\n63:  \tcase exists:\n64: -\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n65: +\t\tw.emit(registry, \"update\", snapshot)\n66:  \tcase !initial:\n67: -\t\tregistry.emitInterfaceEvent(w.container, \"create\", snapshot)\n68: +\t\tw.emit(registry, \"create\", snapshot)\n69:  \tcase w.includeSnapshot:\n70: -\t\tregistry.emitInterfaceEvent(w.container, \"snapshot\", snapshot)\n71: +\t\tw.emit(registry, \"snapshot\", snapshot)\n72:  \t}\n73:  }\n74:  \n75:  // removeVanishedLinks reports the links that were deleted while no\n76:  // subscription was active and returns their indexes.\n77: @@ -532,11 +550,11 @@ func (w *netlinkWatcher) removeVanishedLinks(\n78:  \n79:  \t\tvanished[idx] = struct{}{}\n80:  \n81:  \t\tdelete(states, idx)\n82:  \t\tdelete(statsSamples, idx)\n83: -\t\tregistry.emitInterfaceEvent(w.container, \"delete\", snapshot)\n84: +\t\tw.emit(registry, \"delete\", snapshot)\n85:  \t}\n86:  \n87:  \treturn vanished\n88:  }\n89:  \n90: @@ -567,11 +585,11 @@ func (w *netlinkWatcher) processUpdate(\n91:  \t\t\treturn\n92:  \t\t}\n93:  \n94:  \t\tdelete(states, snapshot.Index)\n95:  \t\tdelete(statsSamples, snapshot.Index)\n96: -\t\tregistry.emitInterfaceEvent(w.container, \"delete\", previous)\n97: +\t\tw.emit(registry, \"delete\", previous)\n98:  \tcase unix.RTM_NEWLINK:\n99:  \t\t// Query netem info for this interface\n100:  \t\tsnapshot = withNetem(snapshot, netemQuery.Query())\n101:  \n102:  \t\tif exists && snapshot.equal(previous) {\n103: @@ -587,11 +605,11 @@ func (w *netlinkWatcher) processUpdate(\n104:  \t\tif w.includeStats && statsSamples != nil {\n105:  \t\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n106:  \t\t\t\tstatsSamples[snapshot.Index] = sample\n107:  \t\t\t}\n108:  \t\t}\n109: -\t\tregistry.emitInterfaceEvent(w.container, action, snapshot)\n110: +\t\tw.emit(registry, action, snapshot)\n111:  \t}\n112:  }\n113:  \n114:  // pollNetemChanges checks for netem changes and emits update events.\n115:  func (w *netlinkWatcher) pollNetemChanges(\n116: @@ -622,13 +640,117 @@ func (w *netlinkWatcher) pollNetemChanges(\n117:  \t\t\tsnapshot.Corruption = 0\n118:  \t\t}\n119:  \n120:  \t\tif !snapshot.equal(previous) {\n121:  \t\t\tstates[idx] = snapshot\n122: -\t\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n123: +\t\t\tw.emit(registry, \"update\", snapshot)\n124: +\t\t}\n125: +\t}\n126: +}\n127: +\n128: +// reportStitchMarks reports the links whose host-side stitch interface got\n129: +// marked after their last event. Only veths reported under their own name\n130: +// shortly before are looked at: the node's end of a veth-stitch link is a veth\n131: +// and is marked while its lab deploys.\n132: +func (w *netlinkWatcher) reportStitchMarks(\n133: +\tstates map[int]ifaceSnapshot,\n134: +\tregistry *netlinkRegistry,\n135: +) {\n136: +\tfor idx, snapshot := range states {\n137: +\t\treported, ok := w.reported[idx]\n138: +\t\tif !ok || snapshot.Type != \"veth\" ||\n139: +\t\t\treported.attributes[\"ifname\"] != snapshot.Name ||\n140: +\t\t\ttime.Since(reported.since) > stitchMarkWindow {\n141: +\t\t\tcontinue\n142: +\t\t}\n143: +\n144: +\t\tif interfaceAttributes(w.container, snapshot)[\"ifname\"] != snapshot.Name {\n145: +\t\t\tw.emit(registry, \"update\", snapshot)\n146: +\t\t}\n147: +\t}\n148: +}\n149: +\n150: +// emit reports an event of a link. A deletion names the link as it was last\n151: +// reported. A link reported under another name before, such as the node's own\n152: +// interface until its stitch interface got marked, is first reported deleted\n153: +// under that name, so that clients do not keep both; it is then new to them.\n154: +func (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {\n155: +\tif w.container == nil {\n156: +\t\treturn\n157: +\t}\n158: +\n159: +\tif action == \"delete\" {\n160: +\t\tattributes := interfaceAttributes(w.container, snapshot)\n161: +\t\tif previous, ok := w.reported[snapshot.Index]; ok {\n162: +\t\t\tattributes = previous.attributes\n163:  \t\t}\n164: +\n165: +\t\tdelete(w.reported, snapshot.Index)\n166: +\t\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n167: +\n168: +\t\treturn\n169: +\t}\n170: +\n171: +\tattributes := interfaceAttributes(w.container, snapshot)\n172: +\tif w.track(registry, snapshot.Index, attributes) && action == \"update\" {\n173: +\t\taction = \"create\"\n174: +\t}\n175: +\n176: +\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n177: +}\n178: +\n179: +// emitStats reports the counters of a link, under the name emit reports it.\n180: +func (w *netlinkWatcher) emitStats(\n181: +\tregistry *netlinkRegistry,\n182: +\tsnapshot ifaceSnapshot,\n183: +\tmetrics ifaceStatsMetrics,\n184: +) {\n185: +\tif !registry.includeStats || w.container == nil || !snapshot.HasStats {\n186: +\t\treturn\n187: +\t}\n188: +\n189: +\tattributes := interfaceAttributes(w.container, snapshot)\n190: +\tif w.track(registry, snapshot.Index, attributes) {\n191: +\t\tregistry.sendInterfaceEvent(\n192: +\t\t\tw.container,\n193: +\t\t\t\"create\",\n194: +\t\t\tmaps.Clone(attributes),\n195: +\t\t\tmetrics.Timestamp,\n196: +\t\t)\n197: +\t}\n198: +\n199: +\tinterfaceStatsAttributes(attributes, metrics)\n200: +\tregistry.sendInterfaceEvent(w.container, \"stats\", attributes, metrics.Timestamp)\n201: +}\n202: +\n203: +// track records what the link at index is reported as. When it was reported\n204: +// under another name before, it reports that name deleted and returns true.\n205: +func (w *netlinkWatcher) track(\n206: +\tregistry *netlinkRegistry,\n207: +\tindex int,\n208: +\tattributes map[string]string,\n209: +) bool {\n210: +\tif w.reported == nil {\n211: +\t\tw.reported = make(map[int]reportedInterface)\n212:  \t}\n213: +\n214: +\tprevious, known := w.reported[index]\n215: +\n216: +\tsince := time.Now()\n217: +\tif known {\n218: +\t\tsince = previous.since\n219: +\t}\n220: +\n221: +\tw.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}\n222: +\n223: +\tif !known || previous.attributes[\"ifname\"] == attributes[\"ifname\"] {\n224: +\t\treturn false\n225: +\t}\n226: +\n227: +\tregistry.sendInterfaceEvent(w.container, \"delete\", previous.attributes, time.Now())\n228: +\n229: +\treturn true\n230:  }\n231:  \n232:  func firstContainerName(container *clabruntime.GenericContainer) string {\n233:  \tif container == nil || len(container.Names) == 0 {\n234:  \t\treturn \"\"\n235: @@ -807,23 +929,18 @@ func overlayToolsInterface(\n236:  \tif snapshot.MAC != \"\" {\n237:  \t\tattributes[\"mac\"] = snapshot.MAC\n238:  \t}\n239:  }\n240:  \n241: -func (r *netlinkRegistry) emitInterfaceEvent(\n242: +func (r *netlinkRegistry) sendInterfaceEvent(\n243:  \tcontainer *clabruntime.GenericContainer,\n244:  \taction string,\n245: -\tsnapshot ifaceSnapshot,\n246: +\tattributes map[string]string,\n247: +\ttimestamp time.Time,\n248:  ) {\n249: -\tif container == nil {\n250: -\t\treturn\n251: -\t}\n252: -\n253: -\tattributes := interfaceAttributes(container, snapshot)\n254: -\n255:  \tevent := aggregatedEvent{\n256: -\t\tTimestamp:   time.Now(),\n257: +\t\tTimestamp:   timestamp,\n258:  \t\tType:        \"interface\",\n259:  \t\tAction:      action,\n260:  \t\tActorID:     container.ShortID,\n261:  \t\tActorName:   firstContainerName(container),\n262:  \t\tActorFullID: container.ID,\n263: @@ -870,38 +987,10 @@ func waitForNamespacePath(\n264:  \t}\n265:  \n266:  \treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n267:  }\n268:  \n269: -func (r *netlinkRegistry) emitInterfaceStatsEvent(\n270: -\tcontainer *clabruntime.GenericContainer,\n271: -\tsnapshot ifaceSnapshot,\n272: -\tmetrics ifaceStatsMetrics,\n273: -) {\n274: -\tif !r.includeStats || container == nil || !snapshot.HasStats {\n275: -\t\treturn\n276: -\t}\n277: -\n278: -\tattributes := interfaceAttributes(container, snapshot)\n279: -\tinterfaceStatsAttributes(attributes, metrics)\n280: -\n281: -\tevent := aggregatedEvent{\n282: -\t\tTimestamp:   metrics.Timestamp,\n283: -\t\tType:        \"interface\",\n284: -\t\tAction:      \"stats\",\n285: -\t\tActorID:     container.ShortID,\n286: -\t\tActorName:   firstContainerName(container),\n287: -\t\tActorFullID: container.ID,\n288: -\t\tAttributes:  attributes,\n289: -\t}\n290: -\n291: -\tselect {\n292: -\tcase r.events <- event:\n293: -\tcase <-r.ctx.Done():\n294: -\t}\n295: -}\n296: -\n297:  func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n298:  \tif netHandle == nil {\n299:  \t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n300:  \t}\n301:  \n302: @@ -1138,11 +1227,11 @@ func (w *netlinkWatcher) collectAndEmitStats(\n303:  \t\t\tTxPps:     float64(txPacketsDelta) / seconds,\n304:  \t\t\tInterval:  interval,\n305:  \t\t\tTimestamp: now,\n306:  \t\t}\n307:  \n308: -\t\tregistry.emitInterfaceStatsEvent(w.container, state, metrics)\n309: +\t\tw.emitStats(registry, state, metrics)\n310:  \n311:  \t\tstatsSamples[idx] = ifaceStatsSample{\n312:  \t\t\tRxBytes:   state.RxBytes,\n313:  \t\t\tTxBytes:   state.TxBytes,\n314:  \t\t\tRxPackets: state.RxPackets,\n315: diff --git a/core/events/netlink_watch_test.go b/core/events/netlink_watch_test.go\n316: index 29fc7ee..b81b0e4 100644\n317: --- a/core/events/netlink_watch_test.go\n318: +++ b/core/events/netlink_watch_test.go\n319: @@ -386,5 +386,149 @@ func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {\n320:  \n321:  \tif _, ok := states[7]; ok {\n322:  \t\tt.Fatal(\"deleted link is still tracked\")\n323:  \t}\n324:  }\n325: +\n326: +// reportedEvent is the action and interface name of an emitted event.\n327: +type reportedEvent struct {\n328: +\taction string\n329: +\tifname string\n330: +}\n331: +\n332: +// drainEvents closes events and returns what was emitted, in order.\n333: +func drainEvents(events chan aggregatedEvent) []reportedEvent {\n334: +\tclose(events)\n335: +\n336: +\tvar got []reportedEvent\n337: +\tfor ev := range events {\n338: +\t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n339: +\t}\n340: +\n341: +\treturn got\n342: +}\n343: +\n344: +// stitchedWatcher returns a watcher that reported the link with index 7 as\n345: +// the host-side stitch interface of its veth-stitch link.\n346: +func stitchedWatcher() *netlinkWatcher {\n347: +\treturn &netlinkWatcher{\n348: +\t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n349: +\t\treported: map[int]reportedInterface{\n350: +\t\t\t7: {\n351: +\t\t\t\tattributes: map[string]string{\"ifname\": \"clab-s-0011aabb\", \"alias\": \"e1-1\"},\n352: +\t\t\t\tsince:      time.Now(),\n353: +\t\t\t},\n354: +\t\t},\n355: +\t}\n356: +}\n357: +\n358: +// TestEmitReportsRenamedLinkDeleted checks that a link reported under another\n359: +// name than before is first reported deleted under the old name, so clients\n360: +// do not keep both, and is then new to them.\n361: +func TestEmitReportsRenamedLinkDeleted(t *testing.T) {\n362: +\tevents := make(chan aggregatedEvent, 8)\n363: +\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n364: +\twatcher := stitchedWatcher()\n365: +\n366: +\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n367: +\twatcher.emit(registry, \"update\", snapshotFromLink(link))\n368: +\twatcher.emit(registry, \"update\", snapshotFromLink(link))\n369: +\n370: +\twant := []reportedEvent{\n371: +\t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n372: +\t\t{action: \"create\", ifname: \"e1-1\"},\n373: +\t\t{action: \"update\", ifname: \"e1-1\"},\n374: +\t}\n375: +\tif got := drainEvents(events); !slices.Equal(got, want) {\n376: +\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n377: +\t}\n378: +}\n379: +\n380: +// TestEmitDeletesLinkAsLastReported checks that a deletion names the link as\n381: +// clients know it, also when its stitch interface is already gone.\n382: +func TestEmitDeletesLinkAsLastReported(t *testing.T) {\n383: +\tevents := make(chan aggregatedEvent, 8)\n384: +\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n385: +\twatcher := stitchedWatcher()\n386: +\n387: +\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n388: +\twatcher.emit(registry, \"delete\", snapshotFromLink(link))\n389: +\n390: +\twant := []reportedEvent{{action: \"delete\", ifname: \"clab-s-0011aabb\"}}\n391: +\tif got := drainEvents(events); !slices.Equal(got, want) {\n392: +\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n393: +\t}\n394: +\n395: +\tif _, ok := watcher.reported[7]; ok {\n396: +\t\tt.Fatal(\"deleted link is still tracked as reported\")\n397: +\t}\n398: +}\n399: +\n400: +// TestEmitStatsReportsRenamedLinkFirst checks that counters of a link reported\n401: +// under another name before follow its deletion under that name and its\n402: +// creation without counters.\n403: +func TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {\n404: +\tevents := make(chan aggregatedEvent, 8)\n405: +\tregistry := newNetlinkRegistry(t.Context(), events, false, true, time.Second)\n406: +\twatcher := stitchedWatcher()\n407: +\n408: +\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{\n409: +\t\tIndex:      7,\n410: +\t\tName:       \"e1-1\",\n411: +\t\tMTU:        1500,\n412: +\t\tStatistics: &netlink.LinkStatistics{RxBytes: 10},\n413: +\t}}\n414: +\twatcher.emitStats(registry, snapshotFromLink(link), ifaceStatsMetrics{\n415: +\t\tTimestamp: time.Now(),\n416: +\t})\n417: +\tclose(events)\n418: +\n419: +\tvar got []reportedEvent\n420: +\tfor ev := range events {\n421: +\t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n422: +\n423: +\t\t_, hasCounters := ev.Attributes[\"rx_bytes\"]\n424: +\t\tif hasCounters != (ev.Action == \"stats\") {\n425: +\t\t\tt.Fatalf(\"%s event has counters: %v\", ev.Action, hasCounters)\n426: +\t\t}\n427: +\t}\n428: +\n429: +\twant := []reportedEvent{\n430: +\t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n431: +\t\t{action: \"create\", ifname: \"e1-1\"},\n432: +\t\t{action: \"stats\", ifname: \"e1-1\"},\n433: +\t}\n434: +\tif !slices.Equal(got, want) {\n435: +\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n436: +\t}\n437: +\n438: +\tif _, ok := watcher.reported[7].attributes[\"rx_bytes\"]; ok {\n439: +\t\tt.Fatal(\"counters are kept as what the link was reported as\")\n440: +\t}\n441: +}\n442: +\n443: +// TestReportStitchMarksLeavesUnmarkedLinks checks that links without a marked\n444: +// stitch interface, or reported too long ago, are not reported again.\n445: +func TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {\n446: +\tevents := make(chan aggregatedEvent, 8)\n447: +\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n448: +\twatcher := &netlinkWatcher{\n449: +\t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n450: +\t}\n451: +\n452: +\trecent := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n453: +\told := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 8, Name: \"e1-2\", MTU: 1500}}\n454: +\tstates := map[int]ifaceSnapshot{7: snapshotFromLink(recent), 8: snapshotFromLink(old)}\n455: +\twatcher.emit(registry, \"create\", states[7])\n456: +\twatcher.emit(registry, \"create\", states[8])\n457: +\twatcher.reported[8] = reportedInterface{\n458: +\t\tattributes: watcher.reported[8].attributes,\n459: +\t\tsince:      time.Now().Add(-2 * stitchMarkWindow),\n460: +\t}\n461: +\n462: +\twatcher.reportStitchMarks(states, registry)\n463: +\n464: +\twant := []reportedEvent{{action: \"create\", ifname: \"e1-1\"}, {action: \"create\", ifname: \"e1-2\"}}\n465: +\tif got := drainEvents(events); !slices.Equal(got, want) {\n466: +\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n467: +\t}\n468: +}\n\n(End of file - total 468 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/core/events/netlink.go b/core/events/netlink.go\nindex 1654a4a..d1ed517 100644\n--- a/core/events/netlink.go\n+++ b/core/events/netlink.go\n@@ -2,10 +2,11 @@ package events\n \n import (\n \t\"context\"\n \t\"errors\"\n \t\"fmt\"\n+\t\"maps\"\n \t\"math\"\n \t\"strconv\"\n \t\"strings\"\n \t\"sync\"\n \t\"time\"\n@@ -245,12 +246,28 @@ type netlinkWatcher struct {\n \tdone            chan struct{}\n \tincludeSnapshot bool\n \tincludeStats    bool",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/core/events/netlink.go b/core/events/netlink.go\nindex 1654a4a..d1ed517 100644\n--- a/core/events/netlink.go\n+++ b/core/events/netlink.go\n@@ -2,10 +2,11 @@ package events\n \n import (\n \t\"context\"\n \t\"errors\"\n \t\"fmt\"\n+\t\"maps\"\n \t\"math\"\n \t\"strconv\"\n \t\"strings\"\n \t\"sync\"\n \t\"time\"\n@@ -245,12 +246,28 @@ type netlinkWatcher struct {\n \tdone            chan struct{}\n \tincludeSnapshot bool\n \tincludeStats    bool\n \tstatsInterval   time.Duration\n \tnsHandle        netns.NsHandle\n+\t// reported holds what each link was last reported as, by its index in the\n+\t// container's namespace.\n+\treported map[int]reportedInterface\n }\n \n+// reportedInterface is what a link was last reported as.\n+type reportedInterface struct {\n+\tattributes map[string]string\n+\t// since is when the link was first reported.\n+\tsince time.Time\n+}\n+\n+// stitchMarkWindow is how long after a link is first reported its host-side\n+// stitch interface is looked for while the link itself does not change.\n+// Deploying a veth-stitch link marks that interface right after it creates the\n+// link, without a change in the node's namespace.\n+var stitchMarkWindow = time.Minute\n+\n // Retry settings for a watcher that could not subscribe to link updates.\n var (\n \twatchMaxAttempts   = 5\n \twatchRetryDelay    = time.Second\n \twatchMaxRetryDelay = 10 * time.Second\n@@ -419,10 +436,11 @@ func (w *netlinkWatcher) watch(\n \t\tselect {\n \t\tcase <-tickerC:\n \t\t\tw.collectAndEmitStats(netHandle, states, statsSamples, registry)\n \t\tcase <-netemTicker.C:\n \t\t\tw.pollNetemChanges(states, registry, netemQuery)\n+\t\t\tw.reportStitchMarks(states, registry)\n \t\tcase <-ctx.Done():\n \t\t\treturn true, nil\n \t\tcase update, ok := <-updates:\n \t\t\tif !ok {\n \t\t\t\terrMu.Lock()\n@@ -494,15 +512,15 @@ func (w *netlinkWatcher) processExisting(\n \t\t}\n \t}\n \n \tswitch {\n \tcase exists:\n-\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n+\t\tw.emit(registry, \"update\", snapshot)\n \tcase !initial:\n-\t\tregistry.emitInterfaceEvent(w.container, \"create\", snapshot)\n+\t\tw.emit(registry, \"create\", snapshot)\n \tcase w.includeSnapshot:\n-\t\tregistry.emitInterfaceEvent(w.container, \"snapshot\", snapshot)\n+\t\tw.emit(registry, \"snapshot\", snapshot)\n \t}\n }\n \n // removeVanishedLinks reports the links that were deleted while no\n // subscription was active and returns their indexes.\n@@ -532,11 +550,11 @@ func (w *netlinkWatcher) removeVanishedLinks(\n \n \t\tvanished[idx] = struct{}{}\n \n \t\tdelete(states, idx)\n \t\tdelete(statsSamples, idx)\n-\t\tregistry.emitInterfaceEvent(w.container, \"delete\", snapshot)\n+\t\tw.emit(registry, \"delete\", snapshot)\n \t}\n \n \treturn vanished\n }\n \n@@ -567,11 +585,11 @@ func (w *netlinkWatcher) processUpdate(\n \t\t\treturn\n \t\t}\n \n \t\tdelete(states, snapshot.Index)\n \t\tdelete(statsSamples, snapshot.Index)\n-\t\tregistry.emitInterfaceEvent(w.container, \"delete\", previous)\n+\t\tw.emit(registry, \"delete\", previous)\n \tcase unix.RTM_NEWLINK:\n \t\t// Query netem info for this interface\n \t\tsnapshot = withNetem(snapshot, netemQuery.Query())\n \n \t\tif exists && snapshot.equal(previous) {\n@@ -587,11 +605,11 @@ func (w *netlinkWatcher) processUpdate(\n \t\tif w.includeStats && statsSamples != nil {\n \t\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n \t\t\t\tstatsSamples[snapshot.Index] = sample\n \t\t\t}\n \t\t}\n-\t\tregistry.emitInterfaceEvent(w.container, action, snapshot)\n+\t\tw.emit(registry, action, snapshot)\n \t}\n }\n \n // pollNetemChanges checks for netem changes and emits update events.\n func (w *netlinkWatcher) pollNetemChanges(\n@@ -622,13 +640,117 @@ func (w *netlinkWatcher) pollNetemChanges(\n \t\t\tsnapshot.Corruption = 0\n \t\t}\n \n \t\tif !snapshot.equal(previous) {\n \t\t\tstates[idx] = snapshot\n-\t\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n+\t\t\tw.emit(registry, \"update\", snapshot)\n+\t\t}\n+\t}\n+}\n+\n+// reportStitchMarks reports the links whose host-side stitch interface got\n+// marked after their last event. Only veths reported under their own name\n+// shortly before are looked at: the node's end of a veth-stitch link is a veth\n+// and is marked while its lab deploys.\n+func (w *netlinkWatcher) reportStitchMarks(\n+\tstates map[int]ifaceSnapshot,\n+\tregistry *netlinkRegistry,\n+) {\n+\tfor idx, snapshot := range states {\n+\t\treported, ok := w.reported[idx]\n+\t\tif !ok || snapshot.Type != \"veth\" ||\n+\t\t\treported.attributes[\"ifname\"] != snapshot.Name ||\n+\t\t\ttime.Since(reported.since) > stitchMarkWindow {\n+\t\t\tcontinue\n+\t\t}\n+\n+\t\tif interfaceAttributes(w.container, snapshot)[\"ifname\"] != snapshot.Name {\n+\t\t\tw.emit(registry, \"update\", snapshot)\n+\t\t}\n+\t}\n+}\n+\n+// emit reports an event of a link. A deletion names the link as it was last\n+// reported. A link reported under another name before, such as the node's own\n+// interface until its stitch interface got marked, is first reported deleted\n+// under that name, so that clients do not keep both; it is then new to them.\n+func (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {\n+\tif w.container == nil {\n+\t\treturn\n+\t}\n+\n+\tif action == \"delete\" {\n+\t\tattributes := interfaceAttributes(w.container, snapshot)\n+\t\tif previous, ok := w.reported[snapshot.Index]; ok {\n+\t\t\tattributes = previous.attributes\n \t\t}\n+\n+\t\tdelete(w.reported, snapshot.Index)\n+\t\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n+\n+\t\treturn\n+\t}\n+\n+\tattributes := interfaceAttributes(w.container, snapshot)\n+\tif w.track(registry, snapshot.Index, attributes) && action == \"update\" {\n+\t\taction = \"create\"\n+\t}\n+\n+\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n+}\n+\n+// emitStats reports the counters of a link, under the name emit reports it.\n+func (w *netlinkWatcher) emitStats(\n+\tregistry *netlinkRegistry,\n+\tsnapshot ifaceSnapshot,\n+\tmetrics ifaceStatsMetrics,\n+) {\n+\tif !registry.includeStats || w.container == nil || !snapshot.HasStats {\n+\t\treturn\n+\t}\n+\n+\tattributes := interfaceAttributes(w.container, snapshot)\n+\tif w.track(registry, snapshot.Index, attributes) {\n+\t\tregistry.sendInterfaceEvent(\n+\t\t\tw.container,\n+\t\t\t\"create\",\n+\t\t\tmaps.Clone(attributes),\n+\t\t\tmetrics.Timestamp,\n+\t\t)\n+\t}\n+\n+\tinterfaceStatsAttributes(attributes, metrics)\n+\tregistry.sendInterfaceEvent(w.container, \"stats\", attributes, metrics.Timestamp)\n+}\n+\n+// track records what the link at index is reported as. When it was reported\n+// under another name before, it reports that name deleted and returns true.\n+func (w *netlinkWatcher) track(\n+\tregistry *netlinkRegistry,\n+\tindex int,\n+\tattributes map[string]string,\n+) bool {\n+\tif w.reported == nil {\n+\t\tw.reported = make(map[int]reportedInterface)\n \t}\n+\n+\tprevious, known := w.reported[index]\n+\n+\tsince := time.Now()\n+\tif known {\n+\t\tsince = previous.since\n+\t}\n+\n+\tw.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}\n+\n+\tif !known || previous.attributes[\"ifname\"] == attributes[\"ifname\"] {\n+\t\treturn false\n+\t}\n+\n+\tregistry.sendInterfaceEvent(w.container, \"delete\", previous.attributes, time.Now())\n+\n+\treturn true\n }\n \n func firstContainerName(container *clabruntime.GenericContainer) string {\n \tif container == nil || len(container.Names) == 0 {\n \t\treturn \"\"\n@@ -807,23 +929,18 @@ func overlayToolsInterface(\n \tif snapshot.MAC != \"\" {\n \t\tattributes[\"mac\"] = snapshot.MAC\n \t}\n }\n \n-func (r *netlinkRegistry) emitInterfaceEvent(\n+func (r *netlinkRegistry) sendInterfaceEvent(\n \tcontainer *clabruntime.GenericContainer,\n \taction string,\n-\tsnapshot ifaceSnapshot,\n+\tattributes map[string]string,\n+\ttimestamp time.Time,\n ) {\n-\tif container == nil {\n-\t\treturn\n-\t}\n-\n-\tattributes := interfaceAttributes(container, snapshot)\n-\n \tevent := aggregatedEvent{\n-\t\tTimestamp:   time.Now(),\n+\t\tTimestamp:   timestamp,\n \t\tType:        \"interface\",\n \t\tAction:      action,\n \t\tActorID:     container.ShortID,\n \t\tActorName:   firstContainerName(container),\n \t\tActorFullID: container.ID,\n@@ -870,38 +987,10 @@ func waitForNamespacePath(\n \t}\n \n \treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n }\n \n-func (r *netlinkRegistry) emitInterfaceStatsEvent(\n-\tcontainer *clabruntime.GenericContainer,\n-\tsnapshot ifaceSnapshot,\n-\tmetrics ifaceStatsMetrics,\n-) {\n-\tif !r.includeStats || container == nil || !snapshot.HasStats {\n-\t\treturn\n-\t}\n-\n-\tattributes := interfaceAttributes(container, snapshot)\n-\tinterfaceStatsAttributes(attributes, metrics)\n-\n-\tevent := aggregatedEvent{\n-\t\tTimestamp:   metrics.Timestamp,\n-\t\tType:        \"interface\",\n-\t\tAction:      \"stats\",\n-\t\tActorID:     container.ShortID,\n-\t\tActorName:   firstContainerName(container),\n-\t\tActorFullID: container.ID,\n-\t\tAttributes:  attributes,\n-\t}\n-\n-\tselect {\n-\tcase r.events <- event:\n-\tcase <-r.ctx.Done():\n-\t}\n-}\n-\n func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n \tif netHandle == nil {\n \t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n \t}\n \n@@ -1138,11 +1227,11 @@ func (w *netlinkWatcher) collectAndEmitStats(\n \t\t\tTxPps:     float64(txPacketsDelta) / seconds,\n \t\t\tInterval:  interval,\n \t\t\tTimestamp: now,\n \t\t}\n \n-\t\tregistry.emitInterfaceStatsEvent(w.container, state, metrics)\n+\t\tw.emitStats(registry, state, metrics)\n \n \t\tstatsSamples[idx] = ifaceStatsSample{\n \t\t\tRxBytes:   state.RxBytes,\n \t\t\tTxBytes:   state.TxBytes,\n \t\t\tRxPackets: state.RxPackets,\ndiff --git a/core/events/netlink_watch_test.go b/core/events/netlink_watch_test.go\nindex 29fc7ee..b81b0e4 100644\n--- a/core/events/netlink_watch_test.go\n+++ b/core/events/netlink_watch_test.go\n@@ -386,5 +386,149 @@ func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {\n \n \tif _, ok := states[7]; ok {\n \t\tt.Fatal(\"deleted link is still tracked\")\n \t}\n }\n+\n+// reportedEvent is the action and interface name of an emitted event.\n+type reportedEvent struct {\n+\taction string\n+\tifname string\n+}\n+\n+// drainEvents closes events and returns what was emitted, in order.\n+func drainEvents(events chan aggregatedEvent) []reportedEvent {\n+\tclose(events)\n+\n+\tvar got []reportedEvent\n+\tfor ev := range events {\n+\t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n+\t}\n+\n+\treturn got\n+}\n+\n+// stitchedWatcher returns a watcher that reported the link with index 7 as\n+// the host-side stitch interface of its veth-stitch link.\n+func stitchedWatcher() *netlinkWatcher {\n+\treturn &netlinkWatcher{\n+\t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n+\t\treported: map[int]reportedInterface{\n+\t\t\t7: {\n+\t\t\t\tattributes: map[string]string{\"ifname\": \"clab-s-0011aabb\", \"alias\": \"e1-1\"},\n+\t\t\t\tsince:      time.Now(),\n+\t\t\t},\n+\t\t},\n+\t}\n+}\n+\n+// TestEmitReportsRenamedLinkDeleted checks that a link reported under another\n+// name than before is first reported deleted under the old name, so clients\n+// do not keep both, and is then new to them.\n+func TestEmitReportsRenamedLinkDeleted(t *testing.T) {\n+\tevents := make(chan aggregatedEvent, 8)\n+\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n+\twatcher := stitchedWatcher()\n+\n+\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n+\twatcher.emit(registry, \"update\", snapshotFromLink(link))\n+\twatcher.emit(registry, \"update\", snapshotFromLink(link))\n+\n+\twant := []reportedEvent{\n+\t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n+\t\t{action: \"create\", ifname: \"e1-1\"},\n+\t\t{action: \"update\", ifname: \"e1-1\"},\n+\t}\n+\tif got := drainEvents(events); !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n+\t}\n+}\n+\n+// TestEmitDeletesLinkAsLastReported checks that a deletion names the link as\n+// clients know it, also when its stitch interface is already gone.\n+func TestEmitDeletesLinkAsLastReported(t *testing.T) {\n+\tevents := make(chan aggregatedEvent, 8)\n+\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n+\twatcher := stitchedWatcher()\n+\n+\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n+\twatcher.emit(registry, \"delete\", snapshotFromLink(link))\n+\n+\twant := []reportedEvent{{action: \"delete\", ifname: \"clab-s-0011aabb\"}}\n+\tif got := drainEvents(events); !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n+\t}\n+\n+\tif _, ok := watcher.reported[7]; ok {\n+\t\tt.Fatal(\"deleted link is still tracked as reported\")\n+\t}\n+}\n+\n+// TestEmitStatsReportsRenamedLinkFirst checks that counters of a link reported\n+// under another name before follow its deletion under that name and its\n+// creation without counters.\n+func TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {\n+\tevents := make(chan aggregatedEvent, 8)\n+\tregistry := newNetlinkRegistry(t.Context(), events, false, true, time.Second)\n+\twatcher := stitchedWatcher()\n+\n+\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{\n+\t\tIndex:      7,\n+\t\tName:       \"e1-1\",\n+\t\tMTU:        1500,\n+\t\tStatistics: &netlink.LinkStatistics{RxBytes: 10},\n+\t}}\n+\twatcher.emitStats(registry, snapshotFromLink(link), ifaceStatsMetrics{\n+\t\tTimestamp: time.Now(),\n+\t})\n+\tclose(events)\n+\n+\tvar got []reportedEvent\n+\tfor ev := range events {\n+\t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n+\n+\t\t_, hasCounters := ev.Attributes[\"rx_bytes\"]\n+\t\tif hasCounters != (ev.Action == \"stats\") {\n+\t\t\tt.Fatalf(\"%s event has counters: %v\", ev.Action, hasCounters)\n+\t\t}\n+\t}\n+\n+\twant := []reportedEvent{\n+\t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n+\t\t{action: \"create\", ifname: \"e1-1\"},\n+\t\t{action: \"stats\", ifname: \"e1-1\"},\n+\t}\n+\tif !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n+\t}\n+\n+\tif _, ok := watcher.reported[7].attributes[\"rx_bytes\"]; ok {\n+\t\tt.Fatal(\"counters are kept as what the link was reported as\")\n+\t}\n+}\n+\n+// TestReportStitchMarksLeavesUnmarkedLinks checks that links without a marked\n+// stitch interface, or reported too long ago, are not reported again.\n+func TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {\n+\tevents := make(chan aggregatedEvent, 8)\n+\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n+\twatcher := &netlinkWatcher{\n+\t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n+\t}\n+\n+\trecent := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n+\told := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 8, Name: \"e1-2\", MTU: 1500}}\n+\tstates := map[int]ifaceSnapshot{7: snapshotFromLink(recent), 8: snapshotFromLink(old)}\n+\twatcher.emit(registry, \"create\", states[7])\n+\twatcher.emit(registry, \"create\", states[8])\n+\twatcher.reported[8] = reportedInterface{\n+\t\tattributes: watcher.reported[8].attributes,\n+\t\tsince:      time.Now().Add(-2 * stitchMarkWindow),\n+\t}\n+\n+\twatcher.reportStitchMarks(states, registry)\n+\n+\twant := []reportedEvent{{action: \"create\", ifname: \"e1-1\"}, {action: \"create\", ifname: \"e1-2\"}}\n+\tif got := drainEvents(events); !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n+\t}\n+}",
        "lineStart": 1,
        "lineEnd": 468,
        "totalLines": 468,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565093438,
      "end": 1794565094688
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46a3d250014EdTUY70ZLcQy7",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a2ad3001l3GJJWnrl3hJy5",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3729,
    "input": 3677,
    "output": 51,
    "reasoning": 1,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46a2ad3001l3GJJWnrl3hJy5",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565090003,
    "completed": 1794565094700
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3729,
    "input": 3677,
    "output": 51,
    "reasoning": 1,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 4
step-start
{
  "type": "step-start",
  "id": "prt_1d46a53f5001js9giSVhXKuFWE",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a3d31001iIjThNQ1viFvc4"
}
Reasoning
Two changed files: `core/events/netlink.go` and `core/events/netlink_watch_test.go`. Let me read the full head files.
read · completed

Input

{
  "filePath": "/source/head/core/events/netlink.go"
}

Output

<path>/source/head/core/events/netlink.go</path>
<type>file</type>
<content>
1: package events
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"maps"
8: 	"math"
9: 	"strconv"
10: 	"strings"
11: 	"sync"
12: 	"time"
13: 
14: 	"github.com/charmbracelet/log"
15: 	gotc "github.com/florianl/go-tc"
16: 	clabconstants "github.com/srl-labs/containerlab/constants"
17: 	clabcore "github.com/srl-labs/containerlab/core"
18: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
19: 	clablinks "github.com/srl-labs/containerlab/links"
20: 	clabnetem "github.com/srl-labs/containerlab/netem"
21: 	clabruntime "github.com/srl-labs/containerlab/runtime"
22: 	clabutils "github.com/srl-labs/containerlab/utils"
23: 	"github.com/vishvananda/netlink"
24: 	"github.com/vishvananda/netns"
25: 	"golang.org/x/sys/unix"
26: )
27: 
28: type netlinkRegistry struct {
29: 	ctx                    context.Context
30: 	mu                     sync.Mutex
31: 	watchers               map[string]*netlinkWatcher
32: 	events                 chan<- aggregatedEvent
33: 	includeInitialSnapshot bool
34: 	includeStats           bool
35: 	statsInterval          time.Duration
36: }
37: 
38: func newNetlinkRegistry(
39: 	ctx context.Context,
40: 	events chan<- aggregatedEvent,
41: 	includeInitialSnapshot bool,
42: 	includeStats bool,
43: 	statsInterval time.Duration,
44: ) *netlinkRegistry {
45: 	return &netlinkRegistry{
46: 		ctx:                    ctx,
47: 		watchers:               make(map[string]*netlinkWatcher),
48: 		events:                 events,
49: 		includeInitialSnapshot: includeInitialSnapshot,
50: 		includeStats:           includeStats,
51: 		statsInterval:          statsInterval,
52: 	}
53: }
54: 
55: func (r *netlinkRegistry) Start(container *clabruntime.GenericContainer) {
56: 	clone := cloneContainer(container)
57: 	if clone == nil {
58: 		return
59: 	}
60: 
61: 	id := clone.ID
62: 	if id == "" {
63: 		id = clone.ShortID
64: 	}
65: 
66: 	if id == "" {
67: 		return
68: 	}
69: 
70: 	r.mu.Lock()
71: 	if _, exists := r.watchers[id]; exists {
72: 		r.mu.Unlock()
73: 
74: 		return
75: 	}
76: 
77: 	watcherCtx, cancel := context.WithCancel(r.ctx)
78: 	watcher := &netlinkWatcher{
79: 		container:       clone,
80: 		cancel:          cancel,
81: 		done:            make(chan struct{}),
82: 		includeSnapshot: r.includeInitialSnapshot,
83: 		includeStats:    r.includeStats,
84: 		statsInterval:   r.statsInterval,
85: 	}
86: 
87: 	r.watchers[id] = watcher
88: 	r.mu.Unlock()
89: 
90: 	go watcher.run(watcherCtx, r)
91: }
92: 
93: func (r *netlinkRegistry) Stop(id string) {
94: 	if id == "" {
95: 		return
96: 	}
97: 
98: 	r.mu.Lock()
99: 	watcher, ok := r.watchers[id]
100: 	if ok {
101: 		delete(r.watchers, id)
102: 	}
103: 	r.mu.Unlock()
104: 
105: 	if !ok {
106: 		return
107: 	}
108: 
109: 	watcher.cancel()
110: 	<-watcher.done
111: }
112: 
113: func (r *netlinkRegistry) remove(id string, watcher *netlinkWatcher) {
114: 	if id == "" {
115: 		return
116: 	}
117: 
118: 	r.mu.Lock()
119: 	defer r.mu.Unlock()
120: 
121: 	if current, ok := r.watchers[id]; ok && current == watcher {
122: 		delete(r.watchers, id)
123: 	}
124: }
125: 
126: func (r *netlinkRegistry) HandleContainerEvent(
127: 	runtime clabruntime.ContainerRuntime,
128: 	ev clabruntime.ContainerEvent,
129: ) {
130: 	if !strings.EqualFold(ev.Type, clabruntime.EventTypeContainer) {
131: 		return
132: 	}
133: 
134: 	action := strings.ToLower(ev.Action)
135: 
136: 	switch action {
137: 	case clabruntime.EventActionStart,
138: 		clabruntime.EventActionUnpause,
139: 		clabruntime.EventActionRestart:
140: 		container := containerFromEvent(runtime, ev)
141: 		if container != nil {
142: 			r.Start(container)
143: 		}
144: 	case clabruntime.EventActionDie,
145: 		clabruntime.EventActionStop,
146: 		clabruntime.EventActionDestroy,
147: 		clabruntime.EventActionKill:
148: 		id := ev.ActorFullID
149: 		if id == "" {
150: 			id = ev.ActorID
151: 		}
152: 
153: 		r.Stop(id)
154: 	}
155: }
156: 
157: func cloneContainer(container *clabruntime.GenericContainer) *clabruntime.GenericContainer {
158: 	if container == nil {
159: 		return nil
160: 	}
161: 
162: 	clone := &clabruntime.GenericContainer{
163: 		Names:   append([]string{}, container.Names...),
164: 		ID:      container.ID,
165: 		ShortID: container.ShortID,
166: 		Labels:  cloneStringMap(container.Labels),
167: 	}
168: 
169: 	if clone.ShortID == "" {
170: 		clone.ShortID = clabutils.ShortID(clone.ID)
171: 	}
172: 
173: 	if container.Runtime == nil {
174: 		return nil
175: 	}
176: 
177: 	clone.SetRuntime(container.Runtime)
178: 
179: 	return clone
180: }
181: 
182: func containerFromEvent(
183: 	runtime clabruntime.ContainerRuntime,
184: 	ev clabruntime.ContainerEvent,
185: ) *clabruntime.GenericContainer {
186: 	attributes := ev.Attributes
187: 
188: 	name := ev.ActorName
189: 	if name == "" && attributes != nil {
190: 		name = attributes["name"]
191: 	}
192: 
193: 	id := ev.ActorFullID
194: 	if id == "" {
195: 		id = ev.ActorID
196: 	}
197: 
198: 	if id == "" && name == "" {
199: 		return nil
200: 	}
201: 
202: 	short := ev.ActorID
203: 	if short == "" {
204: 		short = id
205: 	}
206: 
207: 	container := &clabruntime.GenericContainer{
208: 		ID:      id,
209: 		ShortID: clabutils.ShortID(short),
210: 	}
211: 
212: 	if name != "" {
213: 		container.Names = []string{name}
214: 	}
215: 
216: 	if attributes != nil {
217: 		for _, key := range []string{
218: 			clabconstants.Containerlab,
219: 			clabconstants.NodeName,
220: 			clabconstants.RootNodeName,
221: 		} {
222: 			if v := attributes[key]; v != "" {
223: 				if container.Labels == nil {
224: 					container.Labels = map[string]string{}
225: 				}
226: 
227: 				container.Labels[key] = v
228: 			}
229: 		}
230: 	}
231: 
232: 	if container.ShortID == "" {
233: 		container.ShortID = clabutils.ShortID(container.ID)
234: 	}
235: 
236: 	if runtime != nil {
237: 		container.SetRuntime(runtime)
238: 	}
239: 
240: 	return container
241: }
242: 
243: type netlinkWatcher struct {
244: 	container       *clabruntime.GenericContainer
245: 	cancel          context.CancelFunc
246: 	done            chan struct{}
247: 	includeSnapshot bool
248: 	includeStats    bool
249: 	statsInterval   time.Duration
250: 	nsHandle        netns.NsHandle
251: 	// reported holds what each link was last reported as, by its index in the
252: 	// container's namespace.
253: 	reported map[int]reportedInterface
254: }
255: 
256: // reportedInterface is what a link was last reported as.
257: type reportedInterface struct {
258: 	attributes map[string]string
259: 	// since is when the link was first reported.
260: 	since time.Time
261: }
262: 
263: // stitchMarkWindow is how long after a link is first reported its host-side
264: // stitch interface is looked for while the link itself does not change.
265: // Deploying a veth-stitch link marks that interface right after it creates the
266: // link, without a change in the node's namespace.
267: var stitchMarkWindow = time.Minute
268: 
269: // Retry settings for a watcher that could not subscribe to link updates.
270: var (
271: 	watchMaxAttempts   = 5
272: 	watchRetryDelay    = time.Second
273: 	watchMaxRetryDelay = 10 * time.Second
274: )
275: 
276: func (w *netlinkWatcher) run(ctx context.Context, registry *netlinkRegistry) {
277: 	defer close(w.done)
278: 	if w.container == nil {
279: 		return
280: 	}
281: 
282: 	defer registry.remove(w.container.ID, w)
283: 
284: 	containerName := firstContainerName(w.container)
285: 	if w.container.Runtime == nil {
286: 		log.Debugf("container %s has no runtime, skipping netlink watcher", containerName)
287: 
288: 		return
289: 	}
290: 
291: 	// The states outlive a subscription, so a resubscribe only reports what
292: 	// changed while no subscription was active.
293: 	states := make(map[int]ifaceSnapshot)
294: 
295: 	var statsSamples map[int]ifaceStatsSample
296: 	if w.includeStats {
297: 		statsSamples = make(map[int]ifaceStatsSample)
298: 	}
299: 
300: 	initial := true
301: 	failures := 0
302: 	delay := watchRetryDelay
303: 
304: 	for {
305: 		subscribed, err := w.watch(ctx, registry, states, statsSamples, initial)
306: 		if ctx.Err() != nil {
307: 			return
308: 		}
309: 
310: 		if subscribed {
311: 			initial = false
312: 			failures = 0
313: 			delay = watchRetryDelay
314: 
315: 			log.Warnf(
316: 				"netlink subscription for container %s ended, resubscribing: %v",
317: 				containerName,
318: 				err,
319: 			)
320: 		} else {
321: 			failures++
322: 			if failures >= watchMaxAttempts {
323: 				log.Warnf("stopped watching interfaces of container %s: %v", containerName, err)
324: 
325: 				return
326: 			}
327: 
328: 			log.Debugf(
329: 				"failed to watch interfaces of container %s, retrying in %s: %v",
330: 				containerName,
331: 				delay,
332: 				err,
333: 			)
334: 		}
335: 
336: 		select {
337: 		case <-time.After(delay):
338: 		case <-ctx.Done():
339: 			return
340: 		}
341: 
342: 		delay = min(delay*2, watchMaxRetryDelay)
343: 	}
344: }
345: 
346: // watch subscribes to link updates in the container's namespace and handles
347: // them until ctx ends or the subscription fails. It reports whether it
348: // subscribed. The subscription lists the existing links itself, so no change
349: // between listing and subscribing is lost.
350: func (w *netlinkWatcher) watch(
351: 	ctx context.Context,
352: 	registry *netlinkRegistry,
353: 	states map[int]ifaceSnapshot,
354: 	statsSamples map[int]ifaceStatsSample,
355: 	initial bool,
356: ) (bool, error) {
357: 	nsPath, err := waitForNamespacePath(ctx, w.container.Runtime, w.container.ID)
358: 	if err != nil {
359: 		return false, fmt.Errorf("failed to resolve netns: %w", err)
360: 	}
361: 
362: 	nsHandle, err := netns.GetFromPath(nsPath)
363: 	if err != nil {
364: 		return false, fmt.Errorf("failed to open netns: %w", err)
365: 	}
366: 	defer nsHandle.Close()
367: 
368: 	w.nsHandle = nsHandle
369: 
370: 	netHandle, err := netlink.NewHandleAt(nsHandle)
371: 	if err != nil {
372: 		return false, fmt.Errorf("failed to create netlink handle: %w", err)
373: 	}
374: 	defer netHandle.Close()
375: 
376: 	netemQuery := newNetemQuerier(nsHandle)
377: 	defer netemQuery.Close()
378: 
379: 	netemInfos := netemQuery.Query()
380: 
381: 	updates := make(chan netlink.LinkUpdate, 32)
382: 	done := make(chan struct{})
383: 	defer close(done)
384: 
385: 	var (
386: 		errMu     sync.Mutex
387: 		lastError error
388: 	)
389: 
390: 	opts := netlink.LinkSubscribeOptions{
391: 		Namespace:    &nsHandle,
392: 		ListExisting: true,
393: 		// An interrupted listing is reported here too. It needs no action:
394: 		// links that changed during the listing also arrive as updates.
395: 		ErrorCallback: func(err error) {
396: 			log.Debugf(
397: 				"netlink subscription for container %s: %v",
398: 				firstContainerName(w.container),
399: 				err,
400: 			)
401: 
402: 			errMu.Lock()
403: 			lastError = err
404: 			errMu.Unlock()
405: 		},
406: 	}
407: 
408: 	if err := netlink.LinkSubscribeWithOptions(updates, done, opts); err != nil {
409: 		return false, fmt.Errorf("failed to subscribe to netlink updates: %w", err)
410: 	}
411: 
412: 	var vanished map[int]struct{}
413: 	if len(states) > 0 {
414: 		vanished = w.removeVanishedLinks(netHandle, states, statsSamples, registry)
415: 	}
416: 
417: 	// Set up netem polling interval (reuse stats interval or default to 1s).
418: 	netemPollInterval := w.statsInterval
419: 	if netemPollInterval == 0 {
420: 		netemPollInterval = time.Second
421: 	}
422: 	netemTicker := time.NewTicker(netemPollInterval)
423: 	defer netemTicker.Stop()
424: 
425: 	var (
426: 		ticker  *time.Ticker
427: 		tickerC <-chan time.Time
428: 	)
429: 	if w.includeStats && w.statsInterval > 0 {
430: 		ticker = time.NewTicker(w.statsInterval)
431: 		tickerC = ticker.C
432: 		defer ticker.Stop()
433: 	}
434: 
435: 	for {
436: 		select {
437: 		case <-tickerC:
438: 			w.collectAndEmitStats(netHandle, states, statsSamples, registry)
439: 		case <-netemTicker.C:
440: 			w.pollNetemChanges(states, registry, netemQuery)
441: 			w.reportStitchMarks(states, registry)
442: 		case <-ctx.Done():
443: 			return true, nil
444: 		case update, ok := <-updates:
445: 			if !ok {
446: 				errMu.Lock()
447: 				err := lastError
448: 				errMu.Unlock()
449: 
450: 				if err == nil {
451: 					err = errors.New("update channel closed")
452: 				}
453: 
454: 				return true, err
455: 			}
456: 
457: 			// Replies to the listing carry NLM_F_MULTI, notifications do not.
458: 			if update.Header.Flags&unix.NLM_F_MULTI != 0 {
459: 				w.processExisting(
460: 					states,
461: 					statsSamples,
462: 					update.Link,
463: 					netemInfos,
464: 					vanished,
465: 					registry,
466: 					initial,
467: 				)
468: 
469: 				continue
470: 			}
471: 
472: 			w.processUpdate(states, statsSamples, update, registry, netemQuery)
473: 		}
474: 	}
475: }
476: 
477: // processExisting records a link listed when the subscription started. On the
478: // first subscription a new link is reported as a snapshot when requested; after
479: // a resubscribe it is reported as created.
480: //
481: // The listing can be older than the check in removeVanishedLinks, so it can
482: // still hold a link that check reported as deleted. Such a link is skipped; its
483: // deletion notification follows and is ignored, as the link is not tracked.
484: func (w *netlinkWatcher) processExisting(
485: 	states map[int]ifaceSnapshot,
486: 	statsSamples map[int]ifaceStatsSample,
487: 	link netlink.Link,
488: 	netemInfos map[int]netemInfo,
489: 	vanished map[int]struct{},
490: 	registry *netlinkRegistry,
491: 	initial bool,
492: ) {
493: 	if link == nil || link.Attrs() == nil {
494: 		return
495: 	}
496: 
497: 	if _, ok := vanished[link.Attrs().Index]; ok {
498: 		return
499: 	}
500: 
501: 	snapshot := withNetem(snapshotFromLink(link), netemInfos)
502: 	previous, exists := states[snapshot.Index]
503: 
504: 	if exists && snapshot.equal(previous) {
505: 		return
506: 	}
507: 
508: 	states[snapshot.Index] = snapshot
509: 	if statsSamples != nil {
510: 		if sample, ok := newStatsSample(snapshot, time.Now()); ok {
511: 			statsSamples[snapshot.Index] = sample
512: 		}
513: 	}
514: 
515: 	switch {
516: 	case exists:
517: 		w.emit(registry, "update", snapshot)
518: 	case !initial:
519: 		w.emit(registry, "create", snapshot)
520: 	case w.includeSnapshot:
521: 		w.emit(registry, "snapshot", snapshot)
522: 	}
523: }
524: 
525: // removeVanishedLinks reports the links that were deleted while no
526: // subscription was active and returns their indexes.
527: func (w *netlinkWatcher) removeVanishedLinks(
528: 	netHandle *netlink.Handle,
529: 	states map[int]ifaceSnapshot,
530: 	statsSamples map[int]ifaceStatsSample,
531: 	registry *netlinkRegistry,
532: ) map[int]struct{} {
533: 	current, err := snapshotInterfaces(netHandle)
534: 	if err != nil {
535: 		log.Debugf(
536: 			"failed to list interfaces of container %s: %v",
537: 			firstContainerName(w.container),
538: 			err,
539: 		)
540: 
541: 		return nil
542: 	}
543: 
544: 	vanished := map[int]struct{}{}
545: 
546: 	for idx, snapshot := range states {
547: 		if _, ok := current[idx]; ok {
548: 			continue
549: 		}
550: 
551: 		vanished[idx] = struct{}{}
552: 
553: 		delete(states, idx)
554: 		delete(statsSamples, idx)
555: 		w.emit(registry, "delete", snapshot)
556: 	}
557: 
558: 	return vanished
559: }
560: 
561: func (w *netlinkWatcher) processUpdate(
562: 	states map[int]ifaceSnapshot,
563: 	statsSamples map[int]ifaceStatsSample,
564: 	update netlink.LinkUpdate,
565: 	registry *netlinkRegistry,
566: 	netemQuery *netemQuerier,
567: ) {
568: 	if update.Link == nil {
569: 		return
570: 	}
571: 
572: 	attrs := update.Link.Attrs()
573: 	if attrs == nil {
574: 		return
575: 	}
576: 
577: 	snapshot := snapshotFromLink(update.Link)
578: 	previous, exists := states[snapshot.Index]
579: 
580: 	switch update.Header.Type {
581: 	case unix.RTM_DELLINK:
582: 		// A link that is not tracked was never reported, or its deletion was
583: 		// already reported when the links were listed again after a resubscribe.
584: 		if !exists {
585: 			return
586: 		}
587: 
588: 		delete(states, snapshot.Index)
589: 		delete(statsSamples, snapshot.Index)
590: 		w.emit(registry, "delete", previous)
591: 	case unix.RTM_NEWLINK:
592: 		// Query netem info for this interface
593: 		snapshot = withNetem(snapshot, netemQuery.Query())
594: 
595: 		if exists && snapshot.equal(previous) {
596: 			return
597: 		}
598: 
599: 		action := "create"
600: 		if exists {
601: 			action = "update"
602: 		}
603: 
604: 		states[snapshot.Index] = snapshot
605: 		if w.includeStats && statsSamples != nil {
606: 			if sample, ok := newStatsSample(snapshot, time.Now()); ok {
607: 				statsSamples[snapshot.Index] = sample
608: 			}
609: 		}
610: 		w.emit(registry, action, snapshot)
611: 	}
612: }
613: 
614: // pollNetemChanges checks for netem changes and emits update events.
615: func (w *netlinkWatcher) pollNetemChanges(
616: 	states map[int]ifaceSnapshot,
617: 	registry *netlinkRegistry,
618: 	netemQuery *netemQuerier,
619: ) {
620: 	netemInfos := netemQuery.Query()
621: 
622: 	for idx, snapshot := range states {
623: 		previous := snapshot
624: 		info, hasNetem := netemInfos[idx]
625: 
626: 		if hasNetem {
627: 			snapshot.HasNetem = true
628: 			snapshot.Delay = info.Delay
629: 			snapshot.Jitter = info.Jitter
630: 			snapshot.PacketLoss = info.PacketLoss
631: 			snapshot.Rate = info.Rate
632: 			snapshot.Corruption = info.Corruption
633: 		} else if snapshot.HasNetem {
634: 			// Netem was removed
635: 			snapshot.HasNetem = false
636: 			snapshot.Delay = ""
637: 			snapshot.Jitter = ""
638: 			snapshot.PacketLoss = 0
639: 			snapshot.Rate = 0
640: 			snapshot.Corruption = 0
641: 		}
642: 
643: 		if !snapshot.equal(previous) {
644: 			states[idx] = snapshot
645: 			w.emit(registry, "update", snapshot)
646: 		}
647: 	}
648: }
649: 
650: // reportStitchMarks reports the links whose host-side stitch interface got
651: // marked after their last event. Only veths reported under their own name
652: // shortly before are looked at: the node's end of a veth-stitch link is a veth
653: // and is marked while its lab deploys.
654: func (w *netlinkWatcher) reportStitchMarks(
655: 	states map[int]ifaceSnapshot,
656: 	registry *netlinkRegistry,
657: ) {
658: 	for idx, snapshot := range states {
659: 		reported, ok := w.reported[idx]
660: 		if !ok || snapshot.Type != "veth" ||
661: 			reported.attributes["ifname"] != snapshot.Name ||
662: 			time.Since(reported.since) > stitchMarkWindow {
663: 			continue
664: 		}
665: 
666: 		if interfaceAttributes(w.container, snapshot)["ifname"] != snapshot.Name {
667: 			w.emit(registry, "update", snapshot)
668: 		}
669: 	}
670: }
671: 
672: // emit reports an event of a link. A deletion names the link as it was last
673: // reported. A link reported under another name before, such as the node's own
674: // interface until its stitch interface got marked, is first reported deleted
675: // under that name, so that clients do not keep both; it is then new to them.
676: func (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {
677: 	if w.container == nil {
678: 		return
679: 	}
680: 
681: 	if action == "delete" {
682: 		attributes := interfaceAttributes(w.container, snapshot)
683: 		if previous, ok := w.reported[snapshot.Index]; ok {
684: 			attributes = previous.attributes
685: 		}
686: 
687: 		delete(w.reported, snapshot.Index)
688: 		registry.sendInterfaceEvent(w.container, action, attributes, time.Now())
689: 
690: 		return
691: 	}
692: 
693: 	attributes := interfaceAttributes(w.container, snapshot)
694: 	if w.track(registry, snapshot.Index, attributes) && action == "update" {
695: 		action = "create"
696: 	}
697: 
698: 	registry.sendInterfaceEvent(w.container, action, attributes, time.Now())
699: }
700: 
701: // emitStats reports the counters of a link, under the name emit reports it.
702: func (w *netlinkWatcher) emitStats(
703: 	registry *netlinkRegistry,
704: 	snapshot ifaceSnapshot,
705: 	metrics ifaceStatsMetrics,
706: ) {
707: 	if !registry.includeStats || w.container == nil || !snapshot.HasStats {
708: 		return
709: 	}
710: 
711: 	attributes := interfaceAttributes(w.container, snapshot)
712: 	if w.track(registry, snapshot.Index, attributes) {
713: 		registry.sendInterfaceEvent(
714: 			w.container,
715: 			"create",
716: 			maps.Clone(attributes),
717: 			metrics.Timestamp,
718: 		)
719: 	}
720: 
721: 	interfaceStatsAttributes(attributes, metrics)
722: 	registry.sendInterfaceEvent(w.container, "stats", attributes, metrics.Timestamp)
723: }
724: 
725: // track records what the link at index is reported as. When it was reported
726: // under another name before, it reports that name deleted and returns true.
727: func (w *netlinkWatcher) track(
728: 	registry *netlinkRegistry,
729: 	index int,
730: 	attributes map[string]string,
731: ) bool {
732: 	if w.reported == nil {
733: 		w.reported = make(map[int]reportedInterface)
734: 	}
735: 
736: 	previous, known := w.reported[index]
737: 
738: 	since := time.Now()
739: 	if known {
740: 		since = previous.since
741: 	}
742: 
743: 	w.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}
744: 
745: 	if !known || previous.attributes["ifname"] == attributes["ifname"] {
746: 		return false
747: 	}
748: 
749: 	registry.sendInterfaceEvent(w.container, "delete", previous.attributes, time.Now())
750: 
751: 	return true
752: }
753: 
754: func firstContainerName(container *clabruntime.GenericContainer) string {
755: 	if container == nil || len(container.Names) == 0 {
756: 		return ""
757: 	}
758: 
759: 	return container.Names[0]
760: }
761: 
762: func containerLabel(container *clabruntime.GenericContainer) string {
763: 	if container == nil || container.Labels == nil {
764: 		return ""
765: 	}
766: 
767: 	return container.Labels[clabconstants.Containerlab]
768: }
769: 
770: // interfaceSnapshotAttributes are the attributes every interface event reports for the
771: // interface itself.
772: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {
773: 	attributes := map[string]string{
774: 		"ifname": snapshot.Name,
775: 		"index":  strconv.Itoa(snapshot.Index),
776: 		"mtu":    strconv.Itoa(snapshot.MTU),
777: 		"state":  snapshot.OperState,
778: 		"type":   snapshot.Type,
779: 	}
780: 
781: 	if snapshot.Alias != "" {
782: 		attributes["alias"] = snapshot.Alias
783: 	}
784: 
785: 	if snapshot.MAC != "" {
786: 		attributes["mac"] = snapshot.MAC
787: 	}
788: 
789: 	return attributes
790: }
791: 
792: // interfaceStatsAttributes adds the counters and rates of a stats event.
793: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {
794: 	attributes["rx_bytes"] = strconv.FormatUint(metrics.RxBytes, 10)
795: 	attributes["tx_bytes"] = strconv.FormatUint(metrics.TxBytes, 10)
796: 	attributes["rx_packets"] = strconv.FormatUint(metrics.RxPackets, 10)
797: 	attributes["tx_packets"] = strconv.FormatUint(metrics.TxPackets, 10)
798: 	attributes["rx_bps"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)
799: 	attributes["tx_bps"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)
800: 	attributes["rx_pps"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)
801: 	attributes["tx_pps"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)
802: 	attributes["interval_seconds"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)
803: }
804: 
805: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those
806: // of the netlink interface events, for the node the runtime runs. Values the runtime could not
807: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.
808: func labRuntimeInterfaceAttributes(
809: 	lab, name string,
810: 	iface *clablabruntime.InterfaceEventData,
811: ) map[string]string {
812: 	attributes := interfaceSnapshotAttributes(ifaceSnapshot{
813: 		Index:     iface.Index,
814: 		Name:      iface.Name,
815: 		Alias:     iface.Alias,
816: 		MTU:       iface.MTU,
817: 		MAC:       iface.MAC,
818: 		OperState: iface.OperState,
819: 		Type:      iface.Type,
820: 	})
821: 	if iface.Index <= 0 {
822: 		delete(attributes, "index")
823: 	}
824: 	if iface.MTU <= 0 {
825: 		delete(attributes, "mtu")
826: 	}
827: 
828: 	if lab != "" {
829: 		attributes["lab"] = lab
830: 	}
831: 	if name != "" {
832: 		attributes["name"] = name
833: 	}
834: 
835: 	if stats := iface.Stats; stats != nil {
836: 		interfaceStatsAttributes(attributes, ifaceStatsMetrics{
837: 			RxBytes:   stats.RxBytes,
838: 			TxBytes:   stats.TxBytes,
839: 			RxPackets: stats.RxPackets,
840: 			TxPackets: stats.TxPackets,
841: 			RxBps:     stats.RxBps,
842: 			TxBps:     stats.TxBps,
843: 			RxPps:     stats.RxPps,
844: 			TxPps:     stats.TxPps,
845: 			Interval:  stats.Interval,
846: 		})
847: 	}
848: 
849: 	return attributes
850: }
851: 
852: func interfaceAttributes(
853: 	container *clabruntime.GenericContainer,
854: 	snapshot ifaceSnapshot,
855: ) map[string]string {
856: 	attributes := interfaceSnapshotAttributes(snapshot)
857: 	attributes["origin"] = "netlink"
858: 
859: 	if lab := containerLabel(container); lab != "" {
860: 		attributes["lab"] = lab
861: 	}
862: 
863: 	if name := firstContainerName(container); name != "" {
864: 		attributes["name"] = name
865: 	}
866: 
867: 	overlayToolsInterface(container, attributes)
868: 
869: 	// Add netem attributes if present
870: 	if snapshot.HasNetem {
871: 		if snapshot.Delay != "" {
872: 			attributes["netem_delay"] = snapshot.Delay
873: 		}
874: 		if snapshot.Jitter != "" {
875: 			attributes["netem_jitter"] = snapshot.Jitter
876: 		}
877: 		if snapshot.PacketLoss != 0 {
878: 			attributes["netem_loss"] = strconv.FormatFloat(snapshot.PacketLoss, 'f', 2, 64) + "%"
879: 		}
880: 		if snapshot.Rate != 0 {
881: 			attributes["netem_rate"] = strconv.Itoa(snapshot.Rate) + "kbit"
882: 		}
883: 		if snapshot.Corruption != 0 {
884: 			attributes["netem_corruption"] = strconv.FormatFloat(
885: 				snapshot.Corruption,
886: 				'f',
887: 				2,
888: 				64,
889: 			) + "%"
890: 		}
891: 	}
892: 
893: 	return attributes
894: }
895: 
896: // overlayToolsInterface rewrites attributes to the host-side stitch interface
897: // when one exists, matching `inspect interfaces`.
898: func overlayToolsInterface(
899: 	container *clabruntime.GenericContainer,
900: 	attributes map[string]string,
901: ) {
902: 	if container == nil {
903: 		return
904: 	}
905: 
906: 	lab, node := clabcore.TopoIdentity(container.Labels)
907: 	if lab == "" || node == "" {
908: 		return
909: 	}
910: 
911: 	topoName := attributes["alias"]
912: 	if topoName == "" {
913: 		topoName = attributes["ifname"]
914: 	}
915: 
916: 	tools, ok := clablinks.ToolsInterface(lab, node, topoName)
917: 	if !ok {
918: 		return
919: 	}
920: 
921: 	snapshot := snapshotFromLink(tools)
922: 	attributes["ifname"] = snapshot.Name
923: 	attributes["alias"] = topoName
924: 	attributes["index"] = strconv.Itoa(snapshot.Index)
925: 	attributes["mtu"] = strconv.Itoa(snapshot.MTU)
926: 	attributes["state"] = snapshot.OperState
927: 	attributes["type"] = snapshot.Type
928: 
929: 	if snapshot.MAC != "" {
930: 		attributes["mac"] = snapshot.MAC
931: 	}
932: }
933: 
934: func (r *netlinkRegistry) sendInterfaceEvent(
935: 	container *clabruntime.GenericContainer,
936: 	action string,
937: 	attributes map[string]string,
938: 	timestamp time.Time,
939: ) {
940: 	event := aggregatedEvent{
941: 		Timestamp:   timestamp,
942: 		Type:        "interface",
943: 		Action:      action,
944: 		ActorID:     container.ShortID,
945: 		ActorName:   firstContainerName(container),
946: 		ActorFullID: container.ID,
947: 		Attributes:  attributes,
948: 	}
949: 
950: 	select {
951: 	case r.events <- event:
952: 	case <-r.ctx.Done():
953: 	}
954: }
955: 
956: func waitForNamespacePath(
957: 	ctx context.Context,
958: 	runtime clabruntime.ContainerRuntime,
959: 	containerID string,
960: ) (string, error) {
961: 	const (
962: 		attempts   = 5
963: 		retryDelay = 200 * time.Millisecond
964: 	)
965: 
966: 	var lastErr error
967: 
968: 	for i := 0; i < attempts; i++ {
969: 		nsPath, err := runtime.GetNSPath(ctx, containerID)
970: 		if err == nil && nsPath != "" {
971: 			return nsPath, nil
972: 		}
973: 
974: 		if err != nil {
975: 			lastErr = err
976: 		}
977: 
978: 		select {
979: 		case <-time.After(retryDelay):
980: 		case <-ctx.Done():
981: 			return "", ctx.Err()
982: 		}
983: 	}
984: 
985: 	if lastErr != nil {
986: 		return "", lastErr
987: 	}
988: 
989: 	return "", fmt.Errorf("namespace path not ready for container %s", containerID)
990: }
991: 
992: func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {
993: 	if netHandle == nil {
994: 		return nil, fmt.Errorf("netlink handle is nil")
995: 	}
996: 
997: 	links, err := netHandle.LinkList()
998: 	if err != nil {
999: 		return nil, fmt.Errorf("unable to list links: %w", err)
1000: 	}
1001: 
1002: 	states := make(map[int]ifaceSnapshot, len(links))
1003: 	for _, link := range links {
1004: 		snapshot := snapshotFromLink(link)
1005: 		states[snapshot.Index] = snapshot
1006: 	}
1007: 
1008: 	return states, nil
1009: }
1010: 
1011: // withNetem returns the snapshot with the netem settings of its interface.
1012: func withNetem(snapshot ifaceSnapshot, netemInfos map[int]netemInfo) ifaceSnapshot {
1013: 	if info, ok := netemInfos[snapshot.Index]; ok {
1014: 		snapshot.HasNetem = true
1015: 		snapshot.Delay = info.Delay
1016: 		snapshot.Jitter = info.Jitter
1017: 		snapshot.PacketLoss = info.PacketLoss
1018: 		snapshot.Rate = info.Rate
1019: 		snapshot.Corruption = info.Corruption
1020: 	}
1021: 
1022: 	return snapshot
1023: }
1024: 
1025: func snapshotFromLink(link netlink.Link) ifaceSnapshot {
1026: 	attrs := link.Attrs()
1027: 
1028: 	snapshot := ifaceSnapshot{
1029: 		Type: link.Type(),
1030: 	}
1031: 
1032: 	if attrs != nil {
1033: 		snapshot.Index = attrs.Index
1034: 		snapshot.Name = attrs.Name
1035: 		snapshot.Alias = attrs.Alias
1036: 		snapshot.MTU = attrs.MTU
1037: 		if len(attrs.HardwareAddr) > 0 {
1038: 			snapshot.MAC = attrs.HardwareAddr.String()
1039: 		}
1040: 		snapshot.OperState = attrs.OperState.String()
1041: 		if stats := attrs.Statistics; stats != nil {
1042: 			snapshot.HasStats = true
1043: 			snapshot.RxBytes = stats.RxBytes
1044: 			snapshot.TxBytes = stats.TxBytes
1045: 			snapshot.RxPackets = stats.RxPackets
1046: 			snapshot.TxPackets = stats.TxPackets
1047: 		}
1048: 	}
1049: 
1050: 	return snapshot
1051: }
1052: 
1053: type ifaceSnapshot struct {
1054: 	Index     int
1055: 	Name      string
1056: 	Alias     string
1057: 	MTU       int
1058: 	MAC       string
1059: 	OperState string
1060: 	Type      string
1061: 	HasStats  bool
1062: 	RxBytes   uint64
1063: 	TxBytes   uint64
1064: 	RxPackets uint64
1065: 	TxPackets uint64
1066: 	// Netem fields
1067: 	HasNetem   bool
1068: 	Delay      string
1069: 	Jitter     string
1070: 	PacketLoss float64
1071: 	Rate       int
1072: 	Corruption float64
1073: }
1074: 
1075: func (s ifaceSnapshot) equal(other ifaceSnapshot) bool {
1076: 	return s.Index == other.Index &&
1077: 		s.Name == other.Name &&
1078: 		s.Alias == other.Alias &&
1079: 		s.MTU == other.MTU &&
1080: 		s.MAC == other.MAC &&
1081: 		s.OperState == other.OperState &&
1082: 		s.Type == other.Type &&
1083: 		s.HasNetem == other.HasNetem &&
1084: 		s.Delay == other.Delay &&
1085: 		s.Jitter == other.Jitter &&
1086: 		s.PacketLoss == other.PacketLoss &&
1087: 		s.Rate == other.Rate &&
1088: 		s.Corruption == other.Corruption
1089: }
1090: 
1091: type ifaceStatsSample struct {
1092: 	RxBytes   uint64
1093: 	TxBytes   uint64
1094: 	RxPackets uint64
1095: 	TxPackets uint64
1096: 	Timestamp time.Time
1097: }
1098: 
1099: type ifaceStatsMetrics struct {
1100: 	RxBytes   uint64
1101: 	TxBytes   uint64
1102: 	RxPackets uint64
1103: 	TxPackets uint64
1104: 	RxBps     float64
1105: 	TxBps     float64
1106: 	RxPps     float64
1107: 	TxPps     float64
1108: 	Interval  time.Duration
1109: 	Timestamp time.Time
1110: }
1111: 
1112: func newStatsSample(snapshot ifaceSnapshot, timestamp time.Time) (ifaceStatsSample, bool) {
1113: 	if !snapshot.HasStats {
1114: 		return ifaceStatsSample{}, false
1115: 	}
1116: 
1117: 	return ifaceStatsSample{
1118: 		RxBytes:   snapshot.RxBytes,
1119: 		TxBytes:   snapshot.TxBytes,
1120: 		RxPackets: snapshot.RxPackets,
1121: 		TxPackets: snapshot.TxPackets,
1122: 		Timestamp: timestamp,
1123: 	}, true
1124: }
1125: 
1126: func (w *netlinkWatcher) collectAndEmitStats(
1127: 	netHandle *netlink.Handle,
1128: 	states map[int]ifaceSnapshot,
1129: 	statsSamples map[int]ifaceStatsSample,
1130: 	registry *netlinkRegistry,
1131: ) {
1132: 	if netHandle == nil || statsSamples == nil {
1133: 		return
1134: 	}
1135: 
1136: 	now := time.Now()
1137: 	// Fetch all interfaces with one netlink call per tick instead of one call
1138: 	// per interface to reduce syscall overhead in large labs.
1139: 	currentStates, err := snapshotInterfaces(netHandle)
1140: 	if err != nil {
1141: 		log.Debugf(
1142: 			"failed to collect interface stats snapshot for container %s: %v",
1143: 			firstContainerName(w.container),
1144: 			err,
1145: 		)
1146: 
1147: 		return
1148: 	}
1149: 
1150: 	for idx, state := range states {
1151: 		current, ok := currentStates[idx]
1152: 		if !ok {
1153: 			continue
1154: 		}
1155: 
1156: 		state.Name = current.Name
1157: 		state.Alias = current.Alias
1158: 		state.MTU = current.MTU
1159: 		state.MAC = current.MAC
1160: 		state.OperState = current.OperState
1161: 		state.Type = current.Type
1162: 		state.HasStats = current.HasStats
1163: 		state.RxBytes = current.RxBytes
1164: 		state.TxBytes = current.TxBytes
1165: 		state.RxPackets = current.RxPackets
1166: 		state.TxPackets = current.TxPackets
1167: 		states[idx] = state
1168: 
1169: 		if !state.HasStats {
1170: 			delete(statsSamples, idx)
1171: 
1172: 			continue
1173: 		}
1174: 
1175: 		prev, ok := statsSamples[idx]
1176: 		if !ok || now.Sub(prev.Timestamp) <= 0 {
1177: 			statsSamples[idx] = ifaceStatsSample{
1178: 				RxBytes:   state.RxBytes,
1179: 				TxBytes:   state.TxBytes,
1180: 				RxPackets: state.RxPackets,
1181: 				TxPackets: state.TxPackets,
1182: 				Timestamp: now,
1183: 			}
1184: 
1185: 			continue
1186: 		}
1187: 
1188: 		interval := now.Sub(prev.Timestamp)
1189: 		if interval <= 0 {
1190: 			statsSamples[idx] = ifaceStatsSample{
1191: 				RxBytes:   state.RxBytes,
1192: 				TxBytes:   state.TxBytes,
1193: 				RxPackets: state.RxPackets,
1194: 				TxPackets: state.TxPackets,
1195: 				Timestamp: now,
1196: 			}
1197: 
1198: 			continue
1199: 		}
1200: 
1201: 		rxBytesDelta := deltaCounter(prev.RxBytes, state.RxBytes)
1202: 		txBytesDelta := deltaCounter(prev.TxBytes, state.TxBytes)
1203: 		rxPacketsDelta := deltaCounter(prev.RxPackets, state.RxPackets)
1204: 		txPacketsDelta := deltaCounter(prev.TxPackets, state.TxPackets)
1205: 
1206: 		seconds := interval.Seconds()
1207: 		if seconds <= 0 {
1208: 			statsSamples[idx] = ifaceStatsSample{
1209: 				RxBytes:   state.RxBytes,
1210: 				TxBytes:   state.TxBytes,
1211: 				RxPackets: state.RxPackets,
1212: 				TxPackets: state.TxPackets,
1213: 				Timestamp: now,
1214: 			}
1215: 
1216: 			continue
1217: 		}
1218: 
1219: 		metrics := ifaceStatsMetrics{
1220: 			RxBytes:   state.RxBytes,
1221: 			TxBytes:   state.TxBytes,
1222: 			RxPackets: state.RxPackets,
1223: 			TxPackets: state.TxPackets,
1224: 			RxBps:     float64(rxBytesDelta) * 8 / seconds,
1225: 			TxBps:     float64(txBytesDelta) * 8 / seconds,
1226: 			RxPps:     float64(rxPacketsDelta) / seconds,
1227: 			TxPps:     float64(txPacketsDelta) / seconds,
1228: 			Interval:  interval,
1229: 			Timestamp: now,
1230: 		}
1231: 
1232: 		w.emitStats(registry, state, metrics)
1233: 
1234: 		statsSamples[idx] = ifaceStatsSample{
1235: 			RxBytes:   state.RxBytes,
1236: 			TxBytes:   state.TxBytes,
1237: 			RxPackets: state.RxPackets,
1238: 			TxPackets: state.TxPackets,
1239: 			Timestamp: now,
1240: 		}
1241: 	}
1242: }
1243: 
1244: func deltaCounter(previous, current uint64) uint64 {
1245: 	if current >= previous {
1246: 		return current - previous
1247: 	}
1248: 
1249: 	return current
1250: }
1251: 
1252: const (
1253: 	msPerSec = 1000
1254: )
1255: 
1256: type netemQuerier struct {
1257: 	nsHandle netns.NsHandle
1258: 	tcHandle *gotc.Tc
1259: }
1260: 
1261: func newNetemQuerier(nsHandle netns.NsHandle) *netemQuerier {
1262: 	return &netemQuerier{
1263: 		nsHandle: nsHandle,
1264: 	}
1265: }
1266: 
1267: func (q *netemQuerier) Close() {
1268: 	if q == nil || q.tcHandle == nil {
1269: 		return
1270: 	}
1271: 
1272: 	q.tcHandle.Close()
1273: 	q.tcHandle = nil
1274: }
1275: 
1276: // Query queries the TC qdiscs in the namespace and returns a map of
1277: // interface index to netem data.
1278: func (q *netemQuerier) Query() map[int]netemInfo {
1279: 	result := make(map[int]netemInfo)
1280: 
1281: 	qdiscs, err := q.qdiscs()
1282: 	if err != nil {
1283: 		log.Debugf("failed to query tc qdiscs: %v", err)
1284: 		return result
1285: 	}
1286: 
1287: 	for idx := range qdiscs {
1288: 		qdisc := &qdiscs[idx]
1289: 		if qdisc.Attribute.Kind != "netem" || qdisc.Netem == nil {
1290: 			continue
1291: 		}
1292: 
1293: 		info := netemInfoFromQdisc(qdisc)
1294: 		if info.hasValues() {
1295: 			result[int(qdisc.Ifindex)] = info
1296: 		}
1297: 	}
1298: 
1299: 	return result
1300: }
1301: 
1302: func (q *netemQuerier) qdiscs() ([]gotc.Object, error) {
1303: 	if q == nil {
1304: 		return nil, fmt.Errorf("netem querier is nil")
1305: 	}
1306: 
1307: 	if err := q.ensureHandle(); err != nil {
1308: 		return nil, err
1309: 	}
1310: 
1311: 	qdiscs, err := clabnetem.Impairments(q.tcHandle)
1312: 	if err == nil {
1313: 		return qdiscs, nil
1314: 	}
1315: 
1316: 	// Retry once by reopening the tc socket in case it became stale.
1317: 	q.Close()
1318: 	if errOpen := q.ensureHandle(); errOpen != nil {
1319: 		return nil, fmt.Errorf(
1320: 			"failed to query tc qdiscs (%v), and failed to reopen tc socket (%v)",
1321: 			err,
1322: 			errOpen,
1323: 		)
1324: 	}
1325: 
1326: 	return clabnetem.Impairments(q.tcHandle)
1327: }
1328: 
1329: func (q *netemQuerier) ensureHandle() error {
1330: 	if q == nil {
1331: 		return fmt.Errorf("netem querier is nil")
1332: 	}
1333: 
1334: 	if q.tcHandle != nil {
1335: 		return nil
1336: 	}
1337: 
1338: 	tcnl, err := clabnetem.NewTC(int(q.nsHandle))
1339: 	if err != nil {
1340: 		return fmt.Errorf("failed to open tc socket for netem query: %w", err)
1341: 	}
1342: 
1343: 	q.tcHandle = tcnl
1344: 
1345: 	return nil
1346: }
1347: 
1348: type netemInfo struct {
1349: 	Delay      string
1350: 	Jitter     string
1351: 	PacketLoss float64
1352: 	Rate       int
1353: 	Corruption float64
1354: }
1355: 
1356: func (n netemInfo) hasValues() bool {
1357: 	return n.Delay != "" || n.Jitter != "" || n.PacketLoss != 0 || n.Rate != 0 || n.Corruption != 0
1358: }
1359: 
1360: func netemInfoFromQdisc(qdisc *gotc.Object) netemInfo {
1361: 	var info netemInfo
1362: 
1363: 	if qdisc.Netem == nil {
1364: 		return info
1365: 	}
1366: 
1367: 	if qdisc.Netem.Latency64 != nil && *qdisc.Netem.Latency64 != 0 {
1368: 		info.Delay = (time.Duration(*qdisc.Netem.Latency64) * time.Nanosecond).String()
1369: 	}
1370: 
1371: 	if qdisc.Netem.Jitter64 != nil && *qdisc.Netem.Jitter64 != 0 {
1372: 		info.Jitter = (time.Duration(*qdisc.Netem.Jitter64) * time.Nanosecond).String()
1373: 	}
1374: 
1375: 	if qdisc.Netem.Rate != nil && qdisc.Netem.Rate.Rate != 0 {
1376: 		info.Rate = int(qdisc.Netem.Rate.Rate * 8 / msPerSec)
1377: 	}
1378: 
1379: 	if qdisc.Netem.Corrupt != nil && qdisc.Netem.Corrupt.Probability != 0 {
1380: 		info.Corruption = math.Round((float64(qdisc.Netem.Corrupt.Probability)/
1381: 			float64(math.MaxUint32)*100)*100) / 100
1382: 	}
1383: 
1384: 	if qdisc.Netem.Qopt.Loss != 0 {
1385: 		info.PacketLoss = math.Round(
1386: 			(float64(qdisc.Netem.Qopt.Loss)/float64(math.MaxUint32)*100)*100) / 100
1387: 	}
1388: 
1389: 	return info
1390: }

(End of file - total 1390 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46a65a80015Dp7xIIqnk9FLJ",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a3d31001iIjThNQ1viFvc4",
  "callID": "call_4041647b609245bf97dc9aee",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/netlink.go"
    },
    "output": "<path>/source/head/core/events/netlink.go</path>\n<type>file</type>\n<content>\n1: package events\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"maps\"\n8: \t\"math\"\n9: \t\"strconv\"\n10: \t\"strings\"\n11: \t\"sync\"\n12: \t\"time\"\n13: \n14: \t\"github.com/charmbracelet/log\"\n15: \tgotc \"github.com/florianl/go-tc\"\n16: \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n17: \tclabcore \"github.com/srl-labs/containerlab/core\"\n18: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n19: \tclablinks \"github.com/srl-labs/containerlab/links\"\n20: \tclabnetem \"github.com/srl-labs/containerlab/netem\"\n21: \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n22: \tclabutils \"github.com/srl-labs/containerlab/utils\"\n23: \t\"github.com/vishvananda/netlink\"\n24: \t\"github.com/vishvananda/netns\"\n25: \t\"golang.org/x/sys/unix\"\n26: )\n27: \n28: type netlinkRegistry struct {\n29: \tctx                    context.Context\n30: \tmu                     sync.Mutex\n31: \twatchers               map[string]*netlinkWatcher\n32: \tevents                 chan<- aggregatedEvent\n33: \tincludeInitialSnapshot bool\n34: \tincludeStats           bool\n35: \tstatsInterval          time.Duration\n36: }\n37: \n38: func newNetlinkRegistry(\n39: \tctx context.Context,\n40: \tevents chan<- aggregatedEvent,\n41: \tincludeInitialSnapshot bool,\n42: \tincludeStats bool,\n43: \tstatsInterval time.Duration,\n44: ) *netlinkRegistry {\n45: \treturn &netlinkRegistry{\n46: \t\tctx:                    ctx,\n47: \t\twatchers:               make(map[string]*netlinkWatcher),\n48: \t\tevents:                 events,\n49: \t\tincludeInitialSnapshot: includeInitialSnapshot,\n50: \t\tincludeStats:           includeStats,\n51: \t\tstatsInterval:          statsInterval,\n52: \t}\n53: }\n54: \n55: func (r *netlinkRegistry) Start(container *clabruntime.GenericContainer) {\n56: \tclone := cloneContainer(container)\n57: \tif clone == nil {\n58: \t\treturn\n59: \t}\n60: \n61: \tid := clone.ID\n62: \tif id == \"\" {\n63: \t\tid = clone.ShortID\n64: \t}\n65: \n66: \tif id == \"\" {\n67: \t\treturn\n68: \t}\n69: \n70: \tr.mu.Lock()\n71: \tif _, exists := r.watchers[id]; exists {\n72: \t\tr.mu.Unlock()\n73: \n74: \t\treturn\n75: \t}\n76: \n77: \twatcherCtx, cancel := context.WithCancel(r.ctx)\n78: \twatcher := &netlinkWatcher{\n79: \t\tcontainer:       clone,\n80: \t\tcancel:          cancel,\n81: \t\tdone:            make(chan struct{}),\n82: \t\tincludeSnapshot: r.includeInitialSnapshot,\n83: \t\tincludeStats:    r.includeStats,\n84: \t\tstatsInterval:   r.statsInterval,\n85: \t}\n86: \n87: \tr.watchers[id] = watcher\n88: \tr.mu.Unlock()\n89: \n90: \tgo watcher.run(watcherCtx, r)\n91: }\n92: \n93: func (r *netlinkRegistry) Stop(id string) {\n94: \tif id == \"\" {\n95: \t\treturn\n96: \t}\n97: \n98: \tr.mu.Lock()\n99: \twatcher, ok := r.watchers[id]\n100: \tif ok {\n101: \t\tdelete(r.watchers, id)\n102: \t}\n103: \tr.mu.Unlock()\n104: \n105: \tif !ok {\n106: \t\treturn\n107: \t}\n108: \n109: \twatcher.cancel()\n110: \t<-watcher.done\n111: }\n112: \n113: func (r *netlinkRegistry) remove(id string, watcher *netlinkWatcher) {\n114: \tif id == \"\" {\n115: \t\treturn\n116: \t}\n117: \n118: \tr.mu.Lock()\n119: \tdefer r.mu.Unlock()\n120: \n121: \tif current, ok := r.watchers[id]; ok && current == watcher {\n122: \t\tdelete(r.watchers, id)\n123: \t}\n124: }\n125: \n126: func (r *netlinkRegistry) HandleContainerEvent(\n127: \truntime clabruntime.ContainerRuntime,\n128: \tev clabruntime.ContainerEvent,\n129: ) {\n130: \tif !strings.EqualFold(ev.Type, clabruntime.EventTypeContainer) {\n131: \t\treturn\n132: \t}\n133: \n134: \taction := strings.ToLower(ev.Action)\n135: \n136: \tswitch action {\n137: \tcase clabruntime.EventActionStart,\n138: \t\tclabruntime.EventActionUnpause,\n139: \t\tclabruntime.EventActionRestart:\n140: \t\tcontainer := containerFromEvent(runtime, ev)\n141: \t\tif container != nil {\n142: \t\t\tr.Start(container)\n143: \t\t}\n144: \tcase clabruntime.EventActionDie,\n145: \t\tclabruntime.EventActionStop,\n146: \t\tclabruntime.EventActionDestroy,\n147: \t\tclabruntime.EventActionKill:\n148: \t\tid := ev.ActorFullID\n149: \t\tif id == \"\" {\n150: \t\t\tid = ev.ActorID\n151: \t\t}\n152: \n153: \t\tr.Stop(id)\n154: \t}\n155: }\n156: \n157: func cloneContainer(container *clabruntime.GenericContainer) *clabruntime.GenericContainer {\n158: \tif container == nil {\n159: \t\treturn nil\n160: \t}\n161: \n162: \tclone := &clabruntime.GenericContainer{\n163: \t\tNames:   append([]string{}, container.Names...),\n164: \t\tID:      container.ID,\n165: \t\tShortID: container.ShortID,\n166: \t\tLabels:  cloneStringMap(container.Labels),\n167: \t}\n168: \n169: \tif clone.ShortID == \"\" {\n170: \t\tclone.ShortID = clabutils.ShortID(clone.ID)\n171: \t}\n172: \n173: \tif container.Runtime == nil {\n174: \t\treturn nil\n175: \t}\n176: \n177: \tclone.SetRuntime(container.Runtime)\n178: \n179: \treturn clone\n180: }\n181: \n182: func containerFromEvent(\n183: \truntime clabruntime.ContainerRuntime,\n184: \tev clabruntime.ContainerEvent,\n185: ) *clabruntime.GenericContainer {\n186: \tattributes := ev.Attributes\n187: \n188: \tname := ev.ActorName\n189: \tif name == \"\" && attributes != nil {\n190: \t\tname = attributes[\"name\"]\n191: \t}\n192: \n193: \tid := ev.ActorFullID\n194: \tif id == \"\" {\n195: \t\tid = ev.ActorID\n196: \t}\n197: \n198: \tif id == \"\" && name == \"\" {\n199: \t\treturn nil\n200: \t}\n201: \n202: \tshort := ev.ActorID\n203: \tif short == \"\" {\n204: \t\tshort = id\n205: \t}\n206: \n207: \tcontainer := &clabruntime.GenericContainer{\n208: \t\tID:      id,\n209: \t\tShortID: clabutils.ShortID(short),\n210: \t}\n211: \n212: \tif name != \"\" {\n213: \t\tcontainer.Names = []string{name}\n214: \t}\n215: \n216: \tif attributes != nil {\n217: \t\tfor _, key := range []string{\n218: \t\t\tclabconstants.Containerlab,\n219: \t\t\tclabconstants.NodeName,\n220: \t\t\tclabconstants.RootNodeName,\n221: \t\t} {\n222: \t\t\tif v := attributes[key]; v != \"\" {\n223: \t\t\t\tif container.Labels == nil {\n224: \t\t\t\t\tcontainer.Labels = map[string]string{}\n225: \t\t\t\t}\n226: \n227: \t\t\t\tcontainer.Labels[key] = v\n228: \t\t\t}\n229: \t\t}\n230: \t}\n231: \n232: \tif container.ShortID == \"\" {\n233: \t\tcontainer.ShortID = clabutils.ShortID(container.ID)\n234: \t}\n235: \n236: \tif runtime != nil {\n237: \t\tcontainer.SetRuntime(runtime)\n238: \t}\n239: \n240: \treturn container\n241: }\n242: \n243: type netlinkWatcher struct {\n244: \tcontainer       *clabruntime.GenericContainer\n245: \tcancel          context.CancelFunc\n246: \tdone            chan struct{}\n247: \tincludeSnapshot bool\n248: \tincludeStats    bool\n249: \tstatsInterval   time.Duration\n250: \tnsHandle        netns.NsHandle\n251: \t// reported holds what each link was last reported as, by its index in the\n252: \t// container's namespace.\n253: \treported map[int]reportedInterface\n254: }\n255: \n256: // reportedInterface is what a link was last reported as.\n257: type reportedInterface struct {\n258: \tattributes map[string]string\n259: \t// since is when the link was first reported.\n260: \tsince time.Time\n261: }\n262: \n263: // stitchMarkWindow is how long after a link is first reported its host-side\n264: // stitch interface is looked for while the link itself does not change.\n265: // Deploying a veth-stitch link marks that interface right after it creates the\n266: // link, without a change in the node's namespace.\n267: var stitchMarkWindow = time.Minute\n268: \n269: // Retry settings for a watcher that could not subscribe to link updates.\n270: var (\n271: \twatchMaxAttempts   = 5\n272: \twatchRetryDelay    = time.Second\n273: \twatchMaxRetryDelay = 10 * time.Second\n274: )\n275: \n276: func (w *netlinkWatcher) run(ctx context.Context, registry *netlinkRegistry) {\n277: \tdefer close(w.done)\n278: \tif w.container == nil {\n279: \t\treturn\n280: \t}\n281: \n282: \tdefer registry.remove(w.container.ID, w)\n283: \n284: \tcontainerName := firstContainerName(w.container)\n285: \tif w.container.Runtime == nil {\n286: \t\tlog.Debugf(\"container %s has no runtime, skipping netlink watcher\", containerName)\n287: \n288: \t\treturn\n289: \t}\n290: \n291: \t// The states outlive a subscription, so a resubscribe only reports what\n292: \t// changed while no subscription was active.\n293: \tstates := make(map[int]ifaceSnapshot)\n294: \n295: \tvar statsSamples map[int]ifaceStatsSample\n296: \tif w.includeStats {\n297: \t\tstatsSamples = make(map[int]ifaceStatsSample)\n298: \t}\n299: \n300: \tinitial := true\n301: \tfailures := 0\n302: \tdelay := watchRetryDelay\n303: \n304: \tfor {\n305: \t\tsubscribed, err := w.watch(ctx, registry, states, statsSamples, initial)\n306: \t\tif ctx.Err() != nil {\n307: \t\t\treturn\n308: \t\t}\n309: \n310: \t\tif subscribed {\n311: \t\t\tinitial = false\n312: \t\t\tfailures = 0\n313: \t\t\tdelay = watchRetryDelay\n314: \n315: \t\t\tlog.Warnf(\n316: \t\t\t\t\"netlink subscription for container %s ended, resubscribing: %v\",\n317: \t\t\t\tcontainerName,\n318: \t\t\t\terr,\n319: \t\t\t)\n320: \t\t} else {\n321: \t\t\tfailures++\n322: \t\t\tif failures >= watchMaxAttempts {\n323: \t\t\t\tlog.Warnf(\"stopped watching interfaces of container %s: %v\", containerName, err)\n324: \n325: \t\t\t\treturn\n326: \t\t\t}\n327: \n328: \t\t\tlog.Debugf(\n329: \t\t\t\t\"failed to watch interfaces of container %s, retrying in %s: %v\",\n330: \t\t\t\tcontainerName,\n331: \t\t\t\tdelay,\n332: \t\t\t\terr,\n333: \t\t\t)\n334: \t\t}\n335: \n336: \t\tselect {\n337: \t\tcase <-time.After(delay):\n338: \t\tcase <-ctx.Done():\n339: \t\t\treturn\n340: \t\t}\n341: \n342: \t\tdelay = min(delay*2, watchMaxRetryDelay)\n343: \t}\n344: }\n345: \n346: // watch subscribes to link updates in the container's namespace and handles\n347: // them until ctx ends or the subscription fails. It reports whether it\n348: // subscribed. The subscription lists the existing links itself, so no change\n349: // between listing and subscribing is lost.\n350: func (w *netlinkWatcher) watch(\n351: \tctx context.Context,\n352: \tregistry *netlinkRegistry,\n353: \tstates map[int]ifaceSnapshot,\n354: \tstatsSamples map[int]ifaceStatsSample,\n355: \tinitial bool,\n356: ) (bool, error) {\n357: \tnsPath, err := waitForNamespacePath(ctx, w.container.Runtime, w.container.ID)\n358: \tif err != nil {\n359: \t\treturn false, fmt.Errorf(\"failed to resolve netns: %w\", err)\n360: \t}\n361: \n362: \tnsHandle, err := netns.GetFromPath(nsPath)\n363: \tif err != nil {\n364: \t\treturn false, fmt.Errorf(\"failed to open netns: %w\", err)\n365: \t}\n366: \tdefer nsHandle.Close()\n367: \n368: \tw.nsHandle = nsHandle\n369: \n370: \tnetHandle, err := netlink.NewHandleAt(nsHandle)\n371: \tif err != nil {\n372: \t\treturn false, fmt.Errorf(\"failed to create netlink handle: %w\", err)\n373: \t}\n374: \tdefer netHandle.Close()\n375: \n376: \tnetemQuery := newNetemQuerier(nsHandle)\n377: \tdefer netemQuery.Close()\n378: \n379: \tnetemInfos := netemQuery.Query()\n380: \n381: \tupdates := make(chan netlink.LinkUpdate, 32)\n382: \tdone := make(chan struct{})\n383: \tdefer close(done)\n384: \n385: \tvar (\n386: \t\terrMu     sync.Mutex\n387: \t\tlastError error\n388: \t)\n389: \n390: \topts := netlink.LinkSubscribeOptions{\n391: \t\tNamespace:    &nsHandle,\n392: \t\tListExisting: true,\n393: \t\t// An interrupted listing is reported here too. It needs no action:\n394: \t\t// links that changed during the listing also arrive as updates.\n395: \t\tErrorCallback: func(err error) {\n396: \t\t\tlog.Debugf(\n397: \t\t\t\t\"netlink subscription for container %s: %v\",\n398: \t\t\t\tfirstContainerName(w.container),\n399: \t\t\t\terr,\n400: \t\t\t)\n401: \n402: \t\t\terrMu.Lock()\n403: \t\t\tlastError = err\n404: \t\t\terrMu.Unlock()\n405: \t\t},\n406: \t}\n407: \n408: \tif err := netlink.LinkSubscribeWithOptions(updates, done, opts); err != nil {\n409: \t\treturn false, fmt.Errorf(\"failed to subscribe to netlink updates: %w\", err)\n410: \t}\n411: \n412: \tvar vanished map[int]struct{}\n413: \tif len(states) > 0 {\n414: \t\tvanished = w.removeVanishedLinks(netHandle, states, statsSamples, registry)\n415: \t}\n416: \n417: \t// Set up netem polling interval (reuse stats interval or default to 1s).\n418: \tnetemPollInterval := w.statsInterval\n419: \tif netemPollInterval == 0 {\n420: \t\tnetemPollInterval = time.Second\n421: \t}\n422: \tnetemTicker := time.NewTicker(netemPollInterval)\n423: \tdefer netemTicker.Stop()\n424: \n425: \tvar (\n426: \t\tticker  *time.Ticker\n427: \t\ttickerC <-chan time.Time\n428: \t)\n429: \tif w.includeStats && w.statsInterval > 0 {\n430: \t\tticker = time.NewTicker(w.statsInterval)\n431: \t\ttickerC = ticker.C\n432: \t\tdefer ticker.Stop()\n433: \t}\n434: \n435: \tfor {\n436: \t\tselect {\n437: \t\tcase <-tickerC:\n438: \t\t\tw.collectAndEmitStats(netHandle, states, statsSamples, registry)\n439: \t\tcase <-netemTicker.C:\n440: \t\t\tw.pollNetemChanges(states, registry, netemQuery)\n441: \t\t\tw.reportStitchMarks(states, registry)\n442: \t\tcase <-ctx.Done():\n443: \t\t\treturn true, nil\n444: \t\tcase update, ok := <-updates:\n445: \t\t\tif !ok {\n446: \t\t\t\terrMu.Lock()\n447: \t\t\t\terr := lastError\n448: \t\t\t\terrMu.Unlock()\n449: \n450: \t\t\t\tif err == nil {\n451: \t\t\t\t\terr = errors.New(\"update channel closed\")\n452: \t\t\t\t}\n453: \n454: \t\t\t\treturn true, err\n455: \t\t\t}\n456: \n457: \t\t\t// Replies to the listing carry NLM_F_MULTI, notifications do not.\n458: \t\t\tif update.Header.Flags&unix.NLM_F_MULTI != 0 {\n459: \t\t\t\tw.processExisting(\n460: \t\t\t\t\tstates,\n461: \t\t\t\t\tstatsSamples,\n462: \t\t\t\t\tupdate.Link,\n463: \t\t\t\t\tnetemInfos,\n464: \t\t\t\t\tvanished,\n465: \t\t\t\t\tregistry,\n466: \t\t\t\t\tinitial,\n467: \t\t\t\t)\n468: \n469: \t\t\t\tcontinue\n470: \t\t\t}\n471: \n472: \t\t\tw.processUpdate(states, statsSamples, update, registry, netemQuery)\n473: \t\t}\n474: \t}\n475: }\n476: \n477: // processExisting records a link listed when the subscription started. On the\n478: // first subscription a new link is reported as a snapshot when requested; after\n479: // a resubscribe it is reported as created.\n480: //\n481: // The listing can be older than the check in removeVanishedLinks, so it can\n482: // still hold a link that check reported as deleted. Such a link is skipped; its\n483: // deletion notification follows and is ignored, as the link is not tracked.\n484: func (w *netlinkWatcher) processExisting(\n485: \tstates map[int]ifaceSnapshot,\n486: \tstatsSamples map[int]ifaceStatsSample,\n487: \tlink netlink.Link,\n488: \tnetemInfos map[int]netemInfo,\n489: \tvanished map[int]struct{},\n490: \tregistry *netlinkRegistry,\n491: \tinitial bool,\n492: ) {\n493: \tif link == nil || link.Attrs() == nil {\n494: \t\treturn\n495: \t}\n496: \n497: \tif _, ok := vanished[link.Attrs().Index]; ok {\n498: \t\treturn\n499: \t}\n500: \n501: \tsnapshot := withNetem(snapshotFromLink(link), netemInfos)\n502: \tprevious, exists := states[snapshot.Index]\n503: \n504: \tif exists && snapshot.equal(previous) {\n505: \t\treturn\n506: \t}\n507: \n508: \tstates[snapshot.Index] = snapshot\n509: \tif statsSamples != nil {\n510: \t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n511: \t\t\tstatsSamples[snapshot.Index] = sample\n512: \t\t}\n513: \t}\n514: \n515: \tswitch {\n516: \tcase exists:\n517: \t\tw.emit(registry, \"update\", snapshot)\n518: \tcase !initial:\n519: \t\tw.emit(registry, \"create\", snapshot)\n520: \tcase w.includeSnapshot:\n521: \t\tw.emit(registry, \"snapshot\", snapshot)\n522: \t}\n523: }\n524: \n525: // removeVanishedLinks reports the links that were deleted while no\n526: // subscription was active and returns their indexes.\n527: func (w *netlinkWatcher) removeVanishedLinks(\n528: \tnetHandle *netlink.Handle,\n529: \tstates map[int]ifaceSnapshot,\n530: \tstatsSamples map[int]ifaceStatsSample,\n531: \tregistry *netlinkRegistry,\n532: ) map[int]struct{} {\n533: \tcurrent, err := snapshotInterfaces(netHandle)\n534: \tif err != nil {\n535: \t\tlog.Debugf(\n536: \t\t\t\"failed to list interfaces of container %s: %v\",\n537: \t\t\tfirstContainerName(w.container),\n538: \t\t\terr,\n539: \t\t)\n540: \n541: \t\treturn nil\n542: \t}\n543: \n544: \tvanished := map[int]struct{}{}\n545: \n546: \tfor idx, snapshot := range states {\n547: \t\tif _, ok := current[idx]; ok {\n548: \t\t\tcontinue\n549: \t\t}\n550: \n551: \t\tvanished[idx] = struct{}{}\n552: \n553: \t\tdelete(states, idx)\n554: \t\tdelete(statsSamples, idx)\n555: \t\tw.emit(registry, \"delete\", snapshot)\n556: \t}\n557: \n558: \treturn vanished\n559: }\n560: \n561: func (w *netlinkWatcher) processUpdate(\n562: \tstates map[int]ifaceSnapshot,\n563: \tstatsSamples map[int]ifaceStatsSample,\n564: \tupdate netlink.LinkUpdate,\n565: \tregistry *netlinkRegistry,\n566: \tnetemQuery *netemQuerier,\n567: ) {\n568: \tif update.Link == nil {\n569: \t\treturn\n570: \t}\n571: \n572: \tattrs := update.Link.Attrs()\n573: \tif attrs == nil {\n574: \t\treturn\n575: \t}\n576: \n577: \tsnapshot := snapshotFromLink(update.Link)\n578: \tprevious, exists := states[snapshot.Index]\n579: \n580: \tswitch update.Header.Type {\n581: \tcase unix.RTM_DELLINK:\n582: \t\t// A link that is not tracked was never reported, or its deletion was\n583: \t\t// already reported when the links were listed again after a resubscribe.\n584: \t\tif !exists {\n585: \t\t\treturn\n586: \t\t}\n587: \n588: \t\tdelete(states, snapshot.Index)\n589: \t\tdelete(statsSamples, snapshot.Index)\n590: \t\tw.emit(registry, \"delete\", previous)\n591: \tcase unix.RTM_NEWLINK:\n592: \t\t// Query netem info for this interface\n593: \t\tsnapshot = withNetem(snapshot, netemQuery.Query())\n594: \n595: \t\tif exists && snapshot.equal(previous) {\n596: \t\t\treturn\n597: \t\t}\n598: \n599: \t\taction := \"create\"\n600: \t\tif exists {\n601: \t\t\taction = \"update\"\n602: \t\t}\n603: \n604: \t\tstates[snapshot.Index] = snapshot\n605: \t\tif w.includeStats && statsSamples != nil {\n606: \t\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n607: \t\t\t\tstatsSamples[snapshot.Index] = sample\n608: \t\t\t}\n609: \t\t}\n610: \t\tw.emit(registry, action, snapshot)\n611: \t}\n612: }\n613: \n614: // pollNetemChanges checks for netem changes and emits update events.\n615: func (w *netlinkWatcher) pollNetemChanges(\n616: \tstates map[int]ifaceSnapshot,\n617: \tregistry *netlinkRegistry,\n618: \tnetemQuery *netemQuerier,\n619: ) {\n620: \tnetemInfos := netemQuery.Query()\n621: \n622: \tfor idx, snapshot := range states {\n623: \t\tprevious := snapshot\n624: \t\tinfo, hasNetem := netemInfos[idx]\n625: \n626: \t\tif hasNetem {\n627: \t\t\tsnapshot.HasNetem = true\n628: \t\t\tsnapshot.Delay = info.Delay\n629: \t\t\tsnapshot.Jitter = info.Jitter\n630: \t\t\tsnapshot.PacketLoss = info.PacketLoss\n631: \t\t\tsnapshot.Rate = info.Rate\n632: \t\t\tsnapshot.Corruption = info.Corruption\n633: \t\t} else if snapshot.HasNetem {\n634: \t\t\t// Netem was removed\n635: \t\t\tsnapshot.HasNetem = false\n636: \t\t\tsnapshot.Delay = \"\"\n637: \t\t\tsnapshot.Jitter = \"\"\n638: \t\t\tsnapshot.PacketLoss = 0\n639: \t\t\tsnapshot.Rate = 0\n640: \t\t\tsnapshot.Corruption = 0\n641: \t\t}\n642: \n643: \t\tif !snapshot.equal(previous) {\n644: \t\t\tstates[idx] = snapshot\n645: \t\t\tw.emit(registry, \"update\", snapshot)\n646: \t\t}\n647: \t}\n648: }\n649: \n650: // reportStitchMarks reports the links whose host-side stitch interface got\n651: // marked after their last event. Only veths reported under their own name\n652: // shortly before are looked at: the node's end of a veth-stitch link is a veth\n653: // and is marked while its lab deploys.\n654: func (w *netlinkWatcher) reportStitchMarks(\n655: \tstates map[int]ifaceSnapshot,\n656: \tregistry *netlinkRegistry,\n657: ) {\n658: \tfor idx, snapshot := range states {\n659: \t\treported, ok := w.reported[idx]\n660: \t\tif !ok || snapshot.Type != \"veth\" ||\n661: \t\t\treported.attributes[\"ifname\"] != snapshot.Name ||\n662: \t\t\ttime.Since(reported.since) > stitchMarkWindow {\n663: \t\t\tcontinue\n664: \t\t}\n665: \n666: \t\tif interfaceAttributes(w.container, snapshot)[\"ifname\"] != snapshot.Name {\n667: \t\t\tw.emit(registry, \"update\", snapshot)\n668: \t\t}\n669: \t}\n670: }\n671: \n672: // emit reports an event of a link. A deletion names the link as it was last\n673: // reported. A link reported under another name before, such as the node's own\n674: // interface until its stitch interface got marked, is first reported deleted\n675: // under that name, so that clients do not keep both; it is then new to them.\n676: func (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {\n677: \tif w.container == nil {\n678: \t\treturn\n679: \t}\n680: \n681: \tif action == \"delete\" {\n682: \t\tattributes := interfaceAttributes(w.container, snapshot)\n683: \t\tif previous, ok := w.reported[snapshot.Index]; ok {\n684: \t\t\tattributes = previous.attributes\n685: \t\t}\n686: \n687: \t\tdelete(w.reported, snapshot.Index)\n688: \t\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n689: \n690: \t\treturn\n691: \t}\n692: \n693: \tattributes := interfaceAttributes(w.container, snapshot)\n694: \tif w.track(registry, snapshot.Index, attributes) && action == \"update\" {\n695: \t\taction = \"create\"\n696: \t}\n697: \n698: \tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n699: }\n700: \n701: // emitStats reports the counters of a link, under the name emit reports it.\n702: func (w *netlinkWatcher) emitStats(\n703: \tregistry *netlinkRegistry,\n704: \tsnapshot ifaceSnapshot,\n705: \tmetrics ifaceStatsMetrics,\n706: ) {\n707: \tif !registry.includeStats || w.container == nil || !snapshot.HasStats {\n708: \t\treturn\n709: \t}\n710: \n711: \tattributes := interfaceAttributes(w.container, snapshot)\n712: \tif w.track(registry, snapshot.Index, attributes) {\n713: \t\tregistry.sendInterfaceEvent(\n714: \t\t\tw.container,\n715: \t\t\t\"create\",\n716: \t\t\tmaps.Clone(attributes),\n717: \t\t\tmetrics.Timestamp,\n718: \t\t)\n719: \t}\n720: \n721: \tinterfaceStatsAttributes(attributes, metrics)\n722: \tregistry.sendInterfaceEvent(w.container, \"stats\", attributes, metrics.Timestamp)\n723: }\n724: \n725: // track records what the link at index is reported as. When it was reported\n726: // under another name before, it reports that name deleted and returns true.\n727: func (w *netlinkWatcher) track(\n728: \tregistry *netlinkRegistry,\n729: \tindex int,\n730: \tattributes map[string]string,\n731: ) bool {\n732: \tif w.reported == nil {\n733: \t\tw.reported = make(map[int]reportedInterface)\n734: \t}\n735: \n736: \tprevious, known := w.reported[index]\n737: \n738: \tsince := time.Now()\n739: \tif known {\n740: \t\tsince = previous.since\n741: \t}\n742: \n743: \tw.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}\n744: \n745: \tif !known || previous.attributes[\"ifname\"] == attributes[\"ifname\"] {\n746: \t\treturn false\n747: \t}\n748: \n749: \tregistry.sendInterfaceEvent(w.container, \"delete\", previous.attributes, time.Now())\n750: \n751: \treturn true\n752: }\n753: \n754: func firstContainerName(container *clabruntime.GenericContainer) string {\n755: \tif container == nil || len(container.Names) == 0 {\n756: \t\treturn \"\"\n757: \t}\n758: \n759: \treturn container.Names[0]\n760: }\n761: \n762: func containerLabel(container *clabruntime.GenericContainer) string {\n763: \tif container == nil || container.Labels == nil {\n764: \t\treturn \"\"\n765: \t}\n766: \n767: \treturn container.Labels[clabconstants.Containerlab]\n768: }\n769: \n770: // interfaceSnapshotAttributes are the attributes every interface event reports for the\n771: // interface itself.\n772: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n773: \tattributes := map[string]string{\n774: \t\t\"ifname\": snapshot.Name,\n775: \t\t\"index\":  strconv.Itoa(snapshot.Index),\n776: \t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n777: \t\t\"state\":  snapshot.OperState,\n778: \t\t\"type\":   snapshot.Type,\n779: \t}\n780: \n781: \tif snapshot.Alias != \"\" {\n782: \t\tattributes[\"alias\"] = snapshot.Alias\n783: \t}\n784: \n785: \tif snapshot.MAC != \"\" {\n786: \t\tattributes[\"mac\"] = snapshot.MAC\n787: \t}\n788: \n789: \treturn attributes\n790: }\n791: \n792: // interfaceStatsAttributes adds the counters and rates of a stats event.\n793: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n794: \tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n795: \tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n796: \tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n797: \tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n798: \tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n799: \tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n800: \tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n801: \tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n802: \tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n803: }\n804: \n805: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n806: // of the netlink interface events, for the node the runtime runs. Values the runtime could not\n807: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.\n808: func labRuntimeInterfaceAttributes(\n809: \tlab, name string,\n810: \tiface *clablabruntime.InterfaceEventData,\n811: ) map[string]string {\n812: \tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n813: \t\tIndex:     iface.Index,\n814: \t\tName:      iface.Name,\n815: \t\tAlias:     iface.Alias,\n816: \t\tMTU:       iface.MTU,\n817: \t\tMAC:       iface.MAC,\n818: \t\tOperState: iface.OperState,\n819: \t\tType:      iface.Type,\n820: \t})\n821: \tif iface.Index <= 0 {\n822: \t\tdelete(attributes, \"index\")\n823: \t}\n824: \tif iface.MTU <= 0 {\n825: \t\tdelete(attributes, \"mtu\")\n826: \t}\n827: \n828: \tif lab != \"\" {\n829: \t\tattributes[\"lab\"] = lab\n830: \t}\n831: \tif name != \"\" {\n832: \t\tattributes[\"name\"] = name\n833: \t}\n834: \n835: \tif stats := iface.Stats; stats != nil {\n836: \t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n837: \t\t\tRxBytes:   stats.RxBytes,\n838: \t\t\tTxBytes:   stats.TxBytes,\n839: \t\t\tRxPackets: stats.RxPackets,\n840: \t\t\tTxPackets: stats.TxPackets,\n841: \t\t\tRxBps:     stats.RxBps,\n842: \t\t\tTxBps:     stats.TxBps,\n843: \t\t\tRxPps:     stats.RxPps,\n844: \t\t\tTxPps:     stats.TxPps,\n845: \t\t\tInterval:  stats.Interval,\n846: \t\t})\n847: \t}\n848: \n849: \treturn attributes\n850: }\n851: \n852: func interfaceAttributes(\n853: \tcontainer *clabruntime.GenericContainer,\n854: \tsnapshot ifaceSnapshot,\n855: ) map[string]string {\n856: \tattributes := interfaceSnapshotAttributes(snapshot)\n857: \tattributes[\"origin\"] = \"netlink\"\n858: \n859: \tif lab := containerLabel(container); lab != \"\" {\n860: \t\tattributes[\"lab\"] = lab\n861: \t}\n862: \n863: \tif name := firstContainerName(container); name != \"\" {\n864: \t\tattributes[\"name\"] = name\n865: \t}\n866: \n867: \toverlayToolsInterface(container, attributes)\n868: \n869: \t// Add netem attributes if present\n870: \tif snapshot.HasNetem {\n871: \t\tif snapshot.Delay != \"\" {\n872: \t\t\tattributes[\"netem_delay\"] = snapshot.Delay\n873: \t\t}\n874: \t\tif snapshot.Jitter != \"\" {\n875: \t\t\tattributes[\"netem_jitter\"] = snapshot.Jitter\n876: \t\t}\n877: \t\tif snapshot.PacketLoss != 0 {\n878: \t\t\tattributes[\"netem_loss\"] = strconv.FormatFloat(snapshot.PacketLoss, 'f', 2, 64) + \"%\"\n879: \t\t}\n880: \t\tif snapshot.Rate != 0 {\n881: \t\t\tattributes[\"netem_rate\"] = strconv.Itoa(snapshot.Rate) + \"kbit\"\n882: \t\t}\n883: \t\tif snapshot.Corruption != 0 {\n884: \t\t\tattributes[\"netem_corruption\"] = strconv.FormatFloat(\n885: \t\t\t\tsnapshot.Corruption,\n886: \t\t\t\t'f',\n887: \t\t\t\t2,\n888: \t\t\t\t64,\n889: \t\t\t) + \"%\"\n890: \t\t}\n891: \t}\n892: \n893: \treturn attributes\n894: }\n895: \n896: // overlayToolsInterface rewrites attributes to the host-side stitch interface\n897: // when one exists, matching `inspect interfaces`.\n898: func overlayToolsInterface(\n899: \tcontainer *clabruntime.GenericContainer,\n900: \tattributes map[string]string,\n901: ) {\n902: \tif container == nil {\n903: \t\treturn\n904: \t}\n905: \n906: \tlab, node := clabcore.TopoIdentity(container.Labels)\n907: \tif lab == \"\" || node == \"\" {\n908: \t\treturn\n909: \t}\n910: \n911: \ttopoName := attributes[\"alias\"]\n912: \tif topoName == \"\" {\n913: \t\ttopoName = attributes[\"ifname\"]\n914: \t}\n915: \n916: \ttools, ok := clablinks.ToolsInterface(lab, node, topoName)\n917: \tif !ok {\n918: \t\treturn\n919: \t}\n920: \n921: \tsnapshot := snapshotFromLink(tools)\n922: \tattributes[\"ifname\"] = snapshot.Name\n923: \tattributes[\"alias\"] = topoName\n924: \tattributes[\"index\"] = strconv.Itoa(snapshot.Index)\n925: \tattributes[\"mtu\"] = strconv.Itoa(snapshot.MTU)\n926: \tattributes[\"state\"] = snapshot.OperState\n927: \tattributes[\"type\"] = snapshot.Type\n928: \n929: \tif snapshot.MAC != \"\" {\n930: \t\tattributes[\"mac\"] = snapshot.MAC\n931: \t}\n932: }\n933: \n934: func (r *netlinkRegistry) sendInterfaceEvent(\n935: \tcontainer *clabruntime.GenericContainer,\n936: \taction string,\n937: \tattributes map[string]string,\n938: \ttimestamp time.Time,\n939: ) {\n940: \tevent := aggregatedEvent{\n941: \t\tTimestamp:   timestamp,\n942: \t\tType:        \"interface\",\n943: \t\tAction:      action,\n944: \t\tActorID:     container.ShortID,\n945: \t\tActorName:   firstContainerName(container),\n946: \t\tActorFullID: container.ID,\n947: \t\tAttributes:  attributes,\n948: \t}\n949: \n950: \tselect {\n951: \tcase r.events <- event:\n952: \tcase <-r.ctx.Done():\n953: \t}\n954: }\n955: \n956: func waitForNamespacePath(\n957: \tctx context.Context,\n958: \truntime clabruntime.ContainerRuntime,\n959: \tcontainerID string,\n960: ) (string, error) {\n961: \tconst (\n962: \t\tattempts   = 5\n963: \t\tretryDelay = 200 * time.Millisecond\n964: \t)\n965: \n966: \tvar lastErr error\n967: \n968: \tfor i := 0; i < attempts; i++ {\n969: \t\tnsPath, err := runtime.GetNSPath(ctx, containerID)\n970: \t\tif err == nil && nsPath != \"\" {\n971: \t\t\treturn nsPath, nil\n972: \t\t}\n973: \n974: \t\tif err != nil {\n975: \t\t\tlastErr = err\n976: \t\t}\n977: \n978: \t\tselect {\n979: \t\tcase <-time.After(retryDelay):\n980: \t\tcase <-ctx.Done():\n981: \t\t\treturn \"\", ctx.Err()\n982: \t\t}\n983: \t}\n984: \n985: \tif lastErr != nil {\n986: \t\treturn \"\", lastErr\n987: \t}\n988: \n989: \treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n990: }\n991: \n992: func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n993: \tif netHandle == nil {\n994: \t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n995: \t}\n996: \n997: \tlinks, err := netHandle.LinkList()\n998: \tif err != nil {\n999: \t\treturn nil, fmt.Errorf(\"unable to list links: %w\", err)\n1000: \t}\n1001: \n1002: \tstates := make(map[int]ifaceSnapshot, len(links))\n1003: \tfor _, link := range links {\n1004: \t\tsnapshot := snapshotFromLink(link)\n1005: \t\tstates[snapshot.Index] = snapshot\n1006: \t}\n1007: \n1008: \treturn states, nil\n1009: }\n1010: \n1011: // withNetem returns the snapshot with the netem settings of its interface.\n1012: func withNetem(snapshot ifaceSnapshot, netemInfos map[int]netemInfo) ifaceSnapshot {\n1013: \tif info, ok := netemInfos[snapshot.Index]; ok {\n1014: \t\tsnapshot.HasNetem = true\n1015: \t\tsnapshot.Delay = info.Delay\n1016: \t\tsnapshot.Jitter = info.Jitter\n1017: \t\tsnapshot.PacketLoss = info.PacketLoss\n1018: \t\tsnapshot.Rate = info.Rate\n1019: \t\tsnapshot.Corruption = info.Corruption\n1020: \t}\n1021: \n1022: \treturn snapshot\n1023: }\n1024: \n1025: func snapshotFromLink(link netlink.Link) ifaceSnapshot {\n1026: \tattrs := link.Attrs()\n1027: \n1028: \tsnapshot := ifaceSnapshot{\n1029: \t\tType: link.Type(),\n1030: \t}\n1031: \n1032: \tif attrs != nil {\n1033: \t\tsnapshot.Index = attrs.Index\n1034: \t\tsnapshot.Name = attrs.Name\n1035: \t\tsnapshot.Alias = attrs.Alias\n1036: \t\tsnapshot.MTU = attrs.MTU\n1037: \t\tif len(attrs.HardwareAddr) > 0 {\n1038: \t\t\tsnapshot.MAC = attrs.HardwareAddr.String()\n1039: \t\t}\n1040: \t\tsnapshot.OperState = attrs.OperState.String()\n1041: \t\tif stats := attrs.Statistics; stats != nil {\n1042: \t\t\tsnapshot.HasStats = true\n1043: \t\t\tsnapshot.RxBytes = stats.RxBytes\n1044: \t\t\tsnapshot.TxBytes = stats.TxBytes\n1045: \t\t\tsnapshot.RxPackets = stats.RxPackets\n1046: \t\t\tsnapshot.TxPackets = stats.TxPackets\n1047: \t\t}\n1048: \t}\n1049: \n1050: \treturn snapshot\n1051: }\n1052: \n1053: type ifaceSnapshot struct {\n1054: \tIndex     int\n1055: \tName      string\n1056: \tAlias     string\n1057: \tMTU       int\n1058: \tMAC       string\n1059: \tOperState string\n1060: \tType      string\n1061: \tHasStats  bool\n1062: \tRxBytes   uint64\n1063: \tTxBytes   uint64\n1064: \tRxPackets uint64\n1065: \tTxPackets uint64\n1066: \t// Netem fields\n1067: \tHasNetem   bool\n1068: \tDelay      string\n1069: \tJitter     string\n1070: \tPacketLoss float64\n1071: \tRate       int\n1072: \tCorruption float64\n1073: }\n1074: \n1075: func (s ifaceSnapshot) equal(other ifaceSnapshot) bool {\n1076: \treturn s.Index == other.Index &&\n1077: \t\ts.Name == other.Name &&\n1078: \t\ts.Alias == other.Alias &&\n1079: \t\ts.MTU == other.MTU &&\n1080: \t\ts.MAC == other.MAC &&\n1081: \t\ts.OperState == other.OperState &&\n1082: \t\ts.Type == other.Type &&\n1083: \t\ts.HasNetem == other.HasNetem &&\n1084: \t\ts.Delay == other.Delay &&\n1085: \t\ts.Jitter == other.Jitter &&\n1086: \t\ts.PacketLoss == other.PacketLoss &&\n1087: \t\ts.Rate == other.Rate &&\n1088: \t\ts.Corruption == other.Corruption\n1089: }\n1090: \n1091: type ifaceStatsSample struct {\n1092: \tRxBytes   uint64\n1093: \tTxBytes   uint64\n1094: \tRxPackets uint64\n1095: \tTxPackets uint64\n1096: \tTimestamp time.Time\n1097: }\n1098: \n1099: type ifaceStatsMetrics struct {\n1100: \tRxBytes   uint64\n1101: \tTxBytes   uint64\n1102: \tRxPackets uint64\n1103: \tTxPackets uint64\n1104: \tRxBps     float64\n1105: \tTxBps     float64\n1106: \tRxPps     float64\n1107: \tTxPps     float64\n1108: \tInterval  time.Duration\n1109: \tTimestamp time.Time\n1110: }\n1111: \n1112: func newStatsSample(snapshot ifaceSnapshot, timestamp time.Time) (ifaceStatsSample, bool) {\n1113: \tif !snapshot.HasStats {\n1114: \t\treturn ifaceStatsSample{}, false\n1115: \t}\n1116: \n1117: \treturn ifaceStatsSample{\n1118: \t\tRxBytes:   snapshot.RxBytes,\n1119: \t\tTxBytes:   snapshot.TxBytes,\n1120: \t\tRxPackets: snapshot.RxPackets,\n1121: \t\tTxPackets: snapshot.TxPackets,\n1122: \t\tTimestamp: timestamp,\n1123: \t}, true\n1124: }\n1125: \n1126: func (w *netlinkWatcher) collectAndEmitStats(\n1127: \tnetHandle *netlink.Handle,\n1128: \tstates map[int]ifaceSnapshot,\n1129: \tstatsSamples map[int]ifaceStatsSample,\n1130: \tregistry *netlinkRegistry,\n1131: ) {\n1132: \tif netHandle == nil || statsSamples == nil {\n1133: \t\treturn\n1134: \t}\n1135: \n1136: \tnow := time.Now()\n1137: \t// Fetch all interfaces with one netlink call per tick instead of one call\n1138: \t// per interface to reduce syscall overhead in large labs.\n1139: \tcurrentStates, err := snapshotInterfaces(netHandle)\n1140: \tif err != nil {\n1141: \t\tlog.Debugf(\n1142: \t\t\t\"failed to collect interface stats snapshot for container %s: %v\",\n1143: \t\t\tfirstContainerName(w.container),\n1144: \t\t\terr,\n1145: \t\t)\n1146: \n1147: \t\treturn\n1148: \t}\n1149: \n1150: \tfor idx, state := range states {\n1151: \t\tcurrent, ok := currentStates[idx]\n1152: \t\tif !ok {\n1153: \t\t\tcontinue\n1154: \t\t}\n1155: \n1156: \t\tstate.Name = current.Name\n1157: \t\tstate.Alias = current.Alias\n1158: \t\tstate.MTU = current.MTU\n1159: \t\tstate.MAC = current.MAC\n1160: \t\tstate.OperState = current.OperState\n1161: \t\tstate.Type = current.Type\n1162: \t\tstate.HasStats = current.HasStats\n1163: \t\tstate.RxBytes = current.RxBytes\n1164: \t\tstate.TxBytes = current.TxBytes\n1165: \t\tstate.RxPackets = current.RxPackets\n1166: \t\tstate.TxPackets = current.TxPackets\n1167: \t\tstates[idx] = state\n1168: \n1169: \t\tif !state.HasStats {\n1170: \t\t\tdelete(statsSamples, idx)\n1171: \n1172: \t\t\tcontinue\n1173: \t\t}\n1174: \n1175: \t\tprev, ok := statsSamples[idx]\n1176: \t\tif !ok || now.Sub(prev.Timestamp) <= 0 {\n1177: \t\t\tstatsSamples[idx] = ifaceStatsSample{\n1178: \t\t\t\tRxBytes:   state.RxBytes,\n1179: \t\t\t\tTxBytes:   state.TxBytes,\n1180: \t\t\t\tRxPackets: state.RxPackets,\n1181: \t\t\t\tTxPackets: state.TxPackets,\n1182: \t\t\t\tTimestamp: now,\n1183: \t\t\t}\n1184: \n1185: \t\t\tcontinue\n1186: \t\t}\n1187: \n1188: \t\tinterval := now.Sub(prev.Timestamp)\n1189: \t\tif interval <= 0 {\n1190: \t\t\tstatsSamples[idx] = ifaceStatsSample{\n1191: \t\t\t\tRxBytes:   state.RxBytes,\n1192: \t\t\t\tTxBytes:   state.TxBytes,\n1193: \t\t\t\tRxPackets: state.RxPackets,\n1194: \t\t\t\tTxPackets: state.TxPackets,\n1195: \t\t\t\tTimestamp: now,\n1196: \t\t\t}\n1197: \n1198: \t\t\tcontinue\n1199: \t\t}\n1200: \n1201: \t\trxBytesDelta := deltaCounter(prev.RxBytes, state.RxBytes)\n1202: \t\ttxBytesDelta := deltaCounter(prev.TxBytes, state.TxBytes)\n1203: \t\trxPacketsDelta := deltaCounter(prev.RxPackets, state.RxPackets)\n1204: \t\ttxPacketsDelta := deltaCounter(prev.TxPackets, state.TxPackets)\n1205: \n1206: \t\tseconds := interval.Seconds()\n1207: \t\tif seconds <= 0 {\n1208: \t\t\tstatsSamples[idx] = ifaceStatsSample{\n1209: \t\t\t\tRxBytes:   state.RxBytes,\n1210: \t\t\t\tTxBytes:   state.TxBytes,\n1211: \t\t\t\tRxPackets: state.RxPackets,\n1212: \t\t\t\tTxPackets: state.TxPackets,\n1213: \t\t\t\tTimestamp: now,\n1214: \t\t\t}\n1215: \n1216: \t\t\tcontinue\n1217: \t\t}\n1218: \n1219: \t\tmetrics := ifaceStatsMetrics{\n1220: \t\t\tRxBytes:   state.RxBytes,\n1221: \t\t\tTxBytes:   state.TxBytes,\n1222: \t\t\tRxPackets: state.RxPackets,\n1223: \t\t\tTxPackets: state.TxPackets,\n1224: \t\t\tRxBps:     float64(rxBytesDelta) * 8 / seconds,\n1225: \t\t\tTxBps:     float64(txBytesDelta) * 8 / seconds,\n1226: \t\t\tRxPps:     float64(rxPacketsDelta) / seconds,\n1227: \t\t\tTxPps:     float64(txPacketsDelta) / seconds,\n1228: \t\t\tInterval:  interval,\n1229: \t\t\tTimestamp: now,\n1230: \t\t}\n1231: \n1232: \t\tw.emitStats(registry, state, metrics)\n1233: \n1234: \t\tstatsSamples[idx] = ifaceStatsSample{\n1235: \t\t\tRxBytes:   state.RxBytes,\n1236: \t\t\tTxBytes:   state.TxBytes,\n1237: \t\t\tRxPackets: state.RxPackets,\n1238: \t\t\tTxPackets: state.TxPackets,\n1239: \t\t\tTimestamp: now,\n1240: \t\t}\n1241: \t}\n1242: }\n1243: \n1244: func deltaCounter(previous, current uint64) uint64 {\n1245: \tif current >= previous {\n1246: \t\treturn current - previous\n1247: \t}\n1248: \n1249: \treturn current\n1250: }\n1251: \n1252: const (\n1253: \tmsPerSec = 1000\n1254: )\n1255: \n1256: type netemQuerier struct {\n1257: \tnsHandle netns.NsHandle\n1258: \ttcHandle *gotc.Tc\n1259: }\n1260: \n1261: func newNetemQuerier(nsHandle netns.NsHandle) *netemQuerier {\n1262: \treturn &netemQuerier{\n1263: \t\tnsHandle: nsHandle,\n1264: \t}\n1265: }\n1266: \n1267: func (q *netemQuerier) Close() {\n1268: \tif q == nil || q.tcHandle == nil {\n1269: \t\treturn\n1270: \t}\n1271: \n1272: \tq.tcHandle.Close()\n1273: \tq.tcHandle = nil\n1274: }\n1275: \n1276: // Query queries the TC qdiscs in the namespace and returns a map of\n1277: // interface index to netem data.\n1278: func (q *netemQuerier) Query() map[int]netemInfo {\n1279: \tresult := make(map[int]netemInfo)\n1280: \n1281: \tqdiscs, err := q.qdiscs()\n1282: \tif err != nil {\n1283: \t\tlog.Debugf(\"failed to query tc qdiscs: %v\", err)\n1284: \t\treturn result\n1285: \t}\n1286: \n1287: \tfor idx := range qdiscs {\n1288: \t\tqdisc := &qdiscs[idx]\n1289: \t\tif qdisc.Attribute.Kind != \"netem\" || qdisc.Netem == nil {\n1290: \t\t\tcontinue\n1291: \t\t}\n1292: \n1293: \t\tinfo := netemInfoFromQdisc(qdisc)\n1294: \t\tif info.hasValues() {\n1295: \t\t\tresult[int(qdisc.Ifindex)] = info\n1296: \t\t}\n1297: \t}\n1298: \n1299: \treturn result\n1300: }\n1301: \n1302: func (q *netemQuerier) qdiscs() ([]gotc.Object, error) {\n1303: \tif q == nil {\n1304: \t\treturn nil, fmt.Errorf(\"netem querier is nil\")\n1305: \t}\n1306: \n1307: \tif err := q.ensureHandle(); err != nil {\n1308: \t\treturn nil, err\n1309: \t}\n1310: \n1311: \tqdiscs, err := clabnetem.Impairments(q.tcHandle)\n1312: \tif err == nil {\n1313: \t\treturn qdiscs, nil\n1314: \t}\n1315: \n1316: \t// Retry once by reopening the tc socket in case it became stale.\n1317: \tq.Close()\n1318: \tif errOpen := q.ensureHandle(); errOpen != nil {\n1319: \t\treturn nil, fmt.Errorf(\n1320: \t\t\t\"failed to query tc qdiscs (%v), and failed to reopen tc socket (%v)\",\n1321: \t\t\terr,\n1322: \t\t\terrOpen,\n1323: \t\t)\n1324: \t}\n1325: \n1326: \treturn clabnetem.Impairments(q.tcHandle)\n1327: }\n1328: \n1329: func (q *netemQuerier) ensureHandle() error {\n1330: \tif q == nil {\n1331: \t\treturn fmt.Errorf(\"netem querier is nil\")\n1332: \t}\n1333: \n1334: \tif q.tcHandle != nil {\n1335: \t\treturn nil\n1336: \t}\n1337: \n1338: \ttcnl, err := clabnetem.NewTC(int(q.nsHandle))\n1339: \tif err != nil {\n1340: \t\treturn fmt.Errorf(\"failed to open tc socket for netem query: %w\", err)\n1341: \t}\n1342: \n1343: \tq.tcHandle = tcnl\n1344: \n1345: \treturn nil\n1346: }\n1347: \n1348: type netemInfo struct {\n1349: \tDelay      string\n1350: \tJitter     string\n1351: \tPacketLoss float64\n1352: \tRate       int\n1353: \tCorruption float64\n1354: }\n1355: \n1356: func (n netemInfo) hasValues() bool {\n1357: \treturn n.Delay != \"\" || n.Jitter != \"\" || n.PacketLoss != 0 || n.Rate != 0 || n.Corruption != 0\n1358: }\n1359: \n1360: func netemInfoFromQdisc(qdisc *gotc.Object) netemInfo {\n1361: \tvar info netemInfo\n1362: \n1363: \tif qdisc.Netem == nil {\n1364: \t\treturn info\n1365: \t}\n1366: \n1367: \tif qdisc.Netem.Latency64 != nil && *qdisc.Netem.Latency64 != 0 {\n1368: \t\tinfo.Delay = (time.Duration(*qdisc.Netem.Latency64) * time.Nanosecond).String()\n1369: \t}\n1370: \n1371: \tif qdisc.Netem.Jitter64 != nil && *qdisc.Netem.Jitter64 != 0 {\n1372: \t\tinfo.Jitter = (time.Duration(*qdisc.Netem.Jitter64) * time.Nanosecond).String()\n1373: \t}\n1374: \n1375: \tif qdisc.Netem.Rate != nil && qdisc.Netem.Rate.Rate != 0 {\n1376: \t\tinfo.Rate = int(qdisc.Netem.Rate.Rate * 8 / msPerSec)\n1377: \t}\n1378: \n1379: \tif qdisc.Netem.Corrupt != nil && qdisc.Netem.Corrupt.Probability != 0 {\n1380: \t\tinfo.Corruption = math.Round((float64(qdisc.Netem.Corrupt.Probability)/\n1381: \t\t\tfloat64(math.MaxUint32)*100)*100) / 100\n1382: \t}\n1383: \n1384: \tif qdisc.Netem.Qopt.Loss != 0 {\n1385: \t\tinfo.PacketLoss = math.Round(\n1386: \t\t\t(float64(qdisc.Netem.Qopt.Loss)/float64(math.MaxUint32)*100)*100) / 100\n1387: \t}\n1388: \n1389: \treturn info\n1390: }\n\n(End of file - total 1390 lines)\n</content>",
    "title": "source/head/core/events/netlink.go",
    "metadata": {
      "preview": "package events\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tgotc \"github.com/florianl/go-tc\"\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclabcore \"github.com/srl-labs/containerlab/core\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclablinks \"github.com/srl-labs/containerlab/links\"\n\tclabnetem \"github.com/srl-labs/containerlab/netem\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/netlink.go",
        "text": "package events\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tgotc \"github.com/florianl/go-tc\"\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclabcore \"github.com/srl-labs/containerlab/core\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclablinks \"github.com/srl-labs/containerlab/links\"\n\tclabnetem \"github.com/srl-labs/containerlab/netem\"\n\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n\tclabutils \"github.com/srl-labs/containerlab/utils\"\n\t\"github.com/vishvananda/netlink\"\n\t\"github.com/vishvananda/netns\"\n\t\"golang.org/x/sys/unix\"\n)\n\ntype netlinkRegistry struct {\n\tctx                    context.Context\n\tmu                     sync.Mutex\n\twatchers               map[string]*netlinkWatcher\n\tevents                 chan<- aggregatedEvent\n\tincludeInitialSnapshot bool\n\tincludeStats           bool\n\tstatsInterval          time.Duration\n}\n\nfunc newNetlinkRegistry(\n\tctx context.Context,\n\tevents chan<- aggregatedEvent,\n\tincludeInitialSnapshot bool,\n\tincludeStats bool,\n\tstatsInterval time.Duration,\n) *netlinkRegistry {\n\treturn &netlinkRegistry{\n\t\tctx:                    ctx,\n\t\twatchers:               make(map[string]*netlinkWatcher),\n\t\tevents:                 events,\n\t\tincludeInitialSnapshot: includeInitialSnapshot,\n\t\tincludeStats:           includeStats,\n\t\tstatsInterval:          statsInterval,\n\t}\n}\n\nfunc (r *netlinkRegistry) Start(container *clabruntime.GenericContainer) {\n\tclone := cloneContainer(container)\n\tif clone == nil {\n\t\treturn\n\t}\n\n\tid := clone.ID\n\tif id == \"\" {\n\t\tid = clone.ShortID\n\t}\n\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tr.mu.Lock()\n\tif _, exists := r.watchers[id]; exists {\n\t\tr.mu.Unlock()\n\n\t\treturn\n\t}\n\n\twatcherCtx, cancel := context.WithCancel(r.ctx)\n\twatcher := &netlinkWatcher{\n\t\tcontainer:       clone,\n\t\tcancel:          cancel,\n\t\tdone:            make(chan struct{}),\n\t\tincludeSnapshot: r.includeInitialSnapshot,\n\t\tincludeStats:    r.includeStats,\n\t\tstatsInterval:   r.statsInterval,\n\t}\n\n\tr.watchers[id] = watcher\n\tr.mu.Unlock()\n\n\tgo watcher.run(watcherCtx, r)\n}\n\nfunc (r *netlinkRegistry) Stop(id string) {\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tr.mu.Lock()\n\twatcher, ok := r.watchers[id]\n\tif ok {\n\t\tdelete(r.watchers, id)\n\t}\n\tr.mu.Unlock()\n\n\tif !ok {\n\t\treturn\n\t}\n\n\twatcher.cancel()\n\t<-watcher.done\n}\n\nfunc (r *netlinkRegistry) remove(id string, watcher *netlinkWatcher) {\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tif current, ok := r.watchers[id]; ok && current == watcher {\n\t\tdelete(r.watchers, id)\n\t}\n}\n\nfunc (r *netlinkRegistry) HandleContainerEvent(\n\truntime clabruntime.ContainerRuntime,\n\tev clabruntime.ContainerEvent,\n) {\n\tif !strings.EqualFold(ev.Type, clabruntime.EventTypeContainer) {\n\t\treturn\n\t}\n\n\taction := strings.ToLower(ev.Action)\n\n\tswitch action {\n\tcase clabruntime.EventActionStart,\n\t\tclabruntime.EventActionUnpause,\n\t\tclabruntime.EventActionRestart:\n\t\tcontainer := containerFromEvent(runtime, ev)\n\t\tif container != nil {\n\t\t\tr.Start(container)\n\t\t}\n\tcase clabruntime.EventActionDie,\n\t\tclabruntime.EventActionStop,\n\t\tclabruntime.EventActionDestroy,\n\t\tclabruntime.EventActionKill:\n\t\tid := ev.ActorFullID\n\t\tif id == \"\" {\n\t\t\tid = ev.ActorID\n\t\t}\n\n\t\tr.Stop(id)\n\t}\n}\n\nfunc cloneContainer(container *clabruntime.GenericContainer) *clabruntime.GenericContainer {\n\tif container == nil {\n\t\treturn nil\n\t}\n\n\tclone := &clabruntime.GenericContainer{\n\t\tNames:   append([]string{}, container.Names...),\n\t\tID:      container.ID,\n\t\tShortID: container.ShortID,\n\t\tLabels:  cloneStringMap(container.Labels),\n\t}\n\n\tif clone.ShortID == \"\" {\n\t\tclone.ShortID = clabutils.ShortID(clone.ID)\n\t}\n\n\tif container.Runtime == nil {\n\t\treturn nil\n\t}\n\n\tclone.SetRuntime(container.Runtime)\n\n\treturn clone\n}\n\nfunc containerFromEvent(\n\truntime clabruntime.ContainerRuntime,\n\tev clabruntime.ContainerEvent,\n) *clabruntime.GenericContainer {\n\tattributes := ev.Attributes\n\n\tname := ev.ActorName\n\tif name == \"\" && attributes != nil {\n\t\tname = attributes[\"name\"]\n\t}\n\n\tid := ev.ActorFullID\n\tif id == \"\" {\n\t\tid = ev.ActorID\n\t}\n\n\tif id == \"\" && name == \"\" {\n\t\treturn nil\n\t}\n\n\tshort := ev.ActorID\n\tif short == \"\" {\n\t\tshort = id\n\t}\n\n\tcontainer := &clabruntime.GenericContainer{\n\t\tID:      id,\n\t\tShortID: clabutils.ShortID(short),\n\t}\n\n\tif name != \"\" {\n\t\tcontainer.Names = []string{name}\n\t}\n\n\tif attributes != nil {\n\t\tfor _, key := range []string{\n\t\t\tclabconstants.Containerlab,\n\t\t\tclabconstants.NodeName,\n\t\t\tclabconstants.RootNodeName,\n\t\t} {\n\t\t\tif v := attributes[key]; v != \"\" {\n\t\t\t\tif container.Labels == nil {\n\t\t\t\t\tcontainer.Labels = map[string]string{}\n\t\t\t\t}\n\n\t\t\t\tcontainer.Labels[key] = v\n\t\t\t}\n\t\t}\n\t}\n\n\tif container.ShortID == \"\" {\n\t\tcontainer.ShortID = clabutils.ShortID(container.ID)\n\t}\n\n\tif runtime != nil {\n\t\tcontainer.SetRuntime(runtime)\n\t}\n\n\treturn container\n}\n\ntype netlinkWatcher struct {\n\tcontainer       *clabruntime.GenericContainer\n\tcancel          context.CancelFunc\n\tdone            chan struct{}\n\tincludeSnapshot bool\n\tincludeStats    bool\n\tstatsInterval   time.Duration\n\tnsHandle        netns.NsHandle\n\t// reported holds what each link was last reported as, by its index in the\n\t// container's namespace.\n\treported map[int]reportedInterface\n}\n\n// reportedInterface is what a link was last reported as.\ntype reportedInterface struct {\n\tattributes map[string]string\n\t// since is when the link was first reported.\n\tsince time.Time\n}\n\n// stitchMarkWindow is how long after a link is first reported its host-side\n// stitch interface is looked for while the link itself does not change.\n// Deploying a veth-stitch link marks that interface right after it creates the\n// link, without a change in the node's namespace.\nvar stitchMarkWindow = time.Minute\n\n// Retry settings for a watcher that could not subscribe to link updates.\nvar (\n\twatchMaxAttempts   = 5\n\twatchRetryDelay    = time.Second\n\twatchMaxRetryDelay = 10 * time.Second\n)\n\nfunc (w *netlinkWatcher) run(ctx context.Context, registry *netlinkRegistry) {\n\tdefer close(w.done)\n\tif w.container == nil {\n\t\treturn\n\t}\n\n\tdefer registry.remove(w.container.ID, w)\n\n\tcontainerName := firstContainerName(w.container)\n\tif w.container.Runtime == nil {\n\t\tlog.Debugf(\"container %s has no runtime, skipping netlink watcher\", containerName)\n\n\t\treturn\n\t}\n\n\t// The states outlive a subscription, so a resubscribe only reports what\n\t// changed while no subscription was active.\n\tstates := make(map[int]ifaceSnapshot)\n\n\tvar statsSamples map[int]ifaceStatsSample\n\tif w.includeStats {\n\t\tstatsSamples = make(map[int]ifaceStatsSample)\n\t}\n\n\tinitial := true\n\tfailures := 0\n\tdelay := watchRetryDelay\n\n\tfor {\n\t\tsubscribed, err := w.watch(ctx, registry, states, statsSamples, initial)\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif subscribed {\n\t\t\tinitial = false\n\t\t\tfailures = 0\n\t\t\tdelay = watchRetryDelay\n\n\t\t\tlog.Warnf(\n\t\t\t\t\"netlink subscription for container %s ended, resubscribing: %v\",\n\t\t\t\tcontainerName,\n\t\t\t\terr,\n\t\t\t)\n\t\t} else {\n\t\t\tfailures++\n\t\t\tif failures >= watchMaxAttempts {\n\t\t\t\tlog.Warnf(\"stopped watching interfaces of container %s: %v\", containerName, err)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Debugf(\n\t\t\t\t\"failed to watch interfaces of container %s, retrying in %s: %v\",\n\t\t\t\tcontainerName,\n\t\t\t\tdelay,\n\t\t\t\terr,\n\t\t\t)\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(delay):\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\n\t\tdelay = min(delay*2, watchMaxRetryDelay)\n\t}\n}\n\n// watch subscribes to link updates in the container's namespace and handles\n// them until ctx ends or the subscription fails. It reports whether it\n// subscribed. The subscription lists the existing links itself, so no change\n// between listing and subscribing is lost.\nfunc (w *netlinkWatcher) watch(\n\tctx context.Context,\n\tregistry *netlinkRegistry,\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tinitial bool,\n) (bool, error) {\n\tnsPath, err := waitForNamespacePath(ctx, w.container.Runtime, w.container.ID)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to resolve netns: %w\", err)\n\t}\n\n\tnsHandle, err := netns.GetFromPath(nsPath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to open netns: %w\", err)\n\t}\n\tdefer nsHandle.Close()\n\n\tw.nsHandle = nsHandle\n\n\tnetHandle, err := netlink.NewHandleAt(nsHandle)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to create netlink handle: %w\", err)\n\t}\n\tdefer netHandle.Close()\n\n\tnetemQuery := newNetemQuerier(nsHandle)\n\tdefer netemQuery.Close()\n\n\tnetemInfos := netemQuery.Query()\n\n\tupdates := make(chan netlink.LinkUpdate, 32)\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tvar (\n\t\terrMu     sync.Mutex\n\t\tlastError error\n\t)\n\n\topts := netlink.LinkSubscribeOptions{\n\t\tNamespace:    &nsHandle,\n\t\tListExisting: true,\n\t\t// An interrupted listing is reported here too. It needs no action:\n\t\t// links that changed during the listing also arrive as updates.\n\t\tErrorCallback: func(err error) {\n\t\t\tlog.Debugf(\n\t\t\t\t\"netlink subscription for container %s: %v\",\n\t\t\t\tfirstContainerName(w.container),\n\t\t\t\terr,\n\t\t\t)\n\n\t\t\terrMu.Lock()\n\t\t\tlastError = err\n\t\t\terrMu.Unlock()\n\t\t},\n\t}\n\n\tif err := netlink.LinkSubscribeWithOptions(updates, done, opts); err != nil {\n\t\treturn false, fmt.Errorf(\"failed to subscribe to netlink updates: %w\", err)\n\t}\n\n\tvar vanished map[int]struct{}\n\tif len(states) > 0 {\n\t\tvanished = w.removeVanishedLinks(netHandle, states, statsSamples, registry)\n\t}\n\n\t// Set up netem polling interval (reuse stats interval or default to 1s).\n\tnetemPollInterval := w.statsInterval\n\tif netemPollInterval == 0 {\n\t\tnetemPollInterval = time.Second\n\t}\n\tnetemTicker := time.NewTicker(netemPollInterval)\n\tdefer netemTicker.Stop()\n\n\tvar (\n\t\tticker  *time.Ticker\n\t\ttickerC <-chan time.Time\n\t)\n\tif w.includeStats && w.statsInterval > 0 {\n\t\tticker = time.NewTicker(w.statsInterval)\n\t\ttickerC = ticker.C\n\t\tdefer ticker.Stop()\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-tickerC:\n\t\t\tw.collectAndEmitStats(netHandle, states, statsSamples, registry)\n\t\tcase <-netemTicker.C:\n\t\t\tw.pollNetemChanges(states, registry, netemQuery)\n\t\t\tw.reportStitchMarks(states, registry)\n\t\tcase <-ctx.Done():\n\t\t\treturn true, nil\n\t\tcase update, ok := <-updates:\n\t\t\tif !ok {\n\t\t\t\terrMu.Lock()\n\t\t\t\terr := lastError\n\t\t\t\terrMu.Unlock()\n\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = errors.New(\"update channel closed\")\n\t\t\t\t}\n\n\t\t\t\treturn true, err\n\t\t\t}\n\n\t\t\t// Replies to the listing carry NLM_F_MULTI, notifications do not.\n\t\t\tif update.Header.Flags&unix.NLM_F_MULTI != 0 {\n\t\t\t\tw.processExisting(\n\t\t\t\t\tstates,\n\t\t\t\t\tstatsSamples,\n\t\t\t\t\tupdate.Link,\n\t\t\t\t\tnetemInfos,\n\t\t\t\t\tvanished,\n\t\t\t\t\tregistry,\n\t\t\t\t\tinitial,\n\t\t\t\t)\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tw.processUpdate(states, statsSamples, update, registry, netemQuery)\n\t\t}\n\t}\n}\n\n// processExisting records a link listed when the subscription started. On the\n// first subscription a new link is reported as a snapshot when requested; after\n// a resubscribe it is reported as created.\n//\n// The listing can be older than the check in removeVanishedLinks, so it can\n// still hold a link that check reported as deleted. Such a link is skipped; its\n// deletion notification follows and is ignored, as the link is not tracked.\nfunc (w *netlinkWatcher) processExisting(\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tlink netlink.Link,\n\tnetemInfos map[int]netemInfo,\n\tvanished map[int]struct{},\n\tregistry *netlinkRegistry,\n\tinitial bool,\n) {\n\tif link == nil || link.Attrs() == nil {\n\t\treturn\n\t}\n\n\tif _, ok := vanished[link.Attrs().Index]; ok {\n\t\treturn\n\t}\n\n\tsnapshot := withNetem(snapshotFromLink(link), netemInfos)\n\tprevious, exists := states[snapshot.Index]\n\n\tif exists && snapshot.equal(previous) {\n\t\treturn\n\t}\n\n\tstates[snapshot.Index] = snapshot\n\tif statsSamples != nil {\n\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n\t\t\tstatsSamples[snapshot.Index] = sample\n\t\t}\n\t}\n\n\tswitch {\n\tcase exists:\n\t\tw.emit(registry, \"update\", snapshot)\n\tcase !initial:\n\t\tw.emit(registry, \"create\", snapshot)\n\tcase w.includeSnapshot:\n\t\tw.emit(registry, \"snapshot\", snapshot)\n\t}\n}\n\n// removeVanishedLinks reports the links that were deleted while no\n// subscription was active and returns their indexes.\nfunc (w *netlinkWatcher) removeVanishedLinks(\n\tnetHandle *netlink.Handle,\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tregistry *netlinkRegistry,\n) map[int]struct{} {\n\tcurrent, err := snapshotInterfaces(netHandle)\n\tif err != nil {\n\t\tlog.Debugf(\n\t\t\t\"failed to list interfaces of container %s: %v\",\n\t\t\tfirstContainerName(w.container),\n\t\t\terr,\n\t\t)\n\n\t\treturn nil\n\t}\n\n\tvanished := map[int]struct{}{}\n\n\tfor idx, snapshot := range states {\n\t\tif _, ok := current[idx]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tvanished[idx] = struct{}{}\n\n\t\tdelete(states, idx)\n\t\tdelete(statsSamples, idx)\n\t\tw.emit(registry, \"delete\", snapshot)\n\t}\n\n\treturn vanished\n}\n\nfunc (w *netlinkWatcher) processUpdate(\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tupdate netlink.LinkUpdate,\n\tregistry *netlinkRegistry,\n\tnetemQuery *netemQuerier,\n) {\n\tif update.Link == nil {\n\t\treturn\n\t}\n\n\tattrs := update.Link.Attrs()\n\tif attrs == nil {\n\t\treturn\n\t}\n\n\tsnapshot := snapshotFromLink(update.Link)\n\tprevious, exists := states[snapshot.Index]\n\n\tswitch update.Header.Type {\n\tcase unix.RTM_DELLINK:\n\t\t// A link that is not tracked was never reported, or its deletion was\n\t\t// already reported when the links were listed again after a resubscribe.\n\t\tif !exists {\n\t\t\treturn\n\t\t}\n\n\t\tdelete(states, snapshot.Index)\n\t\tdelete(statsSamples, snapshot.Index)\n\t\tw.emit(registry, \"delete\", previous)\n\tcase unix.RTM_NEWLINK:\n\t\t// Query netem info for this interface\n\t\tsnapshot = withNetem(snapshot, netemQuery.Query())\n\n\t\tif exists && snapshot.equal(previous) {\n\t\t\treturn\n\t\t}\n\n\t\taction := \"create\"\n\t\tif exists {\n\t\t\taction = \"update\"\n\t\t}\n\n\t\tstates[snapshot.Index] = snapshot\n\t\tif w.includeStats && statsSamples != nil {\n\t\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n\t\t\t\tstatsSamples[snapshot.Index] = sample\n\t\t\t}\n\t\t}\n\t\tw.emit(registry, action, snapshot)\n\t}\n}\n\n// pollNetemChanges checks for netem changes and emits update events.\nfunc (w *netlinkWatcher) pollNetemChanges(\n\tstates map[int]ifaceSnapshot,\n\tregistry *netlinkRegistry,\n\tnetemQuery *netemQuerier,\n) {\n\tnetemInfos := netemQuery.Query()\n\n\tfor idx, snapshot := range states {\n\t\tprevious := snapshot\n\t\tinfo, hasNetem := netemInfos[idx]\n\n\t\tif hasNetem {\n\t\t\tsnapshot.HasNetem = true\n\t\t\tsnapshot.Delay = info.Delay\n\t\t\tsnapshot.Jitter = info.Jitter\n\t\t\tsnapshot.PacketLoss = info.PacketLoss\n\t\t\tsnapshot.Rate = info.Rate\n\t\t\tsnapshot.Corruption = info.Corruption\n\t\t} else if snapshot.HasNetem {\n\t\t\t// Netem was removed\n\t\t\tsnapshot.HasNetem = false\n\t\t\tsnapshot.Delay = \"\"\n\t\t\tsnapshot.Jitter = \"\"\n\t\t\tsnapshot.PacketLoss = 0\n\t\t\tsnapshot.Rate = 0\n\t\t\tsnapshot.Corruption = 0\n\t\t}\n\n\t\tif !snapshot.equal(previous) {\n\t\t\tstates[idx] = snapshot\n\t\t\tw.emit(registry, \"update\", snapshot)\n\t\t}\n\t}\n}\n\n// reportStitchMarks reports the links whose host-side stitch interface got\n// marked after their last event. Only veths reported under their own name\n// shortly before are looked at: the node's end of a veth-stitch link is a veth\n// and is marked while its lab deploys.\nfunc (w *netlinkWatcher) reportStitchMarks(\n\tstates map[int]ifaceSnapshot,\n\tregistry *netlinkRegistry,\n) {\n\tfor idx, snapshot := range states {\n\t\treported, ok := w.reported[idx]\n\t\tif !ok || snapshot.Type != \"veth\" ||\n\t\t\treported.attributes[\"ifname\"] != snapshot.Name ||\n\t\t\ttime.Since(reported.since) > stitchMarkWindow {\n\t\t\tcontinue\n\t\t}\n\n\t\tif interfaceAttributes(w.container, snapshot)[\"ifname\"] != snapshot.Name {\n\t\t\tw.emit(registry, \"update\", snapshot)\n\t\t}\n\t}\n}\n\n// emit reports an event of a link. A deletion names the link as it was last\n// reported. A link reported under another name before, such as the node's own\n// interface until its stitch interface got marked, is first reported deleted\n// under that name, so that clients do not keep both; it is then new to them.\nfunc (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {\n\tif w.container == nil {\n\t\treturn\n\t}\n\n\tif action == \"delete\" {\n\t\tattributes := interfaceAttributes(w.container, snapshot)\n\t\tif previous, ok := w.reported[snapshot.Index]; ok {\n\t\t\tattributes = previous.attributes\n\t\t}\n\n\t\tdelete(w.reported, snapshot.Index)\n\t\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n\n\t\treturn\n\t}\n\n\tattributes := interfaceAttributes(w.container, snapshot)\n\tif w.track(registry, snapshot.Index, attributes) && action == \"update\" {\n\t\taction = \"create\"\n\t}\n\n\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n}\n\n// emitStats reports the counters of a link, under the name emit reports it.\nfunc (w *netlinkWatcher) emitStats(\n\tregistry *netlinkRegistry,\n\tsnapshot ifaceSnapshot,\n\tmetrics ifaceStatsMetrics,\n) {\n\tif !registry.includeStats || w.container == nil || !snapshot.HasStats {\n\t\treturn\n\t}\n\n\tattributes := interfaceAttributes(w.container, snapshot)\n\tif w.track(registry, snapshot.Index, attributes) {\n\t\tregistry.sendInterfaceEvent(\n\t\t\tw.container,\n\t\t\t\"create\",\n\t\t\tmaps.Clone(attributes),\n\t\t\tmetrics.Timestamp,\n\t\t)\n\t}\n\n\tinterfaceStatsAttributes(attributes, metrics)\n\tregistry.sendInterfaceEvent(w.container, \"stats\", attributes, metrics.Timestamp)\n}\n\n// track records what the link at index is reported as. When it was reported\n// under another name before, it reports that name deleted and returns true.\nfunc (w *netlinkWatcher) track(\n\tregistry *netlinkRegistry,\n\tindex int,\n\tattributes map[string]string,\n) bool {\n\tif w.reported == nil {\n\t\tw.reported = make(map[int]reportedInterface)\n\t}\n\n\tprevious, known := w.reported[index]\n\n\tsince := time.Now()\n\tif known {\n\t\tsince = previous.since\n\t}\n\n\tw.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}\n\n\tif !known || previous.attributes[\"ifname\"] == attributes[\"ifname\"] {\n\t\treturn false\n\t}\n\n\tregistry.sendInterfaceEvent(w.container, \"delete\", previous.attributes, time.Now())\n\n\treturn true\n}\n\nfunc firstContainerName(container *clabruntime.GenericContainer) string {\n\tif container == nil || len(container.Names) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn container.Names[0]\n}\n\nfunc containerLabel(container *clabruntime.GenericContainer) string {\n\tif container == nil || container.Labels == nil {\n\t\treturn \"\"\n\t}\n\n\treturn container.Labels[clabconstants.Containerlab]\n}\n\n// interfaceSnapshotAttributes are the attributes every interface event reports for the\n// interface itself.\nfunc interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n\tattributes := map[string]string{\n\t\t\"ifname\": snapshot.Name,\n\t\t\"index\":  strconv.Itoa(snapshot.Index),\n\t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n\t\t\"state\":  snapshot.OperState,\n\t\t\"type\":   snapshot.Type,\n\t}\n\n\tif snapshot.Alias != \"\" {\n\t\tattributes[\"alias\"] = snapshot.Alias\n\t}\n\n\tif snapshot.MAC != \"\" {\n\t\tattributes[\"mac\"] = snapshot.MAC\n\t}\n\n\treturn attributes\n}\n\n// interfaceStatsAttributes adds the counters and rates of a stats event.\nfunc interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n}\n\n// labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n// of the netlink interface events, for the node the runtime runs. Values the runtime could not\n// read (no index or MTU without a shell in the node) are left out rather than reported as 0.\nfunc labRuntimeInterfaceAttributes(\n\tlab, name string,\n\tiface *clablabruntime.InterfaceEventData,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n\t\tIndex:     iface.Index,\n\t\tName:      iface.Name,\n\t\tAlias:     iface.Alias,\n\t\tMTU:       iface.MTU,\n\t\tMAC:       iface.MAC,\n\t\tOperState: iface.OperState,\n\t\tType:      iface.Type,\n\t})\n\tif iface.Index <= 0 {\n\t\tdelete(attributes, \"index\")\n\t}\n\tif iface.MTU <= 0 {\n\t\tdelete(attributes, \"mtu\")\n\t}\n\n\tif lab != \"\" {\n\t\tattributes[\"lab\"] = lab\n\t}\n\tif name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\tif stats := iface.Stats; stats != nil {\n\t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n\t\t\tRxBytes:   stats.RxBytes,\n\t\t\tTxBytes:   stats.TxBytes,\n\t\t\tRxPackets: stats.RxPackets,\n\t\t\tTxPackets: stats.TxPackets,\n\t\t\tRxBps:     stats.RxBps,\n\t\t\tTxBps:     stats.TxBps,\n\t\t\tRxPps:     stats.RxPps,\n\t\t\tTxPps:     stats.TxPps,\n\t\t\tInterval:  stats.Interval,\n\t\t})\n\t}\n\n\treturn attributes\n}\n\nfunc interfaceAttributes(\n\tcontainer *clabruntime.GenericContainer,\n\tsnapshot ifaceSnapshot,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(snapshot)\n\tattributes[\"origin\"] = \"netlink\"\n\n\tif lab := containerLabel(container); lab != \"\" {\n\t\tattributes[\"lab\"] = lab\n\t}\n\n\tif name := firstContainerName(container); name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\toverlayToolsInterface(container, attributes)\n\n\t// Add netem attributes if present\n\tif snapshot.HasNetem {\n\t\tif snapshot.Delay != \"\" {\n\t\t\tattributes[\"netem_delay\"] = snapshot.Delay\n\t\t}\n\t\tif snapshot.Jitter != \"\" {\n\t\t\tattributes[\"netem_jitter\"] = snapshot.Jitter\n\t\t}\n\t\tif snapshot.PacketLoss != 0 {\n\t\t\tattributes[\"netem_loss\"] = strconv.FormatFloat(snapshot.PacketLoss, 'f', 2, 64) + \"%\"\n\t\t}\n\t\tif snapshot.Rate != 0 {\n\t\t\tattributes[\"netem_rate\"] = strconv.Itoa(snapshot.Rate) + \"kbit\"\n\t\t}\n\t\tif snapshot.Corruption != 0 {\n\t\t\tattributes[\"netem_corruption\"] = strconv.FormatFloat(\n\t\t\t\tsnapshot.Corruption,\n\t\t\t\t'f',\n\t\t\t\t2,\n\t\t\t\t64,\n\t\t\t) + \"%\"\n\t\t}\n\t}\n\n\treturn attributes\n}\n\n// overlayToolsInterface rewrites attributes to the host-side stitch interface\n// when one exists, matching `inspect interfaces`.\nfunc overlayToolsInterface(\n\tcontainer *clabruntime.GenericContainer,\n\tattributes map[string]string,\n) {\n\tif container == nil {\n\t\treturn\n\t}\n\n\tlab, node := clabcore.TopoIdentity(container.Labels)\n\tif lab == \"\" || node == \"\" {\n\t\treturn\n\t}\n\n\ttopoName := attributes[\"alias\"]\n\tif topoName == \"\" {\n\t\ttopoName = attributes[\"ifname\"]\n\t}\n\n\ttools, ok := clablinks.ToolsInterface(lab, node, topoName)\n\tif !ok {\n\t\treturn\n\t}\n\n\tsnapshot := snapshotFromLink(tools)\n\tattributes[\"ifname\"] = snapshot.Name\n\tattributes[\"alias\"] = topoName\n\tattributes[\"index\"] = strconv.Itoa(snapshot.Index)\n\tattributes[\"mtu\"] = strconv.Itoa(snapshot.MTU)\n\tattributes[\"state\"] = snapshot.OperState\n\tattributes[\"type\"] = snapshot.Type\n\n\tif snapshot.MAC != \"\" {\n\t\tattributes[\"mac\"] = snapshot.MAC\n\t}\n}\n\nfunc (r *netlinkRegistry) sendInterfaceEvent(\n\tcontainer *clabruntime.GenericContainer,\n\taction string,\n\tattributes map[string]string,\n\ttimestamp time.Time,\n) {\n\tevent := aggregatedEvent{\n\t\tTimestamp:   timestamp,\n\t\tType:        \"interface\",\n\t\tAction:      action,\n\t\tActorID:     container.ShortID,\n\t\tActorName:   firstContainerName(container),\n\t\tActorFullID: container.ID,\n\t\tAttributes:  attributes,\n\t}\n\n\tselect {\n\tcase r.events <- event:\n\tcase <-r.ctx.Done():\n\t}\n}\n\nfunc waitForNamespacePath(\n\tctx context.Context,\n\truntime clabruntime.ContainerRuntime,\n\tcontainerID string,\n) (string, error) {\n\tconst (\n\t\tattempts   = 5\n\t\tretryDelay = 200 * time.Millisecond\n\t)\n\n\tvar lastErr error\n\n\tfor i := 0; i < attempts; i++ {\n\t\tnsPath, err := runtime.GetNSPath(ctx, containerID)\n\t\tif err == nil && nsPath != \"\" {\n\t\t\treturn nsPath, nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlastErr = err\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(retryDelay):\n\t\tcase <-ctx.Done():\n\t\t\treturn \"\", ctx.Err()\n\t\t}\n\t}\n\n\tif lastErr != nil {\n\t\treturn \"\", lastErr\n\t}\n\n\treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n}\n\nfunc snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n\tif netHandle == nil {\n\t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n\t}\n\n\tlinks, err := netHandle.LinkList()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to list links: %w\", err)\n\t}\n\n\tstates := make(map[int]ifaceSnapshot, len(links))\n\tfor _, link := range links {\n\t\tsnapshot := snapshotFromLink(link)\n\t\tstates[snapshot.Index] = snapshot\n\t}\n\n\treturn states, nil\n}\n\n// withNetem returns the snapshot with the netem settings of its interface.\nfunc withNetem(snapshot ifaceSnapshot, netemInfos map[int]netemInfo) ifaceSnapshot {\n\tif info, ok := netemInfos[snapshot.Index]; ok {\n\t\tsnapshot.HasNetem = true\n\t\tsnapshot.Delay = info.Delay\n\t\tsnapshot.Jitter = info.Jitter\n\t\tsnapshot.PacketLoss = info.PacketLoss\n\t\tsnapshot.Rate = info.Rate\n\t\tsnapshot.Corruption = info.Corruption\n\t}\n\n\treturn snapshot\n}\n\nfunc snapshotFromLink(link netlink.Link) ifaceSnapshot {\n\tattrs := link.Attrs()\n\n\tsnapshot := ifaceSnapshot{\n\t\tType: link.Type(),\n\t}\n\n\tif attrs != nil {\n\t\tsnapshot.Index = attrs.Index\n\t\tsnapshot.Name = attrs.Name\n\t\tsnapshot.Alias = attrs.Alias\n\t\tsnapshot.MTU = attrs.MTU\n\t\tif len(attrs.HardwareAddr) > 0 {\n\t\t\tsnapshot.MAC = attrs.HardwareAddr.String()\n\t\t}\n\t\tsnapshot.OperState = attrs.OperState.String()\n\t\tif stats := attrs.Statistics; stats != nil {\n\t\t\tsnapshot.HasStats = true\n\t\t\tsnapshot.RxBytes = stats.RxBytes\n\t\t\tsnapshot.TxBytes = stats.TxBytes\n\t\t\tsnapshot.RxPackets = stats.RxPackets\n\t\t\tsnapshot.TxPackets = stats.TxPackets\n\t\t}\n\t}\n\n\treturn snapshot\n}\n\ntype ifaceSnapshot struct {\n\tIndex     int\n\tName      string\n\tAlias     string\n\tMTU       int\n\tMAC       string\n\tOperState string\n\tType      string\n\tHasStats  bool\n\tRxBytes   uint64\n\tTxBytes   uint64\n\tRxPackets uint64\n\tTxPackets uint64\n\t// Netem fields\n\tHasNetem   bool\n\tDelay      string\n\tJitter     string\n\tPacketLoss float64\n\tRate       int\n\tCorruption float64\n}\n\nfunc (s ifaceSnapshot) equal(other ifaceSnapshot) bool {\n\treturn s.Index == other.Index &&\n\t\ts.Name == other.Name &&\n\t\ts.Alias == other.Alias &&\n\t\ts.MTU == other.MTU &&\n\t\ts.MAC == other.MAC &&\n\t\ts.OperState == other.OperState &&\n\t\ts.Type == other.Type &&\n\t\ts.HasNetem == other.HasNetem &&\n\t\ts.Delay == other.Delay &&\n\t\ts.Jitter == other.Jitter &&\n\t\ts.PacketLoss == other.PacketLoss &&\n\t\ts.Rate == other.Rate &&\n\t\ts.Corruption == other.Corruption\n}\n\ntype ifaceStatsSample struct {\n\tRxBytes   uint64\n\tTxBytes   uint64\n\tRxPackets uint64\n\tTxPackets uint64\n\tTimestamp time.Time\n}\n\ntype ifaceStatsMetrics struct {\n\tRxBytes   uint64\n\tTxBytes   uint64\n\tRxPackets uint64\n\tTxPackets uint64\n\tRxBps     float64\n\tTxBps     float64\n\tRxPps     float64\n\tTxPps     float64\n\tInterval  time.Duration\n\tTimestamp time.Time\n}\n\nfunc newStatsSample(snapshot ifaceSnapshot, timestamp time.Time) (ifaceStatsSample, bool) {\n\tif !snapshot.HasStats {\n\t\treturn ifaceStatsSample{}, false\n\t}\n\n\treturn ifaceStatsSample{\n\t\tRxBytes:   snapshot.RxBytes,\n\t\tTxBytes:   snapshot.TxBytes,\n\t\tRxPackets: snapshot.RxPackets,\n\t\tTxPackets: snapshot.TxPackets,\n\t\tTimestamp: timestamp,\n\t}, true\n}\n\nfunc (w *netlinkWatcher) collectAndEmitStats(\n\tnetHandle *netlink.Handle,\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tregistry *netlinkRegistry,\n) {\n\tif netHandle == nil || statsSamples == nil {\n\t\treturn\n\t}\n\n\tnow := time.Now()\n\t// Fetch all interfaces with one netlink call per tick instead of one call\n\t// per interface to reduce syscall overhead in large labs.\n\tcurrentStates, err := snapshotInterfaces(netHandle)\n\tif err != nil {\n\t\tlog.Debugf(\n\t\t\t\"failed to collect interface stats snapshot for container %s: %v\",\n\t\t\tfirstContainerName(w.container),\n\t\t\terr,\n\t\t)\n\n\t\treturn\n\t}\n\n\tfor idx, state := range states {\n\t\tcurrent, ok := currentStates[idx]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tstate.Name = current.Name\n\t\tstate.Alias = current.Alias\n\t\tstate.MTU = current.MTU\n\t\tstate.MAC = current.MAC\n\t\tstate.OperState = current.OperState\n\t\tstate.Type = current.Type\n\t\tstate.HasStats = current.HasStats\n\t\tstate.RxBytes = current.RxBytes\n\t\tstate.TxBytes = current.TxBytes\n\t\tstate.RxPackets = current.RxPackets\n\t\tstate.TxPackets = current.TxPackets\n\t\tstates[idx] = state\n\n\t\tif !state.HasStats {\n\t\t\tdelete(statsSamples, idx)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tprev, ok := statsSamples[idx]\n\t\tif !ok || now.Sub(prev.Timestamp) <= 0 {\n\t\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\t\tRxBytes:   state.RxBytes,\n\t\t\t\tTxBytes:   state.TxBytes,\n\t\t\t\tRxPackets: state.RxPackets,\n\t\t\t\tTxPackets: state.TxPackets,\n\t\t\t\tTimestamp: now,\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tinterval := now.Sub(prev.Timestamp)\n\t\tif interval <= 0 {\n\t\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\t\tRxBytes:   state.RxBytes,\n\t\t\t\tTxBytes:   state.TxBytes,\n\t\t\t\tRxPackets: state.RxPackets,\n\t\t\t\tTxPackets: state.TxPackets,\n\t\t\t\tTimestamp: now,\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\trxBytesDelta := deltaCounter(prev.RxBytes, state.RxBytes)\n\t\ttxBytesDelta := deltaCounter(prev.TxBytes, state.TxBytes)\n\t\trxPacketsDelta := deltaCounter(prev.RxPackets, state.RxPackets)\n\t\ttxPacketsDelta := deltaCounter(prev.TxPackets, state.TxPackets)\n\n\t\tseconds := interval.Seconds()\n\t\tif seconds <= 0 {\n\t\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\t\tRxBytes:   state.RxBytes,\n\t\t\t\tTxBytes:   state.TxBytes,\n\t\t\t\tRxPackets: state.RxPackets,\n\t\t\t\tTxPackets: state.TxPackets,\n\t\t\t\tTimestamp: now,\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tmetrics := ifaceStatsMetrics{\n\t\t\tRxBytes:   state.RxBytes,\n\t\t\tTxBytes:   state.TxBytes,\n\t\t\tRxPackets: state.RxPackets,\n\t\t\tTxPackets: state.TxPackets,\n\t\t\tRxBps:     float64(rxBytesDelta) * 8 / seconds,\n\t\t\tTxBps:     float64(txBytesDelta) * 8 / seconds,\n\t\t\tRxPps:     float64(rxPacketsDelta) / seconds,\n\t\t\tTxPps:     float64(txPacketsDelta) / seconds,\n\t\t\tInterval:  interval,\n\t\t\tTimestamp: now,\n\t\t}\n\n\t\tw.emitStats(registry, state, metrics)\n\n\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\tRxBytes:   state.RxBytes,\n\t\t\tTxBytes:   state.TxBytes,\n\t\t\tRxPackets: state.RxPackets,\n\t\t\tTxPackets: state.TxPackets,\n\t\t\tTimestamp: now,\n\t\t}\n\t}\n}\n\nfunc deltaCounter(previous, current uint64) uint64 {\n\tif current >= previous {\n\t\treturn current - previous\n\t}\n\n\treturn current\n}\n\nconst (\n\tmsPerSec = 1000\n)\n\ntype netemQuerier struct {\n\tnsHandle netns.NsHandle\n\ttcHandle *gotc.Tc\n}\n\nfunc newNetemQuerier(nsHandle netns.NsHandle) *netemQuerier {\n\treturn &netemQuerier{\n\t\tnsHandle: nsHandle,\n\t}\n}\n\nfunc (q *netemQuerier) Close() {\n\tif q == nil || q.tcHandle == nil {\n\t\treturn\n\t}\n\n\tq.tcHandle.Close()\n\tq.tcHandle = nil\n}\n\n// Query queries the TC qdiscs in the namespace and returns a map of\n// interface index to netem data.\nfunc (q *netemQuerier) Query() map[int]netemInfo {\n\tresult := make(map[int]netemInfo)\n\n\tqdiscs, err := q.qdiscs()\n\tif err != nil {\n\t\tlog.Debugf(\"failed to query tc qdiscs: %v\", err)\n\t\treturn result\n\t}\n\n\tfor idx := range qdiscs {\n\t\tqdisc := &qdiscs[idx]\n\t\tif qdisc.Attribute.Kind != \"netem\" || qdisc.Netem == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tinfo := netemInfoFromQdisc(qdisc)\n\t\tif info.hasValues() {\n\t\t\tresult[int(qdisc.Ifindex)] = info\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc (q *netemQuerier) qdiscs() ([]gotc.Object, error) {\n\tif q == nil {\n\t\treturn nil, fmt.Errorf(\"netem querier is nil\")\n\t}\n\n\tif err := q.ensureHandle(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tqdiscs, err := clabnetem.Impairments(q.tcHandle)\n\tif err == nil {\n\t\treturn qdiscs, nil\n\t}\n\n\t// Retry once by reopening the tc socket in case it became stale.\n\tq.Close()\n\tif errOpen := q.ensureHandle(); errOpen != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"failed to query tc qdiscs (%v), and failed to reopen tc socket (%v)\",\n\t\t\terr,\n\t\t\terrOpen,\n\t\t)\n\t}\n\n\treturn clabnetem.Impairments(q.tcHandle)\n}\n\nfunc (q *netemQuerier) ensureHandle() error {\n\tif q == nil {\n\t\treturn fmt.Errorf(\"netem querier is nil\")\n\t}\n\n\tif q.tcHandle != nil {\n\t\treturn nil\n\t}\n\n\ttcnl, err := clabnetem.NewTC(int(q.nsHandle))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open tc socket for netem query: %w\", err)\n\t}\n\n\tq.tcHandle = tcnl\n\n\treturn nil\n}\n\ntype netemInfo struct {\n\tDelay      string\n\tJitter     string\n\tPacketLoss float64\n\tRate       int\n\tCorruption float64\n}\n\nfunc (n netemInfo) hasValues() bool {\n\treturn n.Delay != \"\" || n.Jitter != \"\" || n.PacketLoss != 0 || n.Rate != 0 || n.Corruption != 0\n}\n\nfunc netemInfoFromQdisc(qdisc *gotc.Object) netemInfo {\n\tvar info netemInfo\n\n\tif qdisc.Netem == nil {\n\t\treturn info\n\t}\n\n\tif qdisc.Netem.Latency64 != nil && *qdisc.Netem.Latency64 != 0 {\n\t\tinfo.Delay = (time.Duration(*qdisc.Netem.Latency64) * time.Nanosecond).String()\n\t}\n\n\tif qdisc.Netem.Jitter64 != nil && *qdisc.Netem.Jitter64 != 0 {\n\t\tinfo.Jitter = (time.Duration(*qdisc.Netem.Jitter64) * time.Nanosecond).String()\n\t}\n\n\tif qdisc.Netem.Rate != nil && qdisc.Netem.Rate.Rate != 0 {\n\t\tinfo.Rate = int(qdisc.Netem.Rate.Rate * 8 / msPerSec)\n\t}\n\n\tif qdisc.Netem.Corrupt != nil && qdisc.Netem.Corrupt.Probability != 0 {\n\t\tinfo.Corruption = math.Round((float64(qdisc.Netem.Corrupt.Probability)/\n\t\t\tfloat64(math.MaxUint32)*100)*100) / 100\n\t}\n\n\tif qdisc.Netem.Qopt.Loss != 0 {\n\t\tinfo.PacketLoss = math.Round(\n\t\t\t(float64(qdisc.Netem.Qopt.Loss)/float64(math.MaxUint32)*100)*100) / 100\n\t}\n\n\treturn info\n}",
        "lineStart": 1,
        "lineEnd": 1390,
        "totalLines": 1390,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565105068,
      "end": 1794565105091
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46a65c8001GFLGdayakikHDV",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a3d31001iIjThNQ1viFvc4",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 10719,
    "input": 7409,
    "output": 16,
    "reasoning": 30,
    "cache": {
      "read": 3264,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46a3d31001iIjThNQ1viFvc4",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565094705,
    "completed": 1794565105100
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 10719,
    "input": 7409,
    "output": 16,
    "reasoning": 30,
    "cache": {
      "read": 3264,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 5
step-start
{
  "type": "step-start",
  "id": "prt_1d46ac670001U4S29XUOTAINyQ",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a65d0001FWpkI8jK2UTVJJ"
}
Reasoning
Now let me look at the base version of the file to understand what changed, and the test file. Let me also check the manifest.json.
read · completed

Input

{
  "filePath": "/source/manifest.json"
}

Output

<path>/source/manifest.json</path>
<type>file</type>
<content>
1: {
2:   "version": 1,
3:   "head": "1c9b3577d08f7524fd228e5ab4df3dd3fc107f53",
4:   "base": "f57133d88d7f26767e78a9f4c0f81a9ed070fe8b",
5:   "mergeBase": "f57133d88d7f26767e78a9f4c0f81a9ed070fe8b",
6:   "changed": [
7:     {
8:       "status": "M",
9:       "path": "core/events/netlink.go"
10:     },
11:     {
12:       "status": "M",
13:       "path": "core/events/netlink_watch_test.go"
14:     }
15:   ],
16:   "files": [
17:     {
18:       "revision": "head",
19:       "path": "core/events/netlink_watch_test.go",
20:       "bytes": 15093,
21:       "lines": 534
22:     },
23:     {
24:       "revision": "head",
25:       "path": "core/events/netlink.go",
26:       "bytes": 32781,
27:       "lines": 1390
28:     },
29:     {
30:       "revision": "head",
31:       "path": "docs/cmd/capture.md",
32:       "bytes": 7769,
33:       "lines": 134
34:     },
35:     {
36:       "revision": "head",
37:       "path": "docs/cmd/completion.md",
38:       "bytes": 2336,
39:       "lines": 95
40:     },
41:     {
42:       "revision": "head",
43:       "path": "docs/cmd/deploy.md",
44:       "bytes": 31381,
45:       "lines": 565
46:     },
47:     {
48:       "revision": "head",
49:       "path": "docs/cmd/destroy.md",
50:       "bytes": 3762,
51:       "lines": 100
52:     },
53:     {
54:       "revision": "head",
55:       "path": "docs/cmd/events.md",
56:       "bytes": 6764,
57:       "lines": 99
58:     },
59:     {
60:       "revision": "head",
61:       "path": "docs/cmd/exec.md",
62:       "bytes": 7316,
63:       "lines": 177
64:     },
65:     {
66:       "revision": "head",
67:       "path": "docs/cmd/generate.md",
68:       "bytes": 6005,
69:       "lines": 138
70:     },
71:     {
72:       "revision": "head",
73:       "path": "docs/cmd/graph.md",
74:       "bytes": 8242,
75:       "lines": 192
76:     },
77:     {
78:       "revision": "head",
79:       "path": "docs/cmd/inspect/index.md",
80:       "bytes": 11106,
81:       "lines": 179
82:     },
83:     {
84:       "revision": "head",
85:       "path": "docs/cmd/inspect/interfaces.md",
86:       "bytes": 11855,
87:       "lines": 199
88:     },
89:     {
90:       "revision": "head",
91:       "path": "docs/cmd/logs.md",
92:       "bytes": 1836,
93:       "lines": 57
94:     },
95:     {
96:       "revision": "head",
97:       "path": "docs/cmd/redeploy.md",
98:       "bytes": 6085,
99:       "lines": 150
100:     },
101:     {
102:       "revision": "head",
103:       "path": "docs/cmd/restart.md",
104:       "bytes": 1432,
105:       "lines": 64
106:     },
107:     {
108:       "revision": "head",
109:       "path": "docs/cmd/save.md",
110:       "bytes": 6445,
111:       "lines": 133
112:     },
113:     {
114:       "revision": "head",
115:       "path": "docs/cmd/start.md",
116:       "bytes": 2251,
117:       "lines": 76
118:     },
119:     {
120:       "revision": "head",
121:       "path": "docs/cmd/stop.md",
122:       "bytes": 1313,
123:       "lines": 62
124:     },
125:     {
126:       "revision": "head",
127:       "path": "docs/cmd/tools/api-server/start.md",
128:       "bytes": 5581,
129:       "lines": 165
130:     },
131:     {
132:       "revision": "head",
133:       "path": "docs/cmd/tools/api-server/status.md",
134:       "bytes": 4223,
135:       "lines": 105
136:     },
137:     {
138:       "revision": "head",
139:       "path": "docs/cmd/tools/api-server/stop.md",
140:       "bytes": 1836,
141:       "lines": 56
142:     },
143:     {
144:       "revision": "head",
145:       "path": "docs/cmd/tools/cert/ca/create.md",
146:       "bytes": 2206,
147:       "lines": 77
148:     },
149:     {
150:       "revision": "head",
151:       "path": "docs/cmd/tools/cert/sign.md",
152:       "bytes": 2428,
153:       "lines": 79
154:     },
155:     {
156:       "revision": "head",
157:       "path": "docs/cmd/tools/disable-tx-offload.md",
158:       "bytes": 982,
159:       "lines": 25
160:     },
161:     {
162:       "revision": "head",
163:       "path": "docs/cmd/tools/gotty/attach.md",
164:       "bytes": 1904,
165:       "lines": 67
166:     },
167:     {
168:       "revision": "head",
169:       "path": "docs/cmd/tools/gotty/detach.md",
170:       "bytes": 627,
171:       "lines": 29
172:     },
173:     {
174:       "revision": "head",
175:       "path": "docs/cmd/tools/gotty/list.md",
176:       "bytes": 1070,
177:       "lines": 46
178:     },
179:     {
180:       "revision": "head",
181:       "path": "docs/cmd/tools/gotty/reattach.md",
182:       "bytes": 955,
183:       "lines": 26
184:     },
185:     {
186:       "revision": "head",
187:       "path": "docs/cmd/tools/netem/reset.md",
188:       "bytes": 1635,
189:       "lines": 63
190:     },
191:     {
192:       "revision": "head",
193:       "path": "docs/cmd/tools/netem/set.md",
194:       "bytes": 3979,
195:       "lines": 114
196:     },
197:     {
198:       "revision": "head",
199:       "path": "docs/cmd/tools/netem/show.md",
200:       "bytes": 3651,
201:       "lines": 150
202:     },
203:     {
204:       "revision": "head",
205:       "path": "docs/cmd/tools/snapshot/save.md",
206:       "bytes": 1647,
207:       "lines": 75
208:     },
209:     {
210:       "revision": "head",
211:       "path": "docs/cmd/tools/sshx/attach.md",
212:       "bytes": 5194,
213:       "lines": 128
214:     },
215:     {
216:       "revision": "head",
217:       "path": "docs/cmd/tools/sshx/detach.md",
218:       "bytes": 1837,
219:       "lines": 46
220:     },
221:     {
222:       "revision": "head",
223:       "path": "docs/cmd/tools/sshx/list.md",
224:       "bytes": 3662,
225:       "lines": 77
226:     },
227:     {
228:       "revision": "head",
229:       "path": "docs/cmd/tools/sshx/reattach.md",
230:       "bytes": 4593,
231:       "lines": 101
232:     },
233:     {
234:       "revision": "head",
235:       "path": "docs/cmd/tools/veth/create.md",
236:       "bytes": 1890,
237:       "lines": 51
238:     },
239:     {
240:       "revision": "head",
241:       "path": "docs/cmd/tools/vxlan/create.md",
242:       "bytes": 3355,
243:       "lines": 73
244:     },
245:     {
246:       "revision": "head",
247:       "path": "docs/cmd/tools/vxlan/delete.md",
248:       "bytes": 1230,
249:       "lines": 31
250:     },
251:     {
252:       "revision": "head",
253:       "path": "docs/cmd/validate.md",
254:       "bytes": 1785,
255:       "lines": 51
256:     },
257:     {
258:       "revision": "head",
259:       "path": "docs/cmd/version/check.md",
260:       "bytes": 537,
261:       "lines": 21
262:     },
263:     {
264:       "revision": "head",
265:       "path": "docs/cmd/version/index.md",
266:       "bytes": 1011,
267:       "lines": 37
268:     },
269:     {
270:       "revision": "head",
271:       "path": "docs/CNAME",
272:       "bytes": 16,
273:       "lines": 1
274:     },
275:     {
276:       "revision": "head",
277:       "path": "docs/community.md",
278:       "bytes": 26611,
279:       "lines": 360
280:     },
281:     {
282:       "revision": "head",
283:       "path": "docs/htmltest-pr.yml",
284:       "bytes": 678,
285:       "lines": 14
286:     },
287:     {
288:       "revision": "head",
289:       "path": "docs/htmltest-w-github.yml",
290:       "bytes": 1679,
291:       "lines": 31
292:     },
293:     {
294:       "revision": "head",
295:       "path": "docs/htmltest.yml",
296:       "bytes": 2429,
297:       "lines": 49
298:     },
299:     {
300:       "revision": "head",
301:       "path": "docs/images/clabnew.svg",
302:       "bytes": 16299,
303:       "lines": 13
304:     },
305:     {
306:       "revision": "head",
307:       "path": "docs/images/coloured_wordmark.svg",
308:       "bytes": 8031,
309:       "lines": 91
310:     },
311:     {
312:       "revision": "head",
313:       "path": "docs/images/containerlab_dark_no_text.svg",
314:       "bytes": 3589,
315:       "lines": 8
316:     },
317:     {
318:       "revision": "head",
319:       "path": "docs/images/containerlab_export.svg",
320:       "bytes": 8893,
321:       "lines": 33
322:     },
323:     {
324:       "revision": "head",
325:       "path": "docs/images/containerlab_full_white_no_text.svg",
326:       "bytes": 3801,
327:       "lines": 8
328:     },
329:     {
330:       "revision": "head",
331:       "path": "docs/images/containerlab_white_no_text.svg",
332:       "bytes": 3293,
333:       "lines": 8
334:     },
335:     {
336:       "revision": "head",
337:       "path": "docs/images/containerlab-animated-wordmark.svg",
338:       "bytes": 70018,
339:       "lines": 52
340:     },
341:     {
342:       "revision": "head",
343:       "path": "docs/images/favicon.svg",
344:       "bytes": 16378,
345:       "lines": 20
346:     },
347:     {
348:       "revision": "head",
349:       "path": "docs/images/flask.svg",
350:       "bytes": 378,
351:       "lines": 1
352:     },
353:     {
354:       "revision": "head",
355:       "path": "docs/images/gui/browser-sandbox-placeholder.svg",
356:       "bytes": 2220,
357:       "lines": 25
358:     },
359:     {
360:       "revision": "head",
361:       "path": "docs/images/topoviewer-icons/client.svg",
362:       "bytes": 633,
363:       "lines": 1
364:     },
365:     {
366:       "revision": "head",
367:       "path": "docs/images/topoviewer-icons/controller.svg",
368:       "bytes": 768,
369:       "lines": 1
370:     },
371:     {
372:       "revision": "head",
373:       "path": "docs/images/topoviewer-icons/dcgw.svg",
374:       "bytes": 1015,
375:       "lines": 1
376:     },
377:     {
378:       "revision": "head",
379:       "path": "docs/images/topoviewer-icons/pon.svg",
380:       "bytes": 553,
381:       "lines": 1
382:     },
383:     {
384:       "revision": "head",
385:       "path": "docs/images/topoviewer-icons/rgw.svg",
386:       "bytes": 983,
387:       "lines": 1
388:     },
389:     {
390:       "revision": "head",
391:       "path": "docs/images/topoviewer-icons/router.svg",
392:       "bytes": 864,
393:       "lines": 1
394:     },
395:     {
396:       "revision": "head",
397:       "path": "docs/images/topoviewer-icons/server.svg",
398:       "bytes": 744,
399:       "lines": 1
400:     },
401:     {
402:       "revision": "head",
403:       "path": "docs/images/topoviewer-icons/spine.svg",
404:       "bytes": 940,
405:       "lines": 1
406:     },
407:     {
408:       "revision": "head",
409:       "path": "docs/images/topoviewer-icons/switch.svg",
410:       "bytes": 803,
411:       "lines": 1
412:     },
413:     {
414:       "revision": "head",
415:       "path": "docs/index.md",
416:       "bytes": 6778,
417:       "lines": 189
418:     },
419:     {
420:       "revision": "head",
421:       "path": "docs/install.md",
422:       "bytes": 18001,
423:       "lines": 521
424:     },
425:     {
426:       "revision": "head",
427:       "path": "docs/javascripts/instant-reinit.js",
428:       "bytes": 2040,
429:       "lines": 45
430:     },
431:     {
432:       "revision": "head",
433:       "path": "docs/lab-examples/asav01.md",
434:       "bytes": 4137,
435:       "lines": 90
436:     },
437:     {
438:       "revision": "head",
439:       "path": "docs/lab-examples/bgp-vpls-nok-jun.md",
440:       "bytes": 3374,
441:       "lines": 34
442:     },
443:     {
444:       "revision": "head",
445:       "path": "docs/lab-examples/cisco_iol.md",
446:       "bytes": 4368,
447:       "lines": 100
448:     },
449:     {
450:       "revision": "head",
451:       "path": "docs/lab-examples/cvx01.md",
452:       "bytes": 2989,
453:       "lines": 48
454:     },
455:     {
456:       "revision": "head",
457:       "path": "docs/lab-examples/cvx02.md",
458:       "bytes": 2936,
459:       "lines": 49
460:     },
461:     {
462:       "revision": "head",
463:       "path": "docs/lab-examples/ext-bridge.md",
464:       "bytes": 2042,
465:       "lines": 31
466:     },
467:     {
468:       "revision": "head",
469:       "path": "docs/lab-examples/f5bigipve01.md",
470:       "bytes": 4956,
471:       "lines": 118
472:     },
473:     {
474:       "revision": "head",
475:       "path": "docs/lab-examples/freebsd01.md",
476:       "bytes": 3571,
477:       "lines": 76
478:     },
479:     {
480:       "revision": "head",
481:       "path": "docs/lab-examples/frr01.md",
482:       "bytes": 2987,
483:       "lines": 64
484:     },
485:     {
486:       "revision": "head",
487:       "path": "docs/lab-examples/ftdv01.md",
488:       "bytes": 4108,
489:       "lines": 75
490:     },
491:     {
492:       "revision": "head",
493:       "path": "docs/lab-examples/generic_vm01.md",
494:       "bytes": 3201,
495:       "lines": 66
496:     },
497:     {
498:       "revision": "head",
499:       "path": "docs/lab-examples/ixiacone-srl.md",
500:       "bytes": 6827,
501:       "lines": 135
502:     },
503:     {
504:       "revision": "head",
505:       "path": "docs/lab-examples/lab-examples.md",
506:       "bytes": 4334,
507:       "lines": 80
508:     },
509:     {
510:       "revision": "head",
511:       "path": "docs/lab-examples/min-5clos.md",
512:       "bytes": 9340,
513:       "lines": 127
514:     },
515:     {
516:       "revision": "head",
517:       "path": "docs/lab-examples/min-clos.md",
518:       "bytes": 1970,
519:       "lines": 26
520:     },
521:     {
522:       "revision": "head",
523:       "path": "docs/lab-examples/multinode.md",
524:       "bytes": 14610,
525:       "lines": 264
526:     },
527:     {
528:       "revision": "head",
529:       "path": "docs/lab-examples/openbsd01.md",
530:       "bytes": 3615,
531:       "lines": 76
532:     },
533:     {
534:       "revision": "head",
535:       "path": "docs/lab-examples/ost-srl.md",
536:       "bytes": 6005,
537:       "lines": 114
538:     },
539:     {
540:       "revision": "head",
541:       "path": "docs/lab-examples/osvbng01.md",
542:       "bytes": 3109,
543:       "lines": 71
544:     },
545:     {
546:       "revision": "head",
547:       "path": "docs/lab-examples/peering-lab.md",
548:       "bytes": 23285,
549:       "lines": 391
550:     },
551:     {
552:       "revision": "head",
553:       "path": "docs/lab-examples/rare-freertr.md",
554:       "bytes": 1848,
555:       "lines": 31
556:     },
557:     {
558:       "revision": "head",
559:       "path": "docs/lab-examples/single-srl.md",
560:       "bytes": 2261,
561:       "lines": 32
562:     },
563:     {
564:       "revision": "head",
565:       "path": "docs/lab-examples/sr-sim.md",
566:       "bytes": 3766,
567:       "lines": 64
568:     },
569:     {
570:       "revision": "head",
571:       "path": "docs/lab-examples/srl-arcos.md",
572:       "bytes": 2871,
573:       "lines": 52
574:     },
575:     {
576:       "revision": "head",
577:       "path": "docs/lab-examples/srl-ceos.md",
578:       "bytes": 8462,
579:       "lines": 211
580:     },
581:     {
582:       "revision": "head",
583:       "path": "docs/lab-examples/srl-cjunosevolved.md",
584:       "bytes": 2674,
585:       "lines": 43
586:     },
587:     {
588:       "revision": "head",
589:       "path": "docs/lab-examples/srl-crpd.md",
590:       "bytes": 9443,
591:       "lines": 181
592:     },
593:     {
594:       "revision": "head",
595:       "path": "docs/lab-examples/srl-frr.md",
596:       "bytes": 3163,
597:       "lines": 33
598:     },
599:     {
600:       "revision": "head",
601:       "path": "docs/lab-examples/srl-sonic.md",
602:       "bytes": 9521,
603:       "lines": 193
604:     },
605:     {
606:       "revision": "head",
607:       "path": "docs/lab-examples/srl-vjunos-switch.md",
608:       "bytes": 1886,
609:       "lines": 24
610:     },
611:     {
612:       "revision": "head",
613:       "path": "docs/lab-examples/srl-vjunosevolved.md",
614:       "bytes": 1891,
615:       "lines": 24
616:     },
617:     {
618:       "revision": "head",
619:       "path": "docs/lab-examples/srl-xrd.md",
620:       "bytes": 2877,
621:       "lines": 49
622:     },
623:     {
624:       "revision": "head",
625:       "path": "docs/lab-examples/templated01.md",
626:       "bytes": 2516,
627:       "lines": 56
628:     },
629:     {
630:       "revision": "head",
631:       "path": "docs/lab-examples/templated02.md",
632:       "bytes": 2792,
633:       "lines": 68
634:     },
635:     {
636:       "revision": "head",
637:       "path": "docs/lab-examples/two-srls.md",
638:       "bytes": 3098,
639:       "lines": 47
640:     },
641:     {
642:       "revision": "head",
643:       "path": "docs/lab-examples/vr-sros.md",
644:       "bytes": 2506,
645:       "lines": 28
646:     },
647:     {
648:       "revision": "head",
649:       "path": "docs/lab-examples/vr-vmx.md",
650:       "bytes": 2523,
651:       "lines": 30
652:     },
653:     {
654:       "revision": "head",
655:       "path": "docs/lab-examples/vr-xrv.md",
656:       "bytes": 2419,
657:       "lines": 27
658:     },
659:     {
660:       "revision": "head",
661:       "path": "docs/lab-examples/vr-xrv9k.md",
662:       "bytes": 2441,
663:       "lines": 27
664:     },
665:     {
666:       "revision": "head",
667:       "path": "docs/lab-examples/vsrx01.md",
668:       "bytes": 4497,
669:       "lines": 90
670:     },
671:     {
672:       "revision": "head",
673:       "path": "docs/lab-examples/wan.md",
674:       "bytes": 1820,
675:       "lines": 24
676:     },
677:     {
678:       "revision": "head",
679:       "path": "docs/macos.md",
680:       "bytes": 17237,
681:       "lines": 251
682:     },
683:     {
684:       "revision": "head",
685:       "path": "docs/manual/api-server.md",
686:       "bytes": 7871,
687:       "lines": 223
688:     },
689:     {
690:       "revision": "head",
691:       "path": "docs/manual/cert.md",
692:       "bytes": 3472,
693:       "lines": 59
694:     },
695:     {
696:       "revision": "head",
697:       "path": "docs/manual/clabernetes/index.md",
698:       "bytes": 990,
699:       "lines": 18
700:     },
701:     {
702:       "revision": "head",
703:       "path": "docs/manual/clabernetes/runtime.md",
704:       "bytes": 60226,
705:       "lines": 1421
706:     },
707:     {
708:       "revision": "head",
709:       "path": "docs/manual/codespaces.md",
710:       "bytes": 20644,
711:       "lines": 318
712:     },
713:     {
714:       "revision": "head",
715:       "path": "docs/manual/conf-artifacts.md",
716:       "bytes": 3196,
717:       "lines": 54
718:     },
719:     {
720:       "revision": "head",
721:       "path": "docs/manual/config-mgmt.md",
722:       "bytes": 12920,
723:       "lines": 311
724:     },
725:     {
726:       "revision": "head",
727:       "path": "docs/manual/dev/debug.md",
728:       "bytes": 5255,
729:       "lines": 133
730:     },
731:     {
732:       "revision": "head",
733:       "path": "docs/manual/dev/doc.md",
734:       "bytes": 4366,
735:       "lines": 55
736:     },
737:     {
738:       "revision": "head",
739:       "path": "docs/manual/dev/index.md",
740:       "bytes": 1170,
741:       "lines": 21
742:     },
743:     {
744:       "revision": "head",
745:       "path": "docs/manual/dev/test.md",
746:       "bytes": 4069,
747:       "lines": 100
748:     },
749:     {
750:       "revision": "head",
751:       "path": "docs/manual/gui/desktop.md",
752:       "bytes": 5381,
753:       "lines": 130
754:     },
755:     {
756:       "revision": "head",
757:       "path": "docs/manual/gui/index.md",
758:       "bytes": 16398,
759:       "lines": 314
760:     },
761:     {
762:       "revision": "head",
763:       "path": "docs/manual/gui/vsc-extension.md",
764:       "bytes": 9060,
765:       "lines": 202
766:     },
767:     {
768:       "revision": "head",
769:       "path": "docs/manual/gui/web.md",
770:       "bytes": 6617,
771:       "lines": 178
772:     },
773:     {
774:       "revision": "head",
775:       "path": "docs/manual/images.md",
776:       "bytes": 5119,
777:       "lines": 108
778:     },
779:     {
780:       "revision": "head",
781:       "path": "docs/manual/impairments.md",
782:       "bytes": 881,
783:       "lines": 20
784:     },
785:     {
786:       "revision": "head",
787:       "path": "docs/manual/inventory.md",
788:       "bytes": 11726,
789:       "lines": 398
790:     },
791:     {
792:       "revision": "head",
793:       "path": "docs/manual/kinds/6wind_vsr.md",
794:       "bytes": 9464,
795:       "lines": 208
796:     },
797:     {
798:       "revision": "head",
799:       "path": "docs/manual/kinds/ale_vaos.md",
800:       "bytes": 3188,
801:       "lines": 74
802:     },
803:     {
804:       "revision": "head",
805:       "path": "docs/manual/kinds/arrcus_arcos.md",
806:       "bytes": 4185,
807:       "lines": 134
808:     },
809:     {
810:       "revision": "head",
811:       "path": "docs/manual/kinds/bridge.md",
812:       "bytes": 5527,
813:       "lines": 123
814:     },
815:     {
816:       "revision": "head",
817:       "path": "docs/manual/kinds/c8000.md",
818:       "bytes": 5477,
819:       "lines": 151
820:     },
821:     {
822:       "revision": "head",
823:       "path": "docs/manual/kinds/ceos.md",
824:       "bytes": 22395,
825:       "lines": 548
826:     },
827:     {
828:       "revision": "head",
829:       "path": "docs/manual/kinds/checkpoint_cloudguard.md",
830:       "bytes": 2694,
831:       "lines": 60
832:     },
833:     {
834:       "revision": "head",
835:       "path": "docs/manual/kinds/ciena_saos.md",
836:       "bytes": 8268,
837:       "lines": 244
838:     },
839:     {
840:       "revision": "head",
841:       "path": "docs/manual/kinds/cisco_asav.md",
842:       "bytes": 4142,
843:       "lines": 95
844:     },
845:     {
846:       "revision": "head",
847:       "path": "docs/manual/kinds/cisco_iol.md",
848:       "bytes": 11889,
849:       "lines": 269
850:     },
851:     {
852:       "revision": "head",
853:       "path": "docs/manual/kinds/cisco_sdwan.md",
854:       "bytes": 6415,
855:       "lines": 280
856:     },
857:     {
858:       "revision": "head",
859:       "path": "docs/manual/kinds/cisco_vios.md",
860:       "bytes": 3734,
861:       "lines": 95
862:     },
863:     {
864:       "revision": "head",
865:       "path": "docs/manual/kinds/cisco_xrd_vrouter.md",
866:       "bytes": 5916,
867:       "lines": 139
868:     },
869:     {
870:       "revision": "head",
871:       "path": "docs/manual/kinds/cjunosevolved.md",
872:       "bytes": 7017,
873:       "lines": 150
874:     },
875:     {
876:       "revision": "head",
877:       "path": "docs/manual/kinds/crpd.md",
878:       "bytes": 8048,
879:       "lines": 191
880:     },
881:     {
882:       "revision": "head",
883:       "path": "docs/manual/kinds/csrx.md",
884:       "bytes": 6460,
885:       "lines": 176
886:     },
887:     {
888:       "revision": "head",
889:       "path": "docs/manual/kinds/dell_sonic.md",
890:       "bytes": 3575,
891:       "lines": 96
892:     },
893:     {
894:       "revision": "head",
895:       "path": "docs/manual/kinds/ext-container.md",
896:       "bytes": 2729,
897:       "lines": 64
898:     },
899:     {
900:       "revision": "head",
901:       "path": "docs/manual/kinds/f5_bigipve.md",
902:       "bytes": 8997,
903:       "lines": 220
904:     },
905:     {
906:       "revision": "head",
907:       "path": "docs/manual/kinds/fdio_vpp.md",
908:       "bytes": 10759,
909:       "lines": 225
910:     },
911:     {
912:       "revision": "head",
913:       "path": "docs/manual/kinds/fortinet_fortigate.md",
914:       "bytes": 3737,
915:       "lines": 81
916:     },
917:     {
918:       "revision": "head",
919:       "path": "docs/manual/kinds/freebsd.md",
920:       "bytes": 4052,
921:       "lines": 95
922:     },
923:     {
924:       "revision": "head",
925:       "path": "docs/manual/kinds/frr.md",
926:       "bytes": 7504,
927:       "lines": 151
928:     },
929:     {
930:       "revision": "head",
931:       "path": "docs/manual/kinds/generic_vm.md",
932:       "bytes": 3133,
933:       "lines": 87
934:     },
935:     {
936:       "revision": "head",
937:       "path": "docs/manual/kinds/host.md",
938:       "bytes": 1105,
939:       "lines": 24
940:     },
941:     {
942:       "revision": "head",
943:       "path": "docs/manual/kinds/huawei_vrp.md",
944:       "bytes": 4188,
945:       "lines": 88
946:     },
947:     {
948:       "revision": "head",
949:       "path": "docs/manual/kinds/index.md",
950:       "bytes": 8777,
951:       "lines": 106
952:     },
953:     {
954:       "revision": "head",
955:       "path": "docs/manual/kinds/ipinfusion-ocnos.md",
956:       "bytes": 2890,
957:       "lines": 64
958:     },
959:     {
960:       "revision": "head",
961:       "path": "docs/manual/kinds/k8s-kind.md",
962:       "bytes": 6322,
963:       "lines": 141
964:     },
965:     {
966:       "revision": "head",
967:       "path": "docs/manual/kinds/keysight_ixia-c-one.md",
968:       "bytes": 3228,
969:       "lines": 68
970:     },
971:     {
972:       "revision": "head",
973:       "path": "docs/manual/kinds/linux.md",
974:       "bytes": 2960,
975:       "lines": 55
976:     },
977:     {
978:       "revision": "head",
979:       "path": "docs/manual/kinds/mikrotik_chr.md",
980:       "bytes": 14393,
981:       "lines": 212
982:     },
983:     {
984:       "revision": "head",
985:       "path": "docs/manual/kinds/nvidia_cumulusvx.md",
986:       "bytes": 4019,
987:       "lines": 106
988:     },
989:     {
990:       "revision": "head",
991:       "path": "docs/manual/kinds/openbsd.md",
992:       "bytes": 4034,
993:       "lines": 95
994:     },
995:     {
996:       "revision": "head",
997:       "path": "docs/manual/kinds/openwrt.md",
998:       "bytes": 1725,
999:       "lines": 37
1000:     },
1001:     {
1002:       "revision": "head",
1003:       "path": "docs/manual/kinds/ostinato.md",
1004:       "bytes": 3594,
1005:       "lines": 95
1006:     },
1007:     {
1008:       "revision": "head",
1009:       "path": "docs/manual/kinds/ovs-bridge.md",
1010:       "bytes": 1997,
1011:       "lines": 53
1012:     },
1013:     {
1014:       "revision": "head",
1015:       "path": "docs/manual/kinds/plvision_sonic.md",
1016:       "bytes": 3542,
1017:       "lines": 84
1018:     },
1019:     {
1020:       "revision": "head",
1021:       "path": "docs/manual/kinds/rare-freertr.md",
1022:       "bytes": 6044,
1023:       "lines": 170
1024:     },
1025:     {
1026:       "revision": "head",
1027:       "path": "docs/manual/kinds/sonic-vm.md",
1028:       "bytes": 5902,
1029:       "lines": 145
1030:     },
1031:     {
1032:       "revision": "head",
1033:       "path": "docs/manual/kinds/sonic-vs.md",
1034:       "bytes": 3737,
1035:       "lines": 78
1036:     },
1037:     {
1038:       "revision": "head",
1039:       "path": "docs/manual/kinds/spirent_stc.md",
1040:       "bytes": 3762,
1041:       "lines": 116
1042:     },
1043:     {
1044:       "revision": "head",
1045:       "path": "docs/manual/kinds/srl.md",
1046:       "bytes": 26473,
1047:       "lines": 587
1048:     },
1049:     {
1050:       "revision": "head",
1051:       "path": "docs/manual/kinds/sros.md",
1052:       "bytes": 37049,
1053:       "lines": 908
1054:     },
1055:     {
1056:       "revision": "head",
1057:       "path": "docs/manual/kinds/veesix_osvbng.md",
1058:       "bytes": 3889,
1059:       "lines": 124
1060:     },
1061:     {
1062:       "revision": "head",
1063:       "path": "docs/manual/kinds/vr-aoscx.md",
1064:       "bytes": 3329,
1065:       "lines": 73
1066:     },
1067:     {
1068:       "revision": "head",
1069:       "path": "docs/manual/kinds/vr-c8000v.md",
1070:       "bytes": 6882,
1071:       "lines": 188
1072:     },
1073:     {
1074:       "revision": "head",
1075:       "path": "docs/manual/kinds/vr-cat9kv.md",
1076:       "bytes": 6835,
1077:       "lines": 170
1078:     },
1079:     {
1080:       "revision": "head",
1081:       "path": "docs/manual/kinds/vr-csr.md",
1082:       "bytes": 4119,
1083:       "lines": 86
1084:     },
1085:     {
1086:       "revision": "head",
1087:       "path": "docs/manual/kinds/vr-ftdv.md",
1088:       "bytes": 3343,
1089:       "lines": 79
1090:     },
1091:     {
1092:       "revision": "head",
1093:       "path": "docs/manual/kinds/vr-ftosv.md",
1094:       "bytes": 3557,
1095:       "lines": 79
1096:     },
1097:     {
1098:       "revision": "head",
1099:       "path": "docs/manual/kinds/vr-n9kv.md",
1100:       "bytes": 4790,
1101:       "lines": 123
1102:     },
1103:     {
1104:       "revision": "head",
1105:       "path": "docs/manual/kinds/vr-pan.md",
1106:       "bytes": 3372,
1107:       "lines": 86
1108:     },
1109:     {
1110:       "revision": "head",
1111:       "path": "docs/manual/kinds/vr-ros.md",
1112:       "bytes": 3912,
1113:       "lines": 83
1114:     },
1115:     {
1116:       "revision": "head",
1117:       "path": "docs/manual/kinds/vr-sros.md",
1118:       "bytes": 22067,
1119:       "lines": 505
1120:     },
1121:     {
1122:       "revision": "head",
1123:       "path": "docs/manual/kinds/vr-veos.md",
1124:       "bytes": 4126,
1125:       "lines": 94
1126:     },
1127:     {
1128:       "revision": "head",
1129:       "path": "docs/manual/kinds/vr-vjunosevolved.md",
1130:       "bytes": 5141,
1131:       "lines": 107
1132:     },
1133:     {
1134:       "revision": "head",
1135:       "path": "docs/manual/kinds/vr-vjunosrouter.md",
1136:       "bytes": 5140,
1137:       "lines": 103
1138:     },
1139:     {
1140:       "revision": "head",
1141:       "path": "docs/manual/kinds/vr-vjunosswitch.md",
1142:       "bytes": 5110,
1143:       "lines": 108
1144:     },
1145:     {
1146:       "revision": "head",
1147:       "path": "docs/manual/kinds/vr-vmx.md",
1148:       "bytes": 5371,
1149:       "lines": 121
1150:     },
1151:     {
1152:       "revision": "head",
1153:       "path": "docs/manual/kinds/vr-vqfx.md",
1154:       "bytes": 4053,
1155:       "lines": 90
1156:     },
1157:     {
1158:       "revision": "head",
1159:       "path": "docs/manual/kinds/vr-vsrx.md",
1160:       "bytes": 4053,
1161:       "lines": 89
1162:     },
1163:     {
1164:       "revision": "head",
1165:       "path": "docs/manual/kinds/vr-xrv.md",
1166:       "bytes": 4029,
1167:       "lines": 100
1168:     },
1169:     {
1170:       "revision": "head",
1171:       "path": "docs/manual/kinds/vr-xrv9k.md",
1172:       "bytes": 5157,
1173:       "lines": 120
1174:     },
1175:     {
1176:       "revision": "head",
1177:       "path": "docs/manual/kinds/vyosnetworks_vyos.md",
1178:       "bytes": 6643,
1179:       "lines": 187
1180:     },
1181:     {
1182:       "revision": "head",
1183:       "path": "docs/manual/kinds/xrd.md",
1184:       "bytes": 7951,
1185:       "lines": 177
1186:     },
1187:     {
1188:       "revision": "head",
1189:       "path": "docs/manual/multi-node.md",
1190:       "bytes": 6089,
1191:       "lines": 72
1192:     },
1193:     {
1194:       "revision": "head",
1195:       "path": "docs/manual/network.md",
1196:       "bytes": 41159,
1197:       "lines": 863
1198:     },
1199:     {
1200:       "revision": "head",
1201:       "path": "docs/manual/node-filtering.md",
1202:       "bytes": 3517,
1203:       "lines": 66
1204:     },
1205:     {
1206:       "revision": "head",
1207:       "path": "docs/manual/nodes.md",
1208:       "bytes": 44654,
1209:       "lines": 1199
1210:     },
1211:     {
1212:       "revision": "head",
1213:       "path": "docs/manual/s3-usage-example.md",
1214:       "bytes": 1446,
1215:       "lines": 61
1216:     },
1217:     {
1218:       "revision": "head",
1219:       "path": "docs/manual/share-access.md",
1220:       "bytes": 8219,
1221:       "lines": 150
1222:     },
1223:     {
1224:       "revision": "head",
1225:       "path": "docs/manual/topo-def-file.md",
1226:       "bytes": 38259,
1227:       "lines": 910
1228:     },
1229:     {
1230:       "revision": "head",
1231:       "path": "docs/manual/vrnetlab.md",
1232:       "bytes": 30862,
1233:       "lines": 271
1234:     },
1235:     {
1236:       "revision": "head",
1237:       "path": "docs/manual/wireshark.md",
1238:       "bytes": 16557,
1239:       "lines": 332
1240:     },
1241:     {
1242:       "revision": "head",
1243:       "path": "docs/quickstart.md",
1244:       "bytes": 10692,
1245:       "lines": 213
1246:     },
1247:     {
1248:       "revision": "head",
1249:       "path": "docs/rn/0.11.0.md",
1250:       "bytes": 5330,
1251:       "lines": 71
1252:     },
1253:     {
1254:       "revision": "head",
1255:       "path": "docs/rn/0.12.0.md",
1256:       "bytes": 4928,
1257:       "lines": 75
1258:     },
1259:     {
1260:       "revision": "head",
1261:       "path": "docs/rn/0.13.0.md",
1262:       "bytes": 1772,
1263:       "lines": 30
1264:     },
1265:     {
1266:       "revision": "head",
1267:       "path": "docs/rn/0.14.0.md",
1268:       "bytes": 2612,
1269:       "lines": 35
1270:     },
1271:     {
1272:       "revision": "head",
1273:       "path": "docs/rn/0.14.1.md",
1274:       "bytes": 177,
1275:       "lines": 5
1276:     },
1277:     {
1278:       "revision": "head",
1279:       "path": "docs/rn/0.14.2.md",
1280:       "bytes": 301,
1281:       "lines": 5
1282:     },
1283:     {
1284:       "revision": "head",
1285:       "path": "docs/rn/0.14.3.md",
1286:       "bytes": 317,
1287:       "lines": 9
1288:     },
1289:     {
1290:       "revision": "head",
1291:       "path": "docs/rn/0.14.4.md",
1292:       "bytes": 286,
1293:       "lines": 9
1294:     },
1295:     {
1296:       "revision": "head",
1297:       "path": "docs/rn/0.15.md",
1298:       "bytes": 3827,
1299:       "lines": 69
1300:     },
1301:     {
1302:       "revision": "head",
1303:       "path": "docs/rn/0.16.md",
1304:       "bytes": 3480,
1305:       "lines": 65
1306:     },
1307:     {
1308:       "revision": "head",
1309:       "path": "docs/rn/0.17.md",
1310:       "bytes": 3356,
1311:       "lines": 41
1312:     },
1313:     {
1314:       "revision": "head",
1315:       "path": "docs/rn/0.18.md",
1316:       "bytes": 1527,
1317:       "lines": 34
1318:     },
1319:     {
1320:       "revision": "head",
1321:       "path": "docs/rn/0.19.md",
1322:       "bytes": 2470,
1323:       "lines": 48
1324:     },
1325:     {
1326:       "revision": "head",
1327:       "path": "docs/rn/0.20.md",
1328:       "bytes": 2146,
1329:       "lines": 33
1330:     },
1331:     {
1332:       "revision": "head",
1333:       "path": "docs/rn/0.21.md",
1334:       "bytes": 2459,
1335:       "lines": 48
1336:     },
1337:     {
1338:       "revision": "head",
1339:       "path": "docs/rn/0.22.md",
1340:       "bytes": 1806,
1341:       "lines": 27
1342:     },
1343:     {
1344:       "revision": "head",
1345:       "path": "docs/rn/0.23.md",
1346:       "bytes": 1835,
1347:       "lines": 35
1348:     },
1349:     {
1350:       "revision": "head",
1351:       "path": "docs/rn/0.24.md",
1352:       "bytes": 3490,
1353:       "lines": 51
1354:     },
1355:     {
1356:       "revision": "head",
1357:       "path": "docs/rn/0.25.md",
1358:       "bytes": 2105,
1359:       "lines": 37
1360:     },
1361:     {
1362:       "revision": "head",
1363:       "path": "docs/rn/0.26.md",
1364:       "bytes": 5078,
1365:       "lines": 88
1366:     },
1367:     {
1368:       "revision": "head",
1369:       "path": "docs/rn/0.27.md",
1370:       "bytes": 947,
1371:       "lines": 21
1372:     },
1373:     {
1374:       "revision": "head",
1375:       "path": "docs/rn/0.28.md",
1376:       "bytes": 1382,
1377:       "lines": 32
1378:     },
1379:     {
1380:       "revision": "head",
1381:       "path": "docs/rn/0.29.md",
1382:       "bytes": 750,
1383:       "lines": 13
1384:     },
1385:     {
1386:       "revision": "head",
1387:       "path": "docs/rn/0.30.md",
1388:       "bytes": 566,
1389:       "lines": 14
1390:     },
1391:     {
1392:       "revision": "head",
1393:       "path": "docs/rn/0.31.md",
1394:       "bytes": 1710,
1395:       "lines": 30
1396:     },
1397:     {
1398:       "revision": "head",
1399:       "path": "docs/rn/0.32.md",
1400:       "bytes": 2075,
1401:       "lines": 45
1402:     },
1403:     {
1404:       "revision": "head",
1405:       "path": "docs/rn/0.33.md",
1406:       "bytes": 893,
1407:       "lines": 22
1408:     },
1409:     {
1410:       "revision": "head",
1411:       "path": "docs/rn/0.34.md",
1412:       "bytes": 1019,
1413:       "lines": 23
1414:     },
1415:     {
1416:       "revision": "head",
1417:       "path": "docs/rn/0.35.md",
1418:       "bytes": 876,
1419:       "lines": 29
1420:     },
1421:     {
1422:       "revision": "head",
1423:       "path": "docs/rn/0.36.md",
1424:       "bytes": 868,
1425:       "lines": 23
1426:     },
1427:     {
1428:       "revision": "head",
1429:       "path": "docs/rn/0.37.md",
1430:       "bytes": 1990,
1431:       "lines": 38
1432:     },
1433:     {
1434:       "revision": "head",
1435:       "path": "docs/rn/0.38.md",
1436:       "bytes": 881,
1437:       "lines": 18
1438:     },
1439:     {
1440:       "revision": "head",
1441:       "path": "docs/rn/0.39.md",
1442:       "bytes": 3693,
1443:       "lines": 101
1444:     },
1445:     {
1446:       "revision": "head",
1447:       "path": "docs/rn/0.40.md",
1448:       "bytes": 732,
1449:       "lines": 15
1450:     },
1451:     {
1452:       "revision": "head",
1453:       "path": "docs/rn/0.41.md",
1454:       "bytes": 4520,
1455:       "lines": 88
1456:     },
1457:     {
1458:       "revision": "head",
1459:       "path": "docs/rn/0.42.md",
1460:       "bytes": 955,
1461:       "lines": 15
1462:     },
1463:     {
1464:       "revision": "head",
1465:       "path": "docs/rn/0.43.md",
1466:       "bytes": 3478,
1467:       "lines": 90
1468:     },
1469:     {
1470:       "revision": "head",
1471:       "path": "docs/rn/0.44.md",
1472:       "bytes": 2213,
1473:       "lines": 54
1474:     },
1475:     {
1476:       "revision": "head",
1477:       "path": "docs/rn/0.45.md",
1478:       "bytes": 1807,
1479:       "lines": 32
1480:     },
1481:     {
1482:       "revision": "head",
1483:       "path": "docs/rn/0.46.md",
1484:       "bytes": 3260,
1485:       "lines": 98
1486:     },
1487:     {
1488:       "revision": "head",
1489:       "path": "docs/rn/0.47.md",
1490:       "bytes": 2333,
1491:       "lines": 46
1492:     },
1493:     {
1494:       "revision": "head",
1495:       "path": "docs/rn/0.48.md",
1496:       "bytes": 4072,
1497:       "lines": 75
1498:     },
1499:     {
1500:       "revision": "head",
1501:       "path": "docs/rn/0.49.md",
1502:       "bytes": 1541,
1503:       "lines": 30
1504:     },
1505:     {
1506:       "revision": "head",
1507:       "path": "docs/rn/0.50.md",
1508:       "bytes": 3606,
1509:       "lines": 54
1510:     },
1511:     {
1512:       "revision": "head",
1513:       "path": "docs/rn/0.51.md",
1514:       "bytes": 2871,
1515:       "lines": 68
1516:     },
1517:     {
1518:       "revision": "head",
1519:       "path": "docs/rn/0.52.md",
1520:       "bytes": 3179,
1521:       "lines": 65
1522:     },
1523:     {
1524:       "revision": "head",
1525:       "path": "docs/rn/0.53.md",
1526:       "bytes": 1282,
1527:       "lines": 27
1528:     },
1529:     {
1530:       "revision": "head",
1531:       "path": "docs/rn/0.54.md",
1532:       "bytes": 942,
1533:       "lines": 26
1534:     },
1535:     {
1536:       "revision": "head",
1537:       "path": "docs/rn/0.55.md",
1538:       "bytes": 3026,
1539:       "lines": 77
1540:     },
1541:     {
1542:       "revision": "head",
1543:       "path": "docs/rn/0.56.md",
1544:       "bytes": 2575,
1545:       "lines": 46
1546:     },
1547:     {
1548:       "revision": "head",
1549:       "path": "docs/rn/0.57.md",
1550:       "bytes": 2466,
1551:       "lines": 56
1552:     },
1553:     {
1554:       "revision": "head",
1555:       "path": "docs/rn/0.58.md",
1556:       "bytes": 1868,
1557:       "lines": 30
1558:     },
1559:     {
1560:       "revision": "head",
1561:       "path": "docs/rn/0.59.md",
1562:       "bytes": 1494,
1563:       "lines": 34
1564:     },
1565:     {
1566:       "revision": "head",
1567:       "path": "docs/rn/0.60.md",
1568:       "bytes": 10022,
1569:       "lines": 135
1570:     },
1571:     {
1572:       "revision": "head",
1573:       "path": "docs/rn/0.61.md",
1574:       "bytes": 2588,
1575:       "lines": 45
1576:     },
1577:     {
1578:       "revision": "head",
1579:       "path": "docs/rn/0.62.md",
1580:       "bytes": 2915,
1581:       "lines": 54
1582:     },
1583:     {
1584:       "revision": "head",
1585:       "path": "docs/rn/0.63.md",
1586:       "bytes": 2182,
1587:       "lines": 46
1588:     },
1589:     {
1590:       "revision": "head",
1591:       "path": "docs/rn/0.64.md",
1592:       "bytes": 5000,
1593:       "lines": 45
1594:     },
1595:     {
1596:       "revision": "head",
1597:       "path": "docs/rn/0.65.md",
1598:       "bytes": 1622,
1599:       "lines": 41
1600:     },
1601:     {
1602:       "revision": "head",
1603:       "path": "docs/rn/0.66.md",
1604:       "bytes": 897,
1605:       "lines": 21
1606:     },
1607:     {
1608:       "revision": "head",
1609:       "path": "docs/rn/0.67.md",
1610:       "bytes": 1394,
1611:       "lines": 23
1612:     },
1613:     {
1614:       "revision": "head",
1615:       "path": "docs/rn/0.68.md",
1616:       "bytes": 2604,
1617:       "lines": 40
1618:     },
1619:     {
1620:       "revision": "head",
1621:       "path": "docs/rn/0.69.md",
1622:       "bytes": 5732,
1623:       "lines": 117
1624:     },
1625:     {
1626:       "revision": "head",
1627:       "path": "docs/rn/0.70.md",
1628:       "bytes": 3389,
1629:       "lines": 64
1630:     },
1631:     {
1632:       "revision": "head",
1633:       "path": "docs/rn/0.71.md",
1634:       "bytes": 5144,
1635:       "lines": 120
1636:     },
1637:     {
1638:       "revision": "head",
1639:       "path": "docs/rn/0.72.md",
1640:       "bytes": 3663,
1641:       "lines": 62
1642:     },
1643:     {
1644:       "revision": "head",
1645:       "path": "docs/rn/0.73.md",
1646:       "bytes": 6239,
1647:       "lines": 96
1648:     },
1649:     {
1650:       "revision": "head",
1651:       "path": "docs/rn/0.74.md",
1652:       "bytes": 6031,
1653:       "lines": 94
1654:     },
1655:     {
1656:       "revision": "head",
1657:       "path": "docs/rn/0.75.md",
1658:       "bytes": 5768,
1659:       "lines": 78
1660:     },
1661:     {
1662:       "revision": "head",
1663:       "path": "docs/rn/0.76.md",
1664:       "bytes": 4557,
1665:       "lines": 69
1666:     },
1667:     {
1668:       "revision": "head",
1669:       "path": "docs/rn/0.77.md",
1670:       "bytes": 3761,
1671:       "lines": 71
1672:     },
1673:     {
1674:       "revision": "head",
1675:       "path": "docs/rn/0.78.md",
1676:       "bytes": 5580,
1677:       "lines": 118
1678:     },
1679:     {
1680:       "revision": "head",
1681:       "path": "docs/rn/0.79.md",
1682:       "bytes": 3853,
1683:       "lines": 96
1684:     },
1685:     {
1686:       "revision": "head",
1687:       "path": "docs/rn/0.80.md",
1688:       "bytes": 15226,
1689:       "lines": 280
1690:     },
1691:     {
1692:       "revision": "head",
1693:       "path": "docs/rn/0.81.md",
1694:       "bytes": 5387,
1695:       "lines": 98
1696:     },
1697:     {
1698:       "revision": "head",
1699:       "path": "docs/rn/0.82.md",
1700:       "bytes": 6005,
1701:       "lines": 62
1702:     },
1703:     {
1704:       "revision": "head",
1705:       "path": "docs/rn/0.83.md",
1706:       "bytes": 12864,
1707:       "lines": 171
1708:     },
1709:     {
1710:       "revision": "head",
1711:       "path": "docs/stylesheets/extra.css",
1712:       "bytes": 19354,
1713:       "lines": 750
1714:     },
1715:     {
1716:       "revision": "head",
1717:       "path": "docs/windows.md",
1718:       "bytes": 10218,
1719:       "lines": 225
1720:     },
1721:     {
1722:       "revision": "head",
1723:       "path": "schemas/clab.schema.json",
1724:       "bytes": 168698,
1725:       "lines": 3997
1726:     },
1727:     {
1728:       "revision": "head",
1729:       "path": ".cursor/rules/git-mutations.mdc",
1730:       "bytes": 403,
1731:       "lines": 10
1732:     },
1733:     {
1734:       "revision": "head",
1735:       "path": ".cursor/rules/karpathy-guidelines.mdc",
1736:       "bytes": 2643,
1737:       "lines": 75
1738:     },
1739:     {
1740:       "revision": "head",
1741:       "path": ".cursor/rules/ponytail.mdc",
1742:       "bytes": 2620,
1743:       "lines": 36
1744:     },
1745:     {
1746:       "revision": "head",
1747:       "path": ".cursor/rules/release-note-review.mdc",
1748:       "bytes": 472,
1749:       "lines": 12
1750:     },
1751:     {
1752:       "revision": "head",
1753:       "path": ".cursor/skills/refresh-nix-vendor-hash/SKILL.md",
1754:       "bytes": 2916,
1755:       "lines": 89
1756:     },
1757:     {
1758:       "revision": "head",
1759:       "path": ".devcontainer/dclab",
1760:       "bytes": 40,
1761:       "lines": 2
1762:     },
1763:     {
1764:       "revision": "head",
1765:       "path": ".devcontainer/docker-in-docker_slim/devcontainer.json",
1766:       "bytes": 1749,
1767:       "lines": 50
1768:     },
1769:     {
1770:       "revision": "head",
1771:       "path": ".devcontainer/docker-in-docker/devcontainer.json",
1772:       "bytes": 2351,
1773:       "lines": 63
1774:     },
1775:     {
1776:       "revision": "head",
1777:       "path": ".devcontainer/docker-outside-of-docker_slim/devcontainer.json",
1778:       "bytes": 2004,
1779:       "lines": 59
1780:     },
1781:     {
1782:       "revision": "head",
1783:       "path": ".devcontainer/docker-outside-of-docker/devcontainer.json",
1784:       "bytes": 2336,
1785:       "lines": 69
1786:     },
1787:     {
1788:       "revision": "head",
1789:       "path": ".devcontainer/Dockerfile",
1790:       "bytes": 3250,
1791:       "lines": 77
1792:     },
1793:     {
1794:       "revision": "head",
1795:       "path": ".devcontainer/slim.Dockerfile",
1796:       "bytes": 2981,
1797:       "lines": 72
1798:     },
1799:     {
1800:       "revision": "head",
1801:       "path": ".devcontainer/starship.toml",
1802:       "bytes": 647,
1803:       "lines": 38
1804:     },
1805:     {
1806:       "revision": "head",
1807:       "path": ".devcontainer/zsh/.zshrc",
1808:       "bytes": 4135,
1809:       "lines": 121
1810:     },
1811:     {
1812:       "revision": "head",
1813:       "path": ".devcontainer/zsh/install-tools-completions.sh",
1814:       "bytes": 360,
1815:       "lines": 12
1816:     },
1817:     {
1818:       "revision": "head",
1819:       "path": ".devcontainer/zsh/install-zsh-plugins.sh",
1820:       "bytes": 1139,
1821:       "lines": 30
1822:     },
1823:     {
1824:       "revision": "head",
1825:       "path": ".gitattributes",
1826:       "bytes": 549,
1827:       "lines": 13
1828:     },
1829:     {
1830:       "revision": "head",
1831:       "path": ".github/copilot-instructions.md",
1832:       "bytes": 1569,
1833:       "lines": 30
1834:     },
1835:     {
1836:       "revision": "head",
1837:       "path": ".github/dependabot.yml",
1838:       "bytes": 325,
1839:       "lines": 12
1840:     },
1841:     {
1842:       "revision": "head",
1843:       "path": ".github/vars.env",
1844:       "bytes": 41,
1845:       "lines": 3
1846:     },
1847:     {
1848:       "revision": "head",
1849:       "path": ".github/workflows/build-binaries.yml",
1850:       "bytes": 4409,
1851:       "lines": 130
1852:     },
1853:     {
1854:       "revision": "head",
1855:       "path": ".github/workflows/build-containerlab.yml",
1856:       "bytes": 1407,
1857:       "lines": 53
1858:     },
1859:     {
1860:       "revision": "head",
1861:       "path": ".github/workflows/build-devcontainer.yml",
1862:       "bytes": 6157,
1863:       "lines": 187
1864:     },
1865:     {
1866:       "revision": "head",
1867:       "path": ".github/workflows/cicd.yml",
1868:       "bytes": 24190,
1869:       "lines": 783
1870:     },
1871:     {
1872:       "revision": "head",
1873:       "path": ".github/workflows/cisco_iol-tests.yml",
1874:       "bytes": 2579,
1875:       "lines": 92
1876:     },
1877:     {
1878:       "revision": "head",
1879:       "path": ".github/workflows/clabernetes-tests.yml",
1880:       "bytes": 4404,
1881:       "lines": 127
1882:     },
1883:     {
1884:       "revision": "head",
1885:       "path": ".github/workflows/comment-binaries.yml",
1886:       "bytes": 5646,
1887:       "lines": 155
1888:     },
1889:     {
1890:       "revision": "head",
1891:       "path": ".github/workflows/cumulus-tests.yml",
1892:       "bytes": 2644,
1893:       "lines": 94
1894:     },
1895:     {
1896:       "revision": "head",
1897:       "path": ".github/workflows/download-tests.yml",
1898:       "bytes": 2166,
1899:       "lines": 81
1900:     },
1901:     {
1902:       "revision": "head",
1903:       "path": ".github/workflows/fdio_vpp-tests.yml",
1904:       "bytes": 2351,
1905:       "lines": 85
1906:     },
1907:     {
1908:       "revision": "head",
1909:       "path": ".github/workflows/force-build.yml",
1910:       "bytes": 3052,
1911:       "lines": 102
1912:     },
1913:     {
1914:       "revision": "head",
1915:       "path": ".github/workflows/fortigate-tests.yml",
1916:       "bytes": 2531,
1917:       "lines": 91
1918:     },
1919:     {
1920:       "revision": "head",
1921:       "path": ".github/workflows/frr-tests.yml",
1922:       "bytes": 2409,
1923:       "lines": 85
1924:     },
1925:     {
1926:       "revision": "head",
1927:       "path": ".github/workflows/golangci-lint.yml",
1928:       "bytes": 2015,
1929:       "lines": 57
1930:     },
1931:     {
1932:       "revision": "head",
1933:       "path": ".github/workflows/install-podman.sh",
1934:       "bytes": 734,
1935:       "lines": 15
1936:     },
1937:     {
1938:       "revision": "head",
1939:       "path": ".github/workflows/kind-tests.yml",
1940:       "bytes": 2480,
1941:       "lines": 89
1942:     },
1943:     {
1944:       "revision": "head",
1945:       "path": ".github/workflows/mgmt-tests.yml",
1946:       "bytes": 3974,
1947:       "lines": 128
1948:     },
1949:     {
1950:       "revision": "head",
1951:       "path": ".github/workflows/mikrotik_chr-tests.yml",
1952:       "bytes": 2475,
1953:       "lines": 86
1954:     },
1955:     {
1956:       "revision": "head",
1957:       "path": ".github/workflows/nix.yml",
1958:       "bytes": 5756,
1959:       "lines": 148
1960:     },
1961:     {
1962:       "revision": "head",
1963:       "path": ".github/workflows/smoke-tests.yml",
1964:       "bytes": 3392,
1965:       "lines": 123
1966:     },
1967:     {
1968:       "revision": "head",
1969:       "path": ".github/workflows/srlinux-tests.yml",
1970:       "bytes": 2768,
1971:       "lines": 93
1972:     },
1973:     {
1974:       "revision": "head",
1975:       "path": ".github/workflows/sros-tests.yml",
1976:       "bytes": 2259,
1977:       "lines": 83
1978:     },
1979:     {
1980:       "revision": "head",
1981:       "path": ".github/workflows/srsim-tests.yml",
1982:       "bytes": 4465,
1983:       "lines": 141
1984:     },
1985:     {
1986:       "revision": "head",
1987:       "path": ".github/workflows/test-srsim.yml",
1988:       "bytes": 6628,
1989:       "lines": 203
1990:     },
1991:     {
1992:       "revision": "head",
1993:       "path": ".github/workflows/tofarev.yml",
1994:       "bytes": 1010,
1995:       "lines": 24
1996:     },
1997:     {
1998:       "revision": "head",
1999:       "path": ".github/workflows/vxlan-tests.yml",
2000:       "bytes": 2521,

(Showing lines 1-2000 of 16489. Use offset=2001 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46ac80c001dAC5N9RP8JaLi2",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a65d0001FWpkI8jK2UTVJJ",
  "callID": "call_1a7ed2b14f5349a9bd63542a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/manifest.json"
    },
    "output": "<path>/source/manifest.json</path>\n<type>file</type>\n<content>\n1: {\n2:   \"version\": 1,\n3:   \"head\": \"1c9b3577d08f7524fd228e5ab4df3dd3fc107f53\",\n4:   \"base\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n5:   \"mergeBase\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n6:   \"changed\": [\n7:     {\n8:       \"status\": \"M\",\n9:       \"path\": \"core/events/netlink.go\"\n10:     },\n11:     {\n12:       \"status\": \"M\",\n13:       \"path\": \"core/events/netlink_watch_test.go\"\n14:     }\n15:   ],\n16:   \"files\": [\n17:     {\n18:       \"revision\": \"head\",\n19:       \"path\": \"core/events/netlink_watch_test.go\",\n20:       \"bytes\": 15093,\n21:       \"lines\": 534\n22:     },\n23:     {\n24:       \"revision\": \"head\",\n25:       \"path\": \"core/events/netlink.go\",\n26:       \"bytes\": 32781,\n27:       \"lines\": 1390\n28:     },\n29:     {\n30:       \"revision\": \"head\",\n31:       \"path\": \"docs/cmd/capture.md\",\n32:       \"bytes\": 7769,\n33:       \"lines\": 134\n34:     },\n35:     {\n36:       \"revision\": \"head\",\n37:       \"path\": \"docs/cmd/completion.md\",\n38:       \"bytes\": 2336,\n39:       \"lines\": 95\n40:     },\n41:     {\n42:       \"revision\": \"head\",\n43:       \"path\": \"docs/cmd/deploy.md\",\n44:       \"bytes\": 31381,\n45:       \"lines\": 565\n46:     },\n47:     {\n48:       \"revision\": \"head\",\n49:       \"path\": \"docs/cmd/destroy.md\",\n50:       \"bytes\": 3762,\n51:       \"lines\": 100\n52:     },\n53:     {\n54:       \"revision\": \"head\",\n55:       \"path\": \"docs/cmd/events.md\",\n56:       \"bytes\": 6764,\n57:       \"lines\": 99\n58:     },\n59:     {\n60:       \"revision\": \"head\",\n61:       \"path\": \"docs/cmd/exec.md\",\n62:       \"bytes\": 7316,\n63:       \"lines\": 177\n64:     },\n65:     {\n66:       \"revision\": \"head\",\n67:       \"path\": \"docs/cmd/generate.md\",\n68:       \"bytes\": 6005,\n69:       \"lines\": 138\n70:     },\n71:     {\n72:       \"revision\": \"head\",\n73:       \"path\": \"docs/cmd/graph.md\",\n74:       \"bytes\": 8242,\n75:       \"lines\": 192\n76:     },\n77:     {\n78:       \"revision\": \"head\",\n79:       \"path\": \"docs/cmd/inspect/index.md\",\n80:       \"bytes\": 11106,\n81:       \"lines\": 179\n82:     },\n83:     {\n84:       \"revision\": \"head\",\n85:       \"path\": \"docs/cmd/inspect/interfaces.md\",\n86:       \"bytes\": 11855,\n87:       \"lines\": 199\n88:     },\n89:     {\n90:       \"revision\": \"head\",\n91:       \"path\": \"docs/cmd/logs.md\",\n92:       \"bytes\": 1836,\n93:       \"lines\": 57\n94:     },\n95:     {\n96:       \"revision\": \"head\",\n97:       \"path\": \"docs/cmd/redeploy.md\",\n98:       \"bytes\": 6085,\n99:       \"lines\": 150\n100:     },\n101:     {\n102:       \"revision\": \"head\",\n103:       \"path\": \"docs/cmd/restart.md\",\n104:       \"bytes\": 1432,\n105:       \"lines\": 64\n106:     },\n107:     {\n108:       \"revision\": \"head\",\n109:       \"path\": \"docs/cmd/save.md\",\n110:       \"bytes\": 6445,\n111:       \"lines\": 133\n112:     },\n113:     {\n114:       \"revision\": \"head\",\n115:       \"path\": \"docs/cmd/start.md\",\n116:       \"bytes\": 2251,\n117:       \"lines\": 76\n118:     },\n119:     {\n120:       \"revision\": \"head\",\n121:       \"path\": \"docs/cmd/stop.md\",\n122:       \"bytes\": 1313,\n123:       \"lines\": 62\n124:     },\n125:     {\n126:       \"revision\": \"head\",\n127:       \"path\": \"docs/cmd/tools/api-server/start.md\",\n128:       \"bytes\": 5581,\n129:       \"lines\": 165\n130:     },\n131:     {\n132:       \"revision\": \"head\",\n133:       \"path\": \"docs/cmd/tools/api-server/status.md\",\n134:       \"bytes\": 4223,\n135:       \"lines\": 105\n136:     },\n137:     {\n138:       \"revision\": \"head\",\n139:       \"path\": \"docs/cmd/tools/api-server/stop.md\",\n140:       \"bytes\": 1836,\n141:       \"lines\": 56\n142:     },\n143:     {\n144:       \"revision\": \"head\",\n145:       \"path\": \"docs/cmd/tools/cert/ca/create.md\",\n146:       \"bytes\": 2206,\n147:       \"lines\": 77\n148:     },\n149:     {\n150:       \"revision\": \"head\",\n151:       \"path\": \"docs/cmd/tools/cert/sign.md\",\n152:       \"bytes\": 2428,\n153:       \"lines\": 79\n154:     },\n155:     {\n156:       \"revision\": \"head\",\n157:       \"path\": \"docs/cmd/tools/disable-tx-offload.md\",\n158:       \"bytes\": 982,\n159:       \"lines\": 25\n160:     },\n161:     {\n162:       \"revision\": \"head\",\n163:       \"path\": \"docs/cmd/tools/gotty/attach.md\",\n164:       \"bytes\": 1904,\n165:       \"lines\": 67\n166:     },\n167:     {\n168:       \"revision\": \"head\",\n169:       \"path\": \"docs/cmd/tools/gotty/detach.md\",\n170:       \"bytes\": 627,\n171:       \"lines\": 29\n172:     },\n173:     {\n174:       \"revision\": \"head\",\n175:       \"path\": \"docs/cmd/tools/gotty/list.md\",\n176:       \"bytes\": 1070,\n177:       \"lines\": 46\n178:     },\n179:     {\n180:       \"revision\": \"head\",\n181:       \"path\": \"docs/cmd/tools/gotty/reattach.md\",\n182:       \"bytes\": 955,\n183:       \"lines\": 26\n184:     },\n185:     {\n186:       \"revision\": \"head\",\n187:       \"path\": \"docs/cmd/tools/netem/reset.md\",\n188:       \"bytes\": 1635,\n189:       \"lines\": 63\n190:     },\n191:     {\n192:       \"revision\": \"head\",\n193:       \"path\": \"docs/cmd/tools/netem/set.md\",\n194:       \"bytes\": 3979,\n195:       \"lines\": 114\n196:     },\n197:     {\n198:       \"revision\": \"head\",\n199:       \"path\": \"docs/cmd/tools/netem/show.md\",\n200:       \"bytes\": 3651,\n201:       \"lines\": 150\n202:     },\n203:     {\n204:       \"revision\": \"head\",\n205:       \"path\": \"docs/cmd/tools/snapshot/save.md\",\n206:       \"bytes\": 1647,\n207:       \"lines\": 75\n208:     },\n209:     {\n210:       \"revision\": \"head\",\n211:       \"path\": \"docs/cmd/tools/sshx/attach.md\",\n212:       \"bytes\": 5194,\n213:       \"lines\": 128\n214:     },\n215:     {\n216:       \"revision\": \"head\",\n217:       \"path\": \"docs/cmd/tools/sshx/detach.md\",\n218:       \"bytes\": 1837,\n219:       \"lines\": 46\n220:     },\n221:     {\n222:       \"revision\": \"head\",\n223:       \"path\": \"docs/cmd/tools/sshx/list.md\",\n224:       \"bytes\": 3662,\n225:       \"lines\": 77\n226:     },\n227:     {\n228:       \"revision\": \"head\",\n229:       \"path\": \"docs/cmd/tools/sshx/reattach.md\",\n230:       \"bytes\": 4593,\n231:       \"lines\": 101\n232:     },\n233:     {\n234:       \"revision\": \"head\",\n235:       \"path\": \"docs/cmd/tools/veth/create.md\",\n236:       \"bytes\": 1890,\n237:       \"lines\": 51\n238:     },\n239:     {\n240:       \"revision\": \"head\",\n241:       \"path\": \"docs/cmd/tools/vxlan/create.md\",\n242:       \"bytes\": 3355,\n243:       \"lines\": 73\n244:     },\n245:     {\n246:       \"revision\": \"head\",\n247:       \"path\": \"docs/cmd/tools/vxlan/delete.md\",\n248:       \"bytes\": 1230,\n249:       \"lines\": 31\n250:     },\n251:     {\n252:       \"revision\": \"head\",\n253:       \"path\": \"docs/cmd/validate.md\",\n254:       \"bytes\": 1785,\n255:       \"lines\": 51\n256:     },\n257:     {\n258:       \"revision\": \"head\",\n259:       \"path\": \"docs/cmd/version/check.md\",\n260:       \"bytes\": 537,\n261:       \"lines\": 21\n262:     },\n263:     {\n264:       \"revision\": \"head\",\n265:       \"path\": \"docs/cmd/version/index.md\",\n266:       \"bytes\": 1011,\n267:       \"lines\": 37\n268:     },\n269:     {\n270:       \"revision\": \"head\",\n271:       \"path\": \"docs/CNAME\",\n272:       \"bytes\": 16,\n273:       \"lines\": 1\n274:     },\n275:     {\n276:       \"revision\": \"head\",\n277:       \"path\": \"docs/community.md\",\n278:       \"bytes\": 26611,\n279:       \"lines\": 360\n280:     },\n281:     {\n282:       \"revision\": \"head\",\n283:       \"path\": \"docs/htmltest-pr.yml\",\n284:       \"bytes\": 678,\n285:       \"lines\": 14\n286:     },\n287:     {\n288:       \"revision\": \"head\",\n289:       \"path\": \"docs/htmltest-w-github.yml\",\n290:       \"bytes\": 1679,\n291:       \"lines\": 31\n292:     },\n293:     {\n294:       \"revision\": \"head\",\n295:       \"path\": \"docs/htmltest.yml\",\n296:       \"bytes\": 2429,\n297:       \"lines\": 49\n298:     },\n299:     {\n300:       \"revision\": \"head\",\n301:       \"path\": \"docs/images/clabnew.svg\",\n302:       \"bytes\": 16299,\n303:       \"lines\": 13\n304:     },\n305:     {\n306:       \"revision\": \"head\",\n307:       \"path\": \"docs/images/coloured_wordmark.svg\",\n308:       \"bytes\": 8031,\n309:       \"lines\": 91\n310:     },\n311:     {\n312:       \"revision\": \"head\",\n313:       \"path\": \"docs/images/containerlab_dark_no_text.svg\",\n314:       \"bytes\": 3589,\n315:       \"lines\": 8\n316:     },\n317:     {\n318:       \"revision\": \"head\",\n319:       \"path\": \"docs/images/containerlab_export.svg\",\n320:       \"bytes\": 8893,\n321:       \"lines\": 33\n322:     },\n323:     {\n324:       \"revision\": \"head\",\n325:       \"path\": \"docs/images/containerlab_full_white_no_text.svg\",\n326:       \"bytes\": 3801,\n327:       \"lines\": 8\n328:     },\n329:     {\n330:       \"revision\": \"head\",\n331:       \"path\": \"docs/images/containerlab_white_no_text.svg\",\n332:       \"bytes\": 3293,\n333:       \"lines\": 8\n334:     },\n335:     {\n336:       \"revision\": \"head\",\n337:       \"path\": \"docs/images/containerlab-animated-wordmark.svg\",\n338:       \"bytes\": 70018,\n339:       \"lines\": 52\n340:     },\n341:     {\n342:       \"revision\": \"head\",\n343:       \"path\": \"docs/images/favicon.svg\",\n344:       \"bytes\": 16378,\n345:       \"lines\": 20\n346:     },\n347:     {\n348:       \"revision\": \"head\",\n349:       \"path\": \"docs/images/flask.svg\",\n350:       \"bytes\": 378,\n351:       \"lines\": 1\n352:     },\n353:     {\n354:       \"revision\": \"head\",\n355:       \"path\": \"docs/images/gui/browser-sandbox-placeholder.svg\",\n356:       \"bytes\": 2220,\n357:       \"lines\": 25\n358:     },\n359:     {\n360:       \"revision\": \"head\",\n361:       \"path\": \"docs/images/topoviewer-icons/client.svg\",\n362:       \"bytes\": 633,\n363:       \"lines\": 1\n364:     },\n365:     {\n366:       \"revision\": \"head\",\n367:       \"path\": \"docs/images/topoviewer-icons/controller.svg\",\n368:       \"bytes\": 768,\n369:       \"lines\": 1\n370:     },\n371:     {\n372:       \"revision\": \"head\",\n373:       \"path\": \"docs/images/topoviewer-icons/dcgw.svg\",\n374:       \"bytes\": 1015,\n375:       \"lines\": 1\n376:     },\n377:     {\n378:       \"revision\": \"head\",\n379:       \"path\": \"docs/images/topoviewer-icons/pon.svg\",\n380:       \"bytes\": 553,\n381:       \"lines\": 1\n382:     },\n383:     {\n384:       \"revision\": \"head\",\n385:       \"path\": \"docs/images/topoviewer-icons/rgw.svg\",\n386:       \"bytes\": 983,\n387:       \"lines\": 1\n388:     },\n389:     {\n390:       \"revision\": \"head\",\n391:       \"path\": \"docs/images/topoviewer-icons/router.svg\",\n392:       \"bytes\": 864,\n393:       \"lines\": 1\n394:     },\n395:     {\n396:       \"revision\": \"head\",\n397:       \"path\": \"docs/images/topoviewer-icons/server.svg\",\n398:       \"bytes\": 744,\n399:       \"lines\": 1\n400:     },\n401:     {\n402:       \"revision\": \"head\",\n403:       \"path\": \"docs/images/topoviewer-icons/spine.svg\",\n404:       \"bytes\": 940,\n405:       \"lines\": 1\n406:     },\n407:     {\n408:       \"revision\": \"head\",\n409:       \"path\": \"docs/images/topoviewer-icons/switch.svg\",\n410:       \"bytes\": 803,\n411:       \"lines\": 1\n412:     },\n413:     {\n414:       \"revision\": \"head\",\n415:       \"path\": \"docs/index.md\",\n416:       \"bytes\": 6778,\n417:       \"lines\": 189\n418:     },\n419:     {\n420:       \"revision\": \"head\",\n421:       \"path\": \"docs/install.md\",\n422:       \"bytes\": 18001,\n423:       \"lines\": 521\n424:     },\n425:     {\n426:       \"revision\": \"head\",\n427:       \"path\": \"docs/javascripts/instant-reinit.js\",\n428:       \"bytes\": 2040,\n429:       \"lines\": 45\n430:     },\n431:     {\n432:       \"revision\": \"head\",\n433:       \"path\": \"docs/lab-examples/asav01.md\",\n434:       \"bytes\": 4137,\n435:       \"lines\": 90\n436:     },\n437:     {\n438:       \"revision\": \"head\",\n439:       \"path\": \"docs/lab-examples/bgp-vpls-nok-jun.md\",\n440:       \"bytes\": 3374,\n441:       \"lines\": 34\n442:     },\n443:     {\n444:       \"revision\": \"head\",\n445:       \"path\": \"docs/lab-examples/cisco_iol.md\",\n446:       \"bytes\": 4368,\n447:       \"lines\": 100\n448:     },\n449:     {\n450:       \"revision\": \"head\",\n451:       \"path\": \"docs/lab-examples/cvx01.md\",\n452:       \"bytes\": 2989,\n453:       \"lines\": 48\n454:     },\n455:     {\n456:       \"revision\": \"head\",\n457:       \"path\": \"docs/lab-examples/cvx02.md\",\n458:       \"bytes\": 2936,\n459:       \"lines\": 49\n460:     },\n461:     {\n462:       \"revision\": \"head\",\n463:       \"path\": \"docs/lab-examples/ext-bridge.md\",\n464:       \"bytes\": 2042,\n465:       \"lines\": 31\n466:     },\n467:     {\n468:       \"revision\": \"head\",\n469:       \"path\": \"docs/lab-examples/f5bigipve01.md\",\n470:       \"bytes\": 4956,\n471:       \"lines\": 118\n472:     },\n473:     {\n474:       \"revision\": \"head\",\n475:       \"path\": \"docs/lab-examples/freebsd01.md\",\n476:       \"bytes\": 3571,\n477:       \"lines\": 76\n478:     },\n479:     {\n480:       \"revision\": \"head\",\n481:       \"path\": \"docs/lab-examples/frr01.md\",\n482:       \"bytes\": 2987,\n483:       \"lines\": 64\n484:     },\n485:     {\n486:       \"revision\": \"head\",\n487:       \"path\": \"docs/lab-examples/ftdv01.md\",\n488:       \"bytes\": 4108,\n489:       \"lines\": 75\n490:     },\n491:     {\n492:       \"revision\": \"head\",\n493:       \"path\": \"docs/lab-examples/generic_vm01.md\",\n494:       \"bytes\": 3201,\n495:       \"lines\": 66\n496:     },\n497:     {\n498:       \"revision\": \"head\",\n499:       \"path\": \"docs/lab-examples/ixiacone-srl.md\",\n500:       \"bytes\": 6827,\n501:       \"lines\": 135\n502:     },\n503:     {\n504:       \"revision\": \"head\",\n505:       \"path\": \"docs/lab-examples/lab-examples.md\",\n506:       \"bytes\": 4334,\n507:       \"lines\": 80\n508:     },\n509:     {\n510:       \"revision\": \"head\",\n511:       \"path\": \"docs/lab-examples/min-5clos.md\",\n512:       \"bytes\": 9340,\n513:       \"lines\": 127\n514:     },\n515:     {\n516:       \"revision\": \"head\",\n517:       \"path\": \"docs/lab-examples/min-clos.md\",\n518:       \"bytes\": 1970,\n519:       \"lines\": 26\n520:     },\n521:     {\n522:       \"revision\": \"head\",\n523:       \"path\": \"docs/lab-examples/multinode.md\",\n524:       \"bytes\": 14610,\n525:       \"lines\": 264\n526:     },\n527:     {\n528:       \"revision\": \"head\",\n529:       \"path\": \"docs/lab-examples/openbsd01.md\",\n530:       \"bytes\": 3615,\n531:       \"lines\": 76\n532:     },\n533:     {\n534:       \"revision\": \"head\",\n535:       \"path\": \"docs/lab-examples/ost-srl.md\",\n536:       \"bytes\": 6005,\n537:       \"lines\": 114\n538:     },\n539:     {\n540:       \"revision\": \"head\",\n541:       \"path\": \"docs/lab-examples/osvbng01.md\",\n542:       \"bytes\": 3109,\n543:       \"lines\": 71\n544:     },\n545:     {\n546:       \"revision\": \"head\",\n547:       \"path\": \"docs/lab-examples/peering-lab.md\",\n548:       \"bytes\": 23285,\n549:       \"lines\": 391\n550:     },\n551:     {\n552:       \"revision\": \"head\",\n553:       \"path\": \"docs/lab-examples/rare-freertr.md\",\n554:       \"bytes\": 1848,\n555:       \"lines\": 31\n556:     },\n557:     {\n558:       \"revision\": \"head\",\n559:       \"path\": \"docs/lab-examples/single-srl.md\",\n560:       \"bytes\": 2261,\n561:       \"lines\": 32\n562:     },\n563:     {\n564:       \"revision\": \"head\",\n565:       \"path\": \"docs/lab-examples/sr-sim.md\",\n566:       \"bytes\": 3766,\n567:       \"lines\": 64\n568:     },\n569:     {\n570:       \"revision\": \"head\",\n571:       \"path\": \"docs/lab-examples/srl-arcos.md\",\n572:       \"bytes\": 2871,\n573:       \"lines\": 52\n574:     },\n575:     {\n576:       \"revision\": \"head\",\n577:       \"path\": \"docs/lab-examples/srl-ceos.md\",\n578:       \"bytes\": 8462,\n579:       \"lines\": 211\n580:     },\n581:     {\n582:       \"revision\": \"head\",\n583:       \"path\": \"docs/lab-examples/srl-cjunosevolved.md\",\n584:       \"bytes\": 2674,\n585:       \"lines\": 43\n586:     },\n587:     {\n588:       \"revision\": \"head\",\n589:       \"path\": \"docs/lab-examples/srl-crpd.md\",\n590:       \"bytes\": 9443,\n591:       \"lines\": 181\n592:     },\n593:     {\n594:       \"revision\": \"head\",\n595:       \"path\": \"docs/lab-examples/srl-frr.md\",\n596:       \"bytes\": 3163,\n597:       \"lines\": 33\n598:     },\n599:     {\n600:       \"revision\": \"head\",\n601:       \"path\": \"docs/lab-examples/srl-sonic.md\",\n602:       \"bytes\": 9521,\n603:       \"lines\": 193\n604:     },\n605:     {\n606:       \"revision\": \"head\",\n607:       \"path\": \"docs/lab-examples/srl-vjunos-switch.md\",\n608:       \"bytes\": 1886,\n609:       \"lines\": 24\n610:     },\n611:     {\n612:       \"revision\": \"head\",\n613:       \"path\": \"docs/lab-examples/srl-vjunosevolved.md\",\n614:       \"bytes\": 1891,\n615:       \"lines\": 24\n616:     },\n617:     {\n618:       \"revision\": \"head\",\n619:       \"path\": \"docs/lab-examples/srl-xrd.md\",\n620:       \"bytes\": 2877,\n621:       \"lines\": 49\n622:     },\n623:     {\n624:       \"revision\": \"head\",\n625:       \"path\": \"docs/lab-examples/templated01.md\",\n626:       \"bytes\": 2516,\n627:       \"lines\": 56\n628:     },\n629:     {\n630:       \"revision\": \"head\",\n631:       \"path\": \"docs/lab-examples/templated02.md\",\n632:       \"bytes\": 2792,\n633:       \"lines\": 68\n634:     },\n635:     {\n636:       \"revision\": \"head\",\n637:       \"path\": \"docs/lab-examples/two-srls.md\",\n638:       \"bytes\": 3098,\n639:       \"lines\": 47\n640:     },\n641:     {\n642:       \"revision\": \"head\",\n643:       \"path\": \"docs/lab-examples/vr-sros.md\",\n644:       \"bytes\": 2506,\n645:       \"lines\": 28\n646:     },\n647:     {\n648:       \"revision\": \"head\",\n649:       \"path\": \"docs/lab-examples/vr-vmx.md\",\n650:       \"bytes\": 2523,\n651:       \"lines\": 30\n652:     },\n653:     {\n654:       \"revision\": \"head\",\n655:       \"path\": \"docs/lab-examples/vr-xrv.md\",\n656:       \"bytes\": 2419,\n657:       \"lines\": 27\n658:     },\n659:     {\n660:       \"revision\": \"head\",\n661:       \"path\": \"docs/lab-examples/vr-xrv9k.md\",\n662:       \"bytes\": 2441,\n663:       \"lines\": 27\n664:     },\n665:     {\n666:       \"revision\": \"head\",\n667:       \"path\": \"docs/lab-examples/vsrx01.md\",\n668:       \"bytes\": 4497,\n669:       \"lines\": 90\n670:     },\n671:     {\n672:       \"revision\": \"head\",\n673:       \"path\": \"docs/lab-examples/wan.md\",\n674:       \"bytes\": 1820,\n675:       \"lines\": 24\n676:     },\n677:     {\n678:       \"revision\": \"head\",\n679:       \"path\": \"docs/macos.md\",\n680:       \"bytes\": 17237,\n681:       \"lines\": 251\n682:     },\n683:     {\n684:       \"revision\": \"head\",\n685:       \"path\": \"docs/manual/api-server.md\",\n686:       \"bytes\": 7871,\n687:       \"lines\": 223\n688:     },\n689:     {\n690:       \"revision\": \"head\",\n691:       \"path\": \"docs/manual/cert.md\",\n692:       \"bytes\": 3472,\n693:       \"lines\": 59\n694:     },\n695:     {\n696:       \"revision\": \"head\",\n697:       \"path\": \"docs/manual/clabernetes/index.md\",\n698:       \"bytes\": 990,\n699:       \"lines\": 18\n700:     },\n701:     {\n702:       \"revision\": \"head\",\n703:       \"path\": \"docs/manual/clabernetes/runtime.md\",\n704:       \"bytes\": 60226,\n705:       \"lines\": 1421\n706:     },\n707:     {\n708:       \"revision\": \"head\",\n709:       \"path\": \"docs/manual/codespaces.md\",\n710:       \"bytes\": 20644,\n711:       \"lines\": 318\n712:     },\n713:     {\n714:       \"revision\": \"head\",\n715:       \"path\": \"docs/manual/conf-artifacts.md\",\n716:       \"bytes\": 3196,\n717:       \"lines\": 54\n718:     },\n719:     {\n720:       \"revision\": \"head\",\n721:       \"path\": \"docs/manual/config-mgmt.md\",\n722:       \"bytes\": 12920,\n723:       \"lines\": 311\n724:     },\n725:     {\n726:       \"revision\": \"head\",\n727:       \"path\": \"docs/manual/dev/debug.md\",\n728:       \"bytes\": 5255,\n729:       \"lines\": 133\n730:     },\n731:     {\n732:       \"revision\": \"head\",\n733:       \"path\": \"docs/manual/dev/doc.md\",\n734:       \"bytes\": 4366,\n735:       \"lines\": 55\n736:     },\n737:     {\n738:       \"revision\": \"head\",\n739:       \"path\": \"docs/manual/dev/index.md\",\n740:       \"bytes\": 1170,\n741:       \"lines\": 21\n742:     },\n743:     {\n744:       \"revision\": \"head\",\n745:       \"path\": \"docs/manual/dev/test.md\",\n746:       \"bytes\": 4069,\n747:       \"lines\": 100\n748:     },\n749:     {\n750:       \"revision\": \"head\",\n751:       \"path\": \"docs/manual/gui/desktop.md\",\n752:       \"bytes\": 5381,\n753:       \"lines\": 130\n754:     },\n755:     {\n756:       \"revision\": \"head\",\n757:       \"path\": \"docs/manual/gui/index.md\",\n758:       \"bytes\": 16398,\n759:       \"lines\": 314\n760:     },\n761:     {\n762:       \"revision\": \"head\",\n763:       \"path\": \"docs/manual/gui/vsc-extension.md\",\n764:       \"bytes\": 9060,\n765:       \"lines\": 202\n766:     },\n767:     {\n768:       \"revision\": \"head\",\n769:       \"path\": \"docs/manual/gui/web.md\",\n770:       \"bytes\": 6617,\n771:       \"lines\": 178\n772:     },\n773:     {\n774:       \"revision\": \"head\",\n775:       \"path\": \"docs/manual/images.md\",\n776:       \"bytes\": 5119,\n777:       \"lines\": 108\n778:     },\n779:     {\n780:       \"revision\": \"head\",\n781:       \"path\": \"docs/manual/impairments.md\",\n782:       \"bytes\": 881,\n783:       \"lines\": 20\n784:     },\n785:     {\n786:       \"revision\": \"head\",\n787:       \"path\": \"docs/manual/inventory.md\",\n788:       \"bytes\": 11726,\n789:       \"lines\": 398\n790:     },\n791:     {\n792:       \"revision\": \"head\",\n793:       \"path\": \"docs/manual/kinds/6wind_vsr.md\",\n794:       \"bytes\": 9464,\n795:       \"lines\": 208\n796:     },\n797:     {\n798:       \"revision\": \"head\",\n799:       \"path\": \"docs/manual/kinds/ale_vaos.md\",\n800:       \"bytes\": 3188,\n801:       \"lines\": 74\n802:     },\n803:     {\n804:       \"revision\": \"head\",\n805:       \"path\": \"docs/manual/kinds/arrcus_arcos.md\",\n806:       \"bytes\": 4185,\n807:       \"lines\": 134\n808:     },\n809:     {\n810:       \"revision\": \"head\",\n811:       \"path\": \"docs/manual/kinds/bridge.md\",\n812:       \"bytes\": 5527,\n813:       \"lines\": 123\n814:     },\n815:     {\n816:       \"revision\": \"head\",\n817:       \"path\": \"docs/manual/kinds/c8000.md\",\n818:       \"bytes\": 5477,\n819:       \"lines\": 151\n820:     },\n821:     {\n822:       \"revision\": \"head\",\n823:       \"path\": \"docs/manual/kinds/ceos.md\",\n824:       \"bytes\": 22395,\n825:       \"lines\": 548\n826:     },\n827:     {\n828:       \"revision\": \"head\",\n829:       \"path\": \"docs/manual/kinds/checkpoint_cloudguard.md\",\n830:       \"bytes\": 2694,\n831:       \"lines\": 60\n832:     },\n833:     {\n834:       \"revision\": \"head\",\n835:       \"path\": \"docs/manual/kinds/ciena_saos.md\",\n836:       \"bytes\": 8268,\n837:       \"lines\": 244\n838:     },\n839:     {\n840:       \"revision\": \"head\",\n841:       \"path\": \"docs/manual/kinds/cisco_asav.md\",\n842:       \"bytes\": 4142,\n843:       \"lines\": 95\n844:     },\n845:     {\n846:       \"revision\": \"head\",\n847:       \"path\": \"docs/manual/kinds/cisco_iol.md\",\n848:       \"bytes\": 11889,\n849:       \"lines\": 269\n850:     },\n851:     {\n852:       \"revision\": \"head\",\n853:       \"path\": \"docs/manual/kinds/cisco_sdwan.md\",\n854:       \"bytes\": 6415,\n855:       \"lines\": 280\n856:     },\n857:     {\n858:       \"revision\": \"head\",\n859:       \"path\": \"docs/manual/kinds/cisco_vios.md\",\n860:       \"bytes\": 3734,\n861:       \"lines\": 95\n862:     },\n863:     {\n864:       \"revision\": \"head\",\n865:       \"path\": \"docs/manual/kinds/cisco_xrd_vrouter.md\",\n866:       \"bytes\": 5916,\n867:       \"lines\": 139\n868:     },\n869:     {\n870:       \"revision\": \"head\",\n871:       \"path\": \"docs/manual/kinds/cjunosevolved.md\",\n872:       \"bytes\": 7017,\n873:       \"lines\": 150\n874:     },\n875:     {\n876:       \"revision\": \"head\",\n877:       \"path\": \"docs/manual/kinds/crpd.md\",\n878:       \"bytes\": 8048,\n879:       \"lines\": 191\n880:     },\n881:     {\n882:       \"revision\": \"head\",\n883:       \"path\": \"docs/manual/kinds/csrx.md\",\n884:       \"bytes\": 6460,\n885:       \"lines\": 176\n886:     },\n887:     {\n888:       \"revision\": \"head\",\n889:       \"path\": \"docs/manual/kinds/dell_sonic.md\",\n890:       \"bytes\": 3575,\n891:       \"lines\": 96\n892:     },\n893:     {\n894:       \"revision\": \"head\",\n895:       \"path\": \"docs/manual/kinds/ext-container.md\",\n896:       \"bytes\": 2729,\n897:       \"lines\": 64\n898:     },\n899:     {\n900:       \"revision\": \"head\",\n901:       \"path\": \"docs/manual/kinds/f5_bigipve.md\",\n902:       \"bytes\": 8997,\n903:       \"lines\": 220\n904:     },\n905:     {\n906:       \"revision\": \"head\",\n907:       \"path\": \"docs/manual/kinds/fdio_vpp.md\",\n908:       \"bytes\": 10759,\n909:       \"lines\": 225\n910:     },\n911:     {\n912:       \"revision\": \"head\",\n913:       \"path\": \"docs/manual/kinds/fortinet_fortigate.md\",\n914:       \"bytes\": 3737,\n915:       \"lines\": 81\n916:     },\n917:     {\n918:       \"revision\": \"head\",\n919:       \"path\": \"docs/manual/kinds/freebsd.md\",\n920:       \"bytes\": 4052,\n921:       \"lines\": 95\n922:     },\n923:     {\n924:       \"revision\": \"head\",\n925:       \"path\": \"docs/manual/kinds/frr.md\",\n926:       \"bytes\": 7504,\n927:       \"lines\": 151\n928:     },\n929:     {\n930:       \"revision\": \"head\",\n931:       \"path\": \"docs/manual/kinds/generic_vm.md\",\n932:       \"bytes\": 3133,\n933:       \"lines\": 87\n934:     },\n935:     {\n936:       \"revision\": \"head\",\n937:       \"path\": \"docs/manual/kinds/host.md\",\n938:       \"bytes\": 1105,\n939:       \"lines\": 24\n940:     },\n941:     {\n942:       \"revision\": \"head\",\n943:       \"path\": \"docs/manual/kinds/huawei_vrp.md\",\n944:       \"bytes\": 4188,\n945:       \"lines\": 88\n946:     },\n947:     {\n948:       \"revision\": \"head\",\n949:       \"path\": \"docs/manual/kinds/index.md\",\n950:       \"bytes\": 8777,\n951:       \"lines\": 106\n952:     },\n953:     {\n954:       \"revision\": \"head\",\n955:       \"path\": \"docs/manual/kinds/ipinfusion-ocnos.md\",\n956:       \"bytes\": 2890,\n957:       \"lines\": 64\n958:     },\n959:     {\n960:       \"revision\": \"head\",\n961:       \"path\": \"docs/manual/kinds/k8s-kind.md\",\n962:       \"bytes\": 6322,\n963:       \"lines\": 141\n964:     },\n965:     {\n966:       \"revision\": \"head\",\n967:       \"path\": \"docs/manual/kinds/keysight_ixia-c-one.md\",\n968:       \"bytes\": 3228,\n969:       \"lines\": 68\n970:     },\n971:     {\n972:       \"revision\": \"head\",\n973:       \"path\": \"docs/manual/kinds/linux.md\",\n974:       \"bytes\": 2960,\n975:       \"lines\": 55\n976:     },\n977:     {\n978:       \"revision\": \"head\",\n979:       \"path\": \"docs/manual/kinds/mikrotik_chr.md\",\n980:       \"bytes\": 14393,\n981:       \"lines\": 212\n982:     },\n983:     {\n984:       \"revision\": \"head\",\n985:       \"path\": \"docs/manual/kinds/nvidia_cumulusvx.md\",\n986:       \"bytes\": 4019,\n987:       \"lines\": 106\n988:     },\n989:     {\n990:       \"revision\": \"head\",\n991:       \"path\": \"docs/manual/kinds/openbsd.md\",\n992:       \"bytes\": 4034,\n993:       \"lines\": 95\n994:     },\n995:     {\n996:       \"revision\": \"head\",\n997:       \"path\": \"docs/manual/kinds/openwrt.md\",\n998:       \"bytes\": 1725,\n999:       \"lines\": 37\n1000:     },\n1001:     {\n1002:       \"revision\": \"head\",\n1003:       \"path\": \"docs/manual/kinds/ostinato.md\",\n1004:       \"bytes\": 3594,\n1005:       \"lines\": 95\n1006:     },\n1007:     {\n1008:       \"revision\": \"head\",\n1009:       \"path\": \"docs/manual/kinds/ovs-bridge.md\",\n1010:       \"bytes\": 1997,\n1011:       \"lines\": 53\n1012:     },\n1013:     {\n1014:       \"revision\": \"head\",\n1015:       \"path\": \"docs/manual/kinds/plvision_sonic.md\",\n1016:       \"bytes\": 3542,\n1017:       \"lines\": 84\n1018:     },\n1019:     {\n1020:       \"revision\": \"head\",\n1021:       \"path\": \"docs/manual/kinds/rare-freertr.md\",\n1022:       \"bytes\": 6044,\n1023:       \"lines\": 170\n1024:     },\n1025:     {\n1026:       \"revision\": \"head\",\n1027:       \"path\": \"docs/manual/kinds/sonic-vm.md\",\n1028:       \"bytes\": 5902,\n1029:       \"lines\": 145\n1030:     },\n1031:     {\n1032:       \"revision\": \"head\",\n1033:       \"path\": \"docs/manual/kinds/sonic-vs.md\",\n1034:       \"bytes\": 3737,\n1035:       \"lines\": 78\n1036:     },\n1037:     {\n1038:       \"revision\": \"head\",\n1039:       \"path\": \"docs/manual/kinds/spirent_stc.md\",\n1040:       \"bytes\": 3762,\n1041:       \"lines\": 116\n1042:     },\n1043:     {\n1044:       \"revision\": \"head\",\n1045:       \"path\": \"docs/manual/kinds/srl.md\",\n1046:       \"bytes\": 26473,\n1047:       \"lines\": 587\n1048:     },\n1049:     {\n1050:       \"revision\": \"head\",\n1051:       \"path\": \"docs/manual/kinds/sros.md\",\n1052:       \"bytes\": 37049,\n1053:       \"lines\": 908\n1054:     },\n1055:     {\n1056:       \"revision\": \"head\",\n1057:       \"path\": \"docs/manual/kinds/veesix_osvbng.md\",\n1058:       \"bytes\": 3889,\n1059:       \"lines\": 124\n1060:     },\n1061:     {\n1062:       \"revision\": \"head\",\n1063:       \"path\": \"docs/manual/kinds/vr-aoscx.md\",\n1064:       \"bytes\": 3329,\n1065:       \"lines\": 73\n1066:     },\n1067:     {\n1068:       \"revision\": \"head\",\n1069:       \"path\": \"docs/manual/kinds/vr-c8000v.md\",\n1070:       \"bytes\": 6882,\n1071:       \"lines\": 188\n1072:     },\n1073:     {\n1074:       \"revision\": \"head\",\n1075:       \"path\": \"docs/manual/kinds/vr-cat9kv.md\",\n1076:       \"bytes\": 6835,\n1077:       \"lines\": 170\n1078:     },\n1079:     {\n1080:       \"revision\": \"head\",\n1081:       \"path\": \"docs/manual/kinds/vr-csr.md\",\n1082:       \"bytes\": 4119,\n1083:       \"lines\": 86\n1084:     },\n1085:     {\n1086:       \"revision\": \"head\",\n1087:       \"path\": \"docs/manual/kinds/vr-ftdv.md\",\n1088:       \"bytes\": 3343,\n1089:       \"lines\": 79\n1090:     },\n1091:     {\n1092:       \"revision\": \"head\",\n1093:       \"path\": \"docs/manual/kinds/vr-ftosv.md\",\n1094:       \"bytes\": 3557,\n1095:       \"lines\": 79\n1096:     },\n1097:     {\n1098:       \"revision\": \"head\",\n1099:       \"path\": \"docs/manual/kinds/vr-n9kv.md\",\n1100:       \"bytes\": 4790,\n1101:       \"lines\": 123\n1102:     },\n1103:     {\n1104:       \"revision\": \"head\",\n1105:       \"path\": \"docs/manual/kinds/vr-pan.md\",\n1106:       \"bytes\": 3372,\n1107:       \"lines\": 86\n1108:     },\n1109:     {\n1110:       \"revision\": \"head\",\n1111:       \"path\": \"docs/manual/kinds/vr-ros.md\",\n1112:       \"bytes\": 3912,\n1113:       \"lines\": 83\n1114:     },\n1115:     {\n1116:       \"revision\": \"head\",\n1117:       \"path\": \"docs/manual/kinds/vr-sros.md\",\n1118:       \"bytes\": 22067,\n1119:       \"lines\": 505\n1120:     },\n1121:     {\n1122:       \"revision\": \"head\",\n1123:       \"path\": \"docs/manual/kinds/vr-veos.md\",\n1124:       \"bytes\": 4126,\n1125:       \"lines\": 94\n1126:     },\n1127:     {\n1128:       \"revision\": \"head\",\n1129:       \"path\": \"docs/manual/kinds/vr-vjunosevolved.md\",\n1130:       \"bytes\": 5141,\n1131:       \"lines\": 107\n1132:     },\n1133:     {\n1134:       \"revision\": \"head\",\n1135:       \"path\": \"docs/manual/kinds/vr-vjunosrouter.md\",\n1136:       \"bytes\": 5140,\n1137:       \"lines\": 103\n1138:     },\n1139:     {\n1140:       \"revision\": \"head\",\n1141:       \"path\": \"docs/manual/kinds/vr-vjunosswitch.md\",\n1142:       \"bytes\": 5110,\n1143:       \"lines\": 108\n1144:     },\n1145:     {\n1146:       \"revision\": \"head\",\n1147:       \"path\": \"docs/manual/kinds/vr-vmx.md\",\n1148:       \"bytes\": 5371,\n1149:       \"lines\": 121\n1150:     },\n1151:     {\n1152:       \"revision\": \"head\",\n1153:       \"path\": \"docs/manual/kinds/vr-vqfx.md\",\n1154:       \"bytes\": 4053,\n1155:       \"lines\": 90\n1156:     },\n1157:     {\n1158:       \"revision\": \"head\",\n1159:       \"path\": \"docs/manual/kinds/vr-vsrx.md\",\n1160:       \"bytes\": 4053,\n1161:       \"lines\": 89\n1162:     },\n1163:     {\n1164:       \"revision\": \"head\",\n1165:       \"path\": \"docs/manual/kinds/vr-xrv.md\",\n1166:       \"bytes\": 4029,\n1167:       \"lines\": 100\n1168:     },\n1169:     {\n1170:       \"revision\": \"head\",\n1171:       \"path\": \"docs/manual/kinds/vr-xrv9k.md\",\n1172:       \"bytes\": 5157,\n1173:       \"lines\": 120\n1174:     },\n1175:     {\n1176:       \"revision\": \"head\",\n1177:       \"path\": \"docs/manual/kinds/vyosnetworks_vyos.md\",\n1178:       \"bytes\": 6643,\n1179:       \"lines\": 187\n1180:     },\n1181:     {\n1182:       \"revision\": \"head\",\n1183:       \"path\": \"docs/manual/kinds/xrd.md\",\n1184:       \"bytes\": 7951,\n1185:       \"lines\": 177\n1186:     },\n1187:     {\n1188:       \"revision\": \"head\",\n1189:       \"path\": \"docs/manual/multi-node.md\",\n1190:       \"bytes\": 6089,\n1191:       \"lines\": 72\n1192:     },\n1193:     {\n1194:       \"revision\": \"head\",\n1195:       \"path\": \"docs/manual/network.md\",\n1196:       \"bytes\": 41159,\n1197:       \"lines\": 863\n1198:     },\n1199:     {\n1200:       \"revision\": \"head\",\n1201:       \"path\": \"docs/manual/node-filtering.md\",\n1202:       \"bytes\": 3517,\n1203:       \"lines\": 66\n1204:     },\n1205:     {\n1206:       \"revision\": \"head\",\n1207:       \"path\": \"docs/manual/nodes.md\",\n1208:       \"bytes\": 44654,\n1209:       \"lines\": 1199\n1210:     },\n1211:     {\n1212:       \"revision\": \"head\",\n1213:       \"path\": \"docs/manual/s3-usage-example.md\",\n1214:       \"bytes\": 1446,\n1215:       \"lines\": 61\n1216:     },\n1217:     {\n1218:       \"revision\": \"head\",\n1219:       \"path\": \"docs/manual/share-access.md\",\n1220:       \"bytes\": 8219,\n1221:       \"lines\": 150\n1222:     },\n1223:     {\n1224:       \"revision\": \"head\",\n1225:       \"path\": \"docs/manual/topo-def-file.md\",\n1226:       \"bytes\": 38259,\n1227:       \"lines\": 910\n1228:     },\n1229:     {\n1230:       \"revision\": \"head\",\n1231:       \"path\": \"docs/manual/vrnetlab.md\",\n1232:       \"bytes\": 30862,\n1233:       \"lines\": 271\n1234:     },\n1235:     {\n1236:       \"revision\": \"head\",\n1237:       \"path\": \"docs/manual/wireshark.md\",\n1238:       \"bytes\": 16557,\n1239:       \"lines\": 332\n1240:     },\n1241:     {\n1242:       \"revision\": \"head\",\n1243:       \"path\": \"docs/quickstart.md\",\n1244:       \"bytes\": 10692,\n1245:       \"lines\": 213\n1246:     },\n1247:     {\n1248:       \"revision\": \"head\",\n1249:       \"path\": \"docs/rn/0.11.0.md\",\n1250:       \"bytes\": 5330,\n1251:       \"lines\": 71\n1252:     },\n1253:     {\n1254:       \"revision\": \"head\",\n1255:       \"path\": \"docs/rn/0.12.0.md\",\n1256:       \"bytes\": 4928,\n1257:       \"lines\": 75\n1258:     },\n1259:     {\n1260:       \"revision\": \"head\",\n1261:       \"path\": \"docs/rn/0.13.0.md\",\n1262:       \"bytes\": 1772,\n1263:       \"lines\": 30\n1264:     },\n1265:     {\n1266:       \"revision\": \"head\",\n1267:       \"path\": \"docs/rn/0.14.0.md\",\n1268:       \"bytes\": 2612,\n1269:       \"lines\": 35\n1270:     },\n1271:     {\n1272:       \"revision\": \"head\",\n1273:       \"path\": \"docs/rn/0.14.1.md\",\n1274:       \"bytes\": 177,\n1275:       \"lines\": 5\n1276:     },\n1277:     {\n1278:       \"revision\": \"head\",\n1279:       \"path\": \"docs/rn/0.14.2.md\",\n1280:       \"bytes\": 301,\n1281:       \"lines\": 5\n1282:     },\n1283:     {\n1284:       \"revision\": \"head\",\n1285:       \"path\": \"docs/rn/0.14.3.md\",\n1286:       \"bytes\": 317,\n1287:       \"lines\": 9\n1288:     },\n1289:     {\n1290:       \"revision\": \"head\",\n1291:       \"path\": \"docs/rn/0.14.4.md\",\n1292:       \"bytes\": 286,\n1293:       \"lines\": 9\n1294:     },\n1295:     {\n1296:       \"revision\": \"head\",\n1297:       \"path\": \"docs/rn/0.15.md\",\n1298:       \"bytes\": 3827,\n1299:       \"lines\": 69\n1300:     },\n1301:     {\n1302:       \"revision\": \"head\",\n1303:       \"path\": \"docs/rn/0.16.md\",\n1304:       \"bytes\": 3480,\n1305:       \"lines\": 65\n1306:     },\n1307:     {\n1308:       \"revision\": \"head\",\n1309:       \"path\": \"docs/rn/0.17.md\",\n1310:       \"bytes\": 3356,\n1311:       \"lines\": 41\n1312:     },\n1313:     {\n1314:       \"revision\": \"head\",\n1315:       \"path\": \"docs/rn/0.18.md\",\n1316:       \"bytes\": 1527,\n1317:       \"lines\": 34\n1318:     },\n1319:     {\n1320:       \"revision\": \"head\",\n1321:       \"path\": \"docs/rn/0.19.md\",\n1322:       \"bytes\": 2470,\n1323:       \"lines\": 48\n1324:     },\n1325:     {\n1326:       \"revision\": \"head\",\n1327:       \"path\": \"docs/rn/0.20.md\",\n1328:       \"bytes\": 2146,\n1329:       \"lines\": 33\n1330:     },\n1331:     {\n1332:       \"revision\": \"head\",\n1333:       \"path\": \"docs/rn/0.21.md\",\n1334:       \"bytes\": 2459,\n1335:       \"lines\": 48\n1336:     },\n1337:     {\n1338:       \"revision\": \"head\",\n1339:       \"path\": \"docs/rn/0.22.md\",\n1340:       \"bytes\": 1806,\n1341:       \"lines\": 27\n1342:     },\n1343:     {\n1344:       \"revision\": \"head\",\n1345:       \"path\": \"docs/rn/0.23.md\",\n1346:       \"bytes\": 1835,\n1347:       \"lines\": 35\n1348:     },\n1349:     {\n1350:       \"revision\": \"head\",\n1351:       \"path\": \"docs/rn/0.24.md\",\n1352:       \"bytes\": 3490,\n1353:       \"lines\": 51\n1354:     },\n1355:     {\n1356:       \"revision\": \"head\",\n1357:       \"path\": \"docs/rn/0.25.md\",\n1358:       \"bytes\": 2105,\n1359:       \"lines\": 37\n1360:     },\n1361:     {\n1362:       \"revision\": \"head\",\n1363:       \"path\": \"docs/rn/0.26.md\",\n1364:       \"bytes\": 5078,\n1365:       \"lines\": 88\n1366:     },\n1367:     {\n1368:       \"revision\": \"head\",\n1369:       \"path\": \"docs/rn/0.27.md\",\n1370:       \"bytes\": 947,\n1371:       \"lines\": 21\n1372:     },\n1373:     {\n1374:       \"revision\": \"head\",\n1375:       \"path\": \"docs/rn/0.28.md\",\n1376:       \"bytes\": 1382,\n1377:       \"lines\": 32\n1378:     },\n1379:     {\n1380:       \"revision\": \"head\",\n1381:       \"path\": \"docs/rn/0.29.md\",\n1382:       \"bytes\": 750,\n1383:       \"lines\": 13\n1384:     },\n1385:     {\n1386:       \"revision\": \"head\",\n1387:       \"path\": \"docs/rn/0.30.md\",\n1388:       \"bytes\": 566,\n1389:       \"lines\": 14\n1390:     },\n1391:     {\n1392:       \"revision\": \"head\",\n1393:       \"path\": \"docs/rn/0.31.md\",\n1394:       \"bytes\": 1710,\n1395:       \"lines\": 30\n1396:     },\n1397:     {\n1398:       \"revision\": \"head\",\n1399:       \"path\": \"docs/rn/0.32.md\",\n1400:       \"bytes\": 2075,\n1401:       \"lines\": 45\n1402:     },\n1403:     {\n1404:       \"revision\": \"head\",\n1405:       \"path\": \"docs/rn/0.33.md\",\n1406:       \"bytes\": 893,\n1407:       \"lines\": 22\n1408:     },\n1409:     {\n1410:       \"revision\": \"head\",\n1411:       \"path\": \"docs/rn/0.34.md\",\n1412:       \"bytes\": 1019,\n1413:       \"lines\": 23\n1414:     },\n1415:     {\n1416:       \"revision\": \"head\",\n1417:       \"path\": \"docs/rn/0.35.md\",\n1418:       \"bytes\": 876,\n1419:       \"lines\": 29\n1420:     },\n1421:     {\n1422:       \"revision\": \"head\",\n1423:       \"path\": \"docs/rn/0.36.md\",\n1424:       \"bytes\": 868,\n1425:       \"lines\": 23\n1426:     },\n1427:     {\n1428:       \"revision\": \"head\",\n1429:       \"path\": \"docs/rn/0.37.md\",\n1430:       \"bytes\": 1990,\n1431:       \"lines\": 38\n1432:     },\n1433:     {\n1434:       \"revision\": \"head\",\n1435:       \"path\": \"docs/rn/0.38.md\",\n1436:       \"bytes\": 881,\n1437:       \"lines\": 18\n1438:     },\n1439:     {\n1440:       \"revision\": \"head\",\n1441:       \"path\": \"docs/rn/0.39.md\",\n1442:       \"bytes\": 3693,\n1443:       \"lines\": 101\n1444:     },\n1445:     {\n1446:       \"revision\": \"head\",\n1447:       \"path\": \"docs/rn/0.40.md\",\n1448:       \"bytes\": 732,\n1449:       \"lines\": 15\n1450:     },\n1451:     {\n1452:       \"revision\": \"head\",\n1453:       \"path\": \"docs/rn/0.41.md\",\n1454:       \"bytes\": 4520,\n1455:       \"lines\": 88\n1456:     },\n1457:     {\n1458:       \"revision\": \"head\",\n1459:       \"path\": \"docs/rn/0.42.md\",\n1460:       \"bytes\": 955,\n1461:       \"lines\": 15\n1462:     },\n1463:     {\n1464:       \"revision\": \"head\",\n1465:       \"path\": \"docs/rn/0.43.md\",\n1466:       \"bytes\": 3478,\n1467:       \"lines\": 90\n1468:     },\n1469:     {\n1470:       \"revision\": \"head\",\n1471:       \"path\": \"docs/rn/0.44.md\",\n1472:       \"bytes\": 2213,\n1473:       \"lines\": 54\n1474:     },\n1475:     {\n1476:       \"revision\": \"head\",\n1477:       \"path\": \"docs/rn/0.45.md\",\n1478:       \"bytes\": 1807,\n1479:       \"lines\": 32\n1480:     },\n1481:     {\n1482:       \"revision\": \"head\",\n1483:       \"path\": \"docs/rn/0.46.md\",\n1484:       \"bytes\": 3260,\n1485:       \"lines\": 98\n1486:     },\n1487:     {\n1488:       \"revision\": \"head\",\n1489:       \"path\": \"docs/rn/0.47.md\",\n1490:       \"bytes\": 2333,\n1491:       \"lines\": 46\n1492:     },\n1493:     {\n1494:       \"revision\": \"head\",\n1495:       \"path\": \"docs/rn/0.48.md\",\n1496:       \"bytes\": 4072,\n1497:       \"lines\": 75\n1498:     },\n1499:     {\n1500:       \"revision\": \"head\",\n1501:       \"path\": \"docs/rn/0.49.md\",\n1502:       \"bytes\": 1541,\n1503:       \"lines\": 30\n1504:     },\n1505:     {\n1506:       \"revision\": \"head\",\n1507:       \"path\": \"docs/rn/0.50.md\",\n1508:       \"bytes\": 3606,\n1509:       \"lines\": 54\n1510:     },\n1511:     {\n1512:       \"revision\": \"head\",\n1513:       \"path\": \"docs/rn/0.51.md\",\n1514:       \"bytes\": 2871,\n1515:       \"lines\": 68\n1516:     },\n1517:     {\n1518:       \"revision\": \"head\",\n1519:       \"path\": \"docs/rn/0.52.md\",\n1520:       \"bytes\": 3179,\n1521:       \"lines\": 65\n1522:     },\n1523:     {\n1524:       \"revision\": \"head\",\n1525:       \"path\": \"docs/rn/0.53.md\",\n1526:       \"bytes\": 1282,\n1527:       \"lines\": 27\n1528:     },\n1529:     {\n1530:       \"revision\": \"head\",\n1531:       \"path\": \"docs/rn/0.54.md\",\n1532:       \"bytes\": 942,\n1533:       \"lines\": 26\n1534:     },\n1535:     {\n1536:       \"revision\": \"head\",\n1537:       \"path\": \"docs/rn/0.55.md\",\n1538:       \"bytes\": 3026,\n1539:       \"lines\": 77\n1540:     },\n1541:     {\n1542:       \"revision\": \"head\",\n1543:       \"path\": \"docs/rn/0.56.md\",\n1544:       \"bytes\": 2575,\n1545:       \"lines\": 46\n1546:     },\n1547:     {\n1548:       \"revision\": \"head\",\n1549:       \"path\": \"docs/rn/0.57.md\",\n1550:       \"bytes\": 2466,\n1551:       \"lines\": 56\n1552:     },\n1553:     {\n1554:       \"revision\": \"head\",\n1555:       \"path\": \"docs/rn/0.58.md\",\n1556:       \"bytes\": 1868,\n1557:       \"lines\": 30\n1558:     },\n1559:     {\n1560:       \"revision\": \"head\",\n1561:       \"path\": \"docs/rn/0.59.md\",\n1562:       \"bytes\": 1494,\n1563:       \"lines\": 34\n1564:     },\n1565:     {\n1566:       \"revision\": \"head\",\n1567:       \"path\": \"docs/rn/0.60.md\",\n1568:       \"bytes\": 10022,\n1569:       \"lines\": 135\n1570:     },\n1571:     {\n1572:       \"revision\": \"head\",\n1573:       \"path\": \"docs/rn/0.61.md\",\n1574:       \"bytes\": 2588,\n1575:       \"lines\": 45\n1576:     },\n1577:     {\n1578:       \"revision\": \"head\",\n1579:       \"path\": \"docs/rn/0.62.md\",\n1580:       \"bytes\": 2915,\n1581:       \"lines\": 54\n1582:     },\n1583:     {\n1584:       \"revision\": \"head\",\n1585:       \"path\": \"docs/rn/0.63.md\",\n1586:       \"bytes\": 2182,\n1587:       \"lines\": 46\n1588:     },\n1589:     {\n1590:       \"revision\": \"head\",\n1591:       \"path\": \"docs/rn/0.64.md\",\n1592:       \"bytes\": 5000,\n1593:       \"lines\": 45\n1594:     },\n1595:     {\n1596:       \"revision\": \"head\",\n1597:       \"path\": \"docs/rn/0.65.md\",\n1598:       \"bytes\": 1622,\n1599:       \"lines\": 41\n1600:     },\n1601:     {\n1602:       \"revision\": \"head\",\n1603:       \"path\": \"docs/rn/0.66.md\",\n1604:       \"bytes\": 897,\n1605:       \"lines\": 21\n1606:     },\n1607:     {\n1608:       \"revision\": \"head\",\n1609:       \"path\": \"docs/rn/0.67.md\",\n1610:       \"bytes\": 1394,\n1611:       \"lines\": 23\n1612:     },\n1613:     {\n1614:       \"revision\": \"head\",\n1615:       \"path\": \"docs/rn/0.68.md\",\n1616:       \"bytes\": 2604,\n1617:       \"lines\": 40\n1618:     },\n1619:     {\n1620:       \"revision\": \"head\",\n1621:       \"path\": \"docs/rn/0.69.md\",\n1622:       \"bytes\": 5732,\n1623:       \"lines\": 117\n1624:     },\n1625:     {\n1626:       \"revision\": \"head\",\n1627:       \"path\": \"docs/rn/0.70.md\",\n1628:       \"bytes\": 3389,\n1629:       \"lines\": 64\n1630:     },\n1631:     {\n1632:       \"revision\": \"head\",\n1633:       \"path\": \"docs/rn/0.71.md\",\n1634:       \"bytes\": 5144,\n1635:       \"lines\": 120\n1636:     },\n1637:     {\n1638:       \"revision\": \"head\",\n1639:       \"path\": \"docs/rn/0.72.md\",\n1640:       \"bytes\": 3663,\n1641:       \"lines\": 62\n1642:     },\n1643:     {\n1644:       \"revision\": \"head\",\n1645:       \"path\": \"docs/rn/0.73.md\",\n1646:       \"bytes\": 6239,\n1647:       \"lines\": 96\n1648:     },\n1649:     {\n1650:       \"revision\": \"head\",\n1651:       \"path\": \"docs/rn/0.74.md\",\n1652:       \"bytes\": 6031,\n1653:       \"lines\": 94\n1654:     },\n1655:     {\n1656:       \"revision\": \"head\",\n1657:       \"path\": \"docs/rn/0.75.md\",\n1658:       \"bytes\": 5768,\n1659:       \"lines\": 78\n1660:     },\n1661:     {\n1662:       \"revision\": \"head\",\n1663:       \"path\": \"docs/rn/0.76.md\",\n1664:       \"bytes\": 4557,\n1665:       \"lines\": 69\n1666:     },\n1667:     {\n1668:       \"revision\": \"head\",\n1669:       \"path\": \"docs/rn/0.77.md\",\n1670:       \"bytes\": 3761,\n1671:       \"lines\": 71\n1672:     },\n1673:     {\n1674:       \"revision\": \"head\",\n1675:       \"path\": \"docs/rn/0.78.md\",\n1676:       \"bytes\": 5580,\n1677:       \"lines\": 118\n1678:     },\n1679:     {\n1680:       \"revision\": \"head\",\n1681:       \"path\": \"docs/rn/0.79.md\",\n1682:       \"bytes\": 3853,\n1683:       \"lines\": 96\n1684:     },\n1685:     {\n1686:       \"revision\": \"head\",\n1687:       \"path\": \"docs/rn/0.80.md\",\n1688:       \"bytes\": 15226,\n1689:       \"lines\": 280\n1690:     },\n1691:     {\n1692:       \"revision\": \"head\",\n1693:       \"path\": \"docs/rn/0.81.md\",\n1694:       \"bytes\": 5387,\n1695:       \"lines\": 98\n1696:     },\n1697:     {\n1698:       \"revision\": \"head\",\n1699:       \"path\": \"docs/rn/0.82.md\",\n1700:       \"bytes\": 6005,\n1701:       \"lines\": 62\n1702:     },\n1703:     {\n1704:       \"revision\": \"head\",\n1705:       \"path\": \"docs/rn/0.83.md\",\n1706:       \"bytes\": 12864,\n1707:       \"lines\": 171\n1708:     },\n1709:     {\n1710:       \"revision\": \"head\",\n1711:       \"path\": \"docs/stylesheets/extra.css\",\n1712:       \"bytes\": 19354,\n1713:       \"lines\": 750\n1714:     },\n1715:     {\n1716:       \"revision\": \"head\",\n1717:       \"path\": \"docs/windows.md\",\n1718:       \"bytes\": 10218,\n1719:       \"lines\": 225\n1720:     },\n1721:     {\n1722:       \"revision\": \"head\",\n1723:       \"path\": \"schemas/clab.schema.json\",\n1724:       \"bytes\": 168698,\n1725:       \"lines\": 3997\n1726:     },\n1727:     {\n1728:       \"revision\": \"head\",\n1729:       \"path\": \".cursor/rules/git-mutations.mdc\",\n1730:       \"bytes\": 403,\n1731:       \"lines\": 10\n1732:     },\n1733:     {\n1734:       \"revision\": \"head\",\n1735:       \"path\": \".cursor/rules/karpathy-guidelines.mdc\",\n1736:       \"bytes\": 2643,\n1737:       \"lines\": 75\n1738:     },\n1739:     {\n1740:       \"revision\": \"head\",\n1741:       \"path\": \".cursor/rules/ponytail.mdc\",\n1742:       \"bytes\": 2620,\n1743:       \"lines\": 36\n1744:     },\n1745:     {\n1746:       \"revision\": \"head\",\n1747:       \"path\": \".cursor/rules/release-note-review.mdc\",\n1748:       \"bytes\": 472,\n1749:       \"lines\": 12\n1750:     },\n1751:     {\n1752:       \"revision\": \"head\",\n1753:       \"path\": \".cursor/skills/refresh-nix-vendor-hash/SKILL.md\",\n1754:       \"bytes\": 2916,\n1755:       \"lines\": 89\n1756:     },\n1757:     {\n1758:       \"revision\": \"head\",\n1759:       \"path\": \".devcontainer/dclab\",\n1760:       \"bytes\": 40,\n1761:       \"lines\": 2\n1762:     },\n1763:     {\n1764:       \"revision\": \"head\",\n1765:       \"path\": \".devcontainer/docker-in-docker_slim/devcontainer.json\",\n1766:       \"bytes\": 1749,\n1767:       \"lines\": 50\n1768:     },\n1769:     {\n1770:       \"revision\": \"head\",\n1771:       \"path\": \".devcontainer/docker-in-docker/devcontainer.json\",\n1772:       \"bytes\": 2351,\n1773:       \"lines\": 63\n1774:     },\n1775:     {\n1776:       \"revision\": \"head\",\n1777:       \"path\": \".devcontainer/docker-outside-of-docker_slim/devcontainer.json\",\n1778:       \"bytes\": 2004,\n1779:       \"lines\": 59\n1780:     },\n1781:     {\n1782:       \"revision\": \"head\",\n1783:       \"path\": \".devcontainer/docker-outside-of-docker/devcontainer.json\",\n1784:       \"bytes\": 2336,\n1785:       \"lines\": 69\n1786:     },\n1787:     {\n1788:       \"revision\": \"head\",\n1789:       \"path\": \".devcontainer/Dockerfile\",\n1790:       \"bytes\": 3250,\n1791:       \"lines\": 77\n1792:     },\n1793:     {\n1794:       \"revision\": \"head\",\n1795:       \"path\": \".devcontainer/slim.Dockerfile\",\n1796:       \"bytes\": 2981,\n1797:       \"lines\": 72\n1798:     },\n1799:     {\n1800:       \"revision\": \"head\",\n1801:       \"path\": \".devcontainer/starship.toml\",\n1802:       \"bytes\": 647,\n1803:       \"lines\": 38\n1804:     },\n1805:     {\n1806:       \"revision\": \"head\",\n1807:       \"path\": \".devcontainer/zsh/.zshrc\",\n1808:       \"bytes\": 4135,\n1809:       \"lines\": 121\n1810:     },\n1811:     {\n1812:       \"revision\": \"head\",\n1813:       \"path\": \".devcontainer/zsh/install-tools-completions.sh\",\n1814:       \"bytes\": 360,\n1815:       \"lines\": 12\n1816:     },\n1817:     {\n1818:       \"revision\": \"head\",\n1819:       \"path\": \".devcontainer/zsh/install-zsh-plugins.sh\",\n1820:       \"bytes\": 1139,\n1821:       \"lines\": 30\n1822:     },\n1823:     {\n1824:       \"revision\": \"head\",\n1825:       \"path\": \".gitattributes\",\n1826:       \"bytes\": 549,\n1827:       \"lines\": 13\n1828:     },\n1829:     {\n1830:       \"revision\": \"head\",\n1831:       \"path\": \".github/copilot-instructions.md\",\n1832:       \"bytes\": 1569,\n1833:       \"lines\": 30\n1834:     },\n1835:     {\n1836:       \"revision\": \"head\",\n1837:       \"path\": \".github/dependabot.yml\",\n1838:       \"bytes\": 325,\n1839:       \"lines\": 12\n1840:     },\n1841:     {\n1842:       \"revision\": \"head\",\n1843:       \"path\": \".github/vars.env\",\n1844:       \"bytes\": 41,\n1845:       \"lines\": 3\n1846:     },\n1847:     {\n1848:       \"revision\": \"head\",\n1849:       \"path\": \".github/workflows/build-binaries.yml\",\n1850:       \"bytes\": 4409,\n1851:       \"lines\": 130\n1852:     },\n1853:     {\n1854:       \"revision\": \"head\",\n1855:       \"path\": \".github/workflows/build-containerlab.yml\",\n1856:       \"bytes\": 1407,\n1857:       \"lines\": 53\n1858:     },\n1859:     {\n1860:       \"revision\": \"head\",\n1861:       \"path\": \".github/workflows/build-devcontainer.yml\",\n1862:       \"bytes\": 6157,\n1863:       \"lines\": 187\n1864:     },\n1865:     {\n1866:       \"revision\": \"head\",\n1867:       \"path\": \".github/workflows/cicd.yml\",\n1868:       \"bytes\": 24190,\n1869:       \"lines\": 783\n1870:     },\n1871:     {\n1872:       \"revision\": \"head\",\n1873:       \"path\": \".github/workflows/cisco_iol-tests.yml\",\n1874:       \"bytes\": 2579,\n1875:       \"lines\": 92\n1876:     },\n1877:     {\n1878:       \"revision\": \"head\",\n1879:       \"path\": \".github/workflows/clabernetes-tests.yml\",\n1880:       \"bytes\": 4404,\n1881:       \"lines\": 127\n1882:     },\n1883:     {\n1884:       \"revision\": \"head\",\n1885:       \"path\": \".github/workflows/comment-binaries.yml\",\n1886:       \"bytes\": 5646,\n1887:       \"lines\": 155\n1888:     },\n1889:     {\n1890:       \"revision\": \"head\",\n1891:       \"path\": \".github/workflows/cumulus-tests.yml\",\n1892:       \"bytes\": 2644,\n1893:       \"lines\": 94\n1894:     },\n1895:     {\n1896:       \"revision\": \"head\",\n1897:       \"path\": \".github/workflows/download-tests.yml\",\n1898:       \"bytes\": 2166,\n1899:       \"lines\": 81\n1900:     },\n1901:     {\n1902:       \"revision\": \"head\",\n1903:       \"path\": \".github/workflows/fdio_vpp-tests.yml\",\n1904:       \"bytes\": 2351,\n1905:       \"lines\": 85\n1906:     },\n1907:     {\n1908:       \"revision\": \"head\",\n1909:       \"path\": \".github/workflows/force-build.yml\",\n1910:       \"bytes\": 3052,\n1911:       \"lines\": 102\n1912:     },\n1913:     {\n1914:       \"revision\": \"head\",\n1915:       \"path\": \".github/workflows/fortigate-tests.yml\",\n1916:       \"bytes\": 2531,\n1917:       \"lines\": 91\n1918:     },\n1919:     {\n1920:       \"revision\": \"head\",\n1921:       \"path\": \".github/workflows/frr-tests.yml\",\n1922:       \"bytes\": 2409,\n1923:       \"lines\": 85\n1924:     },\n1925:     {\n1926:       \"revision\": \"head\",\n1927:       \"path\": \".github/workflows/golangci-lint.yml\",\n1928:       \"bytes\": 2015,\n1929:       \"lines\": 57\n1930:     },\n1931:     {\n1932:       \"revision\": \"head\",\n1933:       \"path\": \".github/workflows/install-podman.sh\",\n1934:       \"bytes\": 734,\n1935:       \"lines\": 15\n1936:     },\n1937:     {\n1938:       \"revision\": \"head\",\n1939:       \"path\": \".github/workflows/kind-tests.yml\",\n1940:       \"bytes\": 2480,\n1941:       \"lines\": 89\n1942:     },\n1943:     {\n1944:       \"revision\": \"head\",\n1945:       \"path\": \".github/workflows/mgmt-tests.yml\",\n1946:       \"bytes\": 3974,\n1947:       \"lines\": 128\n1948:     },\n1949:     {\n1950:       \"revision\": \"head\",\n1951:       \"path\": \".github/workflows/mikrotik_chr-tests.yml\",\n1952:       \"bytes\": 2475,\n1953:       \"lines\": 86\n1954:     },\n1955:     {\n1956:       \"revision\": \"head\",\n1957:       \"path\": \".github/workflows/nix.yml\",\n1958:       \"bytes\": 5756,\n1959:       \"lines\": 148\n1960:     },\n1961:     {\n1962:       \"revision\": \"head\",\n1963:       \"path\": \".github/workflows/smoke-tests.yml\",\n1964:       \"bytes\": 3392,\n1965:       \"lines\": 123\n1966:     },\n1967:     {\n1968:       \"revision\": \"head\",\n1969:       \"path\": \".github/workflows/srlinux-tests.yml\",\n1970:       \"bytes\": 2768,\n1971:       \"lines\": 93\n1972:     },\n1973:     {\n1974:       \"revision\": \"head\",\n1975:       \"path\": \".github/workflows/sros-tests.yml\",\n1976:       \"bytes\": 2259,\n1977:       \"lines\": 83\n1978:     },\n1979:     {\n1980:       \"revision\": \"head\",\n1981:       \"path\": \".github/workflows/srsim-tests.yml\",\n1982:       \"bytes\": 4465,\n1983:       \"lines\": 141\n1984:     },\n1985:     {\n1986:       \"revision\": \"head\",\n1987:       \"path\": \".github/workflows/test-srsim.yml\",\n1988:       \"bytes\": 6628,\n1989:       \"lines\": 203\n1990:     },\n1991:     {\n1992:       \"revision\": \"head\",\n1993:       \"path\": \".github/workflows/tofarev.yml\",\n1994:       \"bytes\": 1010,\n1995:       \"lines\": 24\n1996:     },\n1997:     {\n1998:       \"revision\": \"head\",\n1999:       \"path\": \".github/workflows/vxlan-tests.yml\",\n2000:       \"bytes\": 2521,\n\n(Showing lines 1-2000 of 16489. Use offset=2001 to continue.)\n</content>",
    "title": "source/manifest.json",
    "metadata": {
      "preview": "{\n  \"version\": 1,\n  \"head\": \"1c9b3577d08f7524fd228e5ab4df3dd3fc107f53\",\n  \"base\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n  \"mergeBase\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n  \"changed\": [\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/netlink.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/netlink_watch_test.go\"\n    }\n  ],\n  \"files\": [\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/events/netlink_watch_test.go\",\n      \"bytes\": 15093,",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/manifest.json",
        "text": "{\n  \"version\": 1,\n  \"head\": \"1c9b3577d08f7524fd228e5ab4df3dd3fc107f53\",\n  \"base\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n  \"mergeBase\": \"f57133d88d7f26767e78a9f4c0f81a9ed070fe8b\",\n  \"changed\": [\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/netlink.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/netlink_watch_test.go\"\n    }\n  ],\n  \"files\": [\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/events/netlink_watch_test.go\",\n      \"bytes\": 15093,\n      \"lines\": 534\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/events/netlink.go\",\n      \"bytes\": 32781,\n      \"lines\": 1390\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/capture.md\",\n      \"bytes\": 7769,\n      \"lines\": 134\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/completion.md\",\n      \"bytes\": 2336,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/deploy.md\",\n      \"bytes\": 31381,\n      \"lines\": 565\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/destroy.md\",\n      \"bytes\": 3762,\n      \"lines\": 100\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/events.md\",\n      \"bytes\": 6764,\n      \"lines\": 99\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/exec.md\",\n      \"bytes\": 7316,\n      \"lines\": 177\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/generate.md\",\n      \"bytes\": 6005,\n      \"lines\": 138\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/graph.md\",\n      \"bytes\": 8242,\n      \"lines\": 192\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/inspect/index.md\",\n      \"bytes\": 11106,\n      \"lines\": 179\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/inspect/interfaces.md\",\n      \"bytes\": 11855,\n      \"lines\": 199\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/logs.md\",\n      \"bytes\": 1836,\n      \"lines\": 57\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/redeploy.md\",\n      \"bytes\": 6085,\n      \"lines\": 150\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/restart.md\",\n      \"bytes\": 1432,\n      \"lines\": 64\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/save.md\",\n      \"bytes\": 6445,\n      \"lines\": 133\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/start.md\",\n      \"bytes\": 2251,\n      \"lines\": 76\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/stop.md\",\n      \"bytes\": 1313,\n      \"lines\": 62\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/api-server/start.md\",\n      \"bytes\": 5581,\n      \"lines\": 165\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/api-server/status.md\",\n      \"bytes\": 4223,\n      \"lines\": 105\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/api-server/stop.md\",\n      \"bytes\": 1836,\n      \"lines\": 56\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/cert/ca/create.md\",\n      \"bytes\": 2206,\n      \"lines\": 77\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/cert/sign.md\",\n      \"bytes\": 2428,\n      \"lines\": 79\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/disable-tx-offload.md\",\n      \"bytes\": 982,\n      \"lines\": 25\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/gotty/attach.md\",\n      \"bytes\": 1904,\n      \"lines\": 67\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/gotty/detach.md\",\n      \"bytes\": 627,\n      \"lines\": 29\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/gotty/list.md\",\n      \"bytes\": 1070,\n      \"lines\": 46\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/gotty/reattach.md\",\n      \"bytes\": 955,\n      \"lines\": 26\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/netem/reset.md\",\n      \"bytes\": 1635,\n      \"lines\": 63\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/netem/set.md\",\n      \"bytes\": 3979,\n      \"lines\": 114\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/netem/show.md\",\n      \"bytes\": 3651,\n      \"lines\": 150\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/snapshot/save.md\",\n      \"bytes\": 1647,\n      \"lines\": 75\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/sshx/attach.md\",\n      \"bytes\": 5194,\n      \"lines\": 128\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/sshx/detach.md\",\n      \"bytes\": 1837,\n      \"lines\": 46\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/sshx/list.md\",\n      \"bytes\": 3662,\n      \"lines\": 77\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/sshx/reattach.md\",\n      \"bytes\": 4593,\n      \"lines\": 101\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/veth/create.md\",\n      \"bytes\": 1890,\n      \"lines\": 51\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/vxlan/create.md\",\n      \"bytes\": 3355,\n      \"lines\": 73\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/tools/vxlan/delete.md\",\n      \"bytes\": 1230,\n      \"lines\": 31\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/validate.md\",\n      \"bytes\": 1785,\n      \"lines\": 51\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/version/check.md\",\n      \"bytes\": 537,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/version/index.md\",\n      \"bytes\": 1011,\n      \"lines\": 37\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/CNAME\",\n      \"bytes\": 16,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/community.md\",\n      \"bytes\": 26611,\n      \"lines\": 360\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/htmltest-pr.yml\",\n      \"bytes\": 678,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/htmltest-w-github.yml\",\n      \"bytes\": 1679,\n      \"lines\": 31\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/htmltest.yml\",\n      \"bytes\": 2429,\n      \"lines\": 49\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/clabnew.svg\",\n      \"bytes\": 16299,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/coloured_wordmark.svg\",\n      \"bytes\": 8031,\n      \"lines\": 91\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/containerlab_dark_no_text.svg\",\n      \"bytes\": 3589,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/containerlab_export.svg\",\n      \"bytes\": 8893,\n      \"lines\": 33\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/containerlab_full_white_no_text.svg\",\n      \"bytes\": 3801,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/containerlab_white_no_text.svg\",\n      \"bytes\": 3293,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/containerlab-animated-wordmark.svg\",\n      \"bytes\": 70018,\n      \"lines\": 52\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/favicon.svg\",\n      \"bytes\": 16378,\n      \"lines\": 20\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/flask.svg\",\n      \"bytes\": 378,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/gui/browser-sandbox-placeholder.svg\",\n      \"bytes\": 2220,\n      \"lines\": 25\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/client.svg\",\n      \"bytes\": 633,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/controller.svg\",\n      \"bytes\": 768,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/dcgw.svg\",\n      \"bytes\": 1015,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/pon.svg\",\n      \"bytes\": 553,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/rgw.svg\",\n      \"bytes\": 983,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/router.svg\",\n      \"bytes\": 864,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/server.svg\",\n      \"bytes\": 744,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/spine.svg\",\n      \"bytes\": 940,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/images/topoviewer-icons/switch.svg\",\n      \"bytes\": 803,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/index.md\",\n      \"bytes\": 6778,\n      \"lines\": 189\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/install.md\",\n      \"bytes\": 18001,\n      \"lines\": 521\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/javascripts/instant-reinit.js\",\n      \"bytes\": 2040,\n      \"lines\": 45\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/asav01.md\",\n      \"bytes\": 4137,\n      \"lines\": 90\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/bgp-vpls-nok-jun.md\",\n      \"bytes\": 3374,\n      \"lines\": 34\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/cisco_iol.md\",\n      \"bytes\": 4368,\n      \"lines\": 100\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/cvx01.md\",\n      \"bytes\": 2989,\n      \"lines\": 48\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/cvx02.md\",\n      \"bytes\": 2936,\n      \"lines\": 49\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/ext-bridge.md\",\n      \"bytes\": 2042,\n      \"lines\": 31\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/f5bigipve01.md\",\n      \"bytes\": 4956,\n      \"lines\": 118\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/freebsd01.md\",\n      \"bytes\": 3571,\n      \"lines\": 76\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/frr01.md\",\n      \"bytes\": 2987,\n      \"lines\": 64\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/ftdv01.md\",\n      \"bytes\": 4108,\n      \"lines\": 75\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/generic_vm01.md\",\n      \"bytes\": 3201,\n      \"lines\": 66\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/ixiacone-srl.md\",\n      \"bytes\": 6827,\n      \"lines\": 135\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/lab-examples.md\",\n      \"bytes\": 4334,\n      \"lines\": 80\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/min-5clos.md\",\n      \"bytes\": 9340,\n      \"lines\": 127\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/min-clos.md\",\n      \"bytes\": 1970,\n      \"lines\": 26\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/multinode.md\",\n      \"bytes\": 14610,\n      \"lines\": 264\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/openbsd01.md\",\n      \"bytes\": 3615,\n      \"lines\": 76\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/ost-srl.md\",\n      \"bytes\": 6005,\n      \"lines\": 114\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/osvbng01.md\",\n      \"bytes\": 3109,\n      \"lines\": 71\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/peering-lab.md\",\n      \"bytes\": 23285,\n      \"lines\": 391\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/rare-freertr.md\",\n      \"bytes\": 1848,\n      \"lines\": 31\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/single-srl.md\",\n      \"bytes\": 2261,\n      \"lines\": 32\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/sr-sim.md\",\n      \"bytes\": 3766,\n      \"lines\": 64\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-arcos.md\",\n      \"bytes\": 2871,\n      \"lines\": 52\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-ceos.md\",\n      \"bytes\": 8462,\n      \"lines\": 211\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-cjunosevolved.md\",\n      \"bytes\": 2674,\n      \"lines\": 43\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-crpd.md\",\n      \"bytes\": 9443,\n      \"lines\": 181\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-frr.md\",\n      \"bytes\": 3163,\n      \"lines\": 33\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-sonic.md\",\n      \"bytes\": 9521,\n      \"lines\": 193\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-vjunos-switch.md\",\n      \"bytes\": 1886,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-vjunosevolved.md\",\n      \"bytes\": 1891,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/srl-xrd.md\",\n      \"bytes\": 2877,\n      \"lines\": 49\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/templated01.md\",\n      \"bytes\": 2516,\n      \"lines\": 56\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/templated02.md\",\n      \"bytes\": 2792,\n      \"lines\": 68\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/two-srls.md\",\n      \"bytes\": 3098,\n      \"lines\": 47\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/vr-sros.md\",\n      \"bytes\": 2506,\n      \"lines\": 28\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/vr-vmx.md\",\n      \"bytes\": 2523,\n      \"lines\": 30\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/vr-xrv.md\",\n      \"bytes\": 2419,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/vr-xrv9k.md\",\n      \"bytes\": 2441,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/vsrx01.md\",\n      \"bytes\": 4497,\n      \"lines\": 90\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/lab-examples/wan.md\",\n      \"bytes\": 1820,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/macos.md\",\n      \"bytes\": 17237,\n      \"lines\": 251\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/api-server.md\",\n      \"bytes\": 7871,\n      \"lines\": 223\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/cert.md\",\n      \"bytes\": 3472,\n      \"lines\": 59\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/clabernetes/index.md\",\n      \"bytes\": 990,\n      \"lines\": 18\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/clabernetes/runtime.md\",\n      \"bytes\": 60226,\n      \"lines\": 1421\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/codespaces.md\",\n      \"bytes\": 20644,\n      \"lines\": 318\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/conf-artifacts.md\",\n      \"bytes\": 3196,\n      \"lines\": 54\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/config-mgmt.md\",\n      \"bytes\": 12920,\n      \"lines\": 311\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/dev/debug.md\",\n      \"bytes\": 5255,\n      \"lines\": 133\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/dev/doc.md\",\n      \"bytes\": 4366,\n      \"lines\": 55\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/dev/index.md\",\n      \"bytes\": 1170,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/dev/test.md\",\n      \"bytes\": 4069,\n      \"lines\": 100\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/gui/desktop.md\",\n      \"bytes\": 5381,\n      \"lines\": 130\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/gui/index.md\",\n      \"bytes\": 16398,\n      \"lines\": 314\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/gui/vsc-extension.md\",\n      \"bytes\": 9060,\n      \"lines\": 202\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/gui/web.md\",\n      \"bytes\": 6617,\n      \"lines\": 178\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/images.md\",\n      \"bytes\": 5119,\n      \"lines\": 108\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/impairments.md\",\n      \"bytes\": 881,\n      \"lines\": 20\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/inventory.md\",\n      \"bytes\": 11726,\n      \"lines\": 398\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/6wind_vsr.md\",\n      \"bytes\": 9464,\n      \"lines\": 208\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/ale_vaos.md\",\n      \"bytes\": 3188,\n      \"lines\": 74\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/arrcus_arcos.md\",\n      \"bytes\": 4185,\n      \"lines\": 134\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/bridge.md\",\n      \"bytes\": 5527,\n      \"lines\": 123\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/c8000.md\",\n      \"bytes\": 5477,\n      \"lines\": 151\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/ceos.md\",\n      \"bytes\": 22395,\n      \"lines\": 548\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/checkpoint_cloudguard.md\",\n      \"bytes\": 2694,\n      \"lines\": 60\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/ciena_saos.md\",\n      \"bytes\": 8268,\n      \"lines\": 244\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/cisco_asav.md\",\n      \"bytes\": 4142,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/cisco_iol.md\",\n      \"bytes\": 11889,\n      \"lines\": 269\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/cisco_sdwan.md\",\n      \"bytes\": 6415,\n      \"lines\": 280\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/cisco_vios.md\",\n      \"bytes\": 3734,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/cisco_xrd_vrouter.md\",\n      \"bytes\": 5916,\n      \"lines\": 139\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/cjunosevolved.md\",\n      \"bytes\": 7017,\n      \"lines\": 150\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/crpd.md\",\n      \"bytes\": 8048,\n      \"lines\": 191\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/csrx.md\",\n      \"bytes\": 6460,\n      \"lines\": 176\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/dell_sonic.md\",\n      \"bytes\": 3575,\n      \"lines\": 96\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/ext-container.md\",\n      \"bytes\": 2729,\n      \"lines\": 64\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/f5_bigipve.md\",\n      \"bytes\": 8997,\n      \"lines\": 220\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/fdio_vpp.md\",\n      \"bytes\": 10759,\n      \"lines\": 225\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/fortinet_fortigate.md\",\n      \"bytes\": 3737,\n      \"lines\": 81\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/freebsd.md\",\n      \"bytes\": 4052,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/frr.md\",\n      \"bytes\": 7504,\n      \"lines\": 151\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/generic_vm.md\",\n      \"bytes\": 3133,\n      \"lines\": 87\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/host.md\",\n      \"bytes\": 1105,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/huawei_vrp.md\",\n      \"bytes\": 4188,\n      \"lines\": 88\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/index.md\",\n      \"bytes\": 8777,\n      \"lines\": 106\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/ipinfusion-ocnos.md\",\n      \"bytes\": 2890,\n      \"lines\": 64\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/k8s-kind.md\",\n      \"bytes\": 6322,\n      \"lines\": 141\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/keysight_ixia-c-one.md\",\n      \"bytes\": 3228,\n      \"lines\": 68\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/linux.md\",\n      \"bytes\": 2960,\n      \"lines\": 55\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/mikrotik_chr.md\",\n      \"bytes\": 14393,\n      \"lines\": 212\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/nvidia_cumulusvx.md\",\n      \"bytes\": 4019,\n      \"lines\": 106\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/openbsd.md\",\n      \"bytes\": 4034,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/openwrt.md\",\n      \"bytes\": 1725,\n      \"lines\": 37\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/ostinato.md\",\n      \"bytes\": 3594,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/ovs-bridge.md\",\n      \"bytes\": 1997,\n      \"lines\": 53\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/plvision_sonic.md\",\n      \"bytes\": 3542,\n      \"lines\": 84\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/rare-freertr.md\",\n      \"bytes\": 6044,\n      \"lines\": 170\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/sonic-vm.md\",\n      \"bytes\": 5902,\n      \"lines\": 145\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/sonic-vs.md\",\n      \"bytes\": 3737,\n      \"lines\": 78\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/spirent_stc.md\",\n      \"bytes\": 3762,\n      \"lines\": 116\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/srl.md\",\n      \"bytes\": 26473,\n      \"lines\": 587\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/sros.md\",\n      \"bytes\": 37049,\n      \"lines\": 908\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/veesix_osvbng.md\",\n      \"bytes\": 3889,\n      \"lines\": 124\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-aoscx.md\",\n      \"bytes\": 3329,\n      \"lines\": 73\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-c8000v.md\",\n      \"bytes\": 6882,\n      \"lines\": 188\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-cat9kv.md\",\n      \"bytes\": 6835,\n      \"lines\": 170\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-csr.md\",\n      \"bytes\": 4119,\n      \"lines\": 86\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-ftdv.md\",\n      \"bytes\": 3343,\n      \"lines\": 79\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-ftosv.md\",\n      \"bytes\": 3557,\n      \"lines\": 79\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-n9kv.md\",\n      \"bytes\": 4790,\n      \"lines\": 123\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-pan.md\",\n      \"bytes\": 3372,\n      \"lines\": 86\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-ros.md\",\n      \"bytes\": 3912,\n      \"lines\": 83\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-sros.md\",\n      \"bytes\": 22067,\n      \"lines\": 505\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-veos.md\",\n      \"bytes\": 4126,\n      \"lines\": 94\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-vjunosevolved.md\",\n      \"bytes\": 5141,\n      \"lines\": 107\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-vjunosrouter.md\",\n      \"bytes\": 5140,\n      \"lines\": 103\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-vjunosswitch.md\",\n      \"bytes\": 5110,\n      \"lines\": 108\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-vmx.md\",\n      \"bytes\": 5371,\n      \"lines\": 121\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-vqfx.md\",\n      \"bytes\": 4053,\n      \"lines\": 90\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-vsrx.md\",\n      \"bytes\": 4053,\n      \"lines\": 89\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-xrv.md\",\n      \"bytes\": 4029,\n      \"lines\": 100\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vr-xrv9k.md\",\n      \"bytes\": 5157,\n      \"lines\": 120\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/vyosnetworks_vyos.md\",\n      \"bytes\": 6643,\n      \"lines\": 187\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/kinds/xrd.md\",\n      \"bytes\": 7951,\n      \"lines\": 177\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/multi-node.md\",\n      \"bytes\": 6089,\n      \"lines\": 72\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/network.md\",\n      \"bytes\": 41159,\n      \"lines\": 863\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/node-filtering.md\",\n      \"bytes\": 3517,\n      \"lines\": 66\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/nodes.md\",\n      \"bytes\": 44654,\n      \"lines\": 1199\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/s3-usage-example.md\",\n      \"bytes\": 1446,\n      \"lines\": 61\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/share-access.md\",\n      \"bytes\": 8219,\n      \"lines\": 150\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/topo-def-file.md\",\n      \"bytes\": 38259,\n      \"lines\": 910\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/vrnetlab.md\",\n      \"bytes\": 30862,\n      \"lines\": 271\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/manual/wireshark.md\",\n      \"bytes\": 16557,\n      \"lines\": 332\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/quickstart.md\",\n      \"bytes\": 10692,\n      \"lines\": 213\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.11.0.md\",\n      \"bytes\": 5330,\n      \"lines\": 71\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.12.0.md\",\n      \"bytes\": 4928,\n      \"lines\": 75\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.13.0.md\",\n      \"bytes\": 1772,\n      \"lines\": 30\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.14.0.md\",\n      \"bytes\": 2612,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.14.1.md\",\n      \"bytes\": 177,\n      \"lines\": 5\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.14.2.md\",\n      \"bytes\": 301,\n      \"lines\": 5\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.14.3.md\",\n      \"bytes\": 317,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.14.4.md\",\n      \"bytes\": 286,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.15.md\",\n      \"bytes\": 3827,\n      \"lines\": 69\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.16.md\",\n      \"bytes\": 3480,\n      \"lines\": 65\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.17.md\",\n      \"bytes\": 3356,\n      \"lines\": 41\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.18.md\",\n      \"bytes\": 1527,\n      \"lines\": 34\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.19.md\",\n      \"bytes\": 2470,\n      \"lines\": 48\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.20.md\",\n      \"bytes\": 2146,\n      \"lines\": 33\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.21.md\",\n      \"bytes\": 2459,\n      \"lines\": 48\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.22.md\",\n      \"bytes\": 1806,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.23.md\",\n      \"bytes\": 1835,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.24.md\",\n      \"bytes\": 3490,\n      \"lines\": 51\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.25.md\",\n      \"bytes\": 2105,\n      \"lines\": 37\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.26.md\",\n      \"bytes\": 5078,\n      \"lines\": 88\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.27.md\",\n      \"bytes\": 947,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.28.md\",\n      \"bytes\": 1382,\n      \"lines\": 32\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.29.md\",\n      \"bytes\": 750,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.30.md\",\n      \"bytes\": 566,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.31.md\",\n      \"bytes\": 1710,\n      \"lines\": 30\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.32.md\",\n      \"bytes\": 2075,\n      \"lines\": 45\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.33.md\",\n      \"bytes\": 893,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.34.md\",\n      \"bytes\": 1019,\n      \"lines\": 23\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.35.md\",\n      \"bytes\": 876,\n      \"lines\": 29\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.36.md\",\n      \"bytes\": 868,\n      \"lines\": 23\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.37.md\",\n      \"bytes\": 1990,\n      \"lines\": 38\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.38.md\",\n      \"bytes\": 881,\n      \"lines\": 18\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.39.md\",\n      \"bytes\": 3693,\n      \"lines\": 101\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.40.md\",\n      \"bytes\": 732,\n      \"lines\": 15\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.41.md\",\n      \"bytes\": 4520,\n      \"lines\": 88\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.42.md\",\n      \"bytes\": 955,\n      \"lines\": 15\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.43.md\",\n      \"bytes\": 3478,\n      \"lines\": 90\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.44.md\",\n      \"bytes\": 2213,\n      \"lines\": 54\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.45.md\",\n      \"bytes\": 1807,\n      \"lines\": 32\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.46.md\",\n      \"bytes\": 3260,\n      \"lines\": 98\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.47.md\",\n      \"bytes\": 2333,\n      \"lines\": 46\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.48.md\",\n      \"bytes\": 4072,\n      \"lines\": 75\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.49.md\",\n      \"bytes\": 1541,\n      \"lines\": 30\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.50.md\",\n      \"bytes\": 3606,\n      \"lines\": 54\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.51.md\",\n      \"bytes\": 2871,\n      \"lines\": 68\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.52.md\",\n      \"bytes\": 3179,\n      \"lines\": 65\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.53.md\",\n      \"bytes\": 1282,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.54.md\",\n      \"bytes\": 942,\n      \"lines\": 26\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.55.md\",\n      \"bytes\": 3026,\n      \"lines\": 77\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.56.md\",\n      \"bytes\": 2575,\n      \"lines\": 46\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.57.md\",\n      \"bytes\": 2466,\n      \"lines\": 56\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.58.md\",\n      \"bytes\": 1868,\n      \"lines\": 30\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.59.md\",\n      \"bytes\": 1494,\n      \"lines\": 34\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.60.md\",\n      \"bytes\": 10022,\n      \"lines\": 135\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.61.md\",\n      \"bytes\": 2588,\n      \"lines\": 45\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.62.md\",\n      \"bytes\": 2915,\n      \"lines\": 54\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.63.md\",\n      \"bytes\": 2182,\n      \"lines\": 46\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.64.md\",\n      \"bytes\": 5000,\n      \"lines\": 45\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.65.md\",\n      \"bytes\": 1622,\n      \"lines\": 41\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.66.md\",\n      \"bytes\": 897,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.67.md\",\n      \"bytes\": 1394,\n      \"lines\": 23\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.68.md\",\n      \"bytes\": 2604,\n      \"lines\": 40\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.69.md\",\n      \"bytes\": 5732,\n      \"lines\": 117\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.70.md\",\n      \"bytes\": 3389,\n      \"lines\": 64\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.71.md\",\n      \"bytes\": 5144,\n      \"lines\": 120\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.72.md\",\n      \"bytes\": 3663,\n      \"lines\": 62\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.73.md\",\n      \"bytes\": 6239,\n      \"lines\": 96\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.74.md\",\n      \"bytes\": 6031,\n      \"lines\": 94\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.75.md\",\n      \"bytes\": 5768,\n      \"lines\": 78\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.76.md\",\n      \"bytes\": 4557,\n      \"lines\": 69\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.77.md\",\n      \"bytes\": 3761,\n      \"lines\": 71\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.78.md\",\n      \"bytes\": 5580,\n      \"lines\": 118\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.79.md\",\n      \"bytes\": 3853,\n      \"lines\": 96\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.80.md\",\n      \"bytes\": 15226,\n      \"lines\": 280\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.81.md\",\n      \"bytes\": 5387,\n      \"lines\": 98\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.82.md\",\n      \"bytes\": 6005,\n      \"lines\": 62\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/rn/0.83.md\",\n      \"bytes\": 12864,\n      \"lines\": 171\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/stylesheets/extra.css\",\n      \"bytes\": 19354,\n      \"lines\": 750\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/windows.md\",\n      \"bytes\": 10218,\n      \"lines\": 225\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"schemas/clab.schema.json\",\n      \"bytes\": 168698,\n      \"lines\": 3997\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".cursor/rules/git-mutations.mdc\",\n      \"bytes\": 403,\n      \"lines\": 10\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".cursor/rules/karpathy-guidelines.mdc\",\n      \"bytes\": 2643,\n      \"lines\": 75\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".cursor/rules/ponytail.mdc\",\n      \"bytes\": 2620,\n      \"lines\": 36\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".cursor/rules/release-note-review.mdc\",\n      \"bytes\": 472,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".cursor/skills/refresh-nix-vendor-hash/SKILL.md\",\n      \"bytes\": 2916,\n      \"lines\": 89\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/dclab\",\n      \"bytes\": 40,\n      \"lines\": 2\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/docker-in-docker_slim/devcontainer.json\",\n      \"bytes\": 1749,\n      \"lines\": 50\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/docker-in-docker/devcontainer.json\",\n      \"bytes\": 2351,\n      \"lines\": 63\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/docker-outside-of-docker_slim/devcontainer.json\",\n      \"bytes\": 2004,\n      \"lines\": 59\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/docker-outside-of-docker/devcontainer.json\",\n      \"bytes\": 2336,\n      \"lines\": 69\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/Dockerfile\",\n      \"bytes\": 3250,\n      \"lines\": 77\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/slim.Dockerfile\",\n      \"bytes\": 2981,\n      \"lines\": 72\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/starship.toml\",\n      \"bytes\": 647,\n      \"lines\": 38\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/zsh/.zshrc\",\n      \"bytes\": 4135,\n      \"lines\": 121\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/zsh/install-tools-completions.sh\",\n      \"bytes\": 360,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".devcontainer/zsh/install-zsh-plugins.sh\",\n      \"bytes\": 1139,\n      \"lines\": 30\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".gitattributes\",\n      \"bytes\": 549,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/copilot-instructions.md\",\n      \"bytes\": 1569,\n      \"lines\": 30\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/dependabot.yml\",\n      \"bytes\": 325,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/vars.env\",\n      \"bytes\": 41,\n      \"lines\": 3\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/build-binaries.yml\",\n      \"bytes\": 4409,\n      \"lines\": 130\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/build-containerlab.yml\",\n      \"bytes\": 1407,\n      \"lines\": 53\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/build-devcontainer.yml\",\n      \"bytes\": 6157,\n      \"lines\": 187\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/cicd.yml\",\n      \"bytes\": 24190,\n      \"lines\": 783\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/cisco_iol-tests.yml\",\n      \"bytes\": 2579,\n      \"lines\": 92\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/clabernetes-tests.yml\",\n      \"bytes\": 4404,\n      \"lines\": 127\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/comment-binaries.yml\",\n      \"bytes\": 5646,\n      \"lines\": 155\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/cumulus-tests.yml\",\n      \"bytes\": 2644,\n      \"lines\": 94\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/download-tests.yml\",\n      \"bytes\": 2166,\n      \"lines\": 81\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/fdio_vpp-tests.yml\",\n      \"bytes\": 2351,\n      \"lines\": 85\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/force-build.yml\",\n      \"bytes\": 3052,\n      \"lines\": 102\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/fortigate-tests.yml\",\n      \"bytes\": 2531,\n      \"lines\": 91\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/frr-tests.yml\",\n      \"bytes\": 2409,\n      \"lines\": 85\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/golangci-lint.yml\",\n      \"bytes\": 2015,\n      \"lines\": 57\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/install-podman.sh\",\n      \"bytes\": 734,\n      \"lines\": 15\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/kind-tests.yml\",\n      \"bytes\": 2480,\n      \"lines\": 89\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/mgmt-tests.yml\",\n      \"bytes\": 3974,\n      \"lines\": 128\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/mikrotik_chr-tests.yml\",\n      \"bytes\": 2475,\n      \"lines\": 86\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/nix.yml\",\n      \"bytes\": 5756,\n      \"lines\": 148\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/smoke-tests.yml\",\n      \"bytes\": 3392,\n      \"lines\": 123\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/srlinux-tests.yml\",\n      \"bytes\": 2768,\n      \"lines\": 93\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/sros-tests.yml\",\n      \"bytes\": 2259,\n      \"lines\": 83\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/srsim-tests.yml\",\n      \"bytes\": 4465,\n      \"lines\": 141\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/test-srsim.yml\",\n      \"bytes\": 6628,\n      \"lines\": 203\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/tofarev.yml\",\n      \"bytes\": 1010,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/vxlan-tests.yml\",\n      \"bytes\": 2521,",
        "lineStart": 1,
        "lineEnd": 2000,
        "totalLines": 16489,
        "truncated": true
      }
    },
    "time": {
      "start": 1794565130257,
      "end": 1794565130314
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/events/netlink_watch_test.go"
}

Output

<path>/source/head/core/events/netlink_watch_test.go</path>
<type>file</type>
<content>
1: package events
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"os"
8: 	"runtime"
9: 	"slices"
10: 	"sync"
11: 	"testing"
12: 	"time"
13: 
14: 	"github.com/srl-labs/containerlab/mocks/mockruntime"
15: 	clabruntime "github.com/srl-labs/containerlab/runtime"
16: 	"github.com/vishvananda/netlink"
17: 	"github.com/vishvananda/netns"
18: 	"go.uber.org/mock/gomock"
19: 	"golang.org/x/sys/unix"
20: )
21: 
22: // eventLog collects the interface events of a registry by interface name.
23: type eventLog struct {
24: 	mu      sync.Mutex
25: 	actions map[string][]string
26: }
27: 
28: func collectEvents(ctx context.Context, events <-chan aggregatedEvent) *eventLog {
29: 	l := &eventLog{actions: map[string][]string{}}
30: 
31: 	go func() {
32: 		for {
33: 			select {
34: 			case ev := <-events:
35: 				l.mu.Lock()
36: 				name := ev.Attributes["ifname"]
37: 				l.actions[name] = append(l.actions[name], ev.Action)
38: 				l.mu.Unlock()
39: 			case <-ctx.Done():
40: 				return
41: 			}
42: 		}
43: 	}()
44: 
45: 	return l
46: }
47: 
48: func (l *eventLog) get(name string) []string {
49: 	l.mu.Lock()
50: 	defer l.mu.Unlock()
51: 
52: 	return slices.Clone(l.actions[name])
53: }
54: 
55: // waitFor waits until every name has an event with one of the actions.
56: func (l *eventLog) waitFor(t *testing.T, names []string, actions ...string) {
57: 	t.Helper()
58: 
59: 	deadline := time.Now().Add(3 * time.Second)
60: 	for {
61: 		var missing []string
62: 		for _, name := range names {
63: 			if !slices.ContainsFunc(l.get(name), func(a string) bool {
64: 				return slices.Contains(actions, a)
65: 			}) {
66: 				missing = append(missing, name)
67: 			}
68: 		}
69: 
70: 		if len(missing) == 0 {
71: 			return
72: 		}
73: 
74: 		if time.Now().After(deadline) {
75: 			t.Fatalf("no %v event for %v", actions, missing)
76: 		}
77: 
78: 		time.Sleep(10 * time.Millisecond)
79: 	}
80: }
81: 
82: // newTestNetns creates a named network namespace without leaving the
83: // current thread in it.
84: func newTestNetns(t *testing.T) (string, *netlink.Handle) {
85: 	t.Helper()
86: 
87: 	if os.Geteuid() != 0 {
88: 		t.Skip("requires root to create network namespaces")
89: 	}
90: 
91: 	runtime.LockOSThread()
92: 	defer runtime.UnlockOSThread()
93: 
94: 	orig, err := netns.Get()
95: 	if err != nil {
96: 		t.Fatalf("failed to get current netns: %v", err)
97: 	}
98: 	defer orig.Close()
99: 
100: 	name := fmt.Sprintf("clabtst-ev-%d-%d", os.Getpid(), time.Now().UnixNano())
101: 
102: 	ns, err := netns.NewNamed(name)
103: 	if err != nil {
104: 		t.Fatalf("failed to create netns: %v", err)
105: 	}
106: 
107: 	if err := netns.Set(orig); err != nil {
108: 		t.Fatalf("failed to return to the original netns: %v", err)
109: 	}
110: 
111: 	handle, err := netlink.NewHandleAt(ns)
112: 	if err != nil {
113: 		t.Fatalf("failed to create netlink handle: %v", err)
114: 	}
115: 
116: 	t.Cleanup(func() {
117: 		handle.Close()
118: 		ns.Close()
119: 		_ = netns.DeleteNamed(name)
120: 	})
121: 
122: 	return "/run/netns/" + name, handle
123: }
124: 
125: func addDummy(t *testing.T, handle *netlink.Handle, name string) {
126: 	t.Helper()
127: 
128: 	err := handle.LinkAdd(&netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: name}})
129: 	if err != nil {
130: 		t.Errorf("failed to add %s: %v", name, err)
131: 	}
132: }
133: 
134: func newTestContainer(
135: 	t *testing.T,
136: 	getNSPath func() (string, error),
137: ) *clabruntime.GenericContainer {
138: 	t.Helper()
139: 
140: 	rt := mockruntime.NewMockContainerRuntime(gomock.NewController(t))
141: 	rt.EXPECT().GetNSPath(gomock.Any(), gomock.Any()).DoAndReturn(
142: 		func(context.Context, string) (string, error) { return getNSPath() },
143: 	).AnyTimes()
144: 
145: 	container := &clabruntime.GenericContainer{
146: 		ID:      "0123456789abcdef",
147: 		ShortID: "0123456789ab",
148: 		Names:   []string{"clab-test-n1"},
149: 	}
150: 	container.SetRuntime(rt)
151: 
152: 	return container
153: }
154: 
155: func startRegistry(
156: 	t *testing.T,
157: 	container *clabruntime.GenericContainer,
158: ) (*netlinkRegistry, *eventLog) {
159: 	t.Helper()
160: 
161: 	ctx, cancel := context.WithCancel(context.Background())
162: 	events := make(chan aggregatedEvent, 1024)
163: 	registry := newNetlinkRegistry(ctx, events, true, false, 0)
164: 	collected := collectEvents(ctx, events)
165: 
166: 	registry.Start(container)
167: 	t.Cleanup(func() {
168: 		registry.Stop(container.ID)
169: 		cancel()
170: 	})
171: 
172: 	return registry, collected
173: }
174: 
175: // TestNetlinkWatcherReportsExistingAndNewLinks checks that links present at
176: // subscription are reported as snapshots and later ones as created or deleted.
177: func TestNetlinkWatcherReportsExistingAndNewLinks(t *testing.T) {
178: 	nsPath, handle := newTestNetns(t)
179: 	addDummy(t, handle, "early0")
180: 
181: 	container := newTestContainer(t, func() (string, error) { return nsPath, nil })
182: 	_, events := startRegistry(t, container)
183: 
184: 	events.waitFor(t, []string{"lo", "early0"}, "snapshot")
185: 
186: 	addDummy(t, handle, "late0")
187: 	events.waitFor(t, []string{"late0"}, "create")
188: 
189: 	link, err := handle.LinkByName("late0")
190: 	if err != nil {
191: 		t.Fatalf("failed to find late0: %v", err)
192: 	}
193: 
194: 	if err := handle.LinkDel(link); err != nil {
195: 		t.Fatalf("failed to delete late0: %v", err)
196: 	}
197: 
198: 	events.waitFor(t, []string{"late0"}, "delete")
199: 
200: 	if got := events.get("early0"); slices.Contains(got, "create") {
201: 		t.Fatalf("early0 was reported as created: %v", got)
202: 	}
203: }
204: 
205: // TestNetlinkWatcherReportsLinksAddedWhileStarting adds links while the
206: // watcher starts. Each link must be reported, whether the watcher lists it or
207: // is notified about it.
208: func TestNetlinkWatcherReportsLinksAddedWhileStarting(t *testing.T) {
209: 	for round := range 20 {
210: 		t.Run(fmt.Sprintf("round %d", round), func(t *testing.T) {
211: 			nsPath, handle := newTestNetns(t)
212: 			container := newTestContainer(t, func() (string, error) { return nsPath, nil })
213: 
214: 			names := make([]string, 0, 100)
215: 			for i := range cap(names) {
216: 				names = append(names, fmt.Sprintf("dummy%d", i))
217: 			}
218: 
219: 			var wg sync.WaitGroup
220: 			wg.Go(func() {
221: 				for _, name := range names {
222: 					addDummy(t, handle, name)
223: 				}
224: 			})
225: 
226: 			_, events := startRegistry(t, container)
227: 			wg.Wait()
228: 
229: 			events.waitFor(t, names, "snapshot", "create")
230: 		})
231: 	}
232: }
233: 
234: // TestNetlinkWatcherRetriesNamespaceLookup checks that the watcher keeps
235: // trying when the namespace is not found within the first attempt.
236: func TestNetlinkWatcherRetriesNamespaceLookup(t *testing.T) {
237: 	nsPath, _ := newTestNetns(t)
238: 
239: 	origDelay := watchRetryDelay
240: 	watchRetryDelay = 10 * time.Millisecond
241: 	t.Cleanup(func() { watchRetryDelay = origDelay })
242: 
243: 	var (
244: 		mu    sync.Mutex
245: 		calls int
246: 	)
247: 
248: 	// waitForNamespacePath asks five times per attempt, so the first attempt fails.
249: 	container := newTestContainer(t, func() (string, error) {
250: 		mu.Lock()
251: 		defer mu.Unlock()
252: 
253: 		calls++
254: 		if calls <= 6 {
255: 			return "", errors.New("not ready")
256: 		}
257: 
258: 		return nsPath, nil
259: 	})
260: 
261: 	_, events := startRegistry(t, container)
262: 	events.waitFor(t, []string{"lo"}, "snapshot")
263: }
264: 
265: // TestNetlinkWatcherStopsAfterRetries checks that the watcher gives up when
266: // the namespace is never found.
267: func TestNetlinkWatcherStopsAfterRetries(t *testing.T) {
268: 	origAttempts, origDelay := watchMaxAttempts, watchRetryDelay
269: 	watchMaxAttempts, watchRetryDelay = 2, 10*time.Millisecond
270: 	t.Cleanup(func() { watchMaxAttempts, watchRetryDelay = origAttempts, origDelay })
271: 
272: 	container := newTestContainer(t, func() (string, error) { return "", errors.New("gone") })
273: 	registry, _ := startRegistry(t, container)
274: 
275: 	registry.mu.Lock()
276: 	watcher := registry.watchers[container.ID]
277: 	registry.mu.Unlock()
278: 
279: 	select {
280: 	case <-watcher.done:
281: 	case <-time.After(5 * time.Second):
282: 		t.Fatal("watcher did not stop")
283: 	}
284: }
285: 
286: // TestProcessExistingAfterResubscribe checks how a listed link is reported on
287: // the first subscription and after a resubscribe.
288: func TestProcessExistingAfterResubscribe(t *testing.T) {
289: 	link := func(mtu int) netlink.Link {
290: 		return &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "eth1", MTU: mtu}}
291: 	}
292: 
293: 	tests := map[string]struct {
294: 		includeSnapshot bool
295: 		initial         bool
296: 		known           netlink.Link
297: 		vanished        bool
298: 		want            []string
299: 	}{
300: 		"first subscription": {
301: 			includeSnapshot: true,
302: 			initial:         true,
303: 			want:            []string{"snapshot"},
304: 		},
305: 		"first subscription without snapshot": {initial: true},
306: 		"new after resubscribe":               {want: []string{"create"}},
307: 		"changed after resubscribe":           {known: link(1400), want: []string{"update"}},
308: 		"unchanged after resubscribe":         {known: link(1500)},
309: 		"deleted while resubscribing":         {vanished: true},
310: 	}
311: 
312: 	for name, tt := range tests {
313: 		t.Run(name, func(t *testing.T) {
314: 			events := make(chan aggregatedEvent, 8)
315: 			registry := newNetlinkRegistry(t.Context(), events, tt.includeSnapshot, false, 0)
316: 			watcher := &netlinkWatcher{
317: 				container:       &clabruntime.GenericContainer{Names: []string{"n1"}},
318: 				includeSnapshot: tt.includeSnapshot,
319: 			}
320: 
321: 			states := map[int]ifaceSnapshot{}
322: 			if tt.known != nil {
323: 				states[7] = snapshotFromLink(tt.known)
324: 			}
325: 
326: 			var vanished map[int]struct{}
327: 			if tt.vanished {
328: 				vanished = map[int]struct{}{7: {}}
329: 			}
330: 
331: 			watcher.processExisting(states, nil, link(1500), nil, vanished, registry, tt.initial)
332: 			close(events)
333: 
334: 			var got []string
335: 			for ev := range events {
336: 				got = append(got, ev.Action)
337: 			}
338: 
339: 			if !slices.Equal(got, tt.want) {
340: 				t.Fatalf("actions = %v, want %v", got, tt.want)
341: 			}
342: 
343: 			if tt.vanished {
344: 				if _, ok := states[7]; ok {
345: 					t.Fatal("vanished link is tracked again")
346: 				}
347: 
348: 				return
349: 			}
350: 
351: 			if states[7].MTU != 1500 {
352: 				t.Fatalf("state MTU = %d, want 1500", states[7].MTU)
353: 			}
354: 		})
355: 	}
356: }
357: 
358: // TestProcessUpdateDeleteOnlyTrackedLinks checks that a deletion is reported
359: // once, also when its notification arrives after a resubscribe has already
360: // reported it.
361: func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {
362: 	link := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "eth1", MTU: 1500}}
363: 	update := netlink.LinkUpdate{Link: link}
364: 	update.Header.Type = unix.RTM_DELLINK
365: 
366: 	events := make(chan aggregatedEvent, 8)
367: 	registry := newNetlinkRegistry(t.Context(), events, false, false, 0)
368: 	watcher := &netlinkWatcher{
369: 		container: &clabruntime.GenericContainer{Names: []string{"n1"}},
370: 	}
371: 
372: 	states := map[int]ifaceSnapshot{7: snapshotFromLink(link)}
373: 
374: 	watcher.processUpdate(states, nil, update, registry, nil)
375: 	watcher.processUpdate(states, nil, update, registry, nil)
376: 	close(events)
377: 
378: 	var got []string
379: 	for ev := range events {
380: 		got = append(got, ev.Action)
381: 	}
382: 
383: 	if want := []string{"delete"}; !slices.Equal(got, want) {
384: 		t.Fatalf("actions = %v, want %v", got, want)
385: 	}
386: 
387: 	if _, ok := states[7]; ok {
388: 		t.Fatal("deleted link is still tracked")
389: 	}
390: }
391: 
392: // reportedEvent is the action and interface name of an emitted event.
393: type reportedEvent struct {
394: 	action string
395: 	ifname string
396: }
397: 
398: // drainEvents closes events and returns what was emitted, in order.
399: func drainEvents(events chan aggregatedEvent) []reportedEvent {
400: 	close(events)
401: 
402: 	var got []reportedEvent
403: 	for ev := range events {
404: 		got = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes["ifname"]})
405: 	}
406: 
407: 	return got
408: }
409: 
410: // stitchedWatcher returns a watcher that reported the link with index 7 as
411: // the host-side stitch interface of its veth-stitch link.
412: func stitchedWatcher() *netlinkWatcher {
413: 	return &netlinkWatcher{
414: 		container: &clabruntime.GenericContainer{Names: []string{"n1"}},
415: 		reported: map[int]reportedInterface{
416: 			7: {
417: 				attributes: map[string]string{"ifname": "clab-s-0011aabb", "alias": "e1-1"},
418: 				since:      time.Now(),
419: 			},
420: 		},
421: 	}
422: }
423: 
424: // TestEmitReportsRenamedLinkDeleted checks that a link reported under another
425: // name than before is first reported deleted under the old name, so clients
426: // do not keep both, and is then new to them.
427: func TestEmitReportsRenamedLinkDeleted(t *testing.T) {
428: 	events := make(chan aggregatedEvent, 8)
429: 	registry := newNetlinkRegistry(t.Context(), events, false, false, 0)
430: 	watcher := stitchedWatcher()
431: 
432: 	link := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "e1-1", MTU: 1500}}
433: 	watcher.emit(registry, "update", snapshotFromLink(link))
434: 	watcher.emit(registry, "update", snapshotFromLink(link))
435: 
436: 	want := []reportedEvent{
437: 		{action: "delete", ifname: "clab-s-0011aabb"},
438: 		{action: "create", ifname: "e1-1"},
439: 		{action: "update", ifname: "e1-1"},
440: 	}
441: 	if got := drainEvents(events); !slices.Equal(got, want) {
442: 		t.Fatalf("events = %v, want %v", got, want)
443: 	}
444: }
445: 
446: // TestEmitDeletesLinkAsLastReported checks that a deletion names the link as
447: // clients know it, also when its stitch interface is already gone.
448: func TestEmitDeletesLinkAsLastReported(t *testing.T) {
449: 	events := make(chan aggregatedEvent, 8)
450: 	registry := newNetlinkRegistry(t.Context(), events, false, false, 0)
451: 	watcher := stitchedWatcher()
452: 
453: 	link := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "e1-1", MTU: 1500}}
454: 	watcher.emit(registry, "delete", snapshotFromLink(link))
455: 
456: 	want := []reportedEvent{{action: "delete", ifname: "clab-s-0011aabb"}}
457: 	if got := drainEvents(events); !slices.Equal(got, want) {
458: 		t.Fatalf("events = %v, want %v", got, want)
459: 	}
460: 
461: 	if _, ok := watcher.reported[7]; ok {
462: 		t.Fatal("deleted link is still tracked as reported")
463: 	}
464: }
465: 
466: // TestEmitStatsReportsRenamedLinkFirst checks that counters of a link reported
467: // under another name before follow its deletion under that name and its
468: // creation without counters.
469: func TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {
470: 	events := make(chan aggregatedEvent, 8)
471: 	registry := newNetlinkRegistry(t.Context(), events, false, true, time.Second)
472: 	watcher := stitchedWatcher()
473: 
474: 	link := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{
475: 		Index:      7,
476: 		Name:       "e1-1",
477: 		MTU:        1500,
478: 		Statistics: &netlink.LinkStatistics{RxBytes: 10},
479: 	}}
480: 	watcher.emitStats(registry, snapshotFromLink(link), ifaceStatsMetrics{
481: 		Timestamp: time.Now(),
482: 	})
483: 	close(events)
484: 
485: 	var got []reportedEvent
486: 	for ev := range events {
487: 		got = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes["ifname"]})
488: 
489: 		_, hasCounters := ev.Attributes["rx_bytes"]
490: 		if hasCounters != (ev.Action == "stats") {
491: 			t.Fatalf("%s event has counters: %v", ev.Action, hasCounters)
492: 		}
493: 	}
494: 
495: 	want := []reportedEvent{
496: 		{action: "delete", ifname: "clab-s-0011aabb"},
497: 		{action: "create", ifname: "e1-1"},
498: 		{action: "stats", ifname: "e1-1"},
499: 	}
500: 	if !slices.Equal(got, want) {
501: 		t.Fatalf("events = %v, want %v", got, want)
502: 	}
503: 
504: 	if _, ok := watcher.reported[7].attributes["rx_bytes"]; ok {
505: 		t.Fatal("counters are kept as what the link was reported as")
506: 	}
507: }
508: 
509: // TestReportStitchMarksLeavesUnmarkedLinks checks that links without a marked
510: // stitch interface, or reported too long ago, are not reported again.
511: func TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {
512: 	events := make(chan aggregatedEvent, 8)
513: 	registry := newNetlinkRegistry(t.Context(), events, false, false, 0)
514: 	watcher := &netlinkWatcher{
515: 		container: &clabruntime.GenericContainer{Names: []string{"n1"}},
516: 	}
517: 
518: 	recent := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: "e1-1", MTU: 1500}}
519: 	old := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 8, Name: "e1-2", MTU: 1500}}
520: 	states := map[int]ifaceSnapshot{7: snapshotFromLink(recent), 8: snapshotFromLink(old)}
521: 	watcher.emit(registry, "create", states[7])
522: 	watcher.emit(registry, "create", states[8])
523: 	watcher.reported[8] = reportedInterface{
524: 		attributes: watcher.reported[8].attributes,
525: 		since:      time.Now().Add(-2 * stitchMarkWindow),
526: 	}
527: 
528: 	watcher.reportStitchMarks(states, registry)
529: 
530: 	want := []reportedEvent{{action: "create", ifname: "e1-1"}, {action: "create", ifname: "e1-2"}}
531: 	if got := drainEvents(events); !slices.Equal(got, want) {
532: 		t.Fatalf("events = %v, want %v", got, want)
533: 	}
534: }

(End of file - total 534 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46ac883001Q43v7Z5lbBwgK2",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a65d0001FWpkI8jK2UTVJJ",
  "callID": "call_e286a5672b2f43c19f94b0e9",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/netlink_watch_test.go"
    },
    "output": "<path>/source/head/core/events/netlink_watch_test.go</path>\n<type>file</type>\n<content>\n1: package events\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"os\"\n8: \t\"runtime\"\n9: \t\"slices\"\n10: \t\"sync\"\n11: \t\"testing\"\n12: \t\"time\"\n13: \n14: \t\"github.com/srl-labs/containerlab/mocks/mockruntime\"\n15: \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n16: \t\"github.com/vishvananda/netlink\"\n17: \t\"github.com/vishvananda/netns\"\n18: \t\"go.uber.org/mock/gomock\"\n19: \t\"golang.org/x/sys/unix\"\n20: )\n21: \n22: // eventLog collects the interface events of a registry by interface name.\n23: type eventLog struct {\n24: \tmu      sync.Mutex\n25: \tactions map[string][]string\n26: }\n27: \n28: func collectEvents(ctx context.Context, events <-chan aggregatedEvent) *eventLog {\n29: \tl := &eventLog{actions: map[string][]string{}}\n30: \n31: \tgo func() {\n32: \t\tfor {\n33: \t\t\tselect {\n34: \t\t\tcase ev := <-events:\n35: \t\t\t\tl.mu.Lock()\n36: \t\t\t\tname := ev.Attributes[\"ifname\"]\n37: \t\t\t\tl.actions[name] = append(l.actions[name], ev.Action)\n38: \t\t\t\tl.mu.Unlock()\n39: \t\t\tcase <-ctx.Done():\n40: \t\t\t\treturn\n41: \t\t\t}\n42: \t\t}\n43: \t}()\n44: \n45: \treturn l\n46: }\n47: \n48: func (l *eventLog) get(name string) []string {\n49: \tl.mu.Lock()\n50: \tdefer l.mu.Unlock()\n51: \n52: \treturn slices.Clone(l.actions[name])\n53: }\n54: \n55: // waitFor waits until every name has an event with one of the actions.\n56: func (l *eventLog) waitFor(t *testing.T, names []string, actions ...string) {\n57: \tt.Helper()\n58: \n59: \tdeadline := time.Now().Add(3 * time.Second)\n60: \tfor {\n61: \t\tvar missing []string\n62: \t\tfor _, name := range names {\n63: \t\t\tif !slices.ContainsFunc(l.get(name), func(a string) bool {\n64: \t\t\t\treturn slices.Contains(actions, a)\n65: \t\t\t}) {\n66: \t\t\t\tmissing = append(missing, name)\n67: \t\t\t}\n68: \t\t}\n69: \n70: \t\tif len(missing) == 0 {\n71: \t\t\treturn\n72: \t\t}\n73: \n74: \t\tif time.Now().After(deadline) {\n75: \t\t\tt.Fatalf(\"no %v event for %v\", actions, missing)\n76: \t\t}\n77: \n78: \t\ttime.Sleep(10 * time.Millisecond)\n79: \t}\n80: }\n81: \n82: // newTestNetns creates a named network namespace without leaving the\n83: // current thread in it.\n84: func newTestNetns(t *testing.T) (string, *netlink.Handle) {\n85: \tt.Helper()\n86: \n87: \tif os.Geteuid() != 0 {\n88: \t\tt.Skip(\"requires root to create network namespaces\")\n89: \t}\n90: \n91: \truntime.LockOSThread()\n92: \tdefer runtime.UnlockOSThread()\n93: \n94: \torig, err := netns.Get()\n95: \tif err != nil {\n96: \t\tt.Fatalf(\"failed to get current netns: %v\", err)\n97: \t}\n98: \tdefer orig.Close()\n99: \n100: \tname := fmt.Sprintf(\"clabtst-ev-%d-%d\", os.Getpid(), time.Now().UnixNano())\n101: \n102: \tns, err := netns.NewNamed(name)\n103: \tif err != nil {\n104: \t\tt.Fatalf(\"failed to create netns: %v\", err)\n105: \t}\n106: \n107: \tif err := netns.Set(orig); err != nil {\n108: \t\tt.Fatalf(\"failed to return to the original netns: %v\", err)\n109: \t}\n110: \n111: \thandle, err := netlink.NewHandleAt(ns)\n112: \tif err != nil {\n113: \t\tt.Fatalf(\"failed to create netlink handle: %v\", err)\n114: \t}\n115: \n116: \tt.Cleanup(func() {\n117: \t\thandle.Close()\n118: \t\tns.Close()\n119: \t\t_ = netns.DeleteNamed(name)\n120: \t})\n121: \n122: \treturn \"/run/netns/\" + name, handle\n123: }\n124: \n125: func addDummy(t *testing.T, handle *netlink.Handle, name string) {\n126: \tt.Helper()\n127: \n128: \terr := handle.LinkAdd(&netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: name}})\n129: \tif err != nil {\n130: \t\tt.Errorf(\"failed to add %s: %v\", name, err)\n131: \t}\n132: }\n133: \n134: func newTestContainer(\n135: \tt *testing.T,\n136: \tgetNSPath func() (string, error),\n137: ) *clabruntime.GenericContainer {\n138: \tt.Helper()\n139: \n140: \trt := mockruntime.NewMockContainerRuntime(gomock.NewController(t))\n141: \trt.EXPECT().GetNSPath(gomock.Any(), gomock.Any()).DoAndReturn(\n142: \t\tfunc(context.Context, string) (string, error) { return getNSPath() },\n143: \t).AnyTimes()\n144: \n145: \tcontainer := &clabruntime.GenericContainer{\n146: \t\tID:      \"0123456789abcdef\",\n147: \t\tShortID: \"0123456789ab\",\n148: \t\tNames:   []string{\"clab-test-n1\"},\n149: \t}\n150: \tcontainer.SetRuntime(rt)\n151: \n152: \treturn container\n153: }\n154: \n155: func startRegistry(\n156: \tt *testing.T,\n157: \tcontainer *clabruntime.GenericContainer,\n158: ) (*netlinkRegistry, *eventLog) {\n159: \tt.Helper()\n160: \n161: \tctx, cancel := context.WithCancel(context.Background())\n162: \tevents := make(chan aggregatedEvent, 1024)\n163: \tregistry := newNetlinkRegistry(ctx, events, true, false, 0)\n164: \tcollected := collectEvents(ctx, events)\n165: \n166: \tregistry.Start(container)\n167: \tt.Cleanup(func() {\n168: \t\tregistry.Stop(container.ID)\n169: \t\tcancel()\n170: \t})\n171: \n172: \treturn registry, collected\n173: }\n174: \n175: // TestNetlinkWatcherReportsExistingAndNewLinks checks that links present at\n176: // subscription are reported as snapshots and later ones as created or deleted.\n177: func TestNetlinkWatcherReportsExistingAndNewLinks(t *testing.T) {\n178: \tnsPath, handle := newTestNetns(t)\n179: \taddDummy(t, handle, \"early0\")\n180: \n181: \tcontainer := newTestContainer(t, func() (string, error) { return nsPath, nil })\n182: \t_, events := startRegistry(t, container)\n183: \n184: \tevents.waitFor(t, []string{\"lo\", \"early0\"}, \"snapshot\")\n185: \n186: \taddDummy(t, handle, \"late0\")\n187: \tevents.waitFor(t, []string{\"late0\"}, \"create\")\n188: \n189: \tlink, err := handle.LinkByName(\"late0\")\n190: \tif err != nil {\n191: \t\tt.Fatalf(\"failed to find late0: %v\", err)\n192: \t}\n193: \n194: \tif err := handle.LinkDel(link); err != nil {\n195: \t\tt.Fatalf(\"failed to delete late0: %v\", err)\n196: \t}\n197: \n198: \tevents.waitFor(t, []string{\"late0\"}, \"delete\")\n199: \n200: \tif got := events.get(\"early0\"); slices.Contains(got, \"create\") {\n201: \t\tt.Fatalf(\"early0 was reported as created: %v\", got)\n202: \t}\n203: }\n204: \n205: // TestNetlinkWatcherReportsLinksAddedWhileStarting adds links while the\n206: // watcher starts. Each link must be reported, whether the watcher lists it or\n207: // is notified about it.\n208: func TestNetlinkWatcherReportsLinksAddedWhileStarting(t *testing.T) {\n209: \tfor round := range 20 {\n210: \t\tt.Run(fmt.Sprintf(\"round %d\", round), func(t *testing.T) {\n211: \t\t\tnsPath, handle := newTestNetns(t)\n212: \t\t\tcontainer := newTestContainer(t, func() (string, error) { return nsPath, nil })\n213: \n214: \t\t\tnames := make([]string, 0, 100)\n215: \t\t\tfor i := range cap(names) {\n216: \t\t\t\tnames = append(names, fmt.Sprintf(\"dummy%d\", i))\n217: \t\t\t}\n218: \n219: \t\t\tvar wg sync.WaitGroup\n220: \t\t\twg.Go(func() {\n221: \t\t\t\tfor _, name := range names {\n222: \t\t\t\t\taddDummy(t, handle, name)\n223: \t\t\t\t}\n224: \t\t\t})\n225: \n226: \t\t\t_, events := startRegistry(t, container)\n227: \t\t\twg.Wait()\n228: \n229: \t\t\tevents.waitFor(t, names, \"snapshot\", \"create\")\n230: \t\t})\n231: \t}\n232: }\n233: \n234: // TestNetlinkWatcherRetriesNamespaceLookup checks that the watcher keeps\n235: // trying when the namespace is not found within the first attempt.\n236: func TestNetlinkWatcherRetriesNamespaceLookup(t *testing.T) {\n237: \tnsPath, _ := newTestNetns(t)\n238: \n239: \torigDelay := watchRetryDelay\n240: \twatchRetryDelay = 10 * time.Millisecond\n241: \tt.Cleanup(func() { watchRetryDelay = origDelay })\n242: \n243: \tvar (\n244: \t\tmu    sync.Mutex\n245: \t\tcalls int\n246: \t)\n247: \n248: \t// waitForNamespacePath asks five times per attempt, so the first attempt fails.\n249: \tcontainer := newTestContainer(t, func() (string, error) {\n250: \t\tmu.Lock()\n251: \t\tdefer mu.Unlock()\n252: \n253: \t\tcalls++\n254: \t\tif calls <= 6 {\n255: \t\t\treturn \"\", errors.New(\"not ready\")\n256: \t\t}\n257: \n258: \t\treturn nsPath, nil\n259: \t})\n260: \n261: \t_, events := startRegistry(t, container)\n262: \tevents.waitFor(t, []string{\"lo\"}, \"snapshot\")\n263: }\n264: \n265: // TestNetlinkWatcherStopsAfterRetries checks that the watcher gives up when\n266: // the namespace is never found.\n267: func TestNetlinkWatcherStopsAfterRetries(t *testing.T) {\n268: \torigAttempts, origDelay := watchMaxAttempts, watchRetryDelay\n269: \twatchMaxAttempts, watchRetryDelay = 2, 10*time.Millisecond\n270: \tt.Cleanup(func() { watchMaxAttempts, watchRetryDelay = origAttempts, origDelay })\n271: \n272: \tcontainer := newTestContainer(t, func() (string, error) { return \"\", errors.New(\"gone\") })\n273: \tregistry, _ := startRegistry(t, container)\n274: \n275: \tregistry.mu.Lock()\n276: \twatcher := registry.watchers[container.ID]\n277: \tregistry.mu.Unlock()\n278: \n279: \tselect {\n280: \tcase <-watcher.done:\n281: \tcase <-time.After(5 * time.Second):\n282: \t\tt.Fatal(\"watcher did not stop\")\n283: \t}\n284: }\n285: \n286: // TestProcessExistingAfterResubscribe checks how a listed link is reported on\n287: // the first subscription and after a resubscribe.\n288: func TestProcessExistingAfterResubscribe(t *testing.T) {\n289: \tlink := func(mtu int) netlink.Link {\n290: \t\treturn &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"eth1\", MTU: mtu}}\n291: \t}\n292: \n293: \ttests := map[string]struct {\n294: \t\tincludeSnapshot bool\n295: \t\tinitial         bool\n296: \t\tknown           netlink.Link\n297: \t\tvanished        bool\n298: \t\twant            []string\n299: \t}{\n300: \t\t\"first subscription\": {\n301: \t\t\tincludeSnapshot: true,\n302: \t\t\tinitial:         true,\n303: \t\t\twant:            []string{\"snapshot\"},\n304: \t\t},\n305: \t\t\"first subscription without snapshot\": {initial: true},\n306: \t\t\"new after resubscribe\":               {want: []string{\"create\"}},\n307: \t\t\"changed after resubscribe\":           {known: link(1400), want: []string{\"update\"}},\n308: \t\t\"unchanged after resubscribe\":         {known: link(1500)},\n309: \t\t\"deleted while resubscribing\":         {vanished: true},\n310: \t}\n311: \n312: \tfor name, tt := range tests {\n313: \t\tt.Run(name, func(t *testing.T) {\n314: \t\t\tevents := make(chan aggregatedEvent, 8)\n315: \t\t\tregistry := newNetlinkRegistry(t.Context(), events, tt.includeSnapshot, false, 0)\n316: \t\t\twatcher := &netlinkWatcher{\n317: \t\t\t\tcontainer:       &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n318: \t\t\t\tincludeSnapshot: tt.includeSnapshot,\n319: \t\t\t}\n320: \n321: \t\t\tstates := map[int]ifaceSnapshot{}\n322: \t\t\tif tt.known != nil {\n323: \t\t\t\tstates[7] = snapshotFromLink(tt.known)\n324: \t\t\t}\n325: \n326: \t\t\tvar vanished map[int]struct{}\n327: \t\t\tif tt.vanished {\n328: \t\t\t\tvanished = map[int]struct{}{7: {}}\n329: \t\t\t}\n330: \n331: \t\t\twatcher.processExisting(states, nil, link(1500), nil, vanished, registry, tt.initial)\n332: \t\t\tclose(events)\n333: \n334: \t\t\tvar got []string\n335: \t\t\tfor ev := range events {\n336: \t\t\t\tgot = append(got, ev.Action)\n337: \t\t\t}\n338: \n339: \t\t\tif !slices.Equal(got, tt.want) {\n340: \t\t\t\tt.Fatalf(\"actions = %v, want %v\", got, tt.want)\n341: \t\t\t}\n342: \n343: \t\t\tif tt.vanished {\n344: \t\t\t\tif _, ok := states[7]; ok {\n345: \t\t\t\t\tt.Fatal(\"vanished link is tracked again\")\n346: \t\t\t\t}\n347: \n348: \t\t\t\treturn\n349: \t\t\t}\n350: \n351: \t\t\tif states[7].MTU != 1500 {\n352: \t\t\t\tt.Fatalf(\"state MTU = %d, want 1500\", states[7].MTU)\n353: \t\t\t}\n354: \t\t})\n355: \t}\n356: }\n357: \n358: // TestProcessUpdateDeleteOnlyTrackedLinks checks that a deletion is reported\n359: // once, also when its notification arrives after a resubscribe has already\n360: // reported it.\n361: func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {\n362: \tlink := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"eth1\", MTU: 1500}}\n363: \tupdate := netlink.LinkUpdate{Link: link}\n364: \tupdate.Header.Type = unix.RTM_DELLINK\n365: \n366: \tevents := make(chan aggregatedEvent, 8)\n367: \tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n368: \twatcher := &netlinkWatcher{\n369: \t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n370: \t}\n371: \n372: \tstates := map[int]ifaceSnapshot{7: snapshotFromLink(link)}\n373: \n374: \twatcher.processUpdate(states, nil, update, registry, nil)\n375: \twatcher.processUpdate(states, nil, update, registry, nil)\n376: \tclose(events)\n377: \n378: \tvar got []string\n379: \tfor ev := range events {\n380: \t\tgot = append(got, ev.Action)\n381: \t}\n382: \n383: \tif want := []string{\"delete\"}; !slices.Equal(got, want) {\n384: \t\tt.Fatalf(\"actions = %v, want %v\", got, want)\n385: \t}\n386: \n387: \tif _, ok := states[7]; ok {\n388: \t\tt.Fatal(\"deleted link is still tracked\")\n389: \t}\n390: }\n391: \n392: // reportedEvent is the action and interface name of an emitted event.\n393: type reportedEvent struct {\n394: \taction string\n395: \tifname string\n396: }\n397: \n398: // drainEvents closes events and returns what was emitted, in order.\n399: func drainEvents(events chan aggregatedEvent) []reportedEvent {\n400: \tclose(events)\n401: \n402: \tvar got []reportedEvent\n403: \tfor ev := range events {\n404: \t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n405: \t}\n406: \n407: \treturn got\n408: }\n409: \n410: // stitchedWatcher returns a watcher that reported the link with index 7 as\n411: // the host-side stitch interface of its veth-stitch link.\n412: func stitchedWatcher() *netlinkWatcher {\n413: \treturn &netlinkWatcher{\n414: \t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n415: \t\treported: map[int]reportedInterface{\n416: \t\t\t7: {\n417: \t\t\t\tattributes: map[string]string{\"ifname\": \"clab-s-0011aabb\", \"alias\": \"e1-1\"},\n418: \t\t\t\tsince:      time.Now(),\n419: \t\t\t},\n420: \t\t},\n421: \t}\n422: }\n423: \n424: // TestEmitReportsRenamedLinkDeleted checks that a link reported under another\n425: // name than before is first reported deleted under the old name, so clients\n426: // do not keep both, and is then new to them.\n427: func TestEmitReportsRenamedLinkDeleted(t *testing.T) {\n428: \tevents := make(chan aggregatedEvent, 8)\n429: \tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n430: \twatcher := stitchedWatcher()\n431: \n432: \tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n433: \twatcher.emit(registry, \"update\", snapshotFromLink(link))\n434: \twatcher.emit(registry, \"update\", snapshotFromLink(link))\n435: \n436: \twant := []reportedEvent{\n437: \t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n438: \t\t{action: \"create\", ifname: \"e1-1\"},\n439: \t\t{action: \"update\", ifname: \"e1-1\"},\n440: \t}\n441: \tif got := drainEvents(events); !slices.Equal(got, want) {\n442: \t\tt.Fatalf(\"events = %v, want %v\", got, want)\n443: \t}\n444: }\n445: \n446: // TestEmitDeletesLinkAsLastReported checks that a deletion names the link as\n447: // clients know it, also when its stitch interface is already gone.\n448: func TestEmitDeletesLinkAsLastReported(t *testing.T) {\n449: \tevents := make(chan aggregatedEvent, 8)\n450: \tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n451: \twatcher := stitchedWatcher()\n452: \n453: \tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n454: \twatcher.emit(registry, \"delete\", snapshotFromLink(link))\n455: \n456: \twant := []reportedEvent{{action: \"delete\", ifname: \"clab-s-0011aabb\"}}\n457: \tif got := drainEvents(events); !slices.Equal(got, want) {\n458: \t\tt.Fatalf(\"events = %v, want %v\", got, want)\n459: \t}\n460: \n461: \tif _, ok := watcher.reported[7]; ok {\n462: \t\tt.Fatal(\"deleted link is still tracked as reported\")\n463: \t}\n464: }\n465: \n466: // TestEmitStatsReportsRenamedLinkFirst checks that counters of a link reported\n467: // under another name before follow its deletion under that name and its\n468: // creation without counters.\n469: func TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {\n470: \tevents := make(chan aggregatedEvent, 8)\n471: \tregistry := newNetlinkRegistry(t.Context(), events, false, true, time.Second)\n472: \twatcher := stitchedWatcher()\n473: \n474: \tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{\n475: \t\tIndex:      7,\n476: \t\tName:       \"e1-1\",\n477: \t\tMTU:        1500,\n478: \t\tStatistics: &netlink.LinkStatistics{RxBytes: 10},\n479: \t}}\n480: \twatcher.emitStats(registry, snapshotFromLink(link), ifaceStatsMetrics{\n481: \t\tTimestamp: time.Now(),\n482: \t})\n483: \tclose(events)\n484: \n485: \tvar got []reportedEvent\n486: \tfor ev := range events {\n487: \t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n488: \n489: \t\t_, hasCounters := ev.Attributes[\"rx_bytes\"]\n490: \t\tif hasCounters != (ev.Action == \"stats\") {\n491: \t\t\tt.Fatalf(\"%s event has counters: %v\", ev.Action, hasCounters)\n492: \t\t}\n493: \t}\n494: \n495: \twant := []reportedEvent{\n496: \t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n497: \t\t{action: \"create\", ifname: \"e1-1\"},\n498: \t\t{action: \"stats\", ifname: \"e1-1\"},\n499: \t}\n500: \tif !slices.Equal(got, want) {\n501: \t\tt.Fatalf(\"events = %v, want %v\", got, want)\n502: \t}\n503: \n504: \tif _, ok := watcher.reported[7].attributes[\"rx_bytes\"]; ok {\n505: \t\tt.Fatal(\"counters are kept as what the link was reported as\")\n506: \t}\n507: }\n508: \n509: // TestReportStitchMarksLeavesUnmarkedLinks checks that links without a marked\n510: // stitch interface, or reported too long ago, are not reported again.\n511: func TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {\n512: \tevents := make(chan aggregatedEvent, 8)\n513: \tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n514: \twatcher := &netlinkWatcher{\n515: \t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n516: \t}\n517: \n518: \trecent := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n519: \told := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 8, Name: \"e1-2\", MTU: 1500}}\n520: \tstates := map[int]ifaceSnapshot{7: snapshotFromLink(recent), 8: snapshotFromLink(old)}\n521: \twatcher.emit(registry, \"create\", states[7])\n522: \twatcher.emit(registry, \"create\", states[8])\n523: \twatcher.reported[8] = reportedInterface{\n524: \t\tattributes: watcher.reported[8].attributes,\n525: \t\tsince:      time.Now().Add(-2 * stitchMarkWindow),\n526: \t}\n527: \n528: \twatcher.reportStitchMarks(states, registry)\n529: \n530: \twant := []reportedEvent{{action: \"create\", ifname: \"e1-1\"}, {action: \"create\", ifname: \"e1-2\"}}\n531: \tif got := drainEvents(events); !slices.Equal(got, want) {\n532: \t\tt.Fatalf(\"events = %v, want %v\", got, want)\n533: \t}\n534: }\n\n(End of file - total 534 lines)\n</content>",
    "title": "source/head/core/events/netlink_watch_test.go",
    "metadata": {
      "preview": "package events\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"slices\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/srl-labs/containerlab/mocks/mockruntime\"\n\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n\t\"github.com/vishvananda/netlink\"\n\t\"github.com/vishvananda/netns\"\n\t\"go.uber.org/mock/gomock\"\n\t\"golang.org/x/sys/unix\"\n)",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/netlink_watch_test.go",
        "text": "package events\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"slices\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/srl-labs/containerlab/mocks/mockruntime\"\n\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n\t\"github.com/vishvananda/netlink\"\n\t\"github.com/vishvananda/netns\"\n\t\"go.uber.org/mock/gomock\"\n\t\"golang.org/x/sys/unix\"\n)\n\n// eventLog collects the interface events of a registry by interface name.\ntype eventLog struct {\n\tmu      sync.Mutex\n\tactions map[string][]string\n}\n\nfunc collectEvents(ctx context.Context, events <-chan aggregatedEvent) *eventLog {\n\tl := &eventLog{actions: map[string][]string{}}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-events:\n\t\t\t\tl.mu.Lock()\n\t\t\t\tname := ev.Attributes[\"ifname\"]\n\t\t\t\tl.actions[name] = append(l.actions[name], ev.Action)\n\t\t\t\tl.mu.Unlock()\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn l\n}\n\nfunc (l *eventLog) get(name string) []string {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\treturn slices.Clone(l.actions[name])\n}\n\n// waitFor waits until every name has an event with one of the actions.\nfunc (l *eventLog) waitFor(t *testing.T, names []string, actions ...string) {\n\tt.Helper()\n\n\tdeadline := time.Now().Add(3 * time.Second)\n\tfor {\n\t\tvar missing []string\n\t\tfor _, name := range names {\n\t\t\tif !slices.ContainsFunc(l.get(name), func(a string) bool {\n\t\t\t\treturn slices.Contains(actions, a)\n\t\t\t}) {\n\t\t\t\tmissing = append(missing, name)\n\t\t\t}\n\t\t}\n\n\t\tif len(missing) == 0 {\n\t\t\treturn\n\t\t}\n\n\t\tif time.Now().After(deadline) {\n\t\t\tt.Fatalf(\"no %v event for %v\", actions, missing)\n\t\t}\n\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n}\n\n// newTestNetns creates a named network namespace without leaving the\n// current thread in it.\nfunc newTestNetns(t *testing.T) (string, *netlink.Handle) {\n\tt.Helper()\n\n\tif os.Geteuid() != 0 {\n\t\tt.Skip(\"requires root to create network namespaces\")\n\t}\n\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\torig, err := netns.Get()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get current netns: %v\", err)\n\t}\n\tdefer orig.Close()\n\n\tname := fmt.Sprintf(\"clabtst-ev-%d-%d\", os.Getpid(), time.Now().UnixNano())\n\n\tns, err := netns.NewNamed(name)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create netns: %v\", err)\n\t}\n\n\tif err := netns.Set(orig); err != nil {\n\t\tt.Fatalf(\"failed to return to the original netns: %v\", err)\n\t}\n\n\thandle, err := netlink.NewHandleAt(ns)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create netlink handle: %v\", err)\n\t}\n\n\tt.Cleanup(func() {\n\t\thandle.Close()\n\t\tns.Close()\n\t\t_ = netns.DeleteNamed(name)\n\t})\n\n\treturn \"/run/netns/\" + name, handle\n}\n\nfunc addDummy(t *testing.T, handle *netlink.Handle, name string) {\n\tt.Helper()\n\n\terr := handle.LinkAdd(&netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: name}})\n\tif err != nil {\n\t\tt.Errorf(\"failed to add %s: %v\", name, err)\n\t}\n}\n\nfunc newTestContainer(\n\tt *testing.T,\n\tgetNSPath func() (string, error),\n) *clabruntime.GenericContainer {\n\tt.Helper()\n\n\trt := mockruntime.NewMockContainerRuntime(gomock.NewController(t))\n\trt.EXPECT().GetNSPath(gomock.Any(), gomock.Any()).DoAndReturn(\n\t\tfunc(context.Context, string) (string, error) { return getNSPath() },\n\t).AnyTimes()\n\n\tcontainer := &clabruntime.GenericContainer{\n\t\tID:      \"0123456789abcdef\",\n\t\tShortID: \"0123456789ab\",\n\t\tNames:   []string{\"clab-test-n1\"},\n\t}\n\tcontainer.SetRuntime(rt)\n\n\treturn container\n}\n\nfunc startRegistry(\n\tt *testing.T,\n\tcontainer *clabruntime.GenericContainer,\n) (*netlinkRegistry, *eventLog) {\n\tt.Helper()\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tevents := make(chan aggregatedEvent, 1024)\n\tregistry := newNetlinkRegistry(ctx, events, true, false, 0)\n\tcollected := collectEvents(ctx, events)\n\n\tregistry.Start(container)\n\tt.Cleanup(func() {\n\t\tregistry.Stop(container.ID)\n\t\tcancel()\n\t})\n\n\treturn registry, collected\n}\n\n// TestNetlinkWatcherReportsExistingAndNewLinks checks that links present at\n// subscription are reported as snapshots and later ones as created or deleted.\nfunc TestNetlinkWatcherReportsExistingAndNewLinks(t *testing.T) {\n\tnsPath, handle := newTestNetns(t)\n\taddDummy(t, handle, \"early0\")\n\n\tcontainer := newTestContainer(t, func() (string, error) { return nsPath, nil })\n\t_, events := startRegistry(t, container)\n\n\tevents.waitFor(t, []string{\"lo\", \"early0\"}, \"snapshot\")\n\n\taddDummy(t, handle, \"late0\")\n\tevents.waitFor(t, []string{\"late0\"}, \"create\")\n\n\tlink, err := handle.LinkByName(\"late0\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to find late0: %v\", err)\n\t}\n\n\tif err := handle.LinkDel(link); err != nil {\n\t\tt.Fatalf(\"failed to delete late0: %v\", err)\n\t}\n\n\tevents.waitFor(t, []string{\"late0\"}, \"delete\")\n\n\tif got := events.get(\"early0\"); slices.Contains(got, \"create\") {\n\t\tt.Fatalf(\"early0 was reported as created: %v\", got)\n\t}\n}\n\n// TestNetlinkWatcherReportsLinksAddedWhileStarting adds links while the\n// watcher starts. Each link must be reported, whether the watcher lists it or\n// is notified about it.\nfunc TestNetlinkWatcherReportsLinksAddedWhileStarting(t *testing.T) {\n\tfor round := range 20 {\n\t\tt.Run(fmt.Sprintf(\"round %d\", round), func(t *testing.T) {\n\t\t\tnsPath, handle := newTestNetns(t)\n\t\t\tcontainer := newTestContainer(t, func() (string, error) { return nsPath, nil })\n\n\t\t\tnames := make([]string, 0, 100)\n\t\t\tfor i := range cap(names) {\n\t\t\t\tnames = append(names, fmt.Sprintf(\"dummy%d\", i))\n\t\t\t}\n\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Go(func() {\n\t\t\t\tfor _, name := range names {\n\t\t\t\t\taddDummy(t, handle, name)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\t_, events := startRegistry(t, container)\n\t\t\twg.Wait()\n\n\t\t\tevents.waitFor(t, names, \"snapshot\", \"create\")\n\t\t})\n\t}\n}\n\n// TestNetlinkWatcherRetriesNamespaceLookup checks that the watcher keeps\n// trying when the namespace is not found within the first attempt.\nfunc TestNetlinkWatcherRetriesNamespaceLookup(t *testing.T) {\n\tnsPath, _ := newTestNetns(t)\n\n\torigDelay := watchRetryDelay\n\twatchRetryDelay = 10 * time.Millisecond\n\tt.Cleanup(func() { watchRetryDelay = origDelay })\n\n\tvar (\n\t\tmu    sync.Mutex\n\t\tcalls int\n\t)\n\n\t// waitForNamespacePath asks five times per attempt, so the first attempt fails.\n\tcontainer := newTestContainer(t, func() (string, error) {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\n\t\tcalls++\n\t\tif calls <= 6 {\n\t\t\treturn \"\", errors.New(\"not ready\")\n\t\t}\n\n\t\treturn nsPath, nil\n\t})\n\n\t_, events := startRegistry(t, container)\n\tevents.waitFor(t, []string{\"lo\"}, \"snapshot\")\n}\n\n// TestNetlinkWatcherStopsAfterRetries checks that the watcher gives up when\n// the namespace is never found.\nfunc TestNetlinkWatcherStopsAfterRetries(t *testing.T) {\n\torigAttempts, origDelay := watchMaxAttempts, watchRetryDelay\n\twatchMaxAttempts, watchRetryDelay = 2, 10*time.Millisecond\n\tt.Cleanup(func() { watchMaxAttempts, watchRetryDelay = origAttempts, origDelay })\n\n\tcontainer := newTestContainer(t, func() (string, error) { return \"\", errors.New(\"gone\") })\n\tregistry, _ := startRegistry(t, container)\n\n\tregistry.mu.Lock()\n\twatcher := registry.watchers[container.ID]\n\tregistry.mu.Unlock()\n\n\tselect {\n\tcase <-watcher.done:\n\tcase <-time.After(5 * time.Second):\n\t\tt.Fatal(\"watcher did not stop\")\n\t}\n}\n\n// TestProcessExistingAfterResubscribe checks how a listed link is reported on\n// the first subscription and after a resubscribe.\nfunc TestProcessExistingAfterResubscribe(t *testing.T) {\n\tlink := func(mtu int) netlink.Link {\n\t\treturn &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"eth1\", MTU: mtu}}\n\t}\n\n\ttests := map[string]struct {\n\t\tincludeSnapshot bool\n\t\tinitial         bool\n\t\tknown           netlink.Link\n\t\tvanished        bool\n\t\twant            []string\n\t}{\n\t\t\"first subscription\": {\n\t\t\tincludeSnapshot: true,\n\t\t\tinitial:         true,\n\t\t\twant:            []string{\"snapshot\"},\n\t\t},\n\t\t\"first subscription without snapshot\": {initial: true},\n\t\t\"new after resubscribe\":               {want: []string{\"create\"}},\n\t\t\"changed after resubscribe\":           {known: link(1400), want: []string{\"update\"}},\n\t\t\"unchanged after resubscribe\":         {known: link(1500)},\n\t\t\"deleted while resubscribing\":         {vanished: true},\n\t}\n\n\tfor name, tt := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tevents := make(chan aggregatedEvent, 8)\n\t\t\tregistry := newNetlinkRegistry(t.Context(), events, tt.includeSnapshot, false, 0)\n\t\t\twatcher := &netlinkWatcher{\n\t\t\t\tcontainer:       &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n\t\t\t\tincludeSnapshot: tt.includeSnapshot,\n\t\t\t}\n\n\t\t\tstates := map[int]ifaceSnapshot{}\n\t\t\tif tt.known != nil {\n\t\t\t\tstates[7] = snapshotFromLink(tt.known)\n\t\t\t}\n\n\t\t\tvar vanished map[int]struct{}\n\t\t\tif tt.vanished {\n\t\t\t\tvanished = map[int]struct{}{7: {}}\n\t\t\t}\n\n\t\t\twatcher.processExisting(states, nil, link(1500), nil, vanished, registry, tt.initial)\n\t\t\tclose(events)\n\n\t\t\tvar got []string\n\t\t\tfor ev := range events {\n\t\t\t\tgot = append(got, ev.Action)\n\t\t\t}\n\n\t\t\tif !slices.Equal(got, tt.want) {\n\t\t\t\tt.Fatalf(\"actions = %v, want %v\", got, tt.want)\n\t\t\t}\n\n\t\t\tif tt.vanished {\n\t\t\t\tif _, ok := states[7]; ok {\n\t\t\t\t\tt.Fatal(\"vanished link is tracked again\")\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif states[7].MTU != 1500 {\n\t\t\t\tt.Fatalf(\"state MTU = %d, want 1500\", states[7].MTU)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// TestProcessUpdateDeleteOnlyTrackedLinks checks that a deletion is reported\n// once, also when its notification arrives after a resubscribe has already\n// reported it.\nfunc TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {\n\tlink := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"eth1\", MTU: 1500}}\n\tupdate := netlink.LinkUpdate{Link: link}\n\tupdate.Header.Type = unix.RTM_DELLINK\n\n\tevents := make(chan aggregatedEvent, 8)\n\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n\twatcher := &netlinkWatcher{\n\t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n\t}\n\n\tstates := map[int]ifaceSnapshot{7: snapshotFromLink(link)}\n\n\twatcher.processUpdate(states, nil, update, registry, nil)\n\twatcher.processUpdate(states, nil, update, registry, nil)\n\tclose(events)\n\n\tvar got []string\n\tfor ev := range events {\n\t\tgot = append(got, ev.Action)\n\t}\n\n\tif want := []string{\"delete\"}; !slices.Equal(got, want) {\n\t\tt.Fatalf(\"actions = %v, want %v\", got, want)\n\t}\n\n\tif _, ok := states[7]; ok {\n\t\tt.Fatal(\"deleted link is still tracked\")\n\t}\n}\n\n// reportedEvent is the action and interface name of an emitted event.\ntype reportedEvent struct {\n\taction string\n\tifname string\n}\n\n// drainEvents closes events and returns what was emitted, in order.\nfunc drainEvents(events chan aggregatedEvent) []reportedEvent {\n\tclose(events)\n\n\tvar got []reportedEvent\n\tfor ev := range events {\n\t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n\t}\n\n\treturn got\n}\n\n// stitchedWatcher returns a watcher that reported the link with index 7 as\n// the host-side stitch interface of its veth-stitch link.\nfunc stitchedWatcher() *netlinkWatcher {\n\treturn &netlinkWatcher{\n\t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n\t\treported: map[int]reportedInterface{\n\t\t\t7: {\n\t\t\t\tattributes: map[string]string{\"ifname\": \"clab-s-0011aabb\", \"alias\": \"e1-1\"},\n\t\t\t\tsince:      time.Now(),\n\t\t\t},\n\t\t},\n\t}\n}\n\n// TestEmitReportsRenamedLinkDeleted checks that a link reported under another\n// name than before is first reported deleted under the old name, so clients\n// do not keep both, and is then new to them.\nfunc TestEmitReportsRenamedLinkDeleted(t *testing.T) {\n\tevents := make(chan aggregatedEvent, 8)\n\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n\twatcher := stitchedWatcher()\n\n\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n\twatcher.emit(registry, \"update\", snapshotFromLink(link))\n\twatcher.emit(registry, \"update\", snapshotFromLink(link))\n\n\twant := []reportedEvent{\n\t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n\t\t{action: \"create\", ifname: \"e1-1\"},\n\t\t{action: \"update\", ifname: \"e1-1\"},\n\t}\n\tif got := drainEvents(events); !slices.Equal(got, want) {\n\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n\t}\n}\n\n// TestEmitDeletesLinkAsLastReported checks that a deletion names the link as\n// clients know it, also when its stitch interface is already gone.\nfunc TestEmitDeletesLinkAsLastReported(t *testing.T) {\n\tevents := make(chan aggregatedEvent, 8)\n\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n\twatcher := stitchedWatcher()\n\n\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n\twatcher.emit(registry, \"delete\", snapshotFromLink(link))\n\n\twant := []reportedEvent{{action: \"delete\", ifname: \"clab-s-0011aabb\"}}\n\tif got := drainEvents(events); !slices.Equal(got, want) {\n\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n\t}\n\n\tif _, ok := watcher.reported[7]; ok {\n\t\tt.Fatal(\"deleted link is still tracked as reported\")\n\t}\n}\n\n// TestEmitStatsReportsRenamedLinkFirst checks that counters of a link reported\n// under another name before follow its deletion under that name and its\n// creation without counters.\nfunc TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {\n\tevents := make(chan aggregatedEvent, 8)\n\tregistry := newNetlinkRegistry(t.Context(), events, false, true, time.Second)\n\twatcher := stitchedWatcher()\n\n\tlink := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{\n\t\tIndex:      7,\n\t\tName:       \"e1-1\",\n\t\tMTU:        1500,\n\t\tStatistics: &netlink.LinkStatistics{RxBytes: 10},\n\t}}\n\twatcher.emitStats(registry, snapshotFromLink(link), ifaceStatsMetrics{\n\t\tTimestamp: time.Now(),\n\t})\n\tclose(events)\n\n\tvar got []reportedEvent\n\tfor ev := range events {\n\t\tgot = append(got, reportedEvent{action: ev.Action, ifname: ev.Attributes[\"ifname\"]})\n\n\t\t_, hasCounters := ev.Attributes[\"rx_bytes\"]\n\t\tif hasCounters != (ev.Action == \"stats\") {\n\t\t\tt.Fatalf(\"%s event has counters: %v\", ev.Action, hasCounters)\n\t\t}\n\t}\n\n\twant := []reportedEvent{\n\t\t{action: \"delete\", ifname: \"clab-s-0011aabb\"},\n\t\t{action: \"create\", ifname: \"e1-1\"},\n\t\t{action: \"stats\", ifname: \"e1-1\"},\n\t}\n\tif !slices.Equal(got, want) {\n\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n\t}\n\n\tif _, ok := watcher.reported[7].attributes[\"rx_bytes\"]; ok {\n\t\tt.Fatal(\"counters are kept as what the link was reported as\")\n\t}\n}\n\n// TestReportStitchMarksLeavesUnmarkedLinks checks that links without a marked\n// stitch interface, or reported too long ago, are not reported again.\nfunc TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {\n\tevents := make(chan aggregatedEvent, 8)\n\tregistry := newNetlinkRegistry(t.Context(), events, false, false, 0)\n\twatcher := &netlinkWatcher{\n\t\tcontainer: &clabruntime.GenericContainer{Names: []string{\"n1\"}},\n\t}\n\n\trecent := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 7, Name: \"e1-1\", MTU: 1500}}\n\told := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Index: 8, Name: \"e1-2\", MTU: 1500}}\n\tstates := map[int]ifaceSnapshot{7: snapshotFromLink(recent), 8: snapshotFromLink(old)}\n\twatcher.emit(registry, \"create\", states[7])\n\twatcher.emit(registry, \"create\", states[8])\n\twatcher.reported[8] = reportedInterface{\n\t\tattributes: watcher.reported[8].attributes,\n\t\tsince:      time.Now().Add(-2 * stitchMarkWindow),\n\t}\n\n\twatcher.reportStitchMarks(states, registry)\n\n\twant := []reportedEvent{{action: \"create\", ifname: \"e1-1\"}, {action: \"create\", ifname: \"e1-2\"}}\n\tif got := drainEvents(events); !slices.Equal(got, want) {\n\t\tt.Fatalf(\"events = %v, want %v\", got, want)\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 534,
        "totalLines": 534,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565130376,
      "end": 1794565130385
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46ac894001ARAXnlyix5f7n7",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46a65d0001FWpkI8jK2UTVJJ",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 24332,
    "input": 24272,
    "output": 30,
    "reasoning": 30,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46a65d0001FWpkI8jK2UTVJJ",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565105104,
    "completed": 1794565130393
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 24332,
    "input": 24272,
    "output": 30,
    "reasoning": 30,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 6
step-start
{
  "type": "step-start",
  "id": "prt_1d46b9611001ClIB4RqMLlj6sG",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46ac89e0018Q5UXVNZqrfn34"
}
Reasoning
Now let me look at the base version of netlink.go to understand the diff fully, and relevant surrounding code: `clablinks.ToolsInterface`, `snapshotFromLink`, `interfaceAttributes`. Let me check base file.
read · completed

Input

{
  "filePath": "/source/base/core/events/netlink.go",
  "offset": 230,
  "limit": 400
}

Output

<path>/source/base/core/events/netlink.go</path>
<type>file</type>
<content>
230: 
231: 	if container.ShortID == "" {
232: 		container.ShortID = clabutils.ShortID(container.ID)
233: 	}
234: 
235: 	if runtime != nil {
236: 		container.SetRuntime(runtime)
237: 	}
238: 
239: 	return container
240: }
241: 
242: type netlinkWatcher struct {
243: 	container       *clabruntime.GenericContainer
244: 	cancel          context.CancelFunc
245: 	done            chan struct{}
246: 	includeSnapshot bool
247: 	includeStats    bool
248: 	statsInterval   time.Duration
249: 	nsHandle        netns.NsHandle
250: }
251: 
252: // Retry settings for a watcher that could not subscribe to link updates.
253: var (
254: 	watchMaxAttempts   = 5
255: 	watchRetryDelay    = time.Second
256: 	watchMaxRetryDelay = 10 * time.Second
257: )
258: 
259: func (w *netlinkWatcher) run(ctx context.Context, registry *netlinkRegistry) {
260: 	defer close(w.done)
261: 	if w.container == nil {
262: 		return
263: 	}
264: 
265: 	defer registry.remove(w.container.ID, w)
266: 
267: 	containerName := firstContainerName(w.container)
268: 	if w.container.Runtime == nil {
269: 		log.Debugf("container %s has no runtime, skipping netlink watcher", containerName)
270: 
271: 		return
272: 	}
273: 
274: 	// The states outlive a subscription, so a resubscribe only reports what
275: 	// changed while no subscription was active.
276: 	states := make(map[int]ifaceSnapshot)
277: 
278: 	var statsSamples map[int]ifaceStatsSample
279: 	if w.includeStats {
280: 		statsSamples = make(map[int]ifaceStatsSample)
281: 	}
282: 
283: 	initial := true
284: 	failures := 0
285: 	delay := watchRetryDelay
286: 
287: 	for {
288: 		subscribed, err := w.watch(ctx, registry, states, statsSamples, initial)
289: 		if ctx.Err() != nil {
290: 			return
291: 		}
292: 
293: 		if subscribed {
294: 			initial = false
295: 			failures = 0
296: 			delay = watchRetryDelay
297: 
298: 			log.Warnf(
299: 				"netlink subscription for container %s ended, resubscribing: %v",
300: 				containerName,
301: 				err,
302: 			)
303: 		} else {
304: 			failures++
305: 			if failures >= watchMaxAttempts {
306: 				log.Warnf("stopped watching interfaces of container %s: %v", containerName, err)
307: 
308: 				return
309: 			}
310: 
311: 			log.Debugf(
312: 				"failed to watch interfaces of container %s, retrying in %s: %v",
313: 				containerName,
314: 				delay,
315: 				err,
316: 			)
317: 		}
318: 
319: 		select {
320: 		case <-time.After(delay):
321: 		case <-ctx.Done():
322: 			return
323: 		}
324: 
325: 		delay = min(delay*2, watchMaxRetryDelay)
326: 	}
327: }
328: 
329: // watch subscribes to link updates in the container's namespace and handles
330: // them until ctx ends or the subscription fails. It reports whether it
331: // subscribed. The subscription lists the existing links itself, so no change
332: // between listing and subscribing is lost.
333: func (w *netlinkWatcher) watch(
334: 	ctx context.Context,
335: 	registry *netlinkRegistry,
336: 	states map[int]ifaceSnapshot,
337: 	statsSamples map[int]ifaceStatsSample,
338: 	initial bool,
339: ) (bool, error) {
340: 	nsPath, err := waitForNamespacePath(ctx, w.container.Runtime, w.container.ID)
341: 	if err != nil {
342: 		return false, fmt.Errorf("failed to resolve netns: %w", err)
343: 	}
344: 
345: 	nsHandle, err := netns.GetFromPath(nsPath)
346: 	if err != nil {
347: 		return false, fmt.Errorf("failed to open netns: %w", err)
348: 	}
349: 	defer nsHandle.Close()
350: 
351: 	w.nsHandle = nsHandle
352: 
353: 	netHandle, err := netlink.NewHandleAt(nsHandle)
354: 	if err != nil {
355: 		return false, fmt.Errorf("failed to create netlink handle: %w", err)
356: 	}
357: 	defer netHandle.Close()
358: 
359: 	netemQuery := newNetemQuerier(nsHandle)
360: 	defer netemQuery.Close()
361: 
362: 	netemInfos := netemQuery.Query()
363: 
364: 	updates := make(chan netlink.LinkUpdate, 32)
365: 	done := make(chan struct{})
366: 	defer close(done)
367: 
368: 	var (
369: 		errMu     sync.Mutex
370: 		lastError error
371: 	)
372: 
373: 	opts := netlink.LinkSubscribeOptions{
374: 		Namespace:    &nsHandle,
375: 		ListExisting: true,
376: 		// An interrupted listing is reported here too. It needs no action:
377: 		// links that changed during the listing also arrive as updates.
378: 		ErrorCallback: func(err error) {
379: 			log.Debugf(
380: 				"netlink subscription for container %s: %v",
381: 				firstContainerName(w.container),
382: 				err,
383: 			)
384: 
385: 			errMu.Lock()
386: 			lastError = err
387: 			errMu.Unlock()
388: 		},
389: 	}
390: 
391: 	if err := netlink.LinkSubscribeWithOptions(updates, done, opts); err != nil {
392: 		return false, fmt.Errorf("failed to subscribe to netlink updates: %w", err)
393: 	}
394: 
395: 	var vanished map[int]struct{}
396: 	if len(states) > 0 {
397: 		vanished = w.removeVanishedLinks(netHandle, states, statsSamples, registry)
398: 	}
399: 
400: 	// Set up netem polling interval (reuse stats interval or default to 1s).
401: 	netemPollInterval := w.statsInterval
402: 	if netemPollInterval == 0 {
403: 		netemPollInterval = time.Second
404: 	}
405: 	netemTicker := time.NewTicker(netemPollInterval)
406: 	defer netemTicker.Stop()
407: 
408: 	var (
409: 		ticker  *time.Ticker
410: 		tickerC <-chan time.Time
411: 	)
412: 	if w.includeStats && w.statsInterval > 0 {
413: 		ticker = time.NewTicker(w.statsInterval)
414: 		tickerC = ticker.C
415: 		defer ticker.Stop()
416: 	}
417: 
418: 	for {
419: 		select {
420: 		case <-tickerC:
421: 			w.collectAndEmitStats(netHandle, states, statsSamples, registry)
422: 		case <-netemTicker.C:
423: 			w.pollNetemChanges(states, registry, netemQuery)
424: 		case <-ctx.Done():
425: 			return true, nil
426: 		case update, ok := <-updates:
427: 			if !ok {
428: 				errMu.Lock()
429: 				err := lastError
430: 				errMu.Unlock()
431: 
432: 				if err == nil {
433: 					err = errors.New("update channel closed")
434: 				}
435: 
436: 				return true, err
437: 			}
438: 
439: 			// Replies to the listing carry NLM_F_MULTI, notifications do not.
440: 			if update.Header.Flags&unix.NLM_F_MULTI != 0 {
441: 				w.processExisting(
442: 					states,
443: 					statsSamples,
444: 					update.Link,
445: 					netemInfos,
446: 					vanished,
447: 					registry,
448: 					initial,
449: 				)
450: 
451: 				continue
452: 			}
453: 
454: 			w.processUpdate(states, statsSamples, update, registry, netemQuery)
455: 		}
456: 	}
457: }
458: 
459: // processExisting records a link listed when the subscription started. On the
460: // first subscription a new link is reported as a snapshot when requested; after
461: // a resubscribe it is reported as created.
462: //
463: // The listing can be older than the check in removeVanishedLinks, so it can
464: // still hold a link that check reported as deleted. Such a link is skipped; its
465: // deletion notification follows and is ignored, as the link is not tracked.
466: func (w *netlinkWatcher) processExisting(
467: 	states map[int]ifaceSnapshot,
468: 	statsSamples map[int]ifaceStatsSample,
469: 	link netlink.Link,
470: 	netemInfos map[int]netemInfo,
471: 	vanished map[int]struct{},
472: 	registry *netlinkRegistry,
473: 	initial bool,
474: ) {
475: 	if link == nil || link.Attrs() == nil {
476: 		return
477: 	}
478: 
479: 	if _, ok := vanished[link.Attrs().Index]; ok {
480: 		return
481: 	}
482: 
483: 	snapshot := withNetem(snapshotFromLink(link), netemInfos)
484: 	previous, exists := states[snapshot.Index]
485: 
486: 	if exists && snapshot.equal(previous) {
487: 		return
488: 	}
489: 
490: 	states[snapshot.Index] = snapshot
491: 	if statsSamples != nil {
492: 		if sample, ok := newStatsSample(snapshot, time.Now()); ok {
493: 			statsSamples[snapshot.Index] = sample
494: 		}
495: 	}
496: 
497: 	switch {
498: 	case exists:
499: 		registry.emitInterfaceEvent(w.container, "update", snapshot)
500: 	case !initial:
501: 		registry.emitInterfaceEvent(w.container, "create", snapshot)
502: 	case w.includeSnapshot:
503: 		registry.emitInterfaceEvent(w.container, "snapshot", snapshot)
504: 	}
505: }
506: 
507: // removeVanishedLinks reports the links that were deleted while no
508: // subscription was active and returns their indexes.
509: func (w *netlinkWatcher) removeVanishedLinks(
510: 	netHandle *netlink.Handle,
511: 	states map[int]ifaceSnapshot,
512: 	statsSamples map[int]ifaceStatsSample,
513: 	registry *netlinkRegistry,
514: ) map[int]struct{} {
515: 	current, err := snapshotInterfaces(netHandle)
516: 	if err != nil {
517: 		log.Debugf(
518: 			"failed to list interfaces of container %s: %v",
519: 			firstContainerName(w.container),
520: 			err,
521: 		)
522: 
523: 		return nil
524: 	}
525: 
526: 	vanished := map[int]struct{}{}
527: 
528: 	for idx, snapshot := range states {
529: 		if _, ok := current[idx]; ok {
530: 			continue
531: 		}
532: 
533: 		vanished[idx] = struct{}{}
534: 
535: 		delete(states, idx)
536: 		delete(statsSamples, idx)
537: 		registry.emitInterfaceEvent(w.container, "delete", snapshot)
538: 	}
539: 
540: 	return vanished
541: }
542: 
543: func (w *netlinkWatcher) processUpdate(
544: 	states map[int]ifaceSnapshot,
545: 	statsSamples map[int]ifaceStatsSample,
546: 	update netlink.LinkUpdate,
547: 	registry *netlinkRegistry,
548: 	netemQuery *netemQuerier,
549: ) {
550: 	if update.Link == nil {
551: 		return
552: 	}
553: 
554: 	attrs := update.Link.Attrs()
555: 	if attrs == nil {
556: 		return
557: 	}
558: 
559: 	snapshot := snapshotFromLink(update.Link)
560: 	previous, exists := states[snapshot.Index]
561: 
562: 	switch update.Header.Type {
563: 	case unix.RTM_DELLINK:
564: 		// A link that is not tracked was never reported, or its deletion was
565: 		// already reported when the links were listed again after a resubscribe.
566: 		if !exists {
567: 			return
568: 		}
569: 
570: 		delete(states, snapshot.Index)
571: 		delete(statsSamples, snapshot.Index)
572: 		registry.emitInterfaceEvent(w.container, "delete", previous)
573: 	case unix.RTM_NEWLINK:
574: 		// Query netem info for this interface
575: 		snapshot = withNetem(snapshot, netemQuery.Query())
576: 
577: 		if exists && snapshot.equal(previous) {
578: 			return
579: 		}
580: 
581: 		action := "create"
582: 		if exists {
583: 			action = "update"
584: 		}
585: 
586: 		states[snapshot.Index] = snapshot
587: 		if w.includeStats && statsSamples != nil {
588: 			if sample, ok := newStatsSample(snapshot, time.Now()); ok {
589: 				statsSamples[snapshot.Index] = sample
590: 			}
591: 		}
592: 		registry.emitInterfaceEvent(w.container, action, snapshot)
593: 	}
594: }
595: 
596: // pollNetemChanges checks for netem changes and emits update events.
597: func (w *netlinkWatcher) pollNetemChanges(
598: 	states map[int]ifaceSnapshot,
599: 	registry *netlinkRegistry,
600: 	netemQuery *netemQuerier,
601: ) {
602: 	netemInfos := netemQuery.Query()
603: 
604: 	for idx, snapshot := range states {
605: 		previous := snapshot
606: 		info, hasNetem := netemInfos[idx]
607: 
608: 		if hasNetem {
609: 			snapshot.HasNetem = true
610: 			snapshot.Delay = info.Delay
611: 			snapshot.Jitter = info.Jitter
612: 			snapshot.PacketLoss = info.PacketLoss
613: 			snapshot.Rate = info.Rate
614: 			snapshot.Corruption = info.Corruption
615: 		} else if snapshot.HasNetem {
616: 			// Netem was removed
617: 			snapshot.HasNetem = false
618: 			snapshot.Delay = ""
619: 			snapshot.Jitter = ""
620: 			snapshot.PacketLoss = 0
621: 			snapshot.Rate = 0
622: 			snapshot.Corruption = 0
623: 		}
624: 
625: 		if !snapshot.equal(previous) {
626: 			states[idx] = snapshot
627: 			registry.emitInterfaceEvent(w.container, "update", snapshot)
628: 		}
629: 	}

(Showing lines 230-629 of 1301. Use offset=630 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46b9923001iB0SKCt1cm6ZWo",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46ac89e0018Q5UXVNZqrfn34",
  "callID": "call_a1e8a6e05a0c40eaa52df0ff",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/base/core/events/netlink.go",
      "offset": 230,
      "limit": 400
    },
    "output": "<path>/source/base/core/events/netlink.go</path>\n<type>file</type>\n<content>\n230: \n231: \tif container.ShortID == \"\" {\n232: \t\tcontainer.ShortID = clabutils.ShortID(container.ID)\n233: \t}\n234: \n235: \tif runtime != nil {\n236: \t\tcontainer.SetRuntime(runtime)\n237: \t}\n238: \n239: \treturn container\n240: }\n241: \n242: type netlinkWatcher struct {\n243: \tcontainer       *clabruntime.GenericContainer\n244: \tcancel          context.CancelFunc\n245: \tdone            chan struct{}\n246: \tincludeSnapshot bool\n247: \tincludeStats    bool\n248: \tstatsInterval   time.Duration\n249: \tnsHandle        netns.NsHandle\n250: }\n251: \n252: // Retry settings for a watcher that could not subscribe to link updates.\n253: var (\n254: \twatchMaxAttempts   = 5\n255: \twatchRetryDelay    = time.Second\n256: \twatchMaxRetryDelay = 10 * time.Second\n257: )\n258: \n259: func (w *netlinkWatcher) run(ctx context.Context, registry *netlinkRegistry) {\n260: \tdefer close(w.done)\n261: \tif w.container == nil {\n262: \t\treturn\n263: \t}\n264: \n265: \tdefer registry.remove(w.container.ID, w)\n266: \n267: \tcontainerName := firstContainerName(w.container)\n268: \tif w.container.Runtime == nil {\n269: \t\tlog.Debugf(\"container %s has no runtime, skipping netlink watcher\", containerName)\n270: \n271: \t\treturn\n272: \t}\n273: \n274: \t// The states outlive a subscription, so a resubscribe only reports what\n275: \t// changed while no subscription was active.\n276: \tstates := make(map[int]ifaceSnapshot)\n277: \n278: \tvar statsSamples map[int]ifaceStatsSample\n279: \tif w.includeStats {\n280: \t\tstatsSamples = make(map[int]ifaceStatsSample)\n281: \t}\n282: \n283: \tinitial := true\n284: \tfailures := 0\n285: \tdelay := watchRetryDelay\n286: \n287: \tfor {\n288: \t\tsubscribed, err := w.watch(ctx, registry, states, statsSamples, initial)\n289: \t\tif ctx.Err() != nil {\n290: \t\t\treturn\n291: \t\t}\n292: \n293: \t\tif subscribed {\n294: \t\t\tinitial = false\n295: \t\t\tfailures = 0\n296: \t\t\tdelay = watchRetryDelay\n297: \n298: \t\t\tlog.Warnf(\n299: \t\t\t\t\"netlink subscription for container %s ended, resubscribing: %v\",\n300: \t\t\t\tcontainerName,\n301: \t\t\t\terr,\n302: \t\t\t)\n303: \t\t} else {\n304: \t\t\tfailures++\n305: \t\t\tif failures >= watchMaxAttempts {\n306: \t\t\t\tlog.Warnf(\"stopped watching interfaces of container %s: %v\", containerName, err)\n307: \n308: \t\t\t\treturn\n309: \t\t\t}\n310: \n311: \t\t\tlog.Debugf(\n312: \t\t\t\t\"failed to watch interfaces of container %s, retrying in %s: %v\",\n313: \t\t\t\tcontainerName,\n314: \t\t\t\tdelay,\n315: \t\t\t\terr,\n316: \t\t\t)\n317: \t\t}\n318: \n319: \t\tselect {\n320: \t\tcase <-time.After(delay):\n321: \t\tcase <-ctx.Done():\n322: \t\t\treturn\n323: \t\t}\n324: \n325: \t\tdelay = min(delay*2, watchMaxRetryDelay)\n326: \t}\n327: }\n328: \n329: // watch subscribes to link updates in the container's namespace and handles\n330: // them until ctx ends or the subscription fails. It reports whether it\n331: // subscribed. The subscription lists the existing links itself, so no change\n332: // between listing and subscribing is lost.\n333: func (w *netlinkWatcher) watch(\n334: \tctx context.Context,\n335: \tregistry *netlinkRegistry,\n336: \tstates map[int]ifaceSnapshot,\n337: \tstatsSamples map[int]ifaceStatsSample,\n338: \tinitial bool,\n339: ) (bool, error) {\n340: \tnsPath, err := waitForNamespacePath(ctx, w.container.Runtime, w.container.ID)\n341: \tif err != nil {\n342: \t\treturn false, fmt.Errorf(\"failed to resolve netns: %w\", err)\n343: \t}\n344: \n345: \tnsHandle, err := netns.GetFromPath(nsPath)\n346: \tif err != nil {\n347: \t\treturn false, fmt.Errorf(\"failed to open netns: %w\", err)\n348: \t}\n349: \tdefer nsHandle.Close()\n350: \n351: \tw.nsHandle = nsHandle\n352: \n353: \tnetHandle, err := netlink.NewHandleAt(nsHandle)\n354: \tif err != nil {\n355: \t\treturn false, fmt.Errorf(\"failed to create netlink handle: %w\", err)\n356: \t}\n357: \tdefer netHandle.Close()\n358: \n359: \tnetemQuery := newNetemQuerier(nsHandle)\n360: \tdefer netemQuery.Close()\n361: \n362: \tnetemInfos := netemQuery.Query()\n363: \n364: \tupdates := make(chan netlink.LinkUpdate, 32)\n365: \tdone := make(chan struct{})\n366: \tdefer close(done)\n367: \n368: \tvar (\n369: \t\terrMu     sync.Mutex\n370: \t\tlastError error\n371: \t)\n372: \n373: \topts := netlink.LinkSubscribeOptions{\n374: \t\tNamespace:    &nsHandle,\n375: \t\tListExisting: true,\n376: \t\t// An interrupted listing is reported here too. It needs no action:\n377: \t\t// links that changed during the listing also arrive as updates.\n378: \t\tErrorCallback: func(err error) {\n379: \t\t\tlog.Debugf(\n380: \t\t\t\t\"netlink subscription for container %s: %v\",\n381: \t\t\t\tfirstContainerName(w.container),\n382: \t\t\t\terr,\n383: \t\t\t)\n384: \n385: \t\t\terrMu.Lock()\n386: \t\t\tlastError = err\n387: \t\t\terrMu.Unlock()\n388: \t\t},\n389: \t}\n390: \n391: \tif err := netlink.LinkSubscribeWithOptions(updates, done, opts); err != nil {\n392: \t\treturn false, fmt.Errorf(\"failed to subscribe to netlink updates: %w\", err)\n393: \t}\n394: \n395: \tvar vanished map[int]struct{}\n396: \tif len(states) > 0 {\n397: \t\tvanished = w.removeVanishedLinks(netHandle, states, statsSamples, registry)\n398: \t}\n399: \n400: \t// Set up netem polling interval (reuse stats interval or default to 1s).\n401: \tnetemPollInterval := w.statsInterval\n402: \tif netemPollInterval == 0 {\n403: \t\tnetemPollInterval = time.Second\n404: \t}\n405: \tnetemTicker := time.NewTicker(netemPollInterval)\n406: \tdefer netemTicker.Stop()\n407: \n408: \tvar (\n409: \t\tticker  *time.Ticker\n410: \t\ttickerC <-chan time.Time\n411: \t)\n412: \tif w.includeStats && w.statsInterval > 0 {\n413: \t\tticker = time.NewTicker(w.statsInterval)\n414: \t\ttickerC = ticker.C\n415: \t\tdefer ticker.Stop()\n416: \t}\n417: \n418: \tfor {\n419: \t\tselect {\n420: \t\tcase <-tickerC:\n421: \t\t\tw.collectAndEmitStats(netHandle, states, statsSamples, registry)\n422: \t\tcase <-netemTicker.C:\n423: \t\t\tw.pollNetemChanges(states, registry, netemQuery)\n424: \t\tcase <-ctx.Done():\n425: \t\t\treturn true, nil\n426: \t\tcase update, ok := <-updates:\n427: \t\t\tif !ok {\n428: \t\t\t\terrMu.Lock()\n429: \t\t\t\terr := lastError\n430: \t\t\t\terrMu.Unlock()\n431: \n432: \t\t\t\tif err == nil {\n433: \t\t\t\t\terr = errors.New(\"update channel closed\")\n434: \t\t\t\t}\n435: \n436: \t\t\t\treturn true, err\n437: \t\t\t}\n438: \n439: \t\t\t// Replies to the listing carry NLM_F_MULTI, notifications do not.\n440: \t\t\tif update.Header.Flags&unix.NLM_F_MULTI != 0 {\n441: \t\t\t\tw.processExisting(\n442: \t\t\t\t\tstates,\n443: \t\t\t\t\tstatsSamples,\n444: \t\t\t\t\tupdate.Link,\n445: \t\t\t\t\tnetemInfos,\n446: \t\t\t\t\tvanished,\n447: \t\t\t\t\tregistry,\n448: \t\t\t\t\tinitial,\n449: \t\t\t\t)\n450: \n451: \t\t\t\tcontinue\n452: \t\t\t}\n453: \n454: \t\t\tw.processUpdate(states, statsSamples, update, registry, netemQuery)\n455: \t\t}\n456: \t}\n457: }\n458: \n459: // processExisting records a link listed when the subscription started. On the\n460: // first subscription a new link is reported as a snapshot when requested; after\n461: // a resubscribe it is reported as created.\n462: //\n463: // The listing can be older than the check in removeVanishedLinks, so it can\n464: // still hold a link that check reported as deleted. Such a link is skipped; its\n465: // deletion notification follows and is ignored, as the link is not tracked.\n466: func (w *netlinkWatcher) processExisting(\n467: \tstates map[int]ifaceSnapshot,\n468: \tstatsSamples map[int]ifaceStatsSample,\n469: \tlink netlink.Link,\n470: \tnetemInfos map[int]netemInfo,\n471: \tvanished map[int]struct{},\n472: \tregistry *netlinkRegistry,\n473: \tinitial bool,\n474: ) {\n475: \tif link == nil || link.Attrs() == nil {\n476: \t\treturn\n477: \t}\n478: \n479: \tif _, ok := vanished[link.Attrs().Index]; ok {\n480: \t\treturn\n481: \t}\n482: \n483: \tsnapshot := withNetem(snapshotFromLink(link), netemInfos)\n484: \tprevious, exists := states[snapshot.Index]\n485: \n486: \tif exists && snapshot.equal(previous) {\n487: \t\treturn\n488: \t}\n489: \n490: \tstates[snapshot.Index] = snapshot\n491: \tif statsSamples != nil {\n492: \t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n493: \t\t\tstatsSamples[snapshot.Index] = sample\n494: \t\t}\n495: \t}\n496: \n497: \tswitch {\n498: \tcase exists:\n499: \t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n500: \tcase !initial:\n501: \t\tregistry.emitInterfaceEvent(w.container, \"create\", snapshot)\n502: \tcase w.includeSnapshot:\n503: \t\tregistry.emitInterfaceEvent(w.container, \"snapshot\", snapshot)\n504: \t}\n505: }\n506: \n507: // removeVanishedLinks reports the links that were deleted while no\n508: // subscription was active and returns their indexes.\n509: func (w *netlinkWatcher) removeVanishedLinks(\n510: \tnetHandle *netlink.Handle,\n511: \tstates map[int]ifaceSnapshot,\n512: \tstatsSamples map[int]ifaceStatsSample,\n513: \tregistry *netlinkRegistry,\n514: ) map[int]struct{} {\n515: \tcurrent, err := snapshotInterfaces(netHandle)\n516: \tif err != nil {\n517: \t\tlog.Debugf(\n518: \t\t\t\"failed to list interfaces of container %s: %v\",\n519: \t\t\tfirstContainerName(w.container),\n520: \t\t\terr,\n521: \t\t)\n522: \n523: \t\treturn nil\n524: \t}\n525: \n526: \tvanished := map[int]struct{}{}\n527: \n528: \tfor idx, snapshot := range states {\n529: \t\tif _, ok := current[idx]; ok {\n530: \t\t\tcontinue\n531: \t\t}\n532: \n533: \t\tvanished[idx] = struct{}{}\n534: \n535: \t\tdelete(states, idx)\n536: \t\tdelete(statsSamples, idx)\n537: \t\tregistry.emitInterfaceEvent(w.container, \"delete\", snapshot)\n538: \t}\n539: \n540: \treturn vanished\n541: }\n542: \n543: func (w *netlinkWatcher) processUpdate(\n544: \tstates map[int]ifaceSnapshot,\n545: \tstatsSamples map[int]ifaceStatsSample,\n546: \tupdate netlink.LinkUpdate,\n547: \tregistry *netlinkRegistry,\n548: \tnetemQuery *netemQuerier,\n549: ) {\n550: \tif update.Link == nil {\n551: \t\treturn\n552: \t}\n553: \n554: \tattrs := update.Link.Attrs()\n555: \tif attrs == nil {\n556: \t\treturn\n557: \t}\n558: \n559: \tsnapshot := snapshotFromLink(update.Link)\n560: \tprevious, exists := states[snapshot.Index]\n561: \n562: \tswitch update.Header.Type {\n563: \tcase unix.RTM_DELLINK:\n564: \t\t// A link that is not tracked was never reported, or its deletion was\n565: \t\t// already reported when the links were listed again after a resubscribe.\n566: \t\tif !exists {\n567: \t\t\treturn\n568: \t\t}\n569: \n570: \t\tdelete(states, snapshot.Index)\n571: \t\tdelete(statsSamples, snapshot.Index)\n572: \t\tregistry.emitInterfaceEvent(w.container, \"delete\", previous)\n573: \tcase unix.RTM_NEWLINK:\n574: \t\t// Query netem info for this interface\n575: \t\tsnapshot = withNetem(snapshot, netemQuery.Query())\n576: \n577: \t\tif exists && snapshot.equal(previous) {\n578: \t\t\treturn\n579: \t\t}\n580: \n581: \t\taction := \"create\"\n582: \t\tif exists {\n583: \t\t\taction = \"update\"\n584: \t\t}\n585: \n586: \t\tstates[snapshot.Index] = snapshot\n587: \t\tif w.includeStats && statsSamples != nil {\n588: \t\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n589: \t\t\t\tstatsSamples[snapshot.Index] = sample\n590: \t\t\t}\n591: \t\t}\n592: \t\tregistry.emitInterfaceEvent(w.container, action, snapshot)\n593: \t}\n594: }\n595: \n596: // pollNetemChanges checks for netem changes and emits update events.\n597: func (w *netlinkWatcher) pollNetemChanges(\n598: \tstates map[int]ifaceSnapshot,\n599: \tregistry *netlinkRegistry,\n600: \tnetemQuery *netemQuerier,\n601: ) {\n602: \tnetemInfos := netemQuery.Query()\n603: \n604: \tfor idx, snapshot := range states {\n605: \t\tprevious := snapshot\n606: \t\tinfo, hasNetem := netemInfos[idx]\n607: \n608: \t\tif hasNetem {\n609: \t\t\tsnapshot.HasNetem = true\n610: \t\t\tsnapshot.Delay = info.Delay\n611: \t\t\tsnapshot.Jitter = info.Jitter\n612: \t\t\tsnapshot.PacketLoss = info.PacketLoss\n613: \t\t\tsnapshot.Rate = info.Rate\n614: \t\t\tsnapshot.Corruption = info.Corruption\n615: \t\t} else if snapshot.HasNetem {\n616: \t\t\t// Netem was removed\n617: \t\t\tsnapshot.HasNetem = false\n618: \t\t\tsnapshot.Delay = \"\"\n619: \t\t\tsnapshot.Jitter = \"\"\n620: \t\t\tsnapshot.PacketLoss = 0\n621: \t\t\tsnapshot.Rate = 0\n622: \t\t\tsnapshot.Corruption = 0\n623: \t\t}\n624: \n625: \t\tif !snapshot.equal(previous) {\n626: \t\t\tstates[idx] = snapshot\n627: \t\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n628: \t\t}\n629: \t}\n\n(Showing lines 230-629 of 1301. Use offset=630 to continue.)\n</content>",
    "title": "source/base/core/events/netlink.go",
    "metadata": {
      "preview": "\n\tif container.ShortID == \"\" {\n\t\tcontainer.ShortID = clabutils.ShortID(container.ID)\n\t}\n\n\tif runtime != nil {\n\t\tcontainer.SetRuntime(runtime)\n\t}\n\n\treturn container\n}\n\ntype netlinkWatcher struct {\n\tcontainer       *clabruntime.GenericContainer\n\tcancel          context.CancelFunc\n\tdone            chan struct{}\n\tincludeSnapshot bool\n\tincludeStats    bool\n\tstatsInterval   time.Duration\n\tnsHandle        netns.NsHandle",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/base/core/events/netlink.go",
        "text": "\n\tif container.ShortID == \"\" {\n\t\tcontainer.ShortID = clabutils.ShortID(container.ID)\n\t}\n\n\tif runtime != nil {\n\t\tcontainer.SetRuntime(runtime)\n\t}\n\n\treturn container\n}\n\ntype netlinkWatcher struct {\n\tcontainer       *clabruntime.GenericContainer\n\tcancel          context.CancelFunc\n\tdone            chan struct{}\n\tincludeSnapshot bool\n\tincludeStats    bool\n\tstatsInterval   time.Duration\n\tnsHandle        netns.NsHandle\n}\n\n// Retry settings for a watcher that could not subscribe to link updates.\nvar (\n\twatchMaxAttempts   = 5\n\twatchRetryDelay    = time.Second\n\twatchMaxRetryDelay = 10 * time.Second\n)\n\nfunc (w *netlinkWatcher) run(ctx context.Context, registry *netlinkRegistry) {\n\tdefer close(w.done)\n\tif w.container == nil {\n\t\treturn\n\t}\n\n\tdefer registry.remove(w.container.ID, w)\n\n\tcontainerName := firstContainerName(w.container)\n\tif w.container.Runtime == nil {\n\t\tlog.Debugf(\"container %s has no runtime, skipping netlink watcher\", containerName)\n\n\t\treturn\n\t}\n\n\t// The states outlive a subscription, so a resubscribe only reports what\n\t// changed while no subscription was active.\n\tstates := make(map[int]ifaceSnapshot)\n\n\tvar statsSamples map[int]ifaceStatsSample\n\tif w.includeStats {\n\t\tstatsSamples = make(map[int]ifaceStatsSample)\n\t}\n\n\tinitial := true\n\tfailures := 0\n\tdelay := watchRetryDelay\n\n\tfor {\n\t\tsubscribed, err := w.watch(ctx, registry, states, statsSamples, initial)\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif subscribed {\n\t\t\tinitial = false\n\t\t\tfailures = 0\n\t\t\tdelay = watchRetryDelay\n\n\t\t\tlog.Warnf(\n\t\t\t\t\"netlink subscription for container %s ended, resubscribing: %v\",\n\t\t\t\tcontainerName,\n\t\t\t\terr,\n\t\t\t)\n\t\t} else {\n\t\t\tfailures++\n\t\t\tif failures >= watchMaxAttempts {\n\t\t\t\tlog.Warnf(\"stopped watching interfaces of container %s: %v\", containerName, err)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Debugf(\n\t\t\t\t\"failed to watch interfaces of container %s, retrying in %s: %v\",\n\t\t\t\tcontainerName,\n\t\t\t\tdelay,\n\t\t\t\terr,\n\t\t\t)\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(delay):\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\n\t\tdelay = min(delay*2, watchMaxRetryDelay)\n\t}\n}\n\n// watch subscribes to link updates in the container's namespace and handles\n// them until ctx ends or the subscription fails. It reports whether it\n// subscribed. The subscription lists the existing links itself, so no change\n// between listing and subscribing is lost.\nfunc (w *netlinkWatcher) watch(\n\tctx context.Context,\n\tregistry *netlinkRegistry,\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tinitial bool,\n) (bool, error) {\n\tnsPath, err := waitForNamespacePath(ctx, w.container.Runtime, w.container.ID)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to resolve netns: %w\", err)\n\t}\n\n\tnsHandle, err := netns.GetFromPath(nsPath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to open netns: %w\", err)\n\t}\n\tdefer nsHandle.Close()\n\n\tw.nsHandle = nsHandle\n\n\tnetHandle, err := netlink.NewHandleAt(nsHandle)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to create netlink handle: %w\", err)\n\t}\n\tdefer netHandle.Close()\n\n\tnetemQuery := newNetemQuerier(nsHandle)\n\tdefer netemQuery.Close()\n\n\tnetemInfos := netemQuery.Query()\n\n\tupdates := make(chan netlink.LinkUpdate, 32)\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tvar (\n\t\terrMu     sync.Mutex\n\t\tlastError error\n\t)\n\n\topts := netlink.LinkSubscribeOptions{\n\t\tNamespace:    &nsHandle,\n\t\tListExisting: true,\n\t\t// An interrupted listing is reported here too. It needs no action:\n\t\t// links that changed during the listing also arrive as updates.\n\t\tErrorCallback: func(err error) {\n\t\t\tlog.Debugf(\n\t\t\t\t\"netlink subscription for container %s: %v\",\n\t\t\t\tfirstContainerName(w.container),\n\t\t\t\terr,\n\t\t\t)\n\n\t\t\terrMu.Lock()\n\t\t\tlastError = err\n\t\t\terrMu.Unlock()\n\t\t},\n\t}\n\n\tif err := netlink.LinkSubscribeWithOptions(updates, done, opts); err != nil {\n\t\treturn false, fmt.Errorf(\"failed to subscribe to netlink updates: %w\", err)\n\t}\n\n\tvar vanished map[int]struct{}\n\tif len(states) > 0 {\n\t\tvanished = w.removeVanishedLinks(netHandle, states, statsSamples, registry)\n\t}\n\n\t// Set up netem polling interval (reuse stats interval or default to 1s).\n\tnetemPollInterval := w.statsInterval\n\tif netemPollInterval == 0 {\n\t\tnetemPollInterval = time.Second\n\t}\n\tnetemTicker := time.NewTicker(netemPollInterval)\n\tdefer netemTicker.Stop()\n\n\tvar (\n\t\tticker  *time.Ticker\n\t\ttickerC <-chan time.Time\n\t)\n\tif w.includeStats && w.statsInterval > 0 {\n\t\tticker = time.NewTicker(w.statsInterval)\n\t\ttickerC = ticker.C\n\t\tdefer ticker.Stop()\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-tickerC:\n\t\t\tw.collectAndEmitStats(netHandle, states, statsSamples, registry)\n\t\tcase <-netemTicker.C:\n\t\t\tw.pollNetemChanges(states, registry, netemQuery)\n\t\tcase <-ctx.Done():\n\t\t\treturn true, nil\n\t\tcase update, ok := <-updates:\n\t\t\tif !ok {\n\t\t\t\terrMu.Lock()\n\t\t\t\terr := lastError\n\t\t\t\terrMu.Unlock()\n\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = errors.New(\"update channel closed\")\n\t\t\t\t}\n\n\t\t\t\treturn true, err\n\t\t\t}\n\n\t\t\t// Replies to the listing carry NLM_F_MULTI, notifications do not.\n\t\t\tif update.Header.Flags&unix.NLM_F_MULTI != 0 {\n\t\t\t\tw.processExisting(\n\t\t\t\t\tstates,\n\t\t\t\t\tstatsSamples,\n\t\t\t\t\tupdate.Link,\n\t\t\t\t\tnetemInfos,\n\t\t\t\t\tvanished,\n\t\t\t\t\tregistry,\n\t\t\t\t\tinitial,\n\t\t\t\t)\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tw.processUpdate(states, statsSamples, update, registry, netemQuery)\n\t\t}\n\t}\n}\n\n// processExisting records a link listed when the subscription started. On the\n// first subscription a new link is reported as a snapshot when requested; after\n// a resubscribe it is reported as created.\n//\n// The listing can be older than the check in removeVanishedLinks, so it can\n// still hold a link that check reported as deleted. Such a link is skipped; its\n// deletion notification follows and is ignored, as the link is not tracked.\nfunc (w *netlinkWatcher) processExisting(\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tlink netlink.Link,\n\tnetemInfos map[int]netemInfo,\n\tvanished map[int]struct{},\n\tregistry *netlinkRegistry,\n\tinitial bool,\n) {\n\tif link == nil || link.Attrs() == nil {\n\t\treturn\n\t}\n\n\tif _, ok := vanished[link.Attrs().Index]; ok {\n\t\treturn\n\t}\n\n\tsnapshot := withNetem(snapshotFromLink(link), netemInfos)\n\tprevious, exists := states[snapshot.Index]\n\n\tif exists && snapshot.equal(previous) {\n\t\treturn\n\t}\n\n\tstates[snapshot.Index] = snapshot\n\tif statsSamples != nil {\n\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n\t\t\tstatsSamples[snapshot.Index] = sample\n\t\t}\n\t}\n\n\tswitch {\n\tcase exists:\n\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n\tcase !initial:\n\t\tregistry.emitInterfaceEvent(w.container, \"create\", snapshot)\n\tcase w.includeSnapshot:\n\t\tregistry.emitInterfaceEvent(w.container, \"snapshot\", snapshot)\n\t}\n}\n\n// removeVanishedLinks reports the links that were deleted while no\n// subscription was active and returns their indexes.\nfunc (w *netlinkWatcher) removeVanishedLinks(\n\tnetHandle *netlink.Handle,\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tregistry *netlinkRegistry,\n) map[int]struct{} {\n\tcurrent, err := snapshotInterfaces(netHandle)\n\tif err != nil {\n\t\tlog.Debugf(\n\t\t\t\"failed to list interfaces of container %s: %v\",\n\t\t\tfirstContainerName(w.container),\n\t\t\terr,\n\t\t)\n\n\t\treturn nil\n\t}\n\n\tvanished := map[int]struct{}{}\n\n\tfor idx, snapshot := range states {\n\t\tif _, ok := current[idx]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tvanished[idx] = struct{}{}\n\n\t\tdelete(states, idx)\n\t\tdelete(statsSamples, idx)\n\t\tregistry.emitInterfaceEvent(w.container, \"delete\", snapshot)\n\t}\n\n\treturn vanished\n}\n\nfunc (w *netlinkWatcher) processUpdate(\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tupdate netlink.LinkUpdate,\n\tregistry *netlinkRegistry,\n\tnetemQuery *netemQuerier,\n) {\n\tif update.Link == nil {\n\t\treturn\n\t}\n\n\tattrs := update.Link.Attrs()\n\tif attrs == nil {\n\t\treturn\n\t}\n\n\tsnapshot := snapshotFromLink(update.Link)\n\tprevious, exists := states[snapshot.Index]\n\n\tswitch update.Header.Type {\n\tcase unix.RTM_DELLINK:\n\t\t// A link that is not tracked was never reported, or its deletion was\n\t\t// already reported when the links were listed again after a resubscribe.\n\t\tif !exists {\n\t\t\treturn\n\t\t}\n\n\t\tdelete(states, snapshot.Index)\n\t\tdelete(statsSamples, snapshot.Index)\n\t\tregistry.emitInterfaceEvent(w.container, \"delete\", previous)\n\tcase unix.RTM_NEWLINK:\n\t\t// Query netem info for this interface\n\t\tsnapshot = withNetem(snapshot, netemQuery.Query())\n\n\t\tif exists && snapshot.equal(previous) {\n\t\t\treturn\n\t\t}\n\n\t\taction := \"create\"\n\t\tif exists {\n\t\t\taction = \"update\"\n\t\t}\n\n\t\tstates[snapshot.Index] = snapshot\n\t\tif w.includeStats && statsSamples != nil {\n\t\t\tif sample, ok := newStatsSample(snapshot, time.Now()); ok {\n\t\t\t\tstatsSamples[snapshot.Index] = sample\n\t\t\t}\n\t\t}\n\t\tregistry.emitInterfaceEvent(w.container, action, snapshot)\n\t}\n}\n\n// pollNetemChanges checks for netem changes and emits update events.\nfunc (w *netlinkWatcher) pollNetemChanges(\n\tstates map[int]ifaceSnapshot,\n\tregistry *netlinkRegistry,\n\tnetemQuery *netemQuerier,\n) {\n\tnetemInfos := netemQuery.Query()\n\n\tfor idx, snapshot := range states {\n\t\tprevious := snapshot\n\t\tinfo, hasNetem := netemInfos[idx]\n\n\t\tif hasNetem {\n\t\t\tsnapshot.HasNetem = true\n\t\t\tsnapshot.Delay = info.Delay\n\t\t\tsnapshot.Jitter = info.Jitter\n\t\t\tsnapshot.PacketLoss = info.PacketLoss\n\t\t\tsnapshot.Rate = info.Rate\n\t\t\tsnapshot.Corruption = info.Corruption\n\t\t} else if snapshot.HasNetem {\n\t\t\t// Netem was removed\n\t\t\tsnapshot.HasNetem = false\n\t\t\tsnapshot.Delay = \"\"\n\t\t\tsnapshot.Jitter = \"\"\n\t\t\tsnapshot.PacketLoss = 0\n\t\t\tsnapshot.Rate = 0\n\t\t\tsnapshot.Corruption = 0\n\t\t}\n\n\t\tif !snapshot.equal(previous) {\n\t\t\tstates[idx] = snapshot\n\t\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n\t\t}\n\t}",
        "lineStart": 230,
        "lineEnd": 629,
        "totalLines": 1301,
        "truncated": true
      }
    },
    "time": {
      "start": 1794565183783,
      "end": 1794565183795
    }
  }
}
grep · completed

Input

{
  "pattern": "func ToolsInterface",
  "path": "/source/head"
}

Output

Found 1 matches
/source/head/links/link_veth_stitched.go:
  Line 302: func ToolsInterface(labName, node, iface string) (netlink.Link, bool) {
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46b99ef001NnuHlRNd6cuLe9",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46ac89e0018Q5UXVNZqrfn34",
  "callID": "call_6d81f6c3483d40b6be19d27f",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "func ToolsInterface",
      "path": "/source/head"
    },
    "output": "Found 1 matches\n/source/head/links/link_veth_stitched.go:\n  Line 302: func ToolsInterface(labName, node, iface string) (netlink.Link, bool) {\n",
    "title": "func ToolsInterface",
    "metadata": {
      "matches": 1,
      "truncated": false
    },
    "time": {
      "start": 1794565183991,
      "end": 1794565184025
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46b9a1b001ztT4Y768iLmT2o",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46ac89e0018Q5UXVNZqrfn34",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 49728,
    "input": 49636,
    "output": 46,
    "reasoning": 46,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46ac89e0018Q5UXVNZqrfn34",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565130398,
    "completed": 1794565184031
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 49728,
    "input": 49636,
    "output": 46,
    "reasoning": 46,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 7
step-start
{
  "type": "step-start",
  "id": "prt_1d46c2645001ZUyvLPMdwzk87L",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46b9a24001Ce2Cpb3gT2XX1c"
}
Reasoning
Let me see the rest of the base file (lines 630-1301) and the ToolsInterface function.
read · completed

Input

{
  "filePath": "/source/base/core/events/netlink.go",
  "limit": 680,
  "offset": 630
}

Output

<path>/source/base/core/events/netlink.go</path>
<type>file</type>
<content>
630: }
631: 
632: func firstContainerName(container *clabruntime.GenericContainer) string {
633: 	if container == nil || len(container.Names) == 0 {
634: 		return ""
635: 	}
636: 
637: 	return container.Names[0]
638: }
639: 
640: func containerLabel(container *clabruntime.GenericContainer) string {
641: 	if container == nil || container.Labels == nil {
642: 		return ""
643: 	}
644: 
645: 	return container.Labels[clabconstants.Containerlab]
646: }
647: 
648: // interfaceSnapshotAttributes are the attributes every interface event reports for the
649: // interface itself.
650: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {
651: 	attributes := map[string]string{
652: 		"ifname": snapshot.Name,
653: 		"index":  strconv.Itoa(snapshot.Index),
654: 		"mtu":    strconv.Itoa(snapshot.MTU),
655: 		"state":  snapshot.OperState,
656: 		"type":   snapshot.Type,
657: 	}
658: 
659: 	if snapshot.Alias != "" {
660: 		attributes["alias"] = snapshot.Alias
661: 	}
662: 
663: 	if snapshot.MAC != "" {
664: 		attributes["mac"] = snapshot.MAC
665: 	}
666: 
667: 	return attributes
668: }
669: 
670: // interfaceStatsAttributes adds the counters and rates of a stats event.
671: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {
672: 	attributes["rx_bytes"] = strconv.FormatUint(metrics.RxBytes, 10)
673: 	attributes["tx_bytes"] = strconv.FormatUint(metrics.TxBytes, 10)
674: 	attributes["rx_packets"] = strconv.FormatUint(metrics.RxPackets, 10)
675: 	attributes["tx_packets"] = strconv.FormatUint(metrics.TxPackets, 10)
676: 	attributes["rx_bps"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)
677: 	attributes["tx_bps"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)
678: 	attributes["rx_pps"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)
679: 	attributes["tx_pps"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)
680: 	attributes["interval_seconds"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)
681: }
682: 
683: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those
684: // of the netlink interface events, for the node the runtime runs. Values the runtime could not
685: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.
686: func labRuntimeInterfaceAttributes(
687: 	lab, name string,
688: 	iface *clablabruntime.InterfaceEventData,
689: ) map[string]string {
690: 	attributes := interfaceSnapshotAttributes(ifaceSnapshot{
691: 		Index:     iface.Index,
692: 		Name:      iface.Name,
693: 		Alias:     iface.Alias,
694: 		MTU:       iface.MTU,
695: 		MAC:       iface.MAC,
696: 		OperState: iface.OperState,
697: 		Type:      iface.Type,
698: 	})
699: 	if iface.Index <= 0 {
700: 		delete(attributes, "index")
701: 	}
702: 	if iface.MTU <= 0 {
703: 		delete(attributes, "mtu")
704: 	}
705: 
706: 	if lab != "" {
707: 		attributes["lab"] = lab
708: 	}
709: 	if name != "" {
710: 		attributes["name"] = name
711: 	}
712: 
713: 	if stats := iface.Stats; stats != nil {
714: 		interfaceStatsAttributes(attributes, ifaceStatsMetrics{
715: 			RxBytes:   stats.RxBytes,
716: 			TxBytes:   stats.TxBytes,
717: 			RxPackets: stats.RxPackets,
718: 			TxPackets: stats.TxPackets,
719: 			RxBps:     stats.RxBps,
720: 			TxBps:     stats.TxBps,
721: 			RxPps:     stats.RxPps,
722: 			TxPps:     stats.TxPps,
723: 			Interval:  stats.Interval,
724: 		})
725: 	}
726: 
727: 	return attributes
728: }
729: 
730: func interfaceAttributes(
731: 	container *clabruntime.GenericContainer,
732: 	snapshot ifaceSnapshot,
733: ) map[string]string {
734: 	attributes := interfaceSnapshotAttributes(snapshot)
735: 	attributes["origin"] = "netlink"
736: 
737: 	if lab := containerLabel(container); lab != "" {
738: 		attributes["lab"] = lab
739: 	}
740: 
741: 	if name := firstContainerName(container); name != "" {
742: 		attributes["name"] = name
743: 	}
744: 
745: 	overlayToolsInterface(container, attributes)
746: 
747: 	// Add netem attributes if present
748: 	if snapshot.HasNetem {
749: 		if snapshot.Delay != "" {
750: 			attributes["netem_delay"] = snapshot.Delay
751: 		}
752: 		if snapshot.Jitter != "" {
753: 			attributes["netem_jitter"] = snapshot.Jitter
754: 		}
755: 		if snapshot.PacketLoss != 0 {
756: 			attributes["netem_loss"] = strconv.FormatFloat(snapshot.PacketLoss, 'f', 2, 64) + "%"
757: 		}
758: 		if snapshot.Rate != 0 {
759: 			attributes["netem_rate"] = strconv.Itoa(snapshot.Rate) + "kbit"
760: 		}
761: 		if snapshot.Corruption != 0 {
762: 			attributes["netem_corruption"] = strconv.FormatFloat(
763: 				snapshot.Corruption,
764: 				'f',
765: 				2,
766: 				64,
767: 			) + "%"
768: 		}
769: 	}
770: 
771: 	return attributes
772: }
773: 
774: // overlayToolsInterface rewrites attributes to the host-side stitch interface
775: // when one exists, matching `inspect interfaces`.
776: func overlayToolsInterface(
777: 	container *clabruntime.GenericContainer,
778: 	attributes map[string]string,
779: ) {
780: 	if container == nil {
781: 		return
782: 	}
783: 
784: 	lab, node := clabcore.TopoIdentity(container.Labels)
785: 	if lab == "" || node == "" {
786: 		return
787: 	}
788: 
789: 	topoName := attributes["alias"]
790: 	if topoName == "" {
791: 		topoName = attributes["ifname"]
792: 	}
793: 
794: 	tools, ok := clablinks.ToolsInterface(lab, node, topoName)
795: 	if !ok {
796: 		return
797: 	}
798: 
799: 	snapshot := snapshotFromLink(tools)
800: 	attributes["ifname"] = snapshot.Name
801: 	attributes["alias"] = topoName
802: 	attributes["index"] = strconv.Itoa(snapshot.Index)
803: 	attributes["mtu"] = strconv.Itoa(snapshot.MTU)
804: 	attributes["state"] = snapshot.OperState
805: 	attributes["type"] = snapshot.Type
806: 
807: 	if snapshot.MAC != "" {
808: 		attributes["mac"] = snapshot.MAC
809: 	}
810: }
811: 
812: func (r *netlinkRegistry) emitInterfaceEvent(
813: 	container *clabruntime.GenericContainer,
814: 	action string,
815: 	snapshot ifaceSnapshot,
816: ) {
817: 	if container == nil {
818: 		return
819: 	}
820: 
821: 	attributes := interfaceAttributes(container, snapshot)
822: 
823: 	event := aggregatedEvent{
824: 		Timestamp:   time.Now(),
825: 		Type:        "interface",
826: 		Action:      action,
827: 		ActorID:     container.ShortID,
828: 		ActorName:   firstContainerName(container),
829: 		ActorFullID: container.ID,
830: 		Attributes:  attributes,
831: 	}
832: 
833: 	select {
834: 	case r.events <- event:
835: 	case <-r.ctx.Done():
836: 	}
837: }
838: 
839: func waitForNamespacePath(
840: 	ctx context.Context,
841: 	runtime clabruntime.ContainerRuntime,
842: 	containerID string,
843: ) (string, error) {
844: 	const (
845: 		attempts   = 5
846: 		retryDelay = 200 * time.Millisecond
847: 	)
848: 
849: 	var lastErr error
850: 
851: 	for i := 0; i < attempts; i++ {
852: 		nsPath, err := runtime.GetNSPath(ctx, containerID)
853: 		if err == nil && nsPath != "" {
854: 			return nsPath, nil
855: 		}
856: 
857: 		if err != nil {
858: 			lastErr = err
859: 		}
860: 
861: 		select {
862: 		case <-time.After(retryDelay):
863: 		case <-ctx.Done():
864: 			return "", ctx.Err()
865: 		}
866: 	}
867: 
868: 	if lastErr != nil {
869: 		return "", lastErr
870: 	}
871: 
872: 	return "", fmt.Errorf("namespace path not ready for container %s", containerID)
873: }
874: 
875: func (r *netlinkRegistry) emitInterfaceStatsEvent(
876: 	container *clabruntime.GenericContainer,
877: 	snapshot ifaceSnapshot,
878: 	metrics ifaceStatsMetrics,
879: ) {
880: 	if !r.includeStats || container == nil || !snapshot.HasStats {
881: 		return
882: 	}
883: 
884: 	attributes := interfaceAttributes(container, snapshot)
885: 	interfaceStatsAttributes(attributes, metrics)
886: 
887: 	event := aggregatedEvent{
888: 		Timestamp:   metrics.Timestamp,
889: 		Type:        "interface",
890: 		Action:      "stats",
891: 		ActorID:     container.ShortID,
892: 		ActorName:   firstContainerName(container),
893: 		ActorFullID: container.ID,
894: 		Attributes:  attributes,
895: 	}
896: 
897: 	select {
898: 	case r.events <- event:
899: 	case <-r.ctx.Done():
900: 	}
901: }
902: 
903: func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {
904: 	if netHandle == nil {
905: 		return nil, fmt.Errorf("netlink handle is nil")
906: 	}
907: 
908: 	links, err := netHandle.LinkList()
909: 	if err != nil {
910: 		return nil, fmt.Errorf("unable to list links: %w", err)
911: 	}
912: 
913: 	states := make(map[int]ifaceSnapshot, len(links))
914: 	for _, link := range links {
915: 		snapshot := snapshotFromLink(link)
916: 		states[snapshot.Index] = snapshot
917: 	}
918: 
919: 	return states, nil
920: }
921: 
922: // withNetem returns the snapshot with the netem settings of its interface.
923: func withNetem(snapshot ifaceSnapshot, netemInfos map[int]netemInfo) ifaceSnapshot {
924: 	if info, ok := netemInfos[snapshot.Index]; ok {
925: 		snapshot.HasNetem = true
926: 		snapshot.Delay = info.Delay
927: 		snapshot.Jitter = info.Jitter
928: 		snapshot.PacketLoss = info.PacketLoss
929: 		snapshot.Rate = info.Rate
930: 		snapshot.Corruption = info.Corruption
931: 	}
932: 
933: 	return snapshot
934: }
935: 
936: func snapshotFromLink(link netlink.Link) ifaceSnapshot {
937: 	attrs := link.Attrs()
938: 
939: 	snapshot := ifaceSnapshot{
940: 		Type: link.Type(),
941: 	}
942: 
943: 	if attrs != nil {
944: 		snapshot.Index = attrs.Index
945: 		snapshot.Name = attrs.Name
946: 		snapshot.Alias = attrs.Alias
947: 		snapshot.MTU = attrs.MTU
948: 		if len(attrs.HardwareAddr) > 0 {
949: 			snapshot.MAC = attrs.HardwareAddr.String()
950: 		}
951: 		snapshot.OperState = attrs.OperState.String()
952: 		if stats := attrs.Statistics; stats != nil {
953: 			snapshot.HasStats = true
954: 			snapshot.RxBytes = stats.RxBytes
955: 			snapshot.TxBytes = stats.TxBytes
956: 			snapshot.RxPackets = stats.RxPackets
957: 			snapshot.TxPackets = stats.TxPackets
958: 		}
959: 	}
960: 
961: 	return snapshot
962: }
963: 
964: type ifaceSnapshot struct {
965: 	Index     int
966: 	Name      string
967: 	Alias     string
968: 	MTU       int
969: 	MAC       string
970: 	OperState string
971: 	Type      string
972: 	HasStats  bool
973: 	RxBytes   uint64
974: 	TxBytes   uint64
975: 	RxPackets uint64
976: 	TxPackets uint64
977: 	// Netem fields
978: 	HasNetem   bool
979: 	Delay      string
980: 	Jitter     string
981: 	PacketLoss float64
982: 	Rate       int
983: 	Corruption float64
984: }
985: 
986: func (s ifaceSnapshot) equal(other ifaceSnapshot) bool {
987: 	return s.Index == other.Index &&
988: 		s.Name == other.Name &&
989: 		s.Alias == other.Alias &&
990: 		s.MTU == other.MTU &&
991: 		s.MAC == other.MAC &&
992: 		s.OperState == other.OperState &&
993: 		s.Type == other.Type &&
994: 		s.HasNetem == other.HasNetem &&
995: 		s.Delay == other.Delay &&
996: 		s.Jitter == other.Jitter &&
997: 		s.PacketLoss == other.PacketLoss &&
998: 		s.Rate == other.Rate &&
999: 		s.Corruption == other.Corruption
1000: }
1001: 
1002: type ifaceStatsSample struct {
1003: 	RxBytes   uint64
1004: 	TxBytes   uint64
1005: 	RxPackets uint64
1006: 	TxPackets uint64
1007: 	Timestamp time.Time
1008: }
1009: 
1010: type ifaceStatsMetrics struct {
1011: 	RxBytes   uint64
1012: 	TxBytes   uint64
1013: 	RxPackets uint64
1014: 	TxPackets uint64
1015: 	RxBps     float64
1016: 	TxBps     float64
1017: 	RxPps     float64
1018: 	TxPps     float64
1019: 	Interval  time.Duration
1020: 	Timestamp time.Time
1021: }
1022: 
1023: func newStatsSample(snapshot ifaceSnapshot, timestamp time.Time) (ifaceStatsSample, bool) {
1024: 	if !snapshot.HasStats {
1025: 		return ifaceStatsSample{}, false
1026: 	}
1027: 
1028: 	return ifaceStatsSample{
1029: 		RxBytes:   snapshot.RxBytes,
1030: 		TxBytes:   snapshot.TxBytes,
1031: 		RxPackets: snapshot.RxPackets,
1032: 		TxPackets: snapshot.TxPackets,
1033: 		Timestamp: timestamp,
1034: 	}, true
1035: }
1036: 
1037: func (w *netlinkWatcher) collectAndEmitStats(
1038: 	netHandle *netlink.Handle,
1039: 	states map[int]ifaceSnapshot,
1040: 	statsSamples map[int]ifaceStatsSample,
1041: 	registry *netlinkRegistry,
1042: ) {
1043: 	if netHandle == nil || statsSamples == nil {
1044: 		return
1045: 	}
1046: 
1047: 	now := time.Now()
1048: 	// Fetch all interfaces with one netlink call per tick instead of one call
1049: 	// per interface to reduce syscall overhead in large labs.
1050: 	currentStates, err := snapshotInterfaces(netHandle)
1051: 	if err != nil {
1052: 		log.Debugf(
1053: 			"failed to collect interface stats snapshot for container %s: %v",
1054: 			firstContainerName(w.container),
1055: 			err,
1056: 		)
1057: 
1058: 		return
1059: 	}
1060: 
1061: 	for idx, state := range states {
1062: 		current, ok := currentStates[idx]
1063: 		if !ok {
1064: 			continue
1065: 		}
1066: 
1067: 		state.Name = current.Name
1068: 		state.Alias = current.Alias
1069: 		state.MTU = current.MTU
1070: 		state.MAC = current.MAC
1071: 		state.OperState = current.OperState
1072: 		state.Type = current.Type
1073: 		state.HasStats = current.HasStats
1074: 		state.RxBytes = current.RxBytes
1075: 		state.TxBytes = current.TxBytes
1076: 		state.RxPackets = current.RxPackets
1077: 		state.TxPackets = current.TxPackets
1078: 		states[idx] = state
1079: 
1080: 		if !state.HasStats {
1081: 			delete(statsSamples, idx)
1082: 
1083: 			continue
1084: 		}
1085: 
1086: 		prev, ok := statsSamples[idx]
1087: 		if !ok || now.Sub(prev.Timestamp) <= 0 {
1088: 			statsSamples[idx] = ifaceStatsSample{
1089: 				RxBytes:   state.RxBytes,
1090: 				TxBytes:   state.TxBytes,
1091: 				RxPackets: state.RxPackets,
1092: 				TxPackets: state.TxPackets,
1093: 				Timestamp: now,
1094: 			}
1095: 
1096: 			continue
1097: 		}
1098: 
1099: 		interval := now.Sub(prev.Timestamp)
1100: 		if interval <= 0 {
1101: 			statsSamples[idx] = ifaceStatsSample{
1102: 				RxBytes:   state.RxBytes,
1103: 				TxBytes:   state.TxBytes,
1104: 				RxPackets: state.RxPackets,
1105: 				TxPackets: state.TxPackets,
1106: 				Timestamp: now,
1107: 			}
1108: 
1109: 			continue
1110: 		}
1111: 
1112: 		rxBytesDelta := deltaCounter(prev.RxBytes, state.RxBytes)
1113: 		txBytesDelta := deltaCounter(prev.TxBytes, state.TxBytes)
1114: 		rxPacketsDelta := deltaCounter(prev.RxPackets, state.RxPackets)
1115: 		txPacketsDelta := deltaCounter(prev.TxPackets, state.TxPackets)
1116: 
1117: 		seconds := interval.Seconds()
1118: 		if seconds <= 0 {
1119: 			statsSamples[idx] = ifaceStatsSample{
1120: 				RxBytes:   state.RxBytes,
1121: 				TxBytes:   state.TxBytes,
1122: 				RxPackets: state.RxPackets,
1123: 				TxPackets: state.TxPackets,
1124: 				Timestamp: now,
1125: 			}
1126: 
1127: 			continue
1128: 		}
1129: 
1130: 		metrics := ifaceStatsMetrics{
1131: 			RxBytes:   state.RxBytes,
1132: 			TxBytes:   state.TxBytes,
1133: 			RxPackets: state.RxPackets,
1134: 			TxPackets: state.TxPackets,
1135: 			RxBps:     float64(rxBytesDelta) * 8 / seconds,
1136: 			TxBps:     float64(txBytesDelta) * 8 / seconds,
1137: 			RxPps:     float64(rxPacketsDelta) / seconds,
1138: 			TxPps:     float64(txPacketsDelta) / seconds,
1139: 			Interval:  interval,
1140: 			Timestamp: now,
1141: 		}
1142: 
1143: 		registry.emitInterfaceStatsEvent(w.container, state, metrics)
1144: 
1145: 		statsSamples[idx] = ifaceStatsSample{
1146: 			RxBytes:   state.RxBytes,
1147: 			TxBytes:   state.TxBytes,
1148: 			RxPackets: state.RxPackets,
1149: 			TxPackets: state.TxPackets,
1150: 			Timestamp: now,
1151: 		}
1152: 	}
1153: }
1154: 
1155: func deltaCounter(previous, current uint64) uint64 {
1156: 	if current >= previous {
1157: 		return current - previous
1158: 	}
1159: 
1160: 	return current
1161: }
1162: 
1163: const (
1164: 	msPerSec = 1000
1165: )
1166: 
1167: type netemQuerier struct {
1168: 	nsHandle netns.NsHandle
1169: 	tcHandle *gotc.Tc
1170: }
1171: 
1172: func newNetemQuerier(nsHandle netns.NsHandle) *netemQuerier {
1173: 	return &netemQuerier{
1174: 		nsHandle: nsHandle,
1175: 	}
1176: }
1177: 
1178: func (q *netemQuerier) Close() {
1179: 	if q == nil || q.tcHandle == nil {
1180: 		return
1181: 	}
1182: 
1183: 	q.tcHandle.Close()
1184: 	q.tcHandle = nil
1185: }
1186: 
1187: // Query queries the TC qdiscs in the namespace and returns a map of
1188: // interface index to netem data.
1189: func (q *netemQuerier) Query() map[int]netemInfo {
1190: 	result := make(map[int]netemInfo)
1191: 
1192: 	qdiscs, err := q.qdiscs()
1193: 	if err != nil {
1194: 		log.Debugf("failed to query tc qdiscs: %v", err)
1195: 		return result
1196: 	}
1197: 
1198: 	for idx := range qdiscs {
1199: 		qdisc := &qdiscs[idx]
1200: 		if qdisc.Attribute.Kind != "netem" || qdisc.Netem == nil {
1201: 			continue
1202: 		}
1203: 
1204: 		info := netemInfoFromQdisc(qdisc)
1205: 		if info.hasValues() {
1206: 			result[int(qdisc.Ifindex)] = info
1207: 		}
1208: 	}
1209: 
1210: 	return result
1211: }
1212: 
1213: func (q *netemQuerier) qdiscs() ([]gotc.Object, error) {
1214: 	if q == nil {
1215: 		return nil, fmt.Errorf("netem querier is nil")
1216: 	}
1217: 
1218: 	if err := q.ensureHandle(); err != nil {
1219: 		return nil, err
1220: 	}
1221: 
1222: 	qdiscs, err := clabnetem.Impairments(q.tcHandle)
1223: 	if err == nil {
1224: 		return qdiscs, nil
1225: 	}
1226: 
1227: 	// Retry once by reopening the tc socket in case it became stale.
1228: 	q.Close()
1229: 	if errOpen := q.ensureHandle(); errOpen != nil {
1230: 		return nil, fmt.Errorf(
1231: 			"failed to query tc qdiscs (%v), and failed to reopen tc socket (%v)",
1232: 			err,
1233: 			errOpen,
1234: 		)
1235: 	}
1236: 
1237: 	return clabnetem.Impairments(q.tcHandle)
1238: }
1239: 
1240: func (q *netemQuerier) ensureHandle() error {
1241: 	if q == nil {
1242: 		return fmt.Errorf("netem querier is nil")
1243: 	}
1244: 
1245: 	if q.tcHandle != nil {
1246: 		return nil
1247: 	}
1248: 
1249: 	tcnl, err := clabnetem.NewTC(int(q.nsHandle))
1250: 	if err != nil {
1251: 		return fmt.Errorf("failed to open tc socket for netem query: %w", err)
1252: 	}
1253: 
1254: 	q.tcHandle = tcnl
1255: 
1256: 	return nil
1257: }
1258: 
1259: type netemInfo struct {
1260: 	Delay      string
1261: 	Jitter     string
1262: 	PacketLoss float64
1263: 	Rate       int
1264: 	Corruption float64
1265: }
1266: 
1267: func (n netemInfo) hasValues() bool {
1268: 	return n.Delay != "" || n.Jitter != "" || n.PacketLoss != 0 || n.Rate != 0 || n.Corruption != 0
1269: }
1270: 
1271: func netemInfoFromQdisc(qdisc *gotc.Object) netemInfo {
1272: 	var info netemInfo
1273: 
1274: 	if qdisc.Netem == nil {
1275: 		return info
1276: 	}
1277: 
1278: 	if qdisc.Netem.Latency64 != nil && *qdisc.Netem.Latency64 != 0 {
1279: 		info.Delay = (time.Duration(*qdisc.Netem.Latency64) * time.Nanosecond).String()
1280: 	}
1281: 
1282: 	if qdisc.Netem.Jitter64 != nil && *qdisc.Netem.Jitter64 != 0 {
1283: 		info.Jitter = (time.Duration(*qdisc.Netem.Jitter64) * time.Nanosecond).String()
1284: 	}
1285: 
1286: 	if qdisc.Netem.Rate != nil && qdisc.Netem.Rate.Rate != 0 {
1287: 		info.Rate = int(qdisc.Netem.Rate.Rate * 8 / msPerSec)
1288: 	}
1289: 
1290: 	if qdisc.Netem.Corrupt != nil && qdisc.Netem.Corrupt.Probability != 0 {
1291: 		info.Corruption = math.Round((float64(qdisc.Netem.Corrupt.Probability)/
1292: 			float64(math.MaxUint32)*100)*100) / 100
1293: 	}
1294: 
1295: 	if qdisc.Netem.Qopt.Loss != 0 {
1296: 		info.PacketLoss = math.Round(
1297: 			(float64(qdisc.Netem.Qopt.Loss)/float64(math.MaxUint32)*100)*100) / 100
1298: 	}
1299: 
1300: 	return info
1301: }

(End of file - total 1301 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46c27f5001wg6TmpLDV2nAxz",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46b9a24001Ce2Cpb3gT2XX1c",
  "callID": "call_d438e95465fe4735bc3a84d8",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/base/core/events/netlink.go",
      "limit": 680,
      "offset": 630
    },
    "output": "<path>/source/base/core/events/netlink.go</path>\n<type>file</type>\n<content>\n630: }\n631: \n632: func firstContainerName(container *clabruntime.GenericContainer) string {\n633: \tif container == nil || len(container.Names) == 0 {\n634: \t\treturn \"\"\n635: \t}\n636: \n637: \treturn container.Names[0]\n638: }\n639: \n640: func containerLabel(container *clabruntime.GenericContainer) string {\n641: \tif container == nil || container.Labels == nil {\n642: \t\treturn \"\"\n643: \t}\n644: \n645: \treturn container.Labels[clabconstants.Containerlab]\n646: }\n647: \n648: // interfaceSnapshotAttributes are the attributes every interface event reports for the\n649: // interface itself.\n650: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n651: \tattributes := map[string]string{\n652: \t\t\"ifname\": snapshot.Name,\n653: \t\t\"index\":  strconv.Itoa(snapshot.Index),\n654: \t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n655: \t\t\"state\":  snapshot.OperState,\n656: \t\t\"type\":   snapshot.Type,\n657: \t}\n658: \n659: \tif snapshot.Alias != \"\" {\n660: \t\tattributes[\"alias\"] = snapshot.Alias\n661: \t}\n662: \n663: \tif snapshot.MAC != \"\" {\n664: \t\tattributes[\"mac\"] = snapshot.MAC\n665: \t}\n666: \n667: \treturn attributes\n668: }\n669: \n670: // interfaceStatsAttributes adds the counters and rates of a stats event.\n671: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n672: \tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n673: \tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n674: \tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n675: \tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n676: \tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n677: \tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n678: \tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n679: \tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n680: \tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n681: }\n682: \n683: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n684: // of the netlink interface events, for the node the runtime runs. Values the runtime could not\n685: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.\n686: func labRuntimeInterfaceAttributes(\n687: \tlab, name string,\n688: \tiface *clablabruntime.InterfaceEventData,\n689: ) map[string]string {\n690: \tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n691: \t\tIndex:     iface.Index,\n692: \t\tName:      iface.Name,\n693: \t\tAlias:     iface.Alias,\n694: \t\tMTU:       iface.MTU,\n695: \t\tMAC:       iface.MAC,\n696: \t\tOperState: iface.OperState,\n697: \t\tType:      iface.Type,\n698: \t})\n699: \tif iface.Index <= 0 {\n700: \t\tdelete(attributes, \"index\")\n701: \t}\n702: \tif iface.MTU <= 0 {\n703: \t\tdelete(attributes, \"mtu\")\n704: \t}\n705: \n706: \tif lab != \"\" {\n707: \t\tattributes[\"lab\"] = lab\n708: \t}\n709: \tif name != \"\" {\n710: \t\tattributes[\"name\"] = name\n711: \t}\n712: \n713: \tif stats := iface.Stats; stats != nil {\n714: \t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n715: \t\t\tRxBytes:   stats.RxBytes,\n716: \t\t\tTxBytes:   stats.TxBytes,\n717: \t\t\tRxPackets: stats.RxPackets,\n718: \t\t\tTxPackets: stats.TxPackets,\n719: \t\t\tRxBps:     stats.RxBps,\n720: \t\t\tTxBps:     stats.TxBps,\n721: \t\t\tRxPps:     stats.RxPps,\n722: \t\t\tTxPps:     stats.TxPps,\n723: \t\t\tInterval:  stats.Interval,\n724: \t\t})\n725: \t}\n726: \n727: \treturn attributes\n728: }\n729: \n730: func interfaceAttributes(\n731: \tcontainer *clabruntime.GenericContainer,\n732: \tsnapshot ifaceSnapshot,\n733: ) map[string]string {\n734: \tattributes := interfaceSnapshotAttributes(snapshot)\n735: \tattributes[\"origin\"] = \"netlink\"\n736: \n737: \tif lab := containerLabel(container); lab != \"\" {\n738: \t\tattributes[\"lab\"] = lab\n739: \t}\n740: \n741: \tif name := firstContainerName(container); name != \"\" {\n742: \t\tattributes[\"name\"] = name\n743: \t}\n744: \n745: \toverlayToolsInterface(container, attributes)\n746: \n747: \t// Add netem attributes if present\n748: \tif snapshot.HasNetem {\n749: \t\tif snapshot.Delay != \"\" {\n750: \t\t\tattributes[\"netem_delay\"] = snapshot.Delay\n751: \t\t}\n752: \t\tif snapshot.Jitter != \"\" {\n753: \t\t\tattributes[\"netem_jitter\"] = snapshot.Jitter\n754: \t\t}\n755: \t\tif snapshot.PacketLoss != 0 {\n756: \t\t\tattributes[\"netem_loss\"] = strconv.FormatFloat(snapshot.PacketLoss, 'f', 2, 64) + \"%\"\n757: \t\t}\n758: \t\tif snapshot.Rate != 0 {\n759: \t\t\tattributes[\"netem_rate\"] = strconv.Itoa(snapshot.Rate) + \"kbit\"\n760: \t\t}\n761: \t\tif snapshot.Corruption != 0 {\n762: \t\t\tattributes[\"netem_corruption\"] = strconv.FormatFloat(\n763: \t\t\t\tsnapshot.Corruption,\n764: \t\t\t\t'f',\n765: \t\t\t\t2,\n766: \t\t\t\t64,\n767: \t\t\t) + \"%\"\n768: \t\t}\n769: \t}\n770: \n771: \treturn attributes\n772: }\n773: \n774: // overlayToolsInterface rewrites attributes to the host-side stitch interface\n775: // when one exists, matching `inspect interfaces`.\n776: func overlayToolsInterface(\n777: \tcontainer *clabruntime.GenericContainer,\n778: \tattributes map[string]string,\n779: ) {\n780: \tif container == nil {\n781: \t\treturn\n782: \t}\n783: \n784: \tlab, node := clabcore.TopoIdentity(container.Labels)\n785: \tif lab == \"\" || node == \"\" {\n786: \t\treturn\n787: \t}\n788: \n789: \ttopoName := attributes[\"alias\"]\n790: \tif topoName == \"\" {\n791: \t\ttopoName = attributes[\"ifname\"]\n792: \t}\n793: \n794: \ttools, ok := clablinks.ToolsInterface(lab, node, topoName)\n795: \tif !ok {\n796: \t\treturn\n797: \t}\n798: \n799: \tsnapshot := snapshotFromLink(tools)\n800: \tattributes[\"ifname\"] = snapshot.Name\n801: \tattributes[\"alias\"] = topoName\n802: \tattributes[\"index\"] = strconv.Itoa(snapshot.Index)\n803: \tattributes[\"mtu\"] = strconv.Itoa(snapshot.MTU)\n804: \tattributes[\"state\"] = snapshot.OperState\n805: \tattributes[\"type\"] = snapshot.Type\n806: \n807: \tif snapshot.MAC != \"\" {\n808: \t\tattributes[\"mac\"] = snapshot.MAC\n809: \t}\n810: }\n811: \n812: func (r *netlinkRegistry) emitInterfaceEvent(\n813: \tcontainer *clabruntime.GenericContainer,\n814: \taction string,\n815: \tsnapshot ifaceSnapshot,\n816: ) {\n817: \tif container == nil {\n818: \t\treturn\n819: \t}\n820: \n821: \tattributes := interfaceAttributes(container, snapshot)\n822: \n823: \tevent := aggregatedEvent{\n824: \t\tTimestamp:   time.Now(),\n825: \t\tType:        \"interface\",\n826: \t\tAction:      action,\n827: \t\tActorID:     container.ShortID,\n828: \t\tActorName:   firstContainerName(container),\n829: \t\tActorFullID: container.ID,\n830: \t\tAttributes:  attributes,\n831: \t}\n832: \n833: \tselect {\n834: \tcase r.events <- event:\n835: \tcase <-r.ctx.Done():\n836: \t}\n837: }\n838: \n839: func waitForNamespacePath(\n840: \tctx context.Context,\n841: \truntime clabruntime.ContainerRuntime,\n842: \tcontainerID string,\n843: ) (string, error) {\n844: \tconst (\n845: \t\tattempts   = 5\n846: \t\tretryDelay = 200 * time.Millisecond\n847: \t)\n848: \n849: \tvar lastErr error\n850: \n851: \tfor i := 0; i < attempts; i++ {\n852: \t\tnsPath, err := runtime.GetNSPath(ctx, containerID)\n853: \t\tif err == nil && nsPath != \"\" {\n854: \t\t\treturn nsPath, nil\n855: \t\t}\n856: \n857: \t\tif err != nil {\n858: \t\t\tlastErr = err\n859: \t\t}\n860: \n861: \t\tselect {\n862: \t\tcase <-time.After(retryDelay):\n863: \t\tcase <-ctx.Done():\n864: \t\t\treturn \"\", ctx.Err()\n865: \t\t}\n866: \t}\n867: \n868: \tif lastErr != nil {\n869: \t\treturn \"\", lastErr\n870: \t}\n871: \n872: \treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n873: }\n874: \n875: func (r *netlinkRegistry) emitInterfaceStatsEvent(\n876: \tcontainer *clabruntime.GenericContainer,\n877: \tsnapshot ifaceSnapshot,\n878: \tmetrics ifaceStatsMetrics,\n879: ) {\n880: \tif !r.includeStats || container == nil || !snapshot.HasStats {\n881: \t\treturn\n882: \t}\n883: \n884: \tattributes := interfaceAttributes(container, snapshot)\n885: \tinterfaceStatsAttributes(attributes, metrics)\n886: \n887: \tevent := aggregatedEvent{\n888: \t\tTimestamp:   metrics.Timestamp,\n889: \t\tType:        \"interface\",\n890: \t\tAction:      \"stats\",\n891: \t\tActorID:     container.ShortID,\n892: \t\tActorName:   firstContainerName(container),\n893: \t\tActorFullID: container.ID,\n894: \t\tAttributes:  attributes,\n895: \t}\n896: \n897: \tselect {\n898: \tcase r.events <- event:\n899: \tcase <-r.ctx.Done():\n900: \t}\n901: }\n902: \n903: func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n904: \tif netHandle == nil {\n905: \t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n906: \t}\n907: \n908: \tlinks, err := netHandle.LinkList()\n909: \tif err != nil {\n910: \t\treturn nil, fmt.Errorf(\"unable to list links: %w\", err)\n911: \t}\n912: \n913: \tstates := make(map[int]ifaceSnapshot, len(links))\n914: \tfor _, link := range links {\n915: \t\tsnapshot := snapshotFromLink(link)\n916: \t\tstates[snapshot.Index] = snapshot\n917: \t}\n918: \n919: \treturn states, nil\n920: }\n921: \n922: // withNetem returns the snapshot with the netem settings of its interface.\n923: func withNetem(snapshot ifaceSnapshot, netemInfos map[int]netemInfo) ifaceSnapshot {\n924: \tif info, ok := netemInfos[snapshot.Index]; ok {\n925: \t\tsnapshot.HasNetem = true\n926: \t\tsnapshot.Delay = info.Delay\n927: \t\tsnapshot.Jitter = info.Jitter\n928: \t\tsnapshot.PacketLoss = info.PacketLoss\n929: \t\tsnapshot.Rate = info.Rate\n930: \t\tsnapshot.Corruption = info.Corruption\n931: \t}\n932: \n933: \treturn snapshot\n934: }\n935: \n936: func snapshotFromLink(link netlink.Link) ifaceSnapshot {\n937: \tattrs := link.Attrs()\n938: \n939: \tsnapshot := ifaceSnapshot{\n940: \t\tType: link.Type(),\n941: \t}\n942: \n943: \tif attrs != nil {\n944: \t\tsnapshot.Index = attrs.Index\n945: \t\tsnapshot.Name = attrs.Name\n946: \t\tsnapshot.Alias = attrs.Alias\n947: \t\tsnapshot.MTU = attrs.MTU\n948: \t\tif len(attrs.HardwareAddr) > 0 {\n949: \t\t\tsnapshot.MAC = attrs.HardwareAddr.String()\n950: \t\t}\n951: \t\tsnapshot.OperState = attrs.OperState.String()\n952: \t\tif stats := attrs.Statistics; stats != nil {\n953: \t\t\tsnapshot.HasStats = true\n954: \t\t\tsnapshot.RxBytes = stats.RxBytes\n955: \t\t\tsnapshot.TxBytes = stats.TxBytes\n956: \t\t\tsnapshot.RxPackets = stats.RxPackets\n957: \t\t\tsnapshot.TxPackets = stats.TxPackets\n958: \t\t}\n959: \t}\n960: \n961: \treturn snapshot\n962: }\n963: \n964: type ifaceSnapshot struct {\n965: \tIndex     int\n966: \tName      string\n967: \tAlias     string\n968: \tMTU       int\n969: \tMAC       string\n970: \tOperState string\n971: \tType      string\n972: \tHasStats  bool\n973: \tRxBytes   uint64\n974: \tTxBytes   uint64\n975: \tRxPackets uint64\n976: \tTxPackets uint64\n977: \t// Netem fields\n978: \tHasNetem   bool\n979: \tDelay      string\n980: \tJitter     string\n981: \tPacketLoss float64\n982: \tRate       int\n983: \tCorruption float64\n984: }\n985: \n986: func (s ifaceSnapshot) equal(other ifaceSnapshot) bool {\n987: \treturn s.Index == other.Index &&\n988: \t\ts.Name == other.Name &&\n989: \t\ts.Alias == other.Alias &&\n990: \t\ts.MTU == other.MTU &&\n991: \t\ts.MAC == other.MAC &&\n992: \t\ts.OperState == other.OperState &&\n993: \t\ts.Type == other.Type &&\n994: \t\ts.HasNetem == other.HasNetem &&\n995: \t\ts.Delay == other.Delay &&\n996: \t\ts.Jitter == other.Jitter &&\n997: \t\ts.PacketLoss == other.PacketLoss &&\n998: \t\ts.Rate == other.Rate &&\n999: \t\ts.Corruption == other.Corruption\n1000: }\n1001: \n1002: type ifaceStatsSample struct {\n1003: \tRxBytes   uint64\n1004: \tTxBytes   uint64\n1005: \tRxPackets uint64\n1006: \tTxPackets uint64\n1007: \tTimestamp time.Time\n1008: }\n1009: \n1010: type ifaceStatsMetrics struct {\n1011: \tRxBytes   uint64\n1012: \tTxBytes   uint64\n1013: \tRxPackets uint64\n1014: \tTxPackets uint64\n1015: \tRxBps     float64\n1016: \tTxBps     float64\n1017: \tRxPps     float64\n1018: \tTxPps     float64\n1019: \tInterval  time.Duration\n1020: \tTimestamp time.Time\n1021: }\n1022: \n1023: func newStatsSample(snapshot ifaceSnapshot, timestamp time.Time) (ifaceStatsSample, bool) {\n1024: \tif !snapshot.HasStats {\n1025: \t\treturn ifaceStatsSample{}, false\n1026: \t}\n1027: \n1028: \treturn ifaceStatsSample{\n1029: \t\tRxBytes:   snapshot.RxBytes,\n1030: \t\tTxBytes:   snapshot.TxBytes,\n1031: \t\tRxPackets: snapshot.RxPackets,\n1032: \t\tTxPackets: snapshot.TxPackets,\n1033: \t\tTimestamp: timestamp,\n1034: \t}, true\n1035: }\n1036: \n1037: func (w *netlinkWatcher) collectAndEmitStats(\n1038: \tnetHandle *netlink.Handle,\n1039: \tstates map[int]ifaceSnapshot,\n1040: \tstatsSamples map[int]ifaceStatsSample,\n1041: \tregistry *netlinkRegistry,\n1042: ) {\n1043: \tif netHandle == nil || statsSamples == nil {\n1044: \t\treturn\n1045: \t}\n1046: \n1047: \tnow := time.Now()\n1048: \t// Fetch all interfaces with one netlink call per tick instead of one call\n1049: \t// per interface to reduce syscall overhead in large labs.\n1050: \tcurrentStates, err := snapshotInterfaces(netHandle)\n1051: \tif err != nil {\n1052: \t\tlog.Debugf(\n1053: \t\t\t\"failed to collect interface stats snapshot for container %s: %v\",\n1054: \t\t\tfirstContainerName(w.container),\n1055: \t\t\terr,\n1056: \t\t)\n1057: \n1058: \t\treturn\n1059: \t}\n1060: \n1061: \tfor idx, state := range states {\n1062: \t\tcurrent, ok := currentStates[idx]\n1063: \t\tif !ok {\n1064: \t\t\tcontinue\n1065: \t\t}\n1066: \n1067: \t\tstate.Name = current.Name\n1068: \t\tstate.Alias = current.Alias\n1069: \t\tstate.MTU = current.MTU\n1070: \t\tstate.MAC = current.MAC\n1071: \t\tstate.OperState = current.OperState\n1072: \t\tstate.Type = current.Type\n1073: \t\tstate.HasStats = current.HasStats\n1074: \t\tstate.RxBytes = current.RxBytes\n1075: \t\tstate.TxBytes = current.TxBytes\n1076: \t\tstate.RxPackets = current.RxPackets\n1077: \t\tstate.TxPackets = current.TxPackets\n1078: \t\tstates[idx] = state\n1079: \n1080: \t\tif !state.HasStats {\n1081: \t\t\tdelete(statsSamples, idx)\n1082: \n1083: \t\t\tcontinue\n1084: \t\t}\n1085: \n1086: \t\tprev, ok := statsSamples[idx]\n1087: \t\tif !ok || now.Sub(prev.Timestamp) <= 0 {\n1088: \t\t\tstatsSamples[idx] = ifaceStatsSample{\n1089: \t\t\t\tRxBytes:   state.RxBytes,\n1090: \t\t\t\tTxBytes:   state.TxBytes,\n1091: \t\t\t\tRxPackets: state.RxPackets,\n1092: \t\t\t\tTxPackets: state.TxPackets,\n1093: \t\t\t\tTimestamp: now,\n1094: \t\t\t}\n1095: \n1096: \t\t\tcontinue\n1097: \t\t}\n1098: \n1099: \t\tinterval := now.Sub(prev.Timestamp)\n1100: \t\tif interval <= 0 {\n1101: \t\t\tstatsSamples[idx] = ifaceStatsSample{\n1102: \t\t\t\tRxBytes:   state.RxBytes,\n1103: \t\t\t\tTxBytes:   state.TxBytes,\n1104: \t\t\t\tRxPackets: state.RxPackets,\n1105: \t\t\t\tTxPackets: state.TxPackets,\n1106: \t\t\t\tTimestamp: now,\n1107: \t\t\t}\n1108: \n1109: \t\t\tcontinue\n1110: \t\t}\n1111: \n1112: \t\trxBytesDelta := deltaCounter(prev.RxBytes, state.RxBytes)\n1113: \t\ttxBytesDelta := deltaCounter(prev.TxBytes, state.TxBytes)\n1114: \t\trxPacketsDelta := deltaCounter(prev.RxPackets, state.RxPackets)\n1115: \t\ttxPacketsDelta := deltaCounter(prev.TxPackets, state.TxPackets)\n1116: \n1117: \t\tseconds := interval.Seconds()\n1118: \t\tif seconds <= 0 {\n1119: \t\t\tstatsSamples[idx] = ifaceStatsSample{\n1120: \t\t\t\tRxBytes:   state.RxBytes,\n1121: \t\t\t\tTxBytes:   state.TxBytes,\n1122: \t\t\t\tRxPackets: state.RxPackets,\n1123: \t\t\t\tTxPackets: state.TxPackets,\n1124: \t\t\t\tTimestamp: now,\n1125: \t\t\t}\n1126: \n1127: \t\t\tcontinue\n1128: \t\t}\n1129: \n1130: \t\tmetrics := ifaceStatsMetrics{\n1131: \t\t\tRxBytes:   state.RxBytes,\n1132: \t\t\tTxBytes:   state.TxBytes,\n1133: \t\t\tRxPackets: state.RxPackets,\n1134: \t\t\tTxPackets: state.TxPackets,\n1135: \t\t\tRxBps:     float64(rxBytesDelta) * 8 / seconds,\n1136: \t\t\tTxBps:     float64(txBytesDelta) * 8 / seconds,\n1137: \t\t\tRxPps:     float64(rxPacketsDelta) / seconds,\n1138: \t\t\tTxPps:     float64(txPacketsDelta) / seconds,\n1139: \t\t\tInterval:  interval,\n1140: \t\t\tTimestamp: now,\n1141: \t\t}\n1142: \n1143: \t\tregistry.emitInterfaceStatsEvent(w.container, state, metrics)\n1144: \n1145: \t\tstatsSamples[idx] = ifaceStatsSample{\n1146: \t\t\tRxBytes:   state.RxBytes,\n1147: \t\t\tTxBytes:   state.TxBytes,\n1148: \t\t\tRxPackets: state.RxPackets,\n1149: \t\t\tTxPackets: state.TxPackets,\n1150: \t\t\tTimestamp: now,\n1151: \t\t}\n1152: \t}\n1153: }\n1154: \n1155: func deltaCounter(previous, current uint64) uint64 {\n1156: \tif current >= previous {\n1157: \t\treturn current - previous\n1158: \t}\n1159: \n1160: \treturn current\n1161: }\n1162: \n1163: const (\n1164: \tmsPerSec = 1000\n1165: )\n1166: \n1167: type netemQuerier struct {\n1168: \tnsHandle netns.NsHandle\n1169: \ttcHandle *gotc.Tc\n1170: }\n1171: \n1172: func newNetemQuerier(nsHandle netns.NsHandle) *netemQuerier {\n1173: \treturn &netemQuerier{\n1174: \t\tnsHandle: nsHandle,\n1175: \t}\n1176: }\n1177: \n1178: func (q *netemQuerier) Close() {\n1179: \tif q == nil || q.tcHandle == nil {\n1180: \t\treturn\n1181: \t}\n1182: \n1183: \tq.tcHandle.Close()\n1184: \tq.tcHandle = nil\n1185: }\n1186: \n1187: // Query queries the TC qdiscs in the namespace and returns a map of\n1188: // interface index to netem data.\n1189: func (q *netemQuerier) Query() map[int]netemInfo {\n1190: \tresult := make(map[int]netemInfo)\n1191: \n1192: \tqdiscs, err := q.qdiscs()\n1193: \tif err != nil {\n1194: \t\tlog.Debugf(\"failed to query tc qdiscs: %v\", err)\n1195: \t\treturn result\n1196: \t}\n1197: \n1198: \tfor idx := range qdiscs {\n1199: \t\tqdisc := &qdiscs[idx]\n1200: \t\tif qdisc.Attribute.Kind != \"netem\" || qdisc.Netem == nil {\n1201: \t\t\tcontinue\n1202: \t\t}\n1203: \n1204: \t\tinfo := netemInfoFromQdisc(qdisc)\n1205: \t\tif info.hasValues() {\n1206: \t\t\tresult[int(qdisc.Ifindex)] = info\n1207: \t\t}\n1208: \t}\n1209: \n1210: \treturn result\n1211: }\n1212: \n1213: func (q *netemQuerier) qdiscs() ([]gotc.Object, error) {\n1214: \tif q == nil {\n1215: \t\treturn nil, fmt.Errorf(\"netem querier is nil\")\n1216: \t}\n1217: \n1218: \tif err := q.ensureHandle(); err != nil {\n1219: \t\treturn nil, err\n1220: \t}\n1221: \n1222: \tqdiscs, err := clabnetem.Impairments(q.tcHandle)\n1223: \tif err == nil {\n1224: \t\treturn qdiscs, nil\n1225: \t}\n1226: \n1227: \t// Retry once by reopening the tc socket in case it became stale.\n1228: \tq.Close()\n1229: \tif errOpen := q.ensureHandle(); errOpen != nil {\n1230: \t\treturn nil, fmt.Errorf(\n1231: \t\t\t\"failed to query tc qdiscs (%v), and failed to reopen tc socket (%v)\",\n1232: \t\t\terr,\n1233: \t\t\terrOpen,\n1234: \t\t)\n1235: \t}\n1236: \n1237: \treturn clabnetem.Impairments(q.tcHandle)\n1238: }\n1239: \n1240: func (q *netemQuerier) ensureHandle() error {\n1241: \tif q == nil {\n1242: \t\treturn fmt.Errorf(\"netem querier is nil\")\n1243: \t}\n1244: \n1245: \tif q.tcHandle != nil {\n1246: \t\treturn nil\n1247: \t}\n1248: \n1249: \ttcnl, err := clabnetem.NewTC(int(q.nsHandle))\n1250: \tif err != nil {\n1251: \t\treturn fmt.Errorf(\"failed to open tc socket for netem query: %w\", err)\n1252: \t}\n1253: \n1254: \tq.tcHandle = tcnl\n1255: \n1256: \treturn nil\n1257: }\n1258: \n1259: type netemInfo struct {\n1260: \tDelay      string\n1261: \tJitter     string\n1262: \tPacketLoss float64\n1263: \tRate       int\n1264: \tCorruption float64\n1265: }\n1266: \n1267: func (n netemInfo) hasValues() bool {\n1268: \treturn n.Delay != \"\" || n.Jitter != \"\" || n.PacketLoss != 0 || n.Rate != 0 || n.Corruption != 0\n1269: }\n1270: \n1271: func netemInfoFromQdisc(qdisc *gotc.Object) netemInfo {\n1272: \tvar info netemInfo\n1273: \n1274: \tif qdisc.Netem == nil {\n1275: \t\treturn info\n1276: \t}\n1277: \n1278: \tif qdisc.Netem.Latency64 != nil && *qdisc.Netem.Latency64 != 0 {\n1279: \t\tinfo.Delay = (time.Duration(*qdisc.Netem.Latency64) * time.Nanosecond).String()\n1280: \t}\n1281: \n1282: \tif qdisc.Netem.Jitter64 != nil && *qdisc.Netem.Jitter64 != 0 {\n1283: \t\tinfo.Jitter = (time.Duration(*qdisc.Netem.Jitter64) * time.Nanosecond).String()\n1284: \t}\n1285: \n1286: \tif qdisc.Netem.Rate != nil && qdisc.Netem.Rate.Rate != 0 {\n1287: \t\tinfo.Rate = int(qdisc.Netem.Rate.Rate * 8 / msPerSec)\n1288: \t}\n1289: \n1290: \tif qdisc.Netem.Corrupt != nil && qdisc.Netem.Corrupt.Probability != 0 {\n1291: \t\tinfo.Corruption = math.Round((float64(qdisc.Netem.Corrupt.Probability)/\n1292: \t\t\tfloat64(math.MaxUint32)*100)*100) / 100\n1293: \t}\n1294: \n1295: \tif qdisc.Netem.Qopt.Loss != 0 {\n1296: \t\tinfo.PacketLoss = math.Round(\n1297: \t\t\t(float64(qdisc.Netem.Qopt.Loss)/float64(math.MaxUint32)*100)*100) / 100\n1298: \t}\n1299: \n1300: \treturn info\n1301: }\n\n(End of file - total 1301 lines)\n</content>",
    "title": "source/base/core/events/netlink.go",
    "metadata": {
      "preview": "}\n\nfunc firstContainerName(container *clabruntime.GenericContainer) string {\n\tif container == nil || len(container.Names) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn container.Names[0]\n}\n\nfunc containerLabel(container *clabruntime.GenericContainer) string {\n\tif container == nil || container.Labels == nil {\n\t\treturn \"\"\n\t}\n\n\treturn container.Labels[clabconstants.Containerlab]\n}\n\n// interfaceSnapshotAttributes are the attributes every interface event reports for the\n// interface itself.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/base/core/events/netlink.go",
        "text": "}\n\nfunc firstContainerName(container *clabruntime.GenericContainer) string {\n\tif container == nil || len(container.Names) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn container.Names[0]\n}\n\nfunc containerLabel(container *clabruntime.GenericContainer) string {\n\tif container == nil || container.Labels == nil {\n\t\treturn \"\"\n\t}\n\n\treturn container.Labels[clabconstants.Containerlab]\n}\n\n// interfaceSnapshotAttributes are the attributes every interface event reports for the\n// interface itself.\nfunc interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n\tattributes := map[string]string{\n\t\t\"ifname\": snapshot.Name,\n\t\t\"index\":  strconv.Itoa(snapshot.Index),\n\t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n\t\t\"state\":  snapshot.OperState,\n\t\t\"type\":   snapshot.Type,\n\t}\n\n\tif snapshot.Alias != \"\" {\n\t\tattributes[\"alias\"] = snapshot.Alias\n\t}\n\n\tif snapshot.MAC != \"\" {\n\t\tattributes[\"mac\"] = snapshot.MAC\n\t}\n\n\treturn attributes\n}\n\n// interfaceStatsAttributes adds the counters and rates of a stats event.\nfunc interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n}\n\n// labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n// of the netlink interface events, for the node the runtime runs. Values the runtime could not\n// read (no index or MTU without a shell in the node) are left out rather than reported as 0.\nfunc labRuntimeInterfaceAttributes(\n\tlab, name string,\n\tiface *clablabruntime.InterfaceEventData,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n\t\tIndex:     iface.Index,\n\t\tName:      iface.Name,\n\t\tAlias:     iface.Alias,\n\t\tMTU:       iface.MTU,\n\t\tMAC:       iface.MAC,\n\t\tOperState: iface.OperState,\n\t\tType:      iface.Type,\n\t})\n\tif iface.Index <= 0 {\n\t\tdelete(attributes, \"index\")\n\t}\n\tif iface.MTU <= 0 {\n\t\tdelete(attributes, \"mtu\")\n\t}\n\n\tif lab != \"\" {\n\t\tattributes[\"lab\"] = lab\n\t}\n\tif name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\tif stats := iface.Stats; stats != nil {\n\t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n\t\t\tRxBytes:   stats.RxBytes,\n\t\t\tTxBytes:   stats.TxBytes,\n\t\t\tRxPackets: stats.RxPackets,\n\t\t\tTxPackets: stats.TxPackets,\n\t\t\tRxBps:     stats.RxBps,\n\t\t\tTxBps:     stats.TxBps,\n\t\t\tRxPps:     stats.RxPps,\n\t\t\tTxPps:     stats.TxPps,\n\t\t\tInterval:  stats.Interval,\n\t\t})\n\t}\n\n\treturn attributes\n}\n\nfunc interfaceAttributes(\n\tcontainer *clabruntime.GenericContainer,\n\tsnapshot ifaceSnapshot,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(snapshot)\n\tattributes[\"origin\"] = \"netlink\"\n\n\tif lab := containerLabel(container); lab != \"\" {\n\t\tattributes[\"lab\"] = lab\n\t}\n\n\tif name := firstContainerName(container); name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\toverlayToolsInterface(container, attributes)\n\n\t// Add netem attributes if present\n\tif snapshot.HasNetem {\n\t\tif snapshot.Delay != \"\" {\n\t\t\tattributes[\"netem_delay\"] = snapshot.Delay\n\t\t}\n\t\tif snapshot.Jitter != \"\" {\n\t\t\tattributes[\"netem_jitter\"] = snapshot.Jitter\n\t\t}\n\t\tif snapshot.PacketLoss != 0 {\n\t\t\tattributes[\"netem_loss\"] = strconv.FormatFloat(snapshot.PacketLoss, 'f', 2, 64) + \"%\"\n\t\t}\n\t\tif snapshot.Rate != 0 {\n\t\t\tattributes[\"netem_rate\"] = strconv.Itoa(snapshot.Rate) + \"kbit\"\n\t\t}\n\t\tif snapshot.Corruption != 0 {\n\t\t\tattributes[\"netem_corruption\"] = strconv.FormatFloat(\n\t\t\t\tsnapshot.Corruption,\n\t\t\t\t'f',\n\t\t\t\t2,\n\t\t\t\t64,\n\t\t\t) + \"%\"\n\t\t}\n\t}\n\n\treturn attributes\n}\n\n// overlayToolsInterface rewrites attributes to the host-side stitch interface\n// when one exists, matching `inspect interfaces`.\nfunc overlayToolsInterface(\n\tcontainer *clabruntime.GenericContainer,\n\tattributes map[string]string,\n) {\n\tif container == nil {\n\t\treturn\n\t}\n\n\tlab, node := clabcore.TopoIdentity(container.Labels)\n\tif lab == \"\" || node == \"\" {\n\t\treturn\n\t}\n\n\ttopoName := attributes[\"alias\"]\n\tif topoName == \"\" {\n\t\ttopoName = attributes[\"ifname\"]\n\t}\n\n\ttools, ok := clablinks.ToolsInterface(lab, node, topoName)\n\tif !ok {\n\t\treturn\n\t}\n\n\tsnapshot := snapshotFromLink(tools)\n\tattributes[\"ifname\"] = snapshot.Name\n\tattributes[\"alias\"] = topoName\n\tattributes[\"index\"] = strconv.Itoa(snapshot.Index)\n\tattributes[\"mtu\"] = strconv.Itoa(snapshot.MTU)\n\tattributes[\"state\"] = snapshot.OperState\n\tattributes[\"type\"] = snapshot.Type\n\n\tif snapshot.MAC != \"\" {\n\t\tattributes[\"mac\"] = snapshot.MAC\n\t}\n}\n\nfunc (r *netlinkRegistry) emitInterfaceEvent(\n\tcontainer *clabruntime.GenericContainer,\n\taction string,\n\tsnapshot ifaceSnapshot,\n) {\n\tif container == nil {\n\t\treturn\n\t}\n\n\tattributes := interfaceAttributes(container, snapshot)\n\n\tevent := aggregatedEvent{\n\t\tTimestamp:   time.Now(),\n\t\tType:        \"interface\",\n\t\tAction:      action,\n\t\tActorID:     container.ShortID,\n\t\tActorName:   firstContainerName(container),\n\t\tActorFullID: container.ID,\n\t\tAttributes:  attributes,\n\t}\n\n\tselect {\n\tcase r.events <- event:\n\tcase <-r.ctx.Done():\n\t}\n}\n\nfunc waitForNamespacePath(\n\tctx context.Context,\n\truntime clabruntime.ContainerRuntime,\n\tcontainerID string,\n) (string, error) {\n\tconst (\n\t\tattempts   = 5\n\t\tretryDelay = 200 * time.Millisecond\n\t)\n\n\tvar lastErr error\n\n\tfor i := 0; i < attempts; i++ {\n\t\tnsPath, err := runtime.GetNSPath(ctx, containerID)\n\t\tif err == nil && nsPath != \"\" {\n\t\t\treturn nsPath, nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlastErr = err\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(retryDelay):\n\t\tcase <-ctx.Done():\n\t\t\treturn \"\", ctx.Err()\n\t\t}\n\t}\n\n\tif lastErr != nil {\n\t\treturn \"\", lastErr\n\t}\n\n\treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n}\n\nfunc (r *netlinkRegistry) emitInterfaceStatsEvent(\n\tcontainer *clabruntime.GenericContainer,\n\tsnapshot ifaceSnapshot,\n\tmetrics ifaceStatsMetrics,\n) {\n\tif !r.includeStats || container == nil || !snapshot.HasStats {\n\t\treturn\n\t}\n\n\tattributes := interfaceAttributes(container, snapshot)\n\tinterfaceStatsAttributes(attributes, metrics)\n\n\tevent := aggregatedEvent{\n\t\tTimestamp:   metrics.Timestamp,\n\t\tType:        \"interface\",\n\t\tAction:      \"stats\",\n\t\tActorID:     container.ShortID,\n\t\tActorName:   firstContainerName(container),\n\t\tActorFullID: container.ID,\n\t\tAttributes:  attributes,\n\t}\n\n\tselect {\n\tcase r.events <- event:\n\tcase <-r.ctx.Done():\n\t}\n}\n\nfunc snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n\tif netHandle == nil {\n\t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n\t}\n\n\tlinks, err := netHandle.LinkList()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to list links: %w\", err)\n\t}\n\n\tstates := make(map[int]ifaceSnapshot, len(links))\n\tfor _, link := range links {\n\t\tsnapshot := snapshotFromLink(link)\n\t\tstates[snapshot.Index] = snapshot\n\t}\n\n\treturn states, nil\n}\n\n// withNetem returns the snapshot with the netem settings of its interface.\nfunc withNetem(snapshot ifaceSnapshot, netemInfos map[int]netemInfo) ifaceSnapshot {\n\tif info, ok := netemInfos[snapshot.Index]; ok {\n\t\tsnapshot.HasNetem = true\n\t\tsnapshot.Delay = info.Delay\n\t\tsnapshot.Jitter = info.Jitter\n\t\tsnapshot.PacketLoss = info.PacketLoss\n\t\tsnapshot.Rate = info.Rate\n\t\tsnapshot.Corruption = info.Corruption\n\t}\n\n\treturn snapshot\n}\n\nfunc snapshotFromLink(link netlink.Link) ifaceSnapshot {\n\tattrs := link.Attrs()\n\n\tsnapshot := ifaceSnapshot{\n\t\tType: link.Type(),\n\t}\n\n\tif attrs != nil {\n\t\tsnapshot.Index = attrs.Index\n\t\tsnapshot.Name = attrs.Name\n\t\tsnapshot.Alias = attrs.Alias\n\t\tsnapshot.MTU = attrs.MTU\n\t\tif len(attrs.HardwareAddr) > 0 {\n\t\t\tsnapshot.MAC = attrs.HardwareAddr.String()\n\t\t}\n\t\tsnapshot.OperState = attrs.OperState.String()\n\t\tif stats := attrs.Statistics; stats != nil {\n\t\t\tsnapshot.HasStats = true\n\t\t\tsnapshot.RxBytes = stats.RxBytes\n\t\t\tsnapshot.TxBytes = stats.TxBytes\n\t\t\tsnapshot.RxPackets = stats.RxPackets\n\t\t\tsnapshot.TxPackets = stats.TxPackets\n\t\t}\n\t}\n\n\treturn snapshot\n}\n\ntype ifaceSnapshot struct {\n\tIndex     int\n\tName      string\n\tAlias     string\n\tMTU       int\n\tMAC       string\n\tOperState string\n\tType      string\n\tHasStats  bool\n\tRxBytes   uint64\n\tTxBytes   uint64\n\tRxPackets uint64\n\tTxPackets uint64\n\t// Netem fields\n\tHasNetem   bool\n\tDelay      string\n\tJitter     string\n\tPacketLoss float64\n\tRate       int\n\tCorruption float64\n}\n\nfunc (s ifaceSnapshot) equal(other ifaceSnapshot) bool {\n\treturn s.Index == other.Index &&\n\t\ts.Name == other.Name &&\n\t\ts.Alias == other.Alias &&\n\t\ts.MTU == other.MTU &&\n\t\ts.MAC == other.MAC &&\n\t\ts.OperState == other.OperState &&\n\t\ts.Type == other.Type &&\n\t\ts.HasNetem == other.HasNetem &&\n\t\ts.Delay == other.Delay &&\n\t\ts.Jitter == other.Jitter &&\n\t\ts.PacketLoss == other.PacketLoss &&\n\t\ts.Rate == other.Rate &&\n\t\ts.Corruption == other.Corruption\n}\n\ntype ifaceStatsSample struct {\n\tRxBytes   uint64\n\tTxBytes   uint64\n\tRxPackets uint64\n\tTxPackets uint64\n\tTimestamp time.Time\n}\n\ntype ifaceStatsMetrics struct {\n\tRxBytes   uint64\n\tTxBytes   uint64\n\tRxPackets uint64\n\tTxPackets uint64\n\tRxBps     float64\n\tTxBps     float64\n\tRxPps     float64\n\tTxPps     float64\n\tInterval  time.Duration\n\tTimestamp time.Time\n}\n\nfunc newStatsSample(snapshot ifaceSnapshot, timestamp time.Time) (ifaceStatsSample, bool) {\n\tif !snapshot.HasStats {\n\t\treturn ifaceStatsSample{}, false\n\t}\n\n\treturn ifaceStatsSample{\n\t\tRxBytes:   snapshot.RxBytes,\n\t\tTxBytes:   snapshot.TxBytes,\n\t\tRxPackets: snapshot.RxPackets,\n\t\tTxPackets: snapshot.TxPackets,\n\t\tTimestamp: timestamp,\n\t}, true\n}\n\nfunc (w *netlinkWatcher) collectAndEmitStats(\n\tnetHandle *netlink.Handle,\n\tstates map[int]ifaceSnapshot,\n\tstatsSamples map[int]ifaceStatsSample,\n\tregistry *netlinkRegistry,\n) {\n\tif netHandle == nil || statsSamples == nil {\n\t\treturn\n\t}\n\n\tnow := time.Now()\n\t// Fetch all interfaces with one netlink call per tick instead of one call\n\t// per interface to reduce syscall overhead in large labs.\n\tcurrentStates, err := snapshotInterfaces(netHandle)\n\tif err != nil {\n\t\tlog.Debugf(\n\t\t\t\"failed to collect interface stats snapshot for container %s: %v\",\n\t\t\tfirstContainerName(w.container),\n\t\t\terr,\n\t\t)\n\n\t\treturn\n\t}\n\n\tfor idx, state := range states {\n\t\tcurrent, ok := currentStates[idx]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tstate.Name = current.Name\n\t\tstate.Alias = current.Alias\n\t\tstate.MTU = current.MTU\n\t\tstate.MAC = current.MAC\n\t\tstate.OperState = current.OperState\n\t\tstate.Type = current.Type\n\t\tstate.HasStats = current.HasStats\n\t\tstate.RxBytes = current.RxBytes\n\t\tstate.TxBytes = current.TxBytes\n\t\tstate.RxPackets = current.RxPackets\n\t\tstate.TxPackets = current.TxPackets\n\t\tstates[idx] = state\n\n\t\tif !state.HasStats {\n\t\t\tdelete(statsSamples, idx)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tprev, ok := statsSamples[idx]\n\t\tif !ok || now.Sub(prev.Timestamp) <= 0 {\n\t\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\t\tRxBytes:   state.RxBytes,\n\t\t\t\tTxBytes:   state.TxBytes,\n\t\t\t\tRxPackets: state.RxPackets,\n\t\t\t\tTxPackets: state.TxPackets,\n\t\t\t\tTimestamp: now,\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tinterval := now.Sub(prev.Timestamp)\n\t\tif interval <= 0 {\n\t\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\t\tRxBytes:   state.RxBytes,\n\t\t\t\tTxBytes:   state.TxBytes,\n\t\t\t\tRxPackets: state.RxPackets,\n\t\t\t\tTxPackets: state.TxPackets,\n\t\t\t\tTimestamp: now,\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\trxBytesDelta := deltaCounter(prev.RxBytes, state.RxBytes)\n\t\ttxBytesDelta := deltaCounter(prev.TxBytes, state.TxBytes)\n\t\trxPacketsDelta := deltaCounter(prev.RxPackets, state.RxPackets)\n\t\ttxPacketsDelta := deltaCounter(prev.TxPackets, state.TxPackets)\n\n\t\tseconds := interval.Seconds()\n\t\tif seconds <= 0 {\n\t\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\t\tRxBytes:   state.RxBytes,\n\t\t\t\tTxBytes:   state.TxBytes,\n\t\t\t\tRxPackets: state.RxPackets,\n\t\t\t\tTxPackets: state.TxPackets,\n\t\t\t\tTimestamp: now,\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tmetrics := ifaceStatsMetrics{\n\t\t\tRxBytes:   state.RxBytes,\n\t\t\tTxBytes:   state.TxBytes,\n\t\t\tRxPackets: state.RxPackets,\n\t\t\tTxPackets: state.TxPackets,\n\t\t\tRxBps:     float64(rxBytesDelta) * 8 / seconds,\n\t\t\tTxBps:     float64(txBytesDelta) * 8 / seconds,\n\t\t\tRxPps:     float64(rxPacketsDelta) / seconds,\n\t\t\tTxPps:     float64(txPacketsDelta) / seconds,\n\t\t\tInterval:  interval,\n\t\t\tTimestamp: now,\n\t\t}\n\n\t\tregistry.emitInterfaceStatsEvent(w.container, state, metrics)\n\n\t\tstatsSamples[idx] = ifaceStatsSample{\n\t\t\tRxBytes:   state.RxBytes,\n\t\t\tTxBytes:   state.TxBytes,\n\t\t\tRxPackets: state.RxPackets,\n\t\t\tTxPackets: state.TxPackets,\n\t\t\tTimestamp: now,\n\t\t}\n\t}\n}\n\nfunc deltaCounter(previous, current uint64) uint64 {\n\tif current >= previous {\n\t\treturn current - previous\n\t}\n\n\treturn current\n}\n\nconst (\n\tmsPerSec = 1000\n)\n\ntype netemQuerier struct {\n\tnsHandle netns.NsHandle\n\ttcHandle *gotc.Tc\n}\n\nfunc newNetemQuerier(nsHandle netns.NsHandle) *netemQuerier {\n\treturn &netemQuerier{\n\t\tnsHandle: nsHandle,\n\t}\n}\n\nfunc (q *netemQuerier) Close() {\n\tif q == nil || q.tcHandle == nil {\n\t\treturn\n\t}\n\n\tq.tcHandle.Close()\n\tq.tcHandle = nil\n}\n\n// Query queries the TC qdiscs in the namespace and returns a map of\n// interface index to netem data.\nfunc (q *netemQuerier) Query() map[int]netemInfo {\n\tresult := make(map[int]netemInfo)\n\n\tqdiscs, err := q.qdiscs()\n\tif err != nil {\n\t\tlog.Debugf(\"failed to query tc qdiscs: %v\", err)\n\t\treturn result\n\t}\n\n\tfor idx := range qdiscs {\n\t\tqdisc := &qdiscs[idx]\n\t\tif qdisc.Attribute.Kind != \"netem\" || qdisc.Netem == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tinfo := netemInfoFromQdisc(qdisc)\n\t\tif info.hasValues() {\n\t\t\tresult[int(qdisc.Ifindex)] = info\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc (q *netemQuerier) qdiscs() ([]gotc.Object, error) {\n\tif q == nil {\n\t\treturn nil, fmt.Errorf(\"netem querier is nil\")\n\t}\n\n\tif err := q.ensureHandle(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tqdiscs, err := clabnetem.Impairments(q.tcHandle)\n\tif err == nil {\n\t\treturn qdiscs, nil\n\t}\n\n\t// Retry once by reopening the tc socket in case it became stale.\n\tq.Close()\n\tif errOpen := q.ensureHandle(); errOpen != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"failed to query tc qdiscs (%v), and failed to reopen tc socket (%v)\",\n\t\t\terr,\n\t\t\terrOpen,\n\t\t)\n\t}\n\n\treturn clabnetem.Impairments(q.tcHandle)\n}\n\nfunc (q *netemQuerier) ensureHandle() error {\n\tif q == nil {\n\t\treturn fmt.Errorf(\"netem querier is nil\")\n\t}\n\n\tif q.tcHandle != nil {\n\t\treturn nil\n\t}\n\n\ttcnl, err := clabnetem.NewTC(int(q.nsHandle))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open tc socket for netem query: %w\", err)\n\t}\n\n\tq.tcHandle = tcnl\n\n\treturn nil\n}\n\ntype netemInfo struct {\n\tDelay      string\n\tJitter     string\n\tPacketLoss float64\n\tRate       int\n\tCorruption float64\n}\n\nfunc (n netemInfo) hasValues() bool {\n\treturn n.Delay != \"\" || n.Jitter != \"\" || n.PacketLoss != 0 || n.Rate != 0 || n.Corruption != 0\n}\n\nfunc netemInfoFromQdisc(qdisc *gotc.Object) netemInfo {\n\tvar info netemInfo\n\n\tif qdisc.Netem == nil {\n\t\treturn info\n\t}\n\n\tif qdisc.Netem.Latency64 != nil && *qdisc.Netem.Latency64 != 0 {\n\t\tinfo.Delay = (time.Duration(*qdisc.Netem.Latency64) * time.Nanosecond).String()\n\t}\n\n\tif qdisc.Netem.Jitter64 != nil && *qdisc.Netem.Jitter64 != 0 {\n\t\tinfo.Jitter = (time.Duration(*qdisc.Netem.Jitter64) * time.Nanosecond).String()\n\t}\n\n\tif qdisc.Netem.Rate != nil && qdisc.Netem.Rate.Rate != 0 {\n\t\tinfo.Rate = int(qdisc.Netem.Rate.Rate * 8 / msPerSec)\n\t}\n\n\tif qdisc.Netem.Corrupt != nil && qdisc.Netem.Corrupt.Probability != 0 {\n\t\tinfo.Corruption = math.Round((float64(qdisc.Netem.Corrupt.Probability)/\n\t\t\tfloat64(math.MaxUint32)*100)*100) / 100\n\t}\n\n\tif qdisc.Netem.Qopt.Loss != 0 {\n\t\tinfo.PacketLoss = math.Round(\n\t\t\t(float64(qdisc.Netem.Qopt.Loss)/float64(math.MaxUint32)*100)*100) / 100\n\t}\n\n\treturn info\n}",
        "lineStart": 630,
        "lineEnd": 1301,
        "totalLines": 1301,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565220355,
      "end": 1794565220369
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/links/link_veth_stitched.go"
}

Output

<path>/source/head/links/link_veth_stitched.go</path>
<type>file</type>
<content>
1: package links
2: 
3: import (
4: 	"context"
5: 	"crypto/sha1"
6: 	"encoding/hex"
7: 	"errors"
8: 	"fmt"
9: 	"slices"
10: 	"sort"
11: 	"sync"
12: 
13: 	clabconstants "github.com/srl-labs/containerlab/constants"
14: 	clabutils "github.com/srl-labs/containerlab/utils"
15: 	"github.com/vishvananda/netlink"
16: )
17: 
18: type LinkVEthStitchedRaw struct {
19: 	LinkCommonParams `               yaml:",inline"`
20: 	Endpoints        []*EndpointRaw `yaml:"endpoints"`
21: }
22: 
23: func NewVEthStitchedRawFromVEth(v *LinkVEthRaw) *LinkVEthStitchedRaw {
24: 	return &LinkVEthStitchedRaw{
25: 		LinkCommonParams: v.LinkCommonParams,
26: 		Endpoints:        v.Endpoints,
27: 	}
28: }
29: 
30: func (*LinkVEthStitchedRaw) GetType() LinkType {
31: 	return LinkTypeVethStitch
32: }
33: 
34: func (r *LinkVEthStitchedRaw) Resolve(params *ResolveParams) (Link, error) {
35: 	if !isInFilter(params, r.Endpoints) {
36: 		return nil, nil
37: 	}
38: 
39: 	if err := validateVEthStitched(r); err != nil {
40: 		return nil, err
41: 	}
42: 
43: 	mtu := r.MTU
44: 	if mtu == 0 {
45: 		mtu = clabconstants.DefaultLinkMTU
46: 	}
47: 
48: 	l := &LinkVEthStitched{
49: 		LinkCommonParams: r.LinkCommonParams,
50: 		labName:          params.LabName,
51: 	}
52: 	l.MTU = mtu
53: 	l.Vars = normalizeVars(l.Vars)
54: 
55: 	segA, epA, err := buildVEthStitchSegment(params, l, r.Endpoints[0], mtu)
56: 	if err != nil {
57: 		return nil, err
58: 	}
59: 
60: 	segB, epB, err := buildVEthStitchSegment(params, l, r.Endpoints[1], mtu)
61: 	if err != nil {
62: 		return nil, err
63: 	}
64: 
65: 	l.segA, l.segB = segA, segB
66: 	l.epA, l.epB = epA, epB
67: 
68: 	return l, nil
69: }
70: 
71: // LinkVEthStitched is the resolved veth-stitch link: two veth segments
72: // (nodeA<->root-ns, nodeB<->root-ns) whose root-ns ends are joined by a tc stitch.
73: type LinkVEthStitched struct {
74: 	LinkCommonParams
75: 
76: 	lifecycleMutex sync.Mutex
77: 
78: 	// since the stitch veth lives in the root ns, we need to ensure altnames
79: 	// are per-lab unique.
80: 	labName string
81: 
82: 	segA *LinkVEth
83: 	segB *LinkVEth
84: 
85: 	// the two root-ns endpoints that get stitched together
86: 	epA Endpoint
87: 	epB Endpoint
88: }
89: 
90: func (*LinkVEthStitched) GetType() LinkType {
91: 	return LinkTypeVethStitch
92: }
93: 
94: func (l *LinkVEthStitched) GetEndpoints() []Endpoint {
95: 	return []Endpoint{l.segA.Endpoints[0], l.segB.Endpoints[0]}
96: }
97: 
98: // GetRuntimeEndpoints returns every material endpoint managed by the stitched link.
99: func (l *LinkVEthStitched) GetRuntimeEndpoints() []Endpoint {
100: 	return []Endpoint{l.segA.Endpoints[0], l.segB.Endpoints[0], l.epA, l.epB}
101: }
102: 
103: // Deploy creates the veth segment belonging to ep.
104: func (l *LinkVEthStitched) Deploy(ctx context.Context, ep Endpoint) error {
105: 	l.lifecycleMutex.Lock()
106: 	defer l.lifecycleMutex.Unlock()
107: 
108: 	if l.DeploymentState == LinkDeploymentStateFullDeployed {
109: 		return nil
110: 	}
111: 
112: 	var err error
113: 	switch ep {
114: 	case l.segA.Endpoints[0]:
115: 		err = l.segA.Deploy(ctx, ep)
116: 	case l.segB.Endpoints[0]:
117: 		err = l.segB.Deploy(ctx, ep)
118: 	default:
119: 		return fmt.Errorf("endpoint %s does not belong to link [ %s, %s ]",
120: 			ep, l.segA.Endpoints[0], l.segB.Endpoints[0])
121: 	}
122: 	if err != nil {
123: 		return err
124: 	}
125: 
126: 	l.DeploymentState = LinkDeploymentStateHalfDeployed
127: 
128: 	if l.segA.DeploymentState == LinkDeploymentStateFullDeployed &&
129: 		l.segB.DeploymentState == LinkDeploymentStateFullDeployed {
130: 		return l.stitchSegments(ctx)
131: 	}
132: 
133: 	return nil
134: }
135: 
136: // PostDeploy tags the two root-ns far ends and joins them with tc.
137: // if they weren't already stitched in Deploy.
138: func (l *LinkVEthStitched) PostDeploy(ctx context.Context) error {
139: 	l.lifecycleMutex.Lock()
140: 	defer l.lifecycleMutex.Unlock()
141: 
142: 	if l.DeploymentState == LinkDeploymentStateFullDeployed {
143: 		return nil
144: 	}
145: 	if l.segA.DeploymentState != LinkDeploymentStateFullDeployed ||
146: 		l.segB.DeploymentState != LinkDeploymentStateFullDeployed {
147: 		return fmt.Errorf("cannot stitch veth segments before both are fully deployed")
148: 	}
149: 
150: 	return l.stitchSegments(ctx)
151: }
152: 
153: func (l *LinkVEthStitched) stitchSegments(ctx context.Context) error {
154: 	steps := []func() error{
155: 		func() error { return markFarEnd(l.epB, l.segA.Endpoints[0], l.labName) },
156: 		func() error { return markFarEnd(l.epA, l.segB.Endpoints[0], l.labName) },
157: 		func() error { return stitch(l.epA, l.epB) },
158: 		func() error { return stitch(l.epB, l.epA) },
159: 	}
160: 	for _, step := range steps {
161: 		if err := retryTransientNetlink(ctx, "veth-stitch", step); err != nil {
162: 			return err
163: 		}
164: 	}
165: 
166: 	l.DeploymentState = LinkDeploymentStateFullDeployed
167: 
168: 	return nil
169: }
170: 
171: func (l *LinkVEthStitched) Remove(ctx context.Context) error {
172: 	l.lifecycleMutex.Lock()
173: 	defer l.lifecycleMutex.Unlock()
174: 
175: 	if l.DeploymentState == LinkDeploymentStateRemoved {
176: 		return nil
177: 	}
178: 
179: 	err := errors.Join(l.segA.Remove(ctx), l.segB.Remove(ctx))
180: 
181: 	l.DeploymentState = LinkDeploymentStateRemoved
182: 
183: 	return err
184: }
185: 
186: // buildVEthStitchSegment builds one veth segment: the real node endpoint plus a
187: // root-namespace far end named with a hash.
188: func buildVEthStitchSegment(
189: 	params *ResolveParams,
190: 	owner *LinkVEthStitched,
191: 	nodeEpRaw *EndpointRaw,
192: 	mtu int,
193: ) (*LinkVEth, Endpoint, error) {
194: 	seg := NewLinkVEth()
195: 	seg.MTU = mtu
196: 
197: 	nodeEp, err := nodeEpRaw.Resolve(params, owner)
198: 	if err != nil {
199: 		return nil, nil, err
200: 	}
201: 
202: 	// the far end sits in the root namespace (host node) with a short hash name
203: 	// that fits the 15 char name limit.
204: 	farName := stitchFarEndName(params.LabName, nodeEpRaw.Node, nodeEpRaw.Iface)
205: 	farGeneric := NewEndpointGeneric(GetHostLinkNode(), farName, seg)
206: 	farGeneric.MAC = nodeEp.GetMac()
207: 	farEp := NewEndpointHost(farGeneric)
208: 	seg.Endpoints = []Endpoint{nodeEp, farEp}
209: 
210: 	return seg, farEp, nil
211: }
212: 
213: func stitchFarEndName(labName, node, iface string) string {
214: 	sum := sha1.Sum([]byte(labName + "\x00" + node + "\x00" + iface))
215: 	return "clab-s-" + hex.EncodeToString(sum[:4]) // 7 + 8 = 15 chars
216: }
217: 
218: func markFarEnd(farEp, nodeEp Endpoint, labName string) error {
219: 	l, err := netlink.LinkByName(farEp.GetIfaceName())
220: 	if err != nil {
221: 		return fmt.Errorf("failed to look up veth-stitch far end %q: %w", farEp.GetIfaceName(), err)
222: 	}
223: 
224: 	iface := nodeEp.GetIfaceAlias()
225: 	if iface == "" {
226: 		iface = nodeEp.GetIfaceName()
227: 	}
228: 
229: 	altName := StitchAltName(labName, nodeEp.GetNode().GetShortName(), iface)
230: 	if err := netlink.LinkAddAltName(l, altName); err != nil && !isAltNameNotSupportedErr(err) {
231: 		return fmt.Errorf("failed to add veth-stitch altname %q: %w", altName, err)
232: 	}
233: 
234: 	return nil
235: }
236: 
237: func validateVEthStitched(r *LinkVEthStitchedRaw) error {
238: 	if len(r.Endpoints) != 2 {
239: 		return fmt.Errorf(
240: 			"veth-stitch links require exactly two endpoints, got %d",
241: 			len(r.Endpoints),
242: 		)
243: 	}
244: 
245: 	return nil
246: }
247: 
248: func (r *LinkVEthStitchedRaw) cleanupFilteredLink(
249: 	ctx context.Context,
250: 	labName string,
251: 	nodesFilter []string,
252: ) error {
253: 	return cleanupFilteredVethStitch(ctx, labName, nodesFilter, r.Endpoints)
254: }
255: 
256: func cleanupFilteredVethStitch(
257: 	ctx context.Context,
258: 	labName string,
259: 	nodesFilter []string,
260: 	endpoints []*EndpointRaw,
261: ) error {
262: 	for _, altName := range filteredVethStitchAltNames(labName, nodesFilter, endpoints) {
263: 		if err := RemoveOwnedInterface(ctx, GetHostLinkNode(), altName); err != nil {
264: 			return fmt.Errorf("failed cleaning up veth-stitch interface %q: %w", altName, err)
265: 		}
266: 	}
267: 
268: 	return nil
269: }
270: 
271: func filteredVethStitchAltNames(
272: 	labName string,
273: 	nodesFilter []string,
274: 	endpoints []*EndpointRaw,
275: ) []string {
276: 	names := make(map[string]struct{})
277: 	for _, ep := range endpoints {
278: 		if ep == nil || ep.Node == "" || ep.Iface == "" ||
279: 			!slices.Contains(nodesFilter, ep.Node) {
280: 			continue
281: 		}
282: 		names[StitchAltName(labName, ep.Node, ep.Iface)] = struct{}{}
283: 	}
284: 
285: 	result := make([]string, 0, len(names))
286: 	for name := range names {
287: 		result = append(result, name)
288: 	}
289: 	sort.Strings(result)
290: 
291: 	return result
292: }
293: 
294: // StitchAltName returns a unique name for veth-stitch links.
295: func StitchAltName(labName, node, iface string) string {
296: 	return "clab-stitch-" + clabutils.SanitizeInterfaceName(labName+"-"+node+"-"+iface)
297: }
298: 
299: // ToolsInterface returns the host-netns interface veth-stitch (and similar
300: // kinds) publish for node:iface under StitchAltName, or (nil, false) if none.
301: // Single seam for reporting/impairing the host side of the stitch.
302: func ToolsInterface(labName, node, iface string) (netlink.Link, bool) {
303: 	if labName == "" || node == "" || iface == "" {
304: 		return nil, false
305: 	}
306: 
307: 	link, err := netlink.LinkByName(StitchAltName(labName, node, iface))
308: 	if err != nil {
309: 		return nil, false
310: 	}
311: 
312: 	return link, true
313: }

(End of file - total 313 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46c2867001t8nNOO1jpx3p9H",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46b9a24001Ce2Cpb3gT2XX1c",
  "callID": "call_2ac7629a4ae44cf784755e84",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/links/link_veth_stitched.go"
    },
    "output": "<path>/source/head/links/link_veth_stitched.go</path>\n<type>file</type>\n<content>\n1: package links\n2: \n3: import (\n4: \t\"context\"\n5: \t\"crypto/sha1\"\n6: \t\"encoding/hex\"\n7: \t\"errors\"\n8: \t\"fmt\"\n9: \t\"slices\"\n10: \t\"sort\"\n11: \t\"sync\"\n12: \n13: \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n14: \tclabutils \"github.com/srl-labs/containerlab/utils\"\n15: \t\"github.com/vishvananda/netlink\"\n16: )\n17: \n18: type LinkVEthStitchedRaw struct {\n19: \tLinkCommonParams `               yaml:\",inline\"`\n20: \tEndpoints        []*EndpointRaw `yaml:\"endpoints\"`\n21: }\n22: \n23: func NewVEthStitchedRawFromVEth(v *LinkVEthRaw) *LinkVEthStitchedRaw {\n24: \treturn &LinkVEthStitchedRaw{\n25: \t\tLinkCommonParams: v.LinkCommonParams,\n26: \t\tEndpoints:        v.Endpoints,\n27: \t}\n28: }\n29: \n30: func (*LinkVEthStitchedRaw) GetType() LinkType {\n31: \treturn LinkTypeVethStitch\n32: }\n33: \n34: func (r *LinkVEthStitchedRaw) Resolve(params *ResolveParams) (Link, error) {\n35: \tif !isInFilter(params, r.Endpoints) {\n36: \t\treturn nil, nil\n37: \t}\n38: \n39: \tif err := validateVEthStitched(r); err != nil {\n40: \t\treturn nil, err\n41: \t}\n42: \n43: \tmtu := r.MTU\n44: \tif mtu == 0 {\n45: \t\tmtu = clabconstants.DefaultLinkMTU\n46: \t}\n47: \n48: \tl := &LinkVEthStitched{\n49: \t\tLinkCommonParams: r.LinkCommonParams,\n50: \t\tlabName:          params.LabName,\n51: \t}\n52: \tl.MTU = mtu\n53: \tl.Vars = normalizeVars(l.Vars)\n54: \n55: \tsegA, epA, err := buildVEthStitchSegment(params, l, r.Endpoints[0], mtu)\n56: \tif err != nil {\n57: \t\treturn nil, err\n58: \t}\n59: \n60: \tsegB, epB, err := buildVEthStitchSegment(params, l, r.Endpoints[1], mtu)\n61: \tif err != nil {\n62: \t\treturn nil, err\n63: \t}\n64: \n65: \tl.segA, l.segB = segA, segB\n66: \tl.epA, l.epB = epA, epB\n67: \n68: \treturn l, nil\n69: }\n70: \n71: // LinkVEthStitched is the resolved veth-stitch link: two veth segments\n72: // (nodeA<->root-ns, nodeB<->root-ns) whose root-ns ends are joined by a tc stitch.\n73: type LinkVEthStitched struct {\n74: \tLinkCommonParams\n75: \n76: \tlifecycleMutex sync.Mutex\n77: \n78: \t// since the stitch veth lives in the root ns, we need to ensure altnames\n79: \t// are per-lab unique.\n80: \tlabName string\n81: \n82: \tsegA *LinkVEth\n83: \tsegB *LinkVEth\n84: \n85: \t// the two root-ns endpoints that get stitched together\n86: \tepA Endpoint\n87: \tepB Endpoint\n88: }\n89: \n90: func (*LinkVEthStitched) GetType() LinkType {\n91: \treturn LinkTypeVethStitch\n92: }\n93: \n94: func (l *LinkVEthStitched) GetEndpoints() []Endpoint {\n95: \treturn []Endpoint{l.segA.Endpoints[0], l.segB.Endpoints[0]}\n96: }\n97: \n98: // GetRuntimeEndpoints returns every material endpoint managed by the stitched link.\n99: func (l *LinkVEthStitched) GetRuntimeEndpoints() []Endpoint {\n100: \treturn []Endpoint{l.segA.Endpoints[0], l.segB.Endpoints[0], l.epA, l.epB}\n101: }\n102: \n103: // Deploy creates the veth segment belonging to ep.\n104: func (l *LinkVEthStitched) Deploy(ctx context.Context, ep Endpoint) error {\n105: \tl.lifecycleMutex.Lock()\n106: \tdefer l.lifecycleMutex.Unlock()\n107: \n108: \tif l.DeploymentState == LinkDeploymentStateFullDeployed {\n109: \t\treturn nil\n110: \t}\n111: \n112: \tvar err error\n113: \tswitch ep {\n114: \tcase l.segA.Endpoints[0]:\n115: \t\terr = l.segA.Deploy(ctx, ep)\n116: \tcase l.segB.Endpoints[0]:\n117: \t\terr = l.segB.Deploy(ctx, ep)\n118: \tdefault:\n119: \t\treturn fmt.Errorf(\"endpoint %s does not belong to link [ %s, %s ]\",\n120: \t\t\tep, l.segA.Endpoints[0], l.segB.Endpoints[0])\n121: \t}\n122: \tif err != nil {\n123: \t\treturn err\n124: \t}\n125: \n126: \tl.DeploymentState = LinkDeploymentStateHalfDeployed\n127: \n128: \tif l.segA.DeploymentState == LinkDeploymentStateFullDeployed &&\n129: \t\tl.segB.DeploymentState == LinkDeploymentStateFullDeployed {\n130: \t\treturn l.stitchSegments(ctx)\n131: \t}\n132: \n133: \treturn nil\n134: }\n135: \n136: // PostDeploy tags the two root-ns far ends and joins them with tc.\n137: // if they weren't already stitched in Deploy.\n138: func (l *LinkVEthStitched) PostDeploy(ctx context.Context) error {\n139: \tl.lifecycleMutex.Lock()\n140: \tdefer l.lifecycleMutex.Unlock()\n141: \n142: \tif l.DeploymentState == LinkDeploymentStateFullDeployed {\n143: \t\treturn nil\n144: \t}\n145: \tif l.segA.DeploymentState != LinkDeploymentStateFullDeployed ||\n146: \t\tl.segB.DeploymentState != LinkDeploymentStateFullDeployed {\n147: \t\treturn fmt.Errorf(\"cannot stitch veth segments before both are fully deployed\")\n148: \t}\n149: \n150: \treturn l.stitchSegments(ctx)\n151: }\n152: \n153: func (l *LinkVEthStitched) stitchSegments(ctx context.Context) error {\n154: \tsteps := []func() error{\n155: \t\tfunc() error { return markFarEnd(l.epB, l.segA.Endpoints[0], l.labName) },\n156: \t\tfunc() error { return markFarEnd(l.epA, l.segB.Endpoints[0], l.labName) },\n157: \t\tfunc() error { return stitch(l.epA, l.epB) },\n158: \t\tfunc() error { return stitch(l.epB, l.epA) },\n159: \t}\n160: \tfor _, step := range steps {\n161: \t\tif err := retryTransientNetlink(ctx, \"veth-stitch\", step); err != nil {\n162: \t\t\treturn err\n163: \t\t}\n164: \t}\n165: \n166: \tl.DeploymentState = LinkDeploymentStateFullDeployed\n167: \n168: \treturn nil\n169: }\n170: \n171: func (l *LinkVEthStitched) Remove(ctx context.Context) error {\n172: \tl.lifecycleMutex.Lock()\n173: \tdefer l.lifecycleMutex.Unlock()\n174: \n175: \tif l.DeploymentState == LinkDeploymentStateRemoved {\n176: \t\treturn nil\n177: \t}\n178: \n179: \terr := errors.Join(l.segA.Remove(ctx), l.segB.Remove(ctx))\n180: \n181: \tl.DeploymentState = LinkDeploymentStateRemoved\n182: \n183: \treturn err\n184: }\n185: \n186: // buildVEthStitchSegment builds one veth segment: the real node endpoint plus a\n187: // root-namespace far end named with a hash.\n188: func buildVEthStitchSegment(\n189: \tparams *ResolveParams,\n190: \towner *LinkVEthStitched,\n191: \tnodeEpRaw *EndpointRaw,\n192: \tmtu int,\n193: ) (*LinkVEth, Endpoint, error) {\n194: \tseg := NewLinkVEth()\n195: \tseg.MTU = mtu\n196: \n197: \tnodeEp, err := nodeEpRaw.Resolve(params, owner)\n198: \tif err != nil {\n199: \t\treturn nil, nil, err\n200: \t}\n201: \n202: \t// the far end sits in the root namespace (host node) with a short hash name\n203: \t// that fits the 15 char name limit.\n204: \tfarName := stitchFarEndName(params.LabName, nodeEpRaw.Node, nodeEpRaw.Iface)\n205: \tfarGeneric := NewEndpointGeneric(GetHostLinkNode(), farName, seg)\n206: \tfarGeneric.MAC = nodeEp.GetMac()\n207: \tfarEp := NewEndpointHost(farGeneric)\n208: \tseg.Endpoints = []Endpoint{nodeEp, farEp}\n209: \n210: \treturn seg, farEp, nil\n211: }\n212: \n213: func stitchFarEndName(labName, node, iface string) string {\n214: \tsum := sha1.Sum([]byte(labName + \"\\x00\" + node + \"\\x00\" + iface))\n215: \treturn \"clab-s-\" + hex.EncodeToString(sum[:4]) // 7 + 8 = 15 chars\n216: }\n217: \n218: func markFarEnd(farEp, nodeEp Endpoint, labName string) error {\n219: \tl, err := netlink.LinkByName(farEp.GetIfaceName())\n220: \tif err != nil {\n221: \t\treturn fmt.Errorf(\"failed to look up veth-stitch far end %q: %w\", farEp.GetIfaceName(), err)\n222: \t}\n223: \n224: \tiface := nodeEp.GetIfaceAlias()\n225: \tif iface == \"\" {\n226: \t\tiface = nodeEp.GetIfaceName()\n227: \t}\n228: \n229: \taltName := StitchAltName(labName, nodeEp.GetNode().GetShortName(), iface)\n230: \tif err := netlink.LinkAddAltName(l, altName); err != nil && !isAltNameNotSupportedErr(err) {\n231: \t\treturn fmt.Errorf(\"failed to add veth-stitch altname %q: %w\", altName, err)\n232: \t}\n233: \n234: \treturn nil\n235: }\n236: \n237: func validateVEthStitched(r *LinkVEthStitchedRaw) error {\n238: \tif len(r.Endpoints) != 2 {\n239: \t\treturn fmt.Errorf(\n240: \t\t\t\"veth-stitch links require exactly two endpoints, got %d\",\n241: \t\t\tlen(r.Endpoints),\n242: \t\t)\n243: \t}\n244: \n245: \treturn nil\n246: }\n247: \n248: func (r *LinkVEthStitchedRaw) cleanupFilteredLink(\n249: \tctx context.Context,\n250: \tlabName string,\n251: \tnodesFilter []string,\n252: ) error {\n253: \treturn cleanupFilteredVethStitch(ctx, labName, nodesFilter, r.Endpoints)\n254: }\n255: \n256: func cleanupFilteredVethStitch(\n257: \tctx context.Context,\n258: \tlabName string,\n259: \tnodesFilter []string,\n260: \tendpoints []*EndpointRaw,\n261: ) error {\n262: \tfor _, altName := range filteredVethStitchAltNames(labName, nodesFilter, endpoints) {\n263: \t\tif err := RemoveOwnedInterface(ctx, GetHostLinkNode(), altName); err != nil {\n264: \t\t\treturn fmt.Errorf(\"failed cleaning up veth-stitch interface %q: %w\", altName, err)\n265: \t\t}\n266: \t}\n267: \n268: \treturn nil\n269: }\n270: \n271: func filteredVethStitchAltNames(\n272: \tlabName string,\n273: \tnodesFilter []string,\n274: \tendpoints []*EndpointRaw,\n275: ) []string {\n276: \tnames := make(map[string]struct{})\n277: \tfor _, ep := range endpoints {\n278: \t\tif ep == nil || ep.Node == \"\" || ep.Iface == \"\" ||\n279: \t\t\t!slices.Contains(nodesFilter, ep.Node) {\n280: \t\t\tcontinue\n281: \t\t}\n282: \t\tnames[StitchAltName(labName, ep.Node, ep.Iface)] = struct{}{}\n283: \t}\n284: \n285: \tresult := make([]string, 0, len(names))\n286: \tfor name := range names {\n287: \t\tresult = append(result, name)\n288: \t}\n289: \tsort.Strings(result)\n290: \n291: \treturn result\n292: }\n293: \n294: // StitchAltName returns a unique name for veth-stitch links.\n295: func StitchAltName(labName, node, iface string) string {\n296: \treturn \"clab-stitch-\" + clabutils.SanitizeInterfaceName(labName+\"-\"+node+\"-\"+iface)\n297: }\n298: \n299: // ToolsInterface returns the host-netns interface veth-stitch (and similar\n300: // kinds) publish for node:iface under StitchAltName, or (nil, false) if none.\n301: // Single seam for reporting/impairing the host side of the stitch.\n302: func ToolsInterface(labName, node, iface string) (netlink.Link, bool) {\n303: \tif labName == \"\" || node == \"\" || iface == \"\" {\n304: \t\treturn nil, false\n305: \t}\n306: \n307: \tlink, err := netlink.LinkByName(StitchAltName(labName, node, iface))\n308: \tif err != nil {\n309: \t\treturn nil, false\n310: \t}\n311: \n312: \treturn link, true\n313: }\n\n(End of file - total 313 lines)\n</content>",
    "title": "source/head/links/link_veth_stitched.go",
    "metadata": {
      "preview": "package links\n\nimport (\n\t\"context\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"sort\"\n\t\"sync\"\n\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclabutils \"github.com/srl-labs/containerlab/utils\"\n\t\"github.com/vishvananda/netlink\"\n)\n\ntype LinkVEthStitchedRaw struct {\n\tLinkCommonParams `               yaml:\",inline\"`\n\tEndpoints        []*EndpointRaw `yaml:\"endpoints\"`",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/links/link_veth_stitched.go",
        "text": "package links\n\nimport (\n\t\"context\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"sort\"\n\t\"sync\"\n\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclabutils \"github.com/srl-labs/containerlab/utils\"\n\t\"github.com/vishvananda/netlink\"\n)\n\ntype LinkVEthStitchedRaw struct {\n\tLinkCommonParams `               yaml:\",inline\"`\n\tEndpoints        []*EndpointRaw `yaml:\"endpoints\"`\n}\n\nfunc NewVEthStitchedRawFromVEth(v *LinkVEthRaw) *LinkVEthStitchedRaw {\n\treturn &LinkVEthStitchedRaw{\n\t\tLinkCommonParams: v.LinkCommonParams,\n\t\tEndpoints:        v.Endpoints,\n\t}\n}\n\nfunc (*LinkVEthStitchedRaw) GetType() LinkType {\n\treturn LinkTypeVethStitch\n}\n\nfunc (r *LinkVEthStitchedRaw) Resolve(params *ResolveParams) (Link, error) {\n\tif !isInFilter(params, r.Endpoints) {\n\t\treturn nil, nil\n\t}\n\n\tif err := validateVEthStitched(r); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmtu := r.MTU\n\tif mtu == 0 {\n\t\tmtu = clabconstants.DefaultLinkMTU\n\t}\n\n\tl := &LinkVEthStitched{\n\t\tLinkCommonParams: r.LinkCommonParams,\n\t\tlabName:          params.LabName,\n\t}\n\tl.MTU = mtu\n\tl.Vars = normalizeVars(l.Vars)\n\n\tsegA, epA, err := buildVEthStitchSegment(params, l, r.Endpoints[0], mtu)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsegB, epB, err := buildVEthStitchSegment(params, l, r.Endpoints[1], mtu)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tl.segA, l.segB = segA, segB\n\tl.epA, l.epB = epA, epB\n\n\treturn l, nil\n}\n\n// LinkVEthStitched is the resolved veth-stitch link: two veth segments\n// (nodeA<->root-ns, nodeB<->root-ns) whose root-ns ends are joined by a tc stitch.\ntype LinkVEthStitched struct {\n\tLinkCommonParams\n\n\tlifecycleMutex sync.Mutex\n\n\t// since the stitch veth lives in the root ns, we need to ensure altnames\n\t// are per-lab unique.\n\tlabName string\n\n\tsegA *LinkVEth\n\tsegB *LinkVEth\n\n\t// the two root-ns endpoints that get stitched together\n\tepA Endpoint\n\tepB Endpoint\n}\n\nfunc (*LinkVEthStitched) GetType() LinkType {\n\treturn LinkTypeVethStitch\n}\n\nfunc (l *LinkVEthStitched) GetEndpoints() []Endpoint {\n\treturn []Endpoint{l.segA.Endpoints[0], l.segB.Endpoints[0]}\n}\n\n// GetRuntimeEndpoints returns every material endpoint managed by the stitched link.\nfunc (l *LinkVEthStitched) GetRuntimeEndpoints() []Endpoint {\n\treturn []Endpoint{l.segA.Endpoints[0], l.segB.Endpoints[0], l.epA, l.epB}\n}\n\n// Deploy creates the veth segment belonging to ep.\nfunc (l *LinkVEthStitched) Deploy(ctx context.Context, ep Endpoint) error {\n\tl.lifecycleMutex.Lock()\n\tdefer l.lifecycleMutex.Unlock()\n\n\tif l.DeploymentState == LinkDeploymentStateFullDeployed {\n\t\treturn nil\n\t}\n\n\tvar err error\n\tswitch ep {\n\tcase l.segA.Endpoints[0]:\n\t\terr = l.segA.Deploy(ctx, ep)\n\tcase l.segB.Endpoints[0]:\n\t\terr = l.segB.Deploy(ctx, ep)\n\tdefault:\n\t\treturn fmt.Errorf(\"endpoint %s does not belong to link [ %s, %s ]\",\n\t\t\tep, l.segA.Endpoints[0], l.segB.Endpoints[0])\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl.DeploymentState = LinkDeploymentStateHalfDeployed\n\n\tif l.segA.DeploymentState == LinkDeploymentStateFullDeployed &&\n\t\tl.segB.DeploymentState == LinkDeploymentStateFullDeployed {\n\t\treturn l.stitchSegments(ctx)\n\t}\n\n\treturn nil\n}\n\n// PostDeploy tags the two root-ns far ends and joins them with tc.\n// if they weren't already stitched in Deploy.\nfunc (l *LinkVEthStitched) PostDeploy(ctx context.Context) error {\n\tl.lifecycleMutex.Lock()\n\tdefer l.lifecycleMutex.Unlock()\n\n\tif l.DeploymentState == LinkDeploymentStateFullDeployed {\n\t\treturn nil\n\t}\n\tif l.segA.DeploymentState != LinkDeploymentStateFullDeployed ||\n\t\tl.segB.DeploymentState != LinkDeploymentStateFullDeployed {\n\t\treturn fmt.Errorf(\"cannot stitch veth segments before both are fully deployed\")\n\t}\n\n\treturn l.stitchSegments(ctx)\n}\n\nfunc (l *LinkVEthStitched) stitchSegments(ctx context.Context) error {\n\tsteps := []func() error{\n\t\tfunc() error { return markFarEnd(l.epB, l.segA.Endpoints[0], l.labName) },\n\t\tfunc() error { return markFarEnd(l.epA, l.segB.Endpoints[0], l.labName) },\n\t\tfunc() error { return stitch(l.epA, l.epB) },\n\t\tfunc() error { return stitch(l.epB, l.epA) },\n\t}\n\tfor _, step := range steps {\n\t\tif err := retryTransientNetlink(ctx, \"veth-stitch\", step); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tl.DeploymentState = LinkDeploymentStateFullDeployed\n\n\treturn nil\n}\n\nfunc (l *LinkVEthStitched) Remove(ctx context.Context) error {\n\tl.lifecycleMutex.Lock()\n\tdefer l.lifecycleMutex.Unlock()\n\n\tif l.DeploymentState == LinkDeploymentStateRemoved {\n\t\treturn nil\n\t}\n\n\terr := errors.Join(l.segA.Remove(ctx), l.segB.Remove(ctx))\n\n\tl.DeploymentState = LinkDeploymentStateRemoved\n\n\treturn err\n}\n\n// buildVEthStitchSegment builds one veth segment: the real node endpoint plus a\n// root-namespace far end named with a hash.\nfunc buildVEthStitchSegment(\n\tparams *ResolveParams,\n\towner *LinkVEthStitched,\n\tnodeEpRaw *EndpointRaw,\n\tmtu int,\n) (*LinkVEth, Endpoint, error) {\n\tseg := NewLinkVEth()\n\tseg.MTU = mtu\n\n\tnodeEp, err := nodeEpRaw.Resolve(params, owner)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// the far end sits in the root namespace (host node) with a short hash name\n\t// that fits the 15 char name limit.\n\tfarName := stitchFarEndName(params.LabName, nodeEpRaw.Node, nodeEpRaw.Iface)\n\tfarGeneric := NewEndpointGeneric(GetHostLinkNode(), farName, seg)\n\tfarGeneric.MAC = nodeEp.GetMac()\n\tfarEp := NewEndpointHost(farGeneric)\n\tseg.Endpoints = []Endpoint{nodeEp, farEp}\n\n\treturn seg, farEp, nil\n}\n\nfunc stitchFarEndName(labName, node, iface string) string {\n\tsum := sha1.Sum([]byte(labName + \"\\x00\" + node + \"\\x00\" + iface))\n\treturn \"clab-s-\" + hex.EncodeToString(sum[:4]) // 7 + 8 = 15 chars\n}\n\nfunc markFarEnd(farEp, nodeEp Endpoint, labName string) error {\n\tl, err := netlink.LinkByName(farEp.GetIfaceName())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to look up veth-stitch far end %q: %w\", farEp.GetIfaceName(), err)\n\t}\n\n\tiface := nodeEp.GetIfaceAlias()\n\tif iface == \"\" {\n\t\tiface = nodeEp.GetIfaceName()\n\t}\n\n\taltName := StitchAltName(labName, nodeEp.GetNode().GetShortName(), iface)\n\tif err := netlink.LinkAddAltName(l, altName); err != nil && !isAltNameNotSupportedErr(err) {\n\t\treturn fmt.Errorf(\"failed to add veth-stitch altname %q: %w\", altName, err)\n\t}\n\n\treturn nil\n}\n\nfunc validateVEthStitched(r *LinkVEthStitchedRaw) error {\n\tif len(r.Endpoints) != 2 {\n\t\treturn fmt.Errorf(\n\t\t\t\"veth-stitch links require exactly two endpoints, got %d\",\n\t\t\tlen(r.Endpoints),\n\t\t)\n\t}\n\n\treturn nil\n}\n\nfunc (r *LinkVEthStitchedRaw) cleanupFilteredLink(\n\tctx context.Context,\n\tlabName string,\n\tnodesFilter []string,\n) error {\n\treturn cleanupFilteredVethStitch(ctx, labName, nodesFilter, r.Endpoints)\n}\n\nfunc cleanupFilteredVethStitch(\n\tctx context.Context,\n\tlabName string,\n\tnodesFilter []string,\n\tendpoints []*EndpointRaw,\n) error {\n\tfor _, altName := range filteredVethStitchAltNames(labName, nodesFilter, endpoints) {\n\t\tif err := RemoveOwnedInterface(ctx, GetHostLinkNode(), altName); err != nil {\n\t\t\treturn fmt.Errorf(\"failed cleaning up veth-stitch interface %q: %w\", altName, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc filteredVethStitchAltNames(\n\tlabName string,\n\tnodesFilter []string,\n\tendpoints []*EndpointRaw,\n) []string {\n\tnames := make(map[string]struct{})\n\tfor _, ep := range endpoints {\n\t\tif ep == nil || ep.Node == \"\" || ep.Iface == \"\" ||\n\t\t\t!slices.Contains(nodesFilter, ep.Node) {\n\t\t\tcontinue\n\t\t}\n\t\tnames[StitchAltName(labName, ep.Node, ep.Iface)] = struct{}{}\n\t}\n\n\tresult := make([]string, 0, len(names))\n\tfor name := range names {\n\t\tresult = append(result, name)\n\t}\n\tsort.Strings(result)\n\n\treturn result\n}\n\n// StitchAltName returns a unique name for veth-stitch links.\nfunc StitchAltName(labName, node, iface string) string {\n\treturn \"clab-stitch-\" + clabutils.SanitizeInterfaceName(labName+\"-\"+node+\"-\"+iface)\n}\n\n// ToolsInterface returns the host-netns interface veth-stitch (and similar\n// kinds) publish for node:iface under StitchAltName, or (nil, false) if none.\n// Single seam for reporting/impairing the host side of the stitch.\nfunc ToolsInterface(labName, node, iface string) (netlink.Link, bool) {\n\tif labName == \"\" || node == \"\" || iface == \"\" {\n\t\treturn nil, false\n\t}\n\n\tlink, err := netlink.LinkByName(StitchAltName(labName, node, iface))\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\treturn link, true\n}",
        "lineStart": 1,
        "lineEnd": 313,
        "totalLines": 313,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565220460,
      "end": 1794565220466
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46c2899001JuwcyMgkiq1ran",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46b9a24001Ce2Cpb3gT2XX1c",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 53728,
    "input": 29399,
    "output": 48,
    "reasoning": 25,
    "cache": {
      "read": 24256,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46b9a24001Ce2Cpb3gT2XX1c",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565184036,
    "completed": 1794565220509
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 53728,
    "input": 29399,
    "output": 48,
    "reasoning": 25,
    "cache": {
      "read": 24256,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 8
step-start
{
  "type": "step-start",
  "id": "prt_1d46c8a9e001Q0FsMTtxqbR3AE",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46c28a3001vr1NLdqv5hwDqb"
}
Reasoning
Now let me think about the changes:

1. New `reported` map on watcher: tracks what each link was last reported as (attributes + since).
2. `emit` replaces `emitInterfaceEvent` calls: tracks reported state, converts `update`→`create` when the link was reported under a different ifname before (after sending a delete under the old name).
3. `emitStats` moves stats emission to watcher; also emits a create event if the link was renamed (track returns true).
4. `reportStitchMarks`: on netem ticker tick, for veth links reported under their own name within stitchMarkWindow (1 minute), check whether the host-side stitch interface now exists (via `interfaceAttributes` which calls `overlayToolsInterface` → `ToolsInterface` → `netlink.LinkByName` in root namespace). If ifname differs (i.e., stitch interface now exists), emit an update (which will trigger track → delete old name → create new name... wait).

Wait — in `reportStitchMarks`, it calls `w.emit(registry, "update", snapshot)`. Inside emit, attributes = interfaceAttributes(...) which now resolves to stitch name. `track` sees previous ifname == snapshot.Name (the node's own name e.g. "eth1"), and new attributes ifname is "clab-s-..." — different → sends delete under previous name, returns true → action "update" → becomes "create". Then sends create with new attributes. Good.

Now, key issue: `emit` delete path. `w.reported[snapshot.Index]` attributes used as delete event attributes. But `attributes = previous.attributes` — this map is the stored clone. It's sent to the channel. Note `track` stores `maps.Clone(attributes)`, so the stored map is a private copy. OK.

But wait: in emit delete path, if `previous` doesn't exist, `attributes = interfaceAttributes(...)` is computed but then... it's used in sendInterfaceEvent. Fine.

Hmm, but there's a subtlety: `emit` delete path calls `interfaceAttributes(w.container, snapshot)` even when `previous` exists — wasted work? Actually it computes attributes unconditionally at line 682 before checking reported. When previous exists, the freshly computed attributes are discarded. `interfaceAttributes` calls `overlayToolsInterface` which calls `clablinks.ToolsInterface` → `netlink.LinkByName` — a netlink syscall in root namespace. For every delete event of a tracked link this is a wasted syscall. Minor performance, P4-ish. Actually wait, when previous exists, the computed attributes are unused — dead computation. Small but could be reordered. That's a minor perf/cleanliness point.

More important potential issues:

A. `reportStitchMarks` is only called on netemTicker ticks, and the netem poll interval defaults to 1s. But it scans all states and for each candidate veth reported recently, calls `interfaceAttributes` → `ToolsInterface` → `netlink.LinkByName`. If the stitch hasn't been marked yet, this returns not-ok, so each tick it retries. That's a netlink syscall per candidate link per tick for up to 1 minute (stitchMarkWindow). That's a deliberate design ("how long after a link is first reported its host-side stitch interface is looked for"). Cost: per-tick per-link LinkByName for up to a minute. Bounded by stitchMarkWindow. Probably acceptable; ponytail ceiling maybe. Could note as P4.

B. Race condition on `w.reported`? The watcher runs in a single goroutine (run → watch loop). `emit`, `emitStats`, `reportStitchMarks` are all called from the watch loop goroutine. Is `emit` called anywhere concurrently? Let's check: `collectAndEmitStats` is called from watch loop. All within the same goroutine. The registry's `events` channel send is fine. So no data race. But wait — `netlink.LinkSubscribeWithOptions` spawns an internal goroutine that writes to the updates channel; watcher consumes. Fine.

C. `reportStitchMarks` uses `interfaceAttributes(w.container, snapshot)["ifname"] != snapshot.Name` to detect marked stitch. Note `interfaceAttributes` sets `ifname` from `interfaceSnapshotAttributes` = snapshot.Name, then `overlayToolsInterface` overrides if if stitch exists. So the check is: stitch exists → ifname becomes stitch name ≠ snapshot.Name → emit update. Fine.

But there's an ordering subtlety: `reportStitchMarks` runs before... it emits "update" with the stitch-marked attributes. `track` will detect rename and emit delete of old name first. But the condition `reported.attributes["ifname"] != snapshot.Name` — "reported under their own name" — means only links last reported under their node's own name are candidates. If the stitch was already reported (i.e., the last emit resolved to the stitch name), reported.attributes["ifname"] is the stitch name, so the check `reported.attributes["ifname"] != snapshot.Name` skips. Good — avoids repeated re-emits.

But wait: what about a link reported as stitch but then re-reported under its own name? E.g., after resubscribe, `processExisting` emits "update" with snapshot attributes — interfaceAttributes would resolve stitch if it exists, so reported becomes stitch name again. Hmm, `interfaceAttributes` is always applied, so if stitch exists, the emitted attributes always have stitch ifname. So when would `reported.attributes["ifname"] == snapshot.Name`? When the stitch doesn't exist yet (link freshly created, before the host-side mark) — then interfaceAttributes leaves ifname = snapshot.Name. So reported holds the node's own name. Then when mark happens, reportStitchMarks finds reported.attributes["ifname"] == snapshot.Name and stitch now exists → emits update → delete old + create new.

Hmm wait, but actually the ordering: the deployment creates the node-end veth in the node namespace; watcher sees RTM_NEWLINK create. At that point the stitch interface (host-side far end) may not exist yet or may not be marked. Later markFarEnd adds altname to the far end in root ns. `ToolsInterface` looks up by altname — altname addition doesn't change the node ns link. So the node-side watcher would never see an update for it. Hence the polling in reportStitchMarks. Makes sense.

Now the timing issue: `since` is when the link was FIRST reported (track preserves previous.since when known). stitchMarkWindow = 1 minute from first report. If a lab deploy takes longer than a minute (large lab, slow node start), the stitch mark happens >1 min after the node link was first reported... but wait, since is preserved across tracks, so `since` = first report of that index. For a node whose interfaces come up during deploy, deploy of whole lab may exceed 1 minute → the stitch-mark update is never reported. Then the interface stays reported under its own name ("eth1") instead of the stitch name ("clab-s-..."). Is there a later correction? Subsequent updates to that link (e.g., RTM_NEWLINK state changes) go through emit → interfaceAttributes → if stitch now exists, ifname is stitch name → track detects rename → delete+create. So any later update event self-corrects. But if the link never changes again, the report stays under the node name until... resubscribe? On resubscribe, processExisting with exists → emit "update" → same as above: if stitch exists, attributes get stitch ifname → rename detected → delete+create. So it self-corrects on any update or resubscribe. It's a heuristic with a ceiling: mark window of 1 minute; deploy of a large lab could exceed it. Ponytail rule: "Mark deliberate simplifications that cut a real corner with a known ceiling... with a `ponytail:` comment naming the ceiling and upgrade path." There's a comment explaining the window but no `ponytail:` marker. Hmm, the rule says mark deliberate simplifications with a known ceiling with a ponytail comment. This is a heuristic with a ceiling (1-minute window). Worth a P4 note? The comment does name the window rationale. Borderline. I could mention as P4: window may be too short for slow deploys; suggest comment/consider refreshing `since` on update. Actually wait — `since` is preserved from the FIRST report, meaning even repeated updates don't refresh the window. For a node whose interface was created at t=0 but marked at t=70s (slow lab), no report. But any subsequent link attribute change fixes it. Also after resubscribe (which happens on subscription errors), fixes. I'd call this P3/P4. The comment says "Deploying a veth-stitch link marks that interface right after it creates the link" — usually quick. I'll flag as P4 with the note that `since` never refreshes so long deploys (>1 min between node link creation and mark) miss the rename; suggest refreshing `since` on each emit update or documenting.

Hmm wait, actually think again: does `since` refresh on track when known? `since := previous.since` — preserved. So window = time since first report of this index. But note: the index in the node namespace — when a node redeploys, indexes may be reused by different links! The `reported` map is keyed by interface index. If a link is deleted and a new link gets the same index (kernel reuses ifindex? Actually ifindexes are monotonically allocated per netns and generally not reused until wraparound; but after a container restart, the netns is new but the watcher... hmm, watchers are per container ID and stopped/restarted via registry.Start on container events. On restart, a new watcher is created (Stop deletes watcher). So reported map is fresh. Within a running container, ifindexes increase monotonically; reuse is unlikely. OK.

But wait — there's an actual subtle bug: `emit` delete path: `if previous, ok := w.reported[snapshot.Index]; ok { attributes = previous.attributes }`. But this sends the STORED map (the clone) directly to the channel — fine since it's a private clone. However, in `emitStats`, after `track` returns true (rename), it sends "create" with `maps.Clone(attributes)` and then mutates `attributes` with stats for the "stats" event. Why clone for create? Because `attributes` will be mutated by `interfaceStatsAttributes` for the stats event; the create event should not carry counters. But the map stored in `w.reported` by `track` is a clone, so mutation after track doesn't affect stored state — actually track stores `maps.Clone(attributes)` before the mutation. So sending `attributes` (uncloned) for "create" would be safe... unless the consumer mutates it. The clone is defensive for the create event since the same map is then mutated and sent as "stats". Reasonable. But in `TestEmitStatsReportsRenamedLinkFirst`, they assert create has no counters. Fine.

Hmm wait, actually there's a subtle issue in emitStats: `track` is called, which may send a "delete" event for the old name, and stores the NEW attributes clone. Then "create" sent. Then stats event with mutated attributes. The stats event's attributes map is the same map that... no clone issue: `interfaceStatsAttributes(attributes, metrics)` mutates the local `attributes` map (the one from interfaceAttributes, not the stored clone). Fine.

D. What about the "delete" event in emit when previous exists: the stored `previous.attributes` includes the old stitch ifname etc. Good — deletion names the link as clients know it.

E. Now the big question: `reportStitchMarks` and event ordering/consistency. `reportStitchMarks` calls `w.emit(registry, "update", snapshot)` where `snapshot` comes from `states`. It emits an update even though the netlink snapshot didn't change (the change is on the host side). `track` handles the rename. But if the stitch was marked and the attributes now resolve to the stitch name, `track` stores new attributes with the stitch ifname. Subsequent calls to `reportStitchMarks` will skip because `reported.attributes["ifname"] != snapshot.Name`. Good.

But one problem: `reportStitchMarks` emits update events for links whose stitch got marked — but the emitted "update" event has attributes identical (except rename) to previous create event. The event is emitted as "update" (converted to "create" by track's rename path... wait: `track` returns true → in emit, `action == "update"` → action becomes "create"). So the sequence is delete(old name), create(new name). Good.

But there's a scenario: stitch marked AFTER the node link was already reported under stitch name? Not possible—stitch name resolution only succeeds after altname exists.

F. Missing edge: `processExisting` on the FIRST subscription when `includeSnapshot` false and initial=true: nothing emitted, but `states[snapshot.Index] = snapshot` — the link is tracked in `states` but NOT in `w.reported`! Wait — that's the pre-existing behavior... In base, emitInterfaceEvent was only called in some branches. In head, emit is only called in the same branches. So when a link exists at subscription start and includeSnapshot is false, no event is emitted and `w.reported` is never populated. Later, if that link changes (RTM_NEWLINK), processUpdate emits "update" → emit → track → not known → returns false, action stays "update". Client sees "update" for an interface it never got a create for. That's pre-existing behavior though (base did the same: emitInterfaceEvent "update" for unknown link). Hmm, but with the new reported-tracking, this case (update for a never-reported link) still emits "update" rather than "create". Pre-existing semantics; not worsened. Actually wait — is it? In base, same. So not a new issue.

Hmm, but here's a NEW wrinkle: with includeSnapshot=false (the `events` command default?), initial links are not reported. Then `reportStitchMarks` requires `w.reported[idx]` to exist — for never-reported links, skipped. Fine.

G. Now the deletion-ordering bug candidate: In `removeVanishedLinks`, emit(registry, "delete", snapshot) — uses `w.reported` for the last-known name. Good.

H. Potential double-delete or ordering issue in `watch`: after resubscribe, `removeVanishedLinks` emits deletes; then the listing (ListExisting) replays links. `processExisting` for existing unchanged links: `exists && snapshot.equal(previous)` → return (no emit). But the `w.reported` state: after resubscribe, reported still holds old entries (reported map persists across watch calls since it's on the watcher). For a link whose stitch got marked while subscription was down: on resubscribe, processExisting sees exists && snapshot not equal? snapshot.equal compares node-side fields only (Name, Alias, MTU, MAC, OperState, Type, netem) — the stitch mark doesn't change the node-side link, so equal → return, no emit! So after a resubscribe, if the stitch mark happened while unsubscribed, `reportStitchMarks` will pick it up: reported.attributes["ifname"] == snapshot.Name (node name) and within window? The window is since FIRST report — could be way more than 1 minute ago if subscription ran a while. Then the rename is never reported until some other update. Hmm — this is the same ceiling as the window. Resubscribes are relatively rare though.

Wait, actually think about the primary flow again: the deploy marks the interface "right after it creates the link". Watcher sees the RTM_NEWLINK for the node-end veth and emits create with ifname = node's own name (e.g. eth1) because the stitch altname doesn't exist yet. Then within a second or so, markFarEnd adds the altname. The netem ticker fires every ~1s and reportStitchMarks picks it up within a second → delete(eth1) + create(clab-s-xxxx). So the end state converges quickly. The window is just to avoid scanning forever. OK.

But hmm — actually wait. Is there a subtlety: when `reportStitchMarks` finds the stitch exists and calls emit(update), track sends delete + create. But what if between the create event (under node name) and the mark, the client... fine.

Now, what about the `index` attribute? interfaceAttributes sets attributes["index"] from snapshot.Index (node-ns index), then overlayToolsInterface overwrites with stitch link's index (host-ns index). Fine, pre-existing.

I. Now potential correctness bug: in `reportStitchMarks`, the emitted update event uses the states snapshot which may be stale vs. current link state? It's the same snapshot used for prior events. Fine.

J. Event flood concern: `reportStitchMarks` calls `interfaceAttributes` for each candidate — which calls `ToolsInterface` → `netlink.LinkByName` in the ROOT namespace. This is a syscall per veth per tick during the window. For a large lab (e.g., 100-node lab with many veth-stitch links), during the first minute after each node's links are created, this is e.g. 100 links × 1/sec = 100 syscalls/sec per watcher — actually per watcher (per container). Each watcher handles one container's interfaces. So per container, its own links. Fine, bounded.

But hold on — `reportStitchMarks` iterates over ALL states (all interfaces of the container), including `lo` (Type "device"?) — lo type is "lo"? netlink Link.Type() for loopback returns "lo"? Actually loopback device type is "loopback"? In vishvananda/netlink, `Link.Type()` for Loopback returns "loopback"? Let me think — `dummy`, `veth`, `bridge`, `device`, `loopback`. Anyway, filter is Type == "veth", so lo excluded. Only veths.

K. Another possible issue: `stitchMarkWindow` is a package-level `var`, not const — fine for tests.

L. Now the tests: `TestReportStitchMarksLeavesUnmarkedLinks` — uses registry with t.Context() etc. But note that `watcher.emit(registry, "create", states[7])` — `interfaceAttributes` calls `overlayToolsInterface` with container without labels → `TopoIdentity` returns "", "" → return. So ifname stays "e1-1". Then `reportStitchMarks`: for idx 7: reported.attributes["ifname"] == "e1-1" == snapshot.Name, within window, type veth → `interfaceAttributes(...)["ifname"]` — still "e1-1" (no stitch) → no emit. Good. For idx 8: since is 2 minutes ago → skip. want = two creates. Good.

Wait — there's a test issue: `TestReportStitchMarksLeavesUnmarkedLinks` doesn't actually test that a marked link DOES get reported. There's no positive test for reportStitchMarks' rename path (well, `TestEmitReportsRenamedLinkDeleted` tests emit's rename handling but not reportStitchMarks itself). Coverage note, not a finding per se. Actually a small gap: no test that `reportStitchMarks` emits an update when the stitch interface exists. But testing that would require mocking `ToolsInterface` (netlink.LinkByName in root ns) — hard in unit test; they'd need a real host link with the altname. The tests for emit cover the rename logic. Acceptable; coverage note.

M. Now check `TestEmitStatsReportsRenamedLinkFirst`: registry has includeStats=true. `emitStats` checks `!registry.includeStats` → registry.includeStats is true. `snapshot.HasStats` — snapshotFromLink with Statistics set → HasStats true. track → rename → sends delete (old attrs, with alias e1-1, ifname clab-s-0011aabb), stores new clone. sends create with maps.Clone(attributes). Then interfaceStatsAttributes mutates attributes, sends stats. The assertion: hasCounters != (action == "stats") → for delete: hasCounters false, action != stats → ok. create: clone before mutation → no counters → ok. stats: has counters → ok.

Wait — does `interfaceAttributes` for the delete event in `track`... track sends `previous.attributes` which is the stored map {"ifname": "clab-s-0011aabb", "alias": "e1-1"}. OK.

But hmm — one thing: in emitStats, when `track` returns true (rename), it sends a "create" event with metrics.Timestamp — but no counters. And then a "stats" event. So a client gets delete, create (no stats), stats. Consistent.

N. Now think about `emit` "snapshot" action with rename: if action is "snapshot" and track returns true (renamed), action stays "snapshot" — the client gets delete(old) + snapshot(new). Is "snapshot" treated like create by clients? Pre-existing semantics: snapshot events only on first subscription with includeSnapshot. Can a snapshot event rename? reported is empty at first subscription (fresh watcher), so track can't detect rename → returns false. Fine.

Actually wait — can `reported` be non-nil at first subscription? Watcher is new on Start; `reported` nil. But on resubscribe within the same run() loop, processExisting with !initial → "create" action; with exists → "update". Reported map persists across resubscribes — that's the point.

O. Now — a genuine question: does the rename detection handle the case where the same ifname is reused by a different index? E.g., node-ns link "eth1" deleted (delete event, reported entry removed), then new link at different index also named "eth1"? Fine.

P. Now the more serious check — `emit`'s delete path sends `previous.attributes` — but `previous.attributes` map was stored in `track` as a clone, and it's also referenced in `w.reported` before deletion. After `delete(w.reported, ...)`, the map is sent to channel. No mutation. Fine.

Q. Potential missing `since` update: In `track`, when known and ifname unchanged, since is preserved (first report). When renamed, since also preserved (since = previous.since). Hmm — should the window restart after rename? After rename to stitch name, reportStitchMarks skips (ifname mismatch), so irrelevant.

R. Now think about `collectAndEmitStats` + `emitStats`: `collectAndEmitStats` updates `states[idx] = state` with the fresh current link attributes but does NOT compare equality — it unconditionally updates state from current. Pre-existing. Fine.

S. One more: `reportStitchMarks` emits "update" events for links where stitch got marked, but does NOT update `states` — states snapshot unchanged (node-side). That's fine; emit uses snapshot from states.

T. Now, is `w.reported` also updated by `reportStitchMarks` indirectly through emit → track. Yes.

U. Potential issue: In `emit`, the delete path when previous doesn't exist: computes attributes and sends a delete event for a link never reported. When is emit("delete") called for unreported links? `removeVanishedLinks` — states entries always have corresponding... hmm, states entries exist without reported entries when includeSnapshot=false at first subscription (links present at start are tracked in states but never reported). Then if such a link is deleted while subscription down, removeVanishedLinks emits delete with fresh interfaceAttributes. Client never saw a create — sending a delete for an unknown interface. Pre-existing behavior (base did the same via emitInterfaceEvent). Not worsened. Actually wait — in base, was it? Base removeVanishedLinks: `registry.emitInterfaceEvent(w.container, "delete", snapshot)` — same. Yes pre-existing.

Also processUpdate RTM_DELLINK only fires when `exists` in states. But states can contain unreported links (includeSnapshot=false case). Same pre-existing.

Hmm, actually with the new tracking available, this could have been fixed (use w.reported to decide whether to send delete). But not required.

V. Now the netlink.go change removes `emitInterfaceStatsEvent` from registry and adds `emitStats` on watcher. `sendInterfaceEvent` retains the container==nil guard? No! Look: base `emitInterfaceEvent` had `if container == nil { return }`. Head `sendInterfaceEvent` does NOT check container == nil — it dereferences `container.ShortID`. But `emit` and `emitStats` check `w.container == nil` before calling. Is `sendInterfaceEvent` called anywhere else with a possibly-nil container? Let me grep for sendInterfaceEvent callers. In head: emit (guarded), emitStats (guarded), track (called from emit/emitStats which are guarded; track uses w.container — non-nil by then). Any other callers? Need to check. Let me grep.

Also check `labRuntimeInterfaceAttributes` callers — separate file probably. Let me grep the head repo for `sendInterfaceEvent` and other usages.

W. Also check docs: `docs/cmd/events.md` — does the events command doc mention interface events/rename behavior? The change adds new event sequences (delete+create on rename). Docs may describe event actions. Let me check events.md for interface event documentation.

X. Check schema: interface events aren't in clab.schema.json domain (that's topology). Not needed.

Let me now grep for sendInterfaceEvent callers, ToolsInterface callers, and check the events docs.
grep · completed

Input

{
  "path": "/source/head",
  "pattern": "sendInterfaceEvent|emitInterfaceStatsEvent|emitInterfaceEvent"
}

Output

Found 6 matches
/source/head/core/events/netlink.go:
  Line 688: 		registry.sendInterfaceEvent(w.container, action, attributes, time.Now())

  Line 698: 	registry.sendInterfaceEvent(w.container, action, attributes, time.Now())

  Line 713: 		registry.sendInterfaceEvent(

  Line 722: 	registry.sendInterfaceEvent(w.container, "stats", attributes, metrics.Timestamp)

  Line 749: 	registry.sendInterfaceEvent(w.container, "delete", previous.attributes, time.Now())

  Line 934: func (r *netlinkRegistry) sendInterfaceEvent(
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46dc1110014K3eUDOvDZsiOa",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46c28a3001vr1NLdqv5hwDqb",
  "callID": "call_cf0185fe2dda4fe9b3694b5a",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head",
      "pattern": "sendInterfaceEvent|emitInterfaceStatsEvent|emitInterfaceEvent"
    },
    "output": "Found 6 matches\n/source/head/core/events/netlink.go:\n  Line 688: \t\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n\n  Line 698: \tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n\n  Line 713: \t\tregistry.sendInterfaceEvent(\n\n  Line 722: \tregistry.sendInterfaceEvent(w.container, \"stats\", attributes, metrics.Timestamp)\n\n  Line 749: \tregistry.sendInterfaceEvent(w.container, \"delete\", previous.attributes, time.Now())\n\n  Line 934: func (r *netlinkRegistry) sendInterfaceEvent(\n",
    "title": "sendInterfaceEvent|emitInterfaceStatsEvent|emitInterfaceEvent",
    "metadata": {
      "matches": 6,
      "truncated": false
    },
    "time": {
      "start": 1794565325079,
      "end": 1794565325116
    }
  }
}
grep · completed

Input

{
  "path": "/source/head",
  "pattern": "ToolsInterface|reportStitchMarks|stitchMarkWindow"
}

Output

Found 20 matches
/source/head/core/netem.go:
  Line 97: 	if _, ok := clablinks.ToolsInterface(n.lab, n.node, iface); !ok {


/source/head/core/events/netlink_test.go:
  Line 11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {

  Line 32: 			overlayToolsInterface(container, attrs)


/source/head/core/events/netlink.go:
  Line 263: // stitchMarkWindow is how long after a link is first reported its host-side

  Line 267: var stitchMarkWindow = time.Minute

  Line 441: 			w.reportStitchMarks(states, registry)

  Line 650: // reportStitchMarks reports the links whose host-side stitch interface got

  Line 654: func (w *netlinkWatcher) reportStitchMarks(

  Line 662: 			time.Since(reported.since) > stitchMarkWindow {

  Line 867: 	overlayToolsInterface(container, attributes)

  Line 896: // overlayToolsInterface rewrites attributes to the host-side stitch interface

  Line 898: func overlayToolsInterface(

  Line 916: 	tools, ok := clablinks.ToolsInterface(lab, node, topoName)


/source/head/core/events/netlink_watch_test.go:
  Line 525: 		since:      time.Now().Add(-2 * stitchMarkWindow),

  Line 528: 	watcher.reportStitchMarks(states, registry)


/source/head/core/list.go:
  Line 176: 	if tools, ok := clablinks.ToolsInterface(lab, node, topoName); ok {


/source/head/links/link_veth_stitched.go:
  Line 299: // ToolsInterface returns the host-netns interface veth-stitch (and similar

  Line 302: func ToolsInterface(labName, node, iface string) (netlink.Link, bool) {


/source/head/links/link_veth_stitched_test.go:
  Line 178: func TestToolsInterfaceGuardsEmptyIdentity(t *testing.T) {

  Line 185: 			if link, ok := ToolsInterface(args[0], args[1], args[2]); ok || link != nil {
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46dc1c4001X3mAfx7vOpP0s1",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46c28a3001vr1NLdqv5hwDqb",
  "callID": "call_17237cfa346c4041badb9224",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head",
      "pattern": "ToolsInterface|reportStitchMarks|stitchMarkWindow"
    },
    "output": "Found 20 matches\n/source/head/core/netem.go:\n  Line 97: \tif _, ok := clablinks.ToolsInterface(n.lab, n.node, iface); !ok {\n\n\n/source/head/core/events/netlink_test.go:\n  Line 11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {\n\n  Line 32: \t\t\toverlayToolsInterface(container, attrs)\n\n\n/source/head/core/events/netlink.go:\n  Line 263: // stitchMarkWindow is how long after a link is first reported its host-side\n\n  Line 267: var stitchMarkWindow = time.Minute\n\n  Line 441: \t\t\tw.reportStitchMarks(states, registry)\n\n  Line 650: // reportStitchMarks reports the links whose host-side stitch interface got\n\n  Line 654: func (w *netlinkWatcher) reportStitchMarks(\n\n  Line 662: \t\t\ttime.Since(reported.since) > stitchMarkWindow {\n\n  Line 867: \toverlayToolsInterface(container, attributes)\n\n  Line 896: // overlayToolsInterface rewrites attributes to the host-side stitch interface\n\n  Line 898: func overlayToolsInterface(\n\n  Line 916: \ttools, ok := clablinks.ToolsInterface(lab, node, topoName)\n\n\n/source/head/core/events/netlink_watch_test.go:\n  Line 525: \t\tsince:      time.Now().Add(-2 * stitchMarkWindow),\n\n  Line 528: \twatcher.reportStitchMarks(states, registry)\n\n\n/source/head/core/list.go:\n  Line 176: \tif tools, ok := clablinks.ToolsInterface(lab, node, topoName); ok {\n\n\n/source/head/links/link_veth_stitched.go:\n  Line 299: // ToolsInterface returns the host-netns interface veth-stitch (and similar\n\n  Line 302: func ToolsInterface(labName, node, iface string) (netlink.Link, bool) {\n\n\n/source/head/links/link_veth_stitched_test.go:\n  Line 178: func TestToolsInterfaceGuardsEmptyIdentity(t *testing.T) {\n\n  Line 185: \t\t\tif link, ok := ToolsInterface(args[0], args[1], args[2]); ok || link != nil {\n",
    "title": "ToolsInterface|reportStitchMarks|stitchMarkWindow",
    "metadata": {
      "matches": 20,
      "truncated": false
    },
    "time": {
      "start": 1794565325258,
      "end": 1794565325292
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46dc1ef001pN9WtwMjNuwNDp",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46c28a3001vr1NLdqv5hwDqb",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 69501,
    "input": 63925,
    "output": 55,
    "reasoning": 5521,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46c28a3001vr1NLdqv5hwDqb",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565220515,
    "completed": 1794565325300
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 69501,
    "input": 63925,
    "output": 55,
    "reasoning": 5521,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 9
step-start
{
  "type": "step-start",
  "id": "prt_1d46dcbb70010lxt33SvxAJRQE",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dc1f9001riiYyI5T8B4p4l"
}
Reasoning
Now check the events docs and any place that documents interface event actions (delete/create/update/snapshot/stats). Also check `interfaceAttributes` behavior in `emit`'s delete path — the wasted `interfaceAttributes` call. And check the events command documentation.
read · completed

Input

{
  "filePath": "/source/head/docs/cmd/events.md"
}

Output

<path>/source/head/docs/cmd/events.md</path>
<type>file</type>
<content>
1: # events command
2: 
3: ## Description
4: 
5: The `events` command streams lifecycle updates for every Containerlab resource and augments them with interface change notifications collected from the container network namespaces. The output combines the selected runtime's event feed (for example Docker) with the netlink information that powers `containerlab inspect interfaces`, so you can observe container activity and interface state changes in real time without selecting a specific lab.
6: 
7: ## Usage
8: 
9: `containerlab [global-flags] events [local-flags]`
10: 
11: **aliases:** `ev`
12: 
13: The command respects the global flags such as `--runtime`, `--debug`, or `--log-level`. It adds local options:
14: 
15: - `--format` controls the output representation (`plain`, `json`).
16: - `--initial-state` emits a snapshot of currently running containers and their interface states before following live updates.
17: - `--interface-stats` enables periodic interface counter sampling; leave unset to report only lifecycle and state changes.
18: - `--interface-stats-interval` customizes how frequently statistics are collected (for example `500ms`, `2s`, `1m`).
19: 
20: When invoked with no arguments it discovers all running labs and immediately begins streaming events; new labs that start after the command begins are picked up automatically.
21: 
22: ## Event format
23: 
24: In the default `plain` format every line mirrors the `docker events` format:
25: 
26: ```
27: <timestamp> <type> <action> <actor> (<key>=<value>, ...)
28: ```
29: 
30: - **Runtime events** show the short container ID as the actor and include the original attributes supplied by the container runtime (for example `image`, `name`, `containerlab`, `scope`, …). Container events are also enriched with `mgmt_ipv4`, `mgmt_ipv6`, and `ports` (published/exposed ports) when those values are available. When `--initial-state` is enabled the stream starts with `container <state>` snapshots (for example `container running`) that carry an `origin=snapshot` attribute.
31: - **Interface events** use type `interface` and `origin=netlink` in the attribute list. They also report interface-specific data such as `ifname`, `state`, `mtu`, `mac`, `type`, `alias`, and the lab label. The actor is still the container short ID, and the container name is supplied in the attributes (`name=...`).
32: - Interface notifications are emitted when a link appears, disappears, or when its relevant properties (operational state, MTU, alias, MAC address, type) change. Initial snapshots use the `snapshot` action when `--initial-state` is requested. When interface statistics are enabled the stream also includes `interface stats` updates with byte/packet counters and rate estimates.
33: 
34: When `--format json` is used, each event becomes a single JSON object on its own line. The fields match the plain output (`timestamp`, `type`, `action`, `actor_id`, `actor_name`, `actor_full_id`) and include an `attributes` map with the same key/value pairs that the plain formatter prints.
35: 
36: ## Examples
37: 
38: ### Watch an existing lab and new deployments
39: 
40: ```
41: $ containerlab events
42: 2024-07-01T11:02:56.123456000Z container start 5d0b5a9ad3f1 (containerlab=frr-lab, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01, ports=0.0.0.0:2222/tcp->22;0.0.0.0:830/tcp->830)
43: 2024-07-01T11:02:57.004321000Z interface create 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)
44: 2024-07-01T11:02:57.104512000Z interface update 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=9000, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)
45: 2024-07-01T11:05:12.918273000Z container die 5d0b5a9ad3f1 (containerlab=frr-lab, exitCode=0, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01)
46: 2024-07-01T11:05:13.018456000Z interface delete 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)
47: ```
48: 
49: The stream contains all currently running labs and stays active to capture subsequent deployments, restarts, or interface adjustments.
50: 
51: ### Include existing resources in the stream
52: 
53: ```
54: $ containerlab events --initial-state
55: 2024-07-01T11:02:55.912345000Z container running 5d0b5a9ad3f1 (containerlab=frr-lab, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01, origin=snapshot, ports=0.0.0.0:2222/tcp->22;0.0.0.0:830/tcp->830, state=running)
56: 2024-07-01T11:02:55.912678000Z interface snapshot 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)
57: …
58: ```
59: 
60: This mode begins with a point-in-time view of every running container and interface before switching to live updates.
61: 
62: ### Include interface statistics
63: 
64: ```
65: containerlab events --interface-stats
66: ```
67: 
68: Statistics are disabled by default. Enabling them augments the feed with periodic counter samples in addition to lifecycle and state changes. Use `--interface-stats-interval` to balance fidelity with overhead: values between `1s` and `5s` work well for most labs, while larger deployments may prefer longer intervals (for example `10s`) to avoid excessive sampling load.
69: 
70: ### Use with alternative runtimes
71: 
72: Containerlab streams events from the runtime selected via the global `--runtime` flag.
73: 
74: Currently supported runtimes:
75: 
76: - `docker`
77: - `c9s`
78: 
79: With `--runtime c9s`, events are backed by kubernetes watches for Clabernetes
80: `Topology` and `Node` resources and labeled Pods. They use the actions and
81: attributes of the Docker runtime: a node is a container (`create`, `start`,
82: `kill`, `stop`, `die`, `destroy`, `health_status: …`) described by the same
83: labels, and the interface events (`snapshot`, `create`, `update`, `delete`,
84: `stats`) report the node's lab link interfaces, `eth0` and `lo` under the names
85: a Docker container of the node has. Interface state and statistics are sampled
86: inside the device containers, not through local host netlink. The stream covers
87: every namespace by default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it
88: to one namespace, and `-t`/`--name` to one lab. With Docker and Podman the lab
89: selection is ignored and every lab is streamed. The
90: [c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the
91: attributes and the few Docker attributes c9s has no equivalent for.
92: 
93: Runtimes that do not implement the `events` API, or are not yet supported by Containerlab, will exit with an explanatory error.
94: 
95: ## See also
96: 
97: - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.
98: - [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.
99: - `docker events` – the raw runtime feed that Containerlab builds upon.

(End of file - total 99 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46dcf61001DOpsQcMLOfb7xs",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dc1f9001riiYyI5T8B4p4l",
  "callID": "call_002e2b3e2a5d42f6bc4ea186",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/docs/cmd/events.md"
    },
    "output": "<path>/source/head/docs/cmd/events.md</path>\n<type>file</type>\n<content>\n1: # events command\n2: \n3: ## Description\n4: \n5: The `events` command streams lifecycle updates for every Containerlab resource and augments them with interface change notifications collected from the container network namespaces. The output combines the selected runtime's event feed (for example Docker) with the netlink information that powers `containerlab inspect interfaces`, so you can observe container activity and interface state changes in real time without selecting a specific lab.\n6: \n7: ## Usage\n8: \n9: `containerlab [global-flags] events [local-flags]`\n10: \n11: **aliases:** `ev`\n12: \n13: The command respects the global flags such as `--runtime`, `--debug`, or `--log-level`. It adds local options:\n14: \n15: - `--format` controls the output representation (`plain`, `json`).\n16: - `--initial-state` emits a snapshot of currently running containers and their interface states before following live updates.\n17: - `--interface-stats` enables periodic interface counter sampling; leave unset to report only lifecycle and state changes.\n18: - `--interface-stats-interval` customizes how frequently statistics are collected (for example `500ms`, `2s`, `1m`).\n19: \n20: When invoked with no arguments it discovers all running labs and immediately begins streaming events; new labs that start after the command begins are picked up automatically.\n21: \n22: ## Event format\n23: \n24: In the default `plain` format every line mirrors the `docker events` format:\n25: \n26: ```\n27: <timestamp> <type> <action> <actor> (<key>=<value>, ...)\n28: ```\n29: \n30: - **Runtime events** show the short container ID as the actor and include the original attributes supplied by the container runtime (for example `image`, `name`, `containerlab`, `scope`, …). Container events are also enriched with `mgmt_ipv4`, `mgmt_ipv6`, and `ports` (published/exposed ports) when those values are available. When `--initial-state` is enabled the stream starts with `container <state>` snapshots (for example `container running`) that carry an `origin=snapshot` attribute.\n31: - **Interface events** use type `interface` and `origin=netlink` in the attribute list. They also report interface-specific data such as `ifname`, `state`, `mtu`, `mac`, `type`, `alias`, and the lab label. The actor is still the container short ID, and the container name is supplied in the attributes (`name=...`).\n32: - Interface notifications are emitted when a link appears, disappears, or when its relevant properties (operational state, MTU, alias, MAC address, type) change. Initial snapshots use the `snapshot` action when `--initial-state` is requested. When interface statistics are enabled the stream also includes `interface stats` updates with byte/packet counters and rate estimates.\n33: \n34: When `--format json` is used, each event becomes a single JSON object on its own line. The fields match the plain output (`timestamp`, `type`, `action`, `actor_id`, `actor_name`, `actor_full_id`) and include an `attributes` map with the same key/value pairs that the plain formatter prints.\n35: \n36: ## Examples\n37: \n38: ### Watch an existing lab and new deployments\n39: \n40: ```\n41: $ containerlab events\n42: 2024-07-01T11:02:56.123456000Z container start 5d0b5a9ad3f1 (containerlab=frr-lab, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01, ports=0.0.0.0:2222/tcp->22;0.0.0.0:830/tcp->830)\n43: 2024-07-01T11:02:57.004321000Z interface create 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n44: 2024-07-01T11:02:57.104512000Z interface update 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=9000, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n45: 2024-07-01T11:05:12.918273000Z container die 5d0b5a9ad3f1 (containerlab=frr-lab, exitCode=0, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01)\n46: 2024-07-01T11:05:13.018456000Z interface delete 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n47: ```\n48: \n49: The stream contains all currently running labs and stays active to capture subsequent deployments, restarts, or interface adjustments.\n50: \n51: ### Include existing resources in the stream\n52: \n53: ```\n54: $ containerlab events --initial-state\n55: 2024-07-01T11:02:55.912345000Z container running 5d0b5a9ad3f1 (containerlab=frr-lab, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01, origin=snapshot, ports=0.0.0.0:2222/tcp->22;0.0.0.0:830/tcp->830, state=running)\n56: 2024-07-01T11:02:55.912678000Z interface snapshot 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n57: …\n58: ```\n59: \n60: This mode begins with a point-in-time view of every running container and interface before switching to live updates.\n61: \n62: ### Include interface statistics\n63: \n64: ```\n65: containerlab events --interface-stats\n66: ```\n67: \n68: Statistics are disabled by default. Enabling them augments the feed with periodic counter samples in addition to lifecycle and state changes. Use `--interface-stats-interval` to balance fidelity with overhead: values between `1s` and `5s` work well for most labs, while larger deployments may prefer longer intervals (for example `10s`) to avoid excessive sampling load.\n69: \n70: ### Use with alternative runtimes\n71: \n72: Containerlab streams events from the runtime selected via the global `--runtime` flag.\n73: \n74: Currently supported runtimes:\n75: \n76: - `docker`\n77: - `c9s`\n78: \n79: With `--runtime c9s`, events are backed by kubernetes watches for Clabernetes\n80: `Topology` and `Node` resources and labeled Pods. They use the actions and\n81: attributes of the Docker runtime: a node is a container (`create`, `start`,\n82: `kill`, `stop`, `die`, `destroy`, `health_status: …`) described by the same\n83: labels, and the interface events (`snapshot`, `create`, `update`, `delete`,\n84: `stats`) report the node's lab link interfaces, `eth0` and `lo` under the names\n85: a Docker container of the node has. Interface state and statistics are sampled\n86: inside the device containers, not through local host netlink. The stream covers\n87: every namespace by default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it\n88: to one namespace, and `-t`/`--name` to one lab. With Docker and Podman the lab\n89: selection is ignored and every lab is streamed. The\n90: [c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the\n91: attributes and the few Docker attributes c9s has no equivalent for.\n92: \n93: Runtimes that do not implement the `events` API, or are not yet supported by Containerlab, will exit with an explanatory error.\n94: \n95: ## See also\n96: \n97: - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n98: - [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.\n99: - `docker events` – the raw runtime feed that Containerlab builds upon.\n\n(End of file - total 99 lines)\n</content>",
    "title": "source/head/docs/cmd/events.md",
    "metadata": {
      "preview": "# events command\n\n## Description\n\nThe `events` command streams lifecycle updates for every Containerlab resource and augments them with interface change notifications collected from the container network namespaces. The output combines the selected runtime's event feed (for example Docker) with the netlink information that powers `containerlab inspect interfaces`, so you can observe container activity and interface state changes in real time without selecting a specific lab.\n\n## Usage\n\n`containerlab [global-flags] events [local-flags]`\n\n**aliases:** `ev`\n\nThe command respects the global flags such as `--runtime`, `--debug`, or `--log-level`. It adds local options:\n\n- `--format` controls the output representation (`plain`, `json`).\n- `--initial-state` emits a snapshot of currently running containers and their interface states before following live updates.\n- `--interface-stats` enables periodic interface counter sampling; leave unset to report only lifecycle and state changes.\n- `--interface-stats-interval` customizes how frequently statistics are collected (for example `500ms`, `2s`, `1m`).\n\nWhen invoked with no arguments it discovers all running labs and immediately begins streaming events; new labs that start after the command begins are picked up automatically.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/docs/cmd/events.md",
        "text": "# events command\n\n## Description\n\nThe `events` command streams lifecycle updates for every Containerlab resource and augments them with interface change notifications collected from the container network namespaces. The output combines the selected runtime's event feed (for example Docker) with the netlink information that powers `containerlab inspect interfaces`, so you can observe container activity and interface state changes in real time without selecting a specific lab.\n\n## Usage\n\n`containerlab [global-flags] events [local-flags]`\n\n**aliases:** `ev`\n\nThe command respects the global flags such as `--runtime`, `--debug`, or `--log-level`. It adds local options:\n\n- `--format` controls the output representation (`plain`, `json`).\n- `--initial-state` emits a snapshot of currently running containers and their interface states before following live updates.\n- `--interface-stats` enables periodic interface counter sampling; leave unset to report only lifecycle and state changes.\n- `--interface-stats-interval` customizes how frequently statistics are collected (for example `500ms`, `2s`, `1m`).\n\nWhen invoked with no arguments it discovers all running labs and immediately begins streaming events; new labs that start after the command begins are picked up automatically.\n\n## Event format\n\nIn the default `plain` format every line mirrors the `docker events` format:\n\n```\n<timestamp> <type> <action> <actor> (<key>=<value>, ...)\n```\n\n- **Runtime events** show the short container ID as the actor and include the original attributes supplied by the container runtime (for example `image`, `name`, `containerlab`, `scope`, …). Container events are also enriched with `mgmt_ipv4`, `mgmt_ipv6`, and `ports` (published/exposed ports) when those values are available. When `--initial-state` is enabled the stream starts with `container <state>` snapshots (for example `container running`) that carry an `origin=snapshot` attribute.\n- **Interface events** use type `interface` and `origin=netlink` in the attribute list. They also report interface-specific data such as `ifname`, `state`, `mtu`, `mac`, `type`, `alias`, and the lab label. The actor is still the container short ID, and the container name is supplied in the attributes (`name=...`).\n- Interface notifications are emitted when a link appears, disappears, or when its relevant properties (operational state, MTU, alias, MAC address, type) change. Initial snapshots use the `snapshot` action when `--initial-state` is requested. When interface statistics are enabled the stream also includes `interface stats` updates with byte/packet counters and rate estimates.\n\nWhen `--format json` is used, each event becomes a single JSON object on its own line. The fields match the plain output (`timestamp`, `type`, `action`, `actor_id`, `actor_name`, `actor_full_id`) and include an `attributes` map with the same key/value pairs that the plain formatter prints.\n\n## Examples\n\n### Watch an existing lab and new deployments\n\n```\n$ containerlab events\n2024-07-01T11:02:56.123456000Z container start 5d0b5a9ad3f1 (containerlab=frr-lab, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01, ports=0.0.0.0:2222/tcp->22;0.0.0.0:830/tcp->830)\n2024-07-01T11:02:57.004321000Z interface create 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n2024-07-01T11:02:57.104512000Z interface update 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=9000, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n2024-07-01T11:05:12.918273000Z container die 5d0b5a9ad3f1 (containerlab=frr-lab, exitCode=0, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01)\n2024-07-01T11:05:13.018456000Z interface delete 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n```\n\nThe stream contains all currently running labs and stays active to capture subsequent deployments, restarts, or interface adjustments.\n\n### Include existing resources in the stream\n\n```\n$ containerlab events --initial-state\n2024-07-01T11:02:55.912345000Z container running 5d0b5a9ad3f1 (containerlab=frr-lab, image=ghcr.io/srl-labs/frr, name=clab-frr-lab-frr01, origin=snapshot, ports=0.0.0.0:2222/tcp->22;0.0.0.0:830/tcp->830, state=running)\n2024-07-01T11:02:55.912678000Z interface snapshot 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n…\n```\n\nThis mode begins with a point-in-time view of every running container and interface before switching to live updates.\n\n### Include interface statistics\n\n```\ncontainerlab events --interface-stats\n```\n\nStatistics are disabled by default. Enabling them augments the feed with periodic counter samples in addition to lifecycle and state changes. Use `--interface-stats-interval` to balance fidelity with overhead: values between `1s` and `5s` work well for most labs, while larger deployments may prefer longer intervals (for example `10s`) to avoid excessive sampling load.\n\n### Use with alternative runtimes\n\nContainerlab streams events from the runtime selected via the global `--runtime` flag.\n\nCurrently supported runtimes:\n\n- `docker`\n- `c9s`\n\nWith `--runtime c9s`, events are backed by kubernetes watches for Clabernetes\n`Topology` and `Node` resources and labeled Pods. They use the actions and\nattributes of the Docker runtime: a node is a container (`create`, `start`,\n`kill`, `stop`, `die`, `destroy`, `health_status: …`) described by the same\nlabels, and the interface events (`snapshot`, `create`, `update`, `delete`,\n`stats`) report the node's lab link interfaces, `eth0` and `lo` under the names\na Docker container of the node has. Interface state and statistics are sampled\ninside the device containers, not through local host netlink. The stream covers\nevery namespace by default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it\nto one namespace, and `-t`/`--name` to one lab. With Docker and Podman the lab\nselection is ignored and every lab is streamed. The\n[c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the\nattributes and the few Docker attributes c9s has no equivalent for.\n\nRuntimes that do not implement the `events` API, or are not yet supported by Containerlab, will exit with an explanatory error.\n\n## See also\n\n- [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.\n- `docker events` – the raw runtime feed that Containerlab builds upon.",
        "lineStart": 1,
        "lineEnd": 99,
        "totalLines": 99,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565328742,
      "end": 1794565328749
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/docs",
  "pattern": "interface.*event|netlink|ifname"
}

Output

Found 26 matches
/source/head/docs/manual/network.md:
  Line 460: The default management bridge driver options are configured to allow external network access from the containers through the management interface, including internet. In order to prevent unintentional internet or external network access, ip masquerading needs to be disabled on the management interface bridge:


/source/head/docs/manual/clabernetes/runtime.md:
  Line 800: The c9s runtime streams container, interface state and interface-stat events

  Line 932: the local runtimes' netlink events:

  Line 943:     "ifname": "e1-1",

  Line 965: - `state` is the operational state in netlink's names: `up`, `down`,

  Line 972: With `--interface-stats`, the same exec also produces `interface stats` events

  Line 979: /// note | Polling, not netlink

  Line 1337: `exec`, `save`, `save --copy`, and the interface events of `events` need pod


/source/head/docs/rn/0.74.md:
  Line 83: - Fixed netlink errors during concurrent deployment of links. #3102


/source/head/docs/rn/0.78.md:
  Line 117: - Improved `veth-stitch` and `vxlan-stitch` deployment reliability by retrying transient netlink errors and ensuring stitch rules are applied after both endpoints are ready. #3319


/source/head/docs/rn/0.73.md:
  Line 41: Building on the real-time events streaming introduced in 0.72, the [`events`](../cmd/events.md) command now also tracks network emulation (netem) impairment changes. When you apply delay, jitter, packet loss, or rate limiting via `containerlab tools netem set`, these changes appear as interface update events in real time -- giving you full observability into link impairment changes alongside container and interface lifecycle events.


/source/head/docs/rn/0.72.md:
  Line 13: The events command combines Docker's event feed with netlink information, allowing you to observe container activity and interface state changes in real time without selecting a specific lab. This is particularly useful for monitoring dynamic topologies, debugging connectivity issues, and understanding the behavior of your network labs as they evolve - everything [Containerlab VS Code extension](../manual/gui/vsc-extension.md) wanted to have ;)


/source/head/docs/rn/0.83.md:
  Line 163: - `containerlab events` no longer misses interfaces created while a watcher starts. Failed netlink subscriptions are retried and re-established, with changes during the outage reconciled instead of silently ending interface reporting. [#3532](https://github.com/srl-labs/containerlab/pull/3532)


/source/head/docs/rn/0.80.md:
  Line 276: - `sonic-vs` marks its wire interfaces (`ethN`) ARP-off and IPv6-off so only the port interface answers, preventing stale ARP entries with the wrong MAC. [#3390](https://github.com/srl-labs/containerlab/pull/3390)


/source/head/docs/rn/0.75.md:
  Line 73: - **Core:** close netns and netlink handles in interface listing; fix a tool-container cleanup loop when `exec` fails; return errors for bad PEM in cert code paths; stricter `PreDeploy` certificate error propagation; safer env var splitting and `CreateFile` error checks; and closing files to avoid leaks. #3161 #3159 #3130 #3138 #3139 #3140 #3132


/source/head/docs/cmd/inspect/interfaces.md:
  Line 8: With the [c9s runtime](../../manual/clabernetes/runtime.md#interface-events), the listing covers the interfaces a Docker container of the node has: the lab link interfaces of each running node (the ones [`capture`](../capture.md) accepts) with the alias the topology used, the management interface `eth0` and the loopback `lo`, with the MAC address, index, MTU and operational state read in the node's device container. The pod's own interfaces are not listed. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields and values (`veth`/`device`, netlink state names) are the same as with Docker. `eth0` and `lo` cannot be captured on c9s.


/source/head/docs/cmd/events.md:
  Line 5: The `events` command streams lifecycle updates for every Containerlab resource and augments them with interface change notifications collected from the container network namespaces. The output combines the selected runtime's event feed (for example Docker) with the netlink information that powers `containerlab inspect interfaces`, so you can observe container activity and interface state changes in real time without selecting a specific lab.

  Line 31: - **Interface events** use type `interface` and `origin=netlink` in the attribute list. They also report interface-specific data such as `ifname`, `state`, `mtu`, `mac`, `type`, `alias`, and the lab label. The actor is still the container short ID, and the container name is supplied in the attributes (`name=...`).

  Line 43: 2024-07-01T11:02:57.004321000Z interface create 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)

  Line 44: 2024-07-01T11:02:57.104512000Z interface update 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=9000, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)

  Line 46: 2024-07-01T11:05:13.018456000Z interface delete 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)

  Line 56: 2024-07-01T11:02:55.912678000Z interface snapshot 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)

  Line 83: labels, and the interface events (`snapshot`, `create`, `update`, `delete`,

  Line 86: inside the device containers, not through local host netlink. The stream covers

  Line 97: - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.


/source/head/docs/macos.md:
  Line 30: 3. **Linux on macOS?** It is not only Docker that containerlab is based on. We leverage some Linux kernel APIs (like netlink) either directly or via Docker to be available to setup links, namespaces, bind-mounts, etc.  
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46dd037001iGgsW3UqtRqzbN",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dc1f9001riiYyI5T8B4p4l",
  "callID": "call_912c5c37b1de4c27a0059440",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/docs",
      "pattern": "interface.*event|netlink|ifname"
    },
    "output": "Found 26 matches\n/source/head/docs/manual/network.md:\n  Line 460: The default management bridge driver options are configured to allow external network access from the containers through the management interface, including internet. In order to prevent unintentional internet or external network access, ip masquerading needs to be disabled on the management interface bridge:\n\n\n/source/head/docs/manual/clabernetes/runtime.md:\n  Line 800: The c9s runtime streams container, interface state and interface-stat events\n\n  Line 932: the local runtimes' netlink events:\n\n  Line 943:     \"ifname\": \"e1-1\",\n\n  Line 965: - `state` is the operational state in netlink's names: `up`, `down`,\n\n  Line 972: With `--interface-stats`, the same exec also produces `interface stats` events\n\n  Line 979: /// note | Polling, not netlink\n\n  Line 1337: `exec`, `save`, `save --copy`, and the interface events of `events` need pod\n\n\n/source/head/docs/rn/0.74.md:\n  Line 83: - Fixed netlink errors during concurrent deployment of links. #3102\n\n\n/source/head/docs/rn/0.78.md:\n  Line 117: - Improved `veth-stitch` and `vxlan-stitch` deployment reliability by retrying transient netlink errors and ensuring stitch rules are applied after both endpoints are ready. #3319\n\n\n/source/head/docs/rn/0.73.md:\n  Line 41: Building on the real-time events streaming introduced in 0.72, the [`events`](../cmd/events.md) command now also tracks network emulation (netem) impairment changes. When you apply delay, jitter, packet loss, or rate limiting via `containerlab tools netem set`, these changes appear as interface update events in real time -- giving you full observability into link impairment changes alongside container and interface lifecycle events.\n\n\n/source/head/docs/rn/0.72.md:\n  Line 13: The events command combines Docker's event feed with netlink information, allowing you to observe container activity and interface state changes in real time without selecting a specific lab. This is particularly useful for monitoring dynamic topologies, debugging connectivity issues, and understanding the behavior of your network labs as they evolve - everything [Containerlab VS Code extension](../manual/gui/vsc-extension.md) wanted to have ;)\n\n\n/source/head/docs/rn/0.83.md:\n  Line 163: - `containerlab events` no longer misses interfaces created while a watcher starts. Failed netlink subscriptions are retried and re-established, with changes during the outage reconciled instead of silently ending interface reporting. [#3532](https://github.com/srl-labs/containerlab/pull/3532)\n\n\n/source/head/docs/rn/0.80.md:\n  Line 276: - `sonic-vs` marks its wire interfaces (`ethN`) ARP-off and IPv6-off so only the port interface answers, preventing stale ARP entries with the wrong MAC. [#3390](https://github.com/srl-labs/containerlab/pull/3390)\n\n\n/source/head/docs/rn/0.75.md:\n  Line 73: - **Core:** close netns and netlink handles in interface listing; fix a tool-container cleanup loop when `exec` fails; return errors for bad PEM in cert code paths; stricter `PreDeploy` certificate error propagation; safer env var splitting and `CreateFile` error checks; and closing files to avoid leaks. #3161 #3159 #3130 #3138 #3139 #3140 #3132\n\n\n/source/head/docs/cmd/inspect/interfaces.md:\n  Line 8: With the [c9s runtime](../../manual/clabernetes/runtime.md#interface-events), the listing covers the interfaces a Docker container of the node has: the lab link interfaces of each running node (the ones [`capture`](../capture.md) accepts) with the alias the topology used, the management interface `eth0` and the loopback `lo`, with the MAC address, index, MTU and operational state read in the node's device container. The pod's own interfaces are not listed. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields and values (`veth`/`device`, netlink state names) are the same as with Docker. `eth0` and `lo` cannot be captured on c9s.\n\n\n/source/head/docs/cmd/events.md:\n  Line 5: The `events` command streams lifecycle updates for every Containerlab resource and augments them with interface change notifications collected from the container network namespaces. The output combines the selected runtime's event feed (for example Docker) with the netlink information that powers `containerlab inspect interfaces`, so you can observe container activity and interface state changes in real time without selecting a specific lab.\n\n  Line 31: - **Interface events** use type `interface` and `origin=netlink` in the attribute list. They also report interface-specific data such as `ifname`, `state`, `mtu`, `mac`, `type`, `alias`, and the lab label. The actor is still the container short ID, and the container name is supplied in the attributes (`name=...`).\n\n  Line 43: 2024-07-01T11:02:57.004321000Z interface create 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n\n  Line 44: 2024-07-01T11:02:57.104512000Z interface update 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=9000, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n\n  Line 46: 2024-07-01T11:05:13.018456000Z interface delete 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n\n  Line 56: 2024-07-01T11:02:55.912678000Z interface snapshot 5d0b5a9ad3f1 (ifname=eth0, index=22, lab=frr-lab, mac=02:42:ac:14:00:02, mtu=1500, name=clab-frr-lab-frr01, origin=netlink, state=up, type=veth)\n\n  Line 83: labels, and the interface events (`snapshot`, `create`, `update`, `delete`,\n\n  Line 86: inside the device containers, not through local host netlink. The stream covers\n\n  Line 97: - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n\n\n/source/head/docs/macos.md:\n  Line 30: 3. **Linux on macOS?** It is not only Docker that containerlab is based on. We leverage some Linux kernel APIs (like netlink) either directly or via Docker to be available to setup links, namespaces, bind-mounts, etc.  \n",
    "title": "interface.*event|netlink|ifname",
    "metadata": {
      "matches": 26,
      "truncated": false
    },
    "time": {
      "start": 1794565328961,
      "end": 1794565328983
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46dd077001dVCdy3vw9kOsNh",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dc1f9001riiYyI5T8B4p4l",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 70212,
    "input": 743,
    "output": 40,
    "reasoning": 53,
    "cache": {
      "read": 69376,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46dc1f9001riiYyI5T8B4p4l",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565325305,
    "completed": 1794565329023
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 70212,
    "input": 743,
    "output": 40,
    "reasoning": 53,
    "cache": {
      "read": 69376,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 10
step-start
{
  "type": "step-start",
  "id": "prt_1d46ddce2001h64LgQMy81GERg",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dd0850019pu9eWPwYXBzD3"
}
Reasoning
Docs: The events doc says interface notifications are emitted when a link "appears, disappears, or when its relevant properties change". The new behavior adds: an interface can be reported under the host-side stitch interface name (ifname=clab-s-xxx) — previously, `overlayToolsInterface` already rewrote ifname for existing events, so events already reported stitch names when the stitch interface existed. The new behavior adds: on rename, delete(old)+create(new) instead of a plain update. And the new polling path means a link may appear first under the node name and then be re-reported as delete+create under the stitch name. Docs don't mention this; but they also never documented the ifname rewrite. This is a user-visible behavior change (event consumers e.g. VS Code extension may see delete+create for the same logical interface). Worth a P3/P4 doc note? The events doc line 32 describes when notifications are emitted. The new delete+create sequence for the same underlying link is a behavior consumers may need to handle. I'd flag a P4 documentation gap: docs/cmd/events.md (and possibly release notes) not updated to mention that an interface reported under its node-side name can be re-reported as delete+create when the host-side stitch interface is marked.

Now check for correctness issues more carefully.

Issue candidate 1: `emit` delete path computes `interfaceAttributes` before checking `w.reported` — when previous exists, computed attributes discarded. interfaceAttributes → overlayToolsInterface → clablinks.ToolsInterface → netlink.LinkByName (root netns syscall). So every delete of a tracked link does a wasted netlink lookup. Also for non-stitched labs, TopoIdentity returns empty → early return, cheap. For stitched labs, an extra syscall per delete event. Minor; P4.

Wait actually, is it wasted? `attributes := interfaceAttributes(...)` then `if previous, ok := ...; ok { attributes = previous.attributes }`. Yes, discarded. Could reorder: check reported first, only compute attributes if not known. P4 perf.

Issue candidate 2: `reportStitchMarks` scan cost: for each tick (default 1s), iterates all states; for each veth reported under own name within window, calls interfaceAttributes → LinkByName. Bounded by window (1 min) and number of veths. This is the designed mechanism. Fine — deliberate ceiling; the comment explains it. No ponytail: marker but there's a rationale comment. Per ponytail rule, "Mark deliberate simplifications that cut a real corner with a known ceiling ... with a ponytail: comment naming the ceiling and upgrade path." The window is a deliberate ceiling. Hmm, the comment does name the ceiling ("how long after a link is first reported its host-side stitch interface is looked for"). I think that satisfies the spirit. I won't flag.

Issue candidate 3: The `since` never-refresh problem: `since` = first report time of that index; if the lab takes >1 minute between creating the node-side veth and marking the stitch, the rename is missed and the interface remains reported under the node name indefinitely (until the link itself changes or resubscribe). Also `since` is preserved across resubscribes and across link updates — actually since is preserved when known. So e.g. a big Clos lab where a node's interface is created at t=0, marked at t=90s → never reported with stitch name. Then when the node's link later changes (e.g. state up), emit → track → rename detected (if stitch now exists) → delete+create. So the missed window is only permanent if the link never changes again and no resubscribe. For a veth that just sits there, that's plausible: interface reported as `eth1` instead of `clab-s-xxxx` forever.

Hmm wait, actually also consider: `reportStitchMarks` runs on netem ticker ticks — the ticker exists regardless of stats being enabled. Default 1s. OK.

But there's another subtle problem with the window: `since` is when the link was FIRST reported — for links that existed before the watcher started (includeSnapshot=true, snapshot events), since = subscription start. For long-running labs redeploying one link: the existing link was snapshotted at watcher start (t0). Redeploy of that link later: link deleted & recreated? Actually redeploy destroys the container → watcher stopped, new watcher. Hmm.

Scenario: container started at t0, watcher reports snapshot. At t0+5min, user creates a veth-stitch link attached to this container's existing interface? Not how it works — links are created during deploy before the node starts, so the stitch mark happens during deploy, right after container start typically. So the 1-minute window covers normal deploy. Slow deploys (large labs, slow image pulls) could exceed it. Is the mark done after container start? Deploy creates veth segments: node end in node netns — requires the netns to exist, i.e., container started. So the mark happens around container start; watcher starts on container start event. Time between watcher seeing the link and the mark is small (same deploy loop). So the window is mostly fine; but if the watcher subscribes late (ns path retries ~1s each, up to...), or system load... Edge case. Also note: the reported map entry survives from the FIRST report — for a link present before the watcher started (restarted container? No—new watcher). Actually when a container restarts, the watcher is stopped and restarted fresh, so reported is fresh; the links exist at subscription → snapshot events → since = subscription time. Stitch marks already exist at that point (from the original deploy) → reportStitchMarks: reported.attributes["ifname"] — wait, at snapshot emit, interfaceAttributes resolves the stitch (it exists already) → ifname = stitch name ≠ snapshot.Name → reportStitchMarks skips. Good.

Hmm wait, one more: does `reportStitchMarks` need to run even when the rename already happened? No.

Issue candidate 4: In `reportStitchMarks`, the emitted update triggers track which sends "delete" of old name. But what if the old name was never actually reported to clients? The `reported` map is populated by `track` on every emit — including events sent to the channel. So previous.attributes was actually sent. OK consistent.

Issue candidate 5: `w.reported` nil-map handling: `track` lazily creates the map. `reportStitchMarks` reads `w.reported[idx]` on a nil map — reading a nil map is fine (returns zero). OK.

Issue candidate 6: Concurrency — all calls on w.reported happen from the watcher goroutine (run → watch). Verified: emit, emitStats, reportStitchMarks, track all called from within watch/collectAndEmitStats which run in the watcher goroutine. Tests call them directly. No race. Good.

Issue candidate 7: `emitStats` when track returns true (rename) sends "create" with metrics.Timestamp then "stats". But it does NOT send a "delete" of the old name? It does — inside track. OK.

But notice: in emitStats, the create event uses `maps.Clone(attributes)` and the stats event mutates and sends `attributes`. But the stored `w.reported` clone (from track) — the stats event's attributes map is a different map (the one from interfaceAttributes) than the stored clone. Fine.

Issue candidate 8: Ordering anomaly in `watch`: on the netemTicker tick, `pollNetemChanges` then `reportStitchMarks`. Fine.

Issue candidate 9: `reportStitchMarks` condition uses `interfaceAttributes(w.container, snapshot)["ifname"] != snapshot.Name`. But `interfaceAttributes` includes netem attrs etc. — fine. One subtlety: `overlayToolsInterface` sets ifname from stitch link snapshot.Name. If the stitch link's actual name equals... the stitch far-end name is "clab-s-XXXXXXXX" (the host veth name) while the altname is "clab-stitch-...". `ToolsInterface` looks up by altname `StitchAltName(...)`, then `snapshotFromLink(tools)` — attrs.Name of a link looked up by altname: netlink.LinkByName with an altname returns the link; what is attrs.Name? The link's primary name ("clab-s-...")? Hmm — actually netlink returns the link with its primary ifname; altnames come in the altname list attribute. `netlink.LinkByName` does handle altnames (kernel supports IFLA_ALT_IFNAME lookup; the vishvananda lib sends the name and kernel matches altname too). The returned link's Attrs().Name would be the primary name "clab-s-0011aabb". Wait but does the lib parse altnames into Attrs().AltNames? Newer versions do (ILFA_PROP_LIST). Anyway, attrs.Name = primary name. The test uses `"ifname": "clab-s-0011aabb"` consistent with primary name. So events report ifname=clab-s-0011aabb. And `overlayToolsInterface` sets attributes["alias"] = topoName (the node's iface name/alias). So the event carries alias=eth1, ifname=clab-s-0011aabb. Consistent with pre-existing behavior (`inspect interfaces` matching). OK.

Issue candidate 10: Missing handling — `processExisting` on resubscribe when a link's stitch got marked while unsubscribed: snapshot.equal(previous) → no emit; and `states` unchanged. `reportStitchMarks` will pick it up only if within the window (since first report). If subscription was down long, missed. Same ceiling as candidate 3. Combine into one finding: the 1-minute window measured from first report can miss stitch marks in slow deploys or after subscription outages; suggest refreshing `since` per report or noting the ceiling. Severity: P3? It's a real correctness gap in the heuristic for large labs (deploy of a 50-node lab can exceed 1 minute easily — but the window is per-interface measured from when the watcher first reported THAT interface, which is around the container start, and the mark happens shortly after container start within the same deploy). Hmm, when is the node-end veth created vs when is the mark applied? Deploy creates the veth segment (node end + host far end) — the host far end is created at the same time (a veth has both ends created together!). Wait: buildVEthStitchSegment creates a LinkVEth with nodeEp and farEp (host endpoint). So the veth pair is created in one operation: node end in node netns, far end in root ns. Then markFarEnd adds the altname to the far end. In Deploy: seg.Deploy creates the veth; PostDeploy/stitchSegments marks. Between link creation and altname marking: segA.Deploy, segB.Deploy, then markFarEnd steps. So the gap is milliseconds to seconds. The watcher sees the node-end RTM_NEWLINK (create event) and within ~1s the netem ticker runs reportStitchMarks → finds the mark. So normal flow is fast.

When could it exceed 1 min? If the node's interface is created but the stitch's mark is delayed >1min — e.g., deploy of two endpoints in different containers where segB's container is slow to start: segA.Deploy (creates nodeA's veth + far end) at t0; watcher for nodeA reports it; segB container starts at t0+120s; then stitchSegments → markFarEnd at t0+120s → the altname added >1min after nodeA's link was first reported → missed! Then nodeA's interface remains reported as `eth1` instead of `clab-s-xxx` permanently (until the link changes). This is a realistic scenario: large labs where one node takes a long time to pull/start while the other endpoint is already up. Also note `PostDeploy` is where stitching happens when not both deployed in Deploy — i.e., the second node's deploy triggers the stitch. So the window measured from the FIRST endpoint's link creation covers the whole time until the second node is deployed. Slow pulls can exceed a minute easily.

Hmm, but wait — when the second node deploys and stitches, does nodeA's interface see any netlink change? markFarEnd only adds an altname to the HOST far end (in root ns), not in nodeA's netns. `stitch` — let me check what stitch does (tc mirror/redirect). It applies tc rules on host-side interfaces. So no nodeA-netns event. So indeed the rename event for nodeA would be missed if >1min gap. And then the reported name stays "eth1" — the client (VS Code extension / events consumer) sees the wrong interface name for that link. Impact: incorrect/stale reporting for veth-stitch links in slow deploys; self-corrects only on later node-side link change or resubscribe. That's a genuine P3 (correctness/reliability, bounded impact, heuristic by design).

Also the `since` is "when the link was first reported" — one could refresh `since` on every track (each emit/update), which would widen coverage: after the second endpoint deploys, are there updates on nodeA's interface? Probably not. So refreshing wouldn't help in that scenario either; the real fix would be a longer window or event-based detection (netlink monitor in root ns for altname addition isn't possible — altname changes do generate RTM_NEWLINK notifications in the root namespace! Actually LinkAddAltName triggers a NEWLINK notification in root ns. But the watcher subscribes in the node's netns, not root. Could the registry watch root-ns altname additions? That'd be more code.) The simplest correction: make the window more generous or document the ceiling with a `ponytail:` comment. I'll flag P3 with concrete trigger.

Actually, let me reconsider severity: the impact is an events-stream consumer seeing the node-side name for a stitched link (the pre-PR behavior, actually — before this PR, the interface was ALWAYS reported under the node name unless the link changed after marking). So the PR improves things; the window is a residual gap. P3/P4. I'd say P4 optional improvement? It's a correctness limitation of a new heuristic — but the PR is strictly improving reporting. The residual gap: slow deploys. I'd rate P4 (optional improvement, name the ceiling per ponytail). Hmm, but the rule says mark with a ponytail comment. The finding could be: "Stitch-mark window can miss renames in slow deploys; add ponytail ceiling comment or refresh." P4.

Issue candidate 11: Test `TestReportStitchMarksLeavesUnmarkedLinks` — "reported too long ago, are not reported again" — good. But no positive test for reportStitchMarks (a link whose stitch exists gets delete+create). The emit rename path is tested. Gap: reportStitchMarks's positive path (the new polling logic) is untested. Also `emitStats` non-rename path (normal stats emission) — was previously covered by other tests? Base had no direct stats test either it seems. Coverage note.

Issue candidate 12: `TestEmitStatsReportsRenamedLinkFirst` mutates `watcher.reported[7].attributes` check — fine.

Issue candidate 13: Docs: `docs/cmd/events.md` line 32 says "Interface notifications are emitted when a link appears, disappears, or when its relevant properties ... change." The new behavior: a link can be re-reported (delete+create) without any property of the node-side link changing — when its host-side stitch interface gets marked. Docs don't mention this. Also the `ifname` may change from the node name to the stitch name mid-stream. P4 doc gap. Actually is it user-visible behavior introduced by this PR? Yes — previously (base), an interface was only reported with the stitch ifname when the link itself changed after marking (overlayToolsInterface applied on each emit). The PR adds proactive rename reporting (delete+create). Consumers following the doc's model (create/update/delete keyed by ifname) will see delete+create pairs for the same interface. A doc note would help. P4.

Issue candidate 14: The delete-then-create naming: when track detects rename, it sends `delete` with `previous.attributes` — which includes the OLD attributes fully (ifname=old, alias, index, mtu...). Good.

Issue candidate 15: Now — a potential real bug: in `emit`, for action "update" where track returns false (same name), the event is sent as "update". But consider the case where the link was reported under the same ifname but the STITCH now exists with different attributes... can't happen: if stitch exists, ifname differs from node name → rename path.

Consider the reverse: stitch existed (reported as clab-s-x), then the stitch altname is REMOVED (link destroyed) — next emit (e.g., node-side update) resolves ifname back to node name → rename detected → delete(clab-s-x) + create(eth1). Good, handled.

But: when the whole veth-stitch link is destroyed, both node end and host far end are deleted. Node-ns watcher sees RTM_DELLINK → processUpdate: exists → emit delete with previous.attributes (stitch name). Good — matches TestEmitDeletesLinkAsLastReported.

Issue candidate 16: `reportStitchMarks` — what if `w.container` is nil? Guarded in emit; interfaceAttributes(w.container, snapshot) with nil container → containerLabel(nil) → "", firstContainerName(nil) → "", overlayToolsInterface(nil) → return early. So attributes["ifname"] == snapshot.Name → no emit. Safe.

Issue candidate 17: `interfaceAttributes` is called twice for the same snapshot in reportStitchMarks → emit path: reportStitchMarks calls interfaceAttributes (1), then emit calls interfaceAttributes again (2). Two LinkByName lookups per marked link. Minor.

Issue candidate 18: A real correctness question about `track` + `emit` action semantics: `processExisting` on resubscribe emits "update" for changed links and "create" for new. If a link reported before resubscribe under stitch name, and now reported under node name (e.g., stitch altname removed while down) → rename → delete+create. fine.

What about `processExisting` first subscription with includeSnapshot=true: emits "snapshot". track populates reported. If the snapshot event resolves to stitch name, reported = stitch attrs. fine.

Issue candidate 19: In `emit`, when action is "create" and track detects rename (returns true), action stays "create" — so sequence delete(old), create(new). Good.

When action is "snapshot" and track returns true — impossible as discussed (fresh watcher). Except... hmm, is `emit` ever called with "snapshot" when reported is non-nil? `initial` is only true on the first watch call; reported is empty then. OK.

Issue candidate 20: A subtle one — `emit`'s delete path when `previous` does NOT exist: attributes freshly computed (with stitch if stitched). Fine.

Issue candidate 21: `interfaceAttributes` in the delete path of emit: if previous exists, the computed attributes are discarded — but wait, there's a cost concern already noted. Also in the delete path, if the link was never reported but the stitch exists, delete event reports ifname = stitch name — client never saw it. Pre-existing-ish (base: delete for a state-tracked but never-reported link — with stitch, ifname rewritten). OK.

Issue candidate 22: Now check `TestEmitReportsRenamedLinkDeleted` expectations: first emit "update": track → previous ifname "clab-s-0011aabb" ≠ "e1-1" → send delete(clab-s-0011aabb), store new, return true → action "update"→"create" → send create(e1-1). Second emit "update": track → same name → return false → send update(e1-1). Want: [delete clab-s, create e1-1, update e1-1]. Matches.

But note: `registry.sendInterfaceEvent(w.container, "delete", previous.attributes, time.Now())` inside track — `previous.attributes` is the stored clone. Sent to channel. Consumers get a reference to... the map is shared with w.reported until deleted — the map is only referenced by w.reported[index].attributes and now the event. After track replaces w.reported[index] with a NEW clone, no aliasing. OK.

Issue candidate 23: Now — check the events flow consumer side: aggregatedEvent attributes map is passed to consumers. Since we send stored clones and interfaceAttributes-fresh maps, no shared mutable state issues.

Issue candidate 24: What about `w.reported` growing unboundedly? Entries are deleted on emit("delete"). Links deleted while subscription down: removeVanishedLinks → emit delete → cleaned. But: a link that was in `states` but never reported (includeSnapshot=false first subscription) then deleted → removeVanishedLinks emits delete with fresh attributes — reported has no entry → nothing to delete; fine. And processUpdate RTM_DELLINK requires exists in states. States and reported can drift: a link in states but not reported (snapshot-suppressed). When that link is later updated → emit "update" → track adds to reported. So reported ⊆ states roughly, and delete paths clean both. Bounded by number of interfaces. Fine.

Hmm wait, actually there's an asymmetry bug candidate: In `removeVanishedLinks` and `processUpdate` RTM_DELLINK, states entry deleted, emit(delete) → reported entry deleted. But what about the reverse: reported entry exists without states entry? Could happen? track is only called via emit which is called with snapshots that are in states (processExisting/processUpdate/pollNetemChanges all set states before/around emit) — except `reportStitchMarks` iterates states. emitStats is called for state in states. So reported tracks states. When states entry deleted, emit delete cleans reported. Consistent.

Hmm — one more: `processUpdate` RTM_NEWLINK for a link not in states but... emits create → track adds. Fine.

Issue candidate 25: Check `emitStats` guard order: `!registry.includeStats` — registry.includeStats is set from the registry's global includeStats; watcher also has includeStats. Pre-existing pattern (emitInterfaceStatsEvent used r.includeStats). Same.

Issue candidate 26: `run()` resubscribe: `states` persists; `reported` persists. Good.

Issue candidate 27: The netem ticker runs `reportStitchMarks` every second even when there are no veth links — iterating states map each tick: O(#interfaces) per second per container, cheap (map iteration). For a container with many interfaces (say 100), 100 map reads/sec — trivial. But `interfaceAttributes` (with LinkByName syscall) only for candidates. OK.

Issue candidate 28: One more possible issue: `reportStitchMarks` calls `interfaceAttributes` which includes `overlayToolsInterface` — this does a `netlink.LinkByName` in the ROOT namespace. But the watcher goroutine — does it need to be in any particular netns for that call? `netlink.LinkByName` without a handle uses the current thread's netns. The watcher... does `watch` change the thread's netns? It uses `netlink.NewHandleAt(nsHandle)` — handle-based calls specify the netns. But `ToolsInterface` calls the package-level `netlink.LinkByName`, which operates on the current process/thread netns (root, since containerlab CLI runs in root ns). Does anything put the watcher goroutine's thread into the container netns? `netns.GetFromPath` just opens an fd. `netlink.LinkSubscribeWithOptions` with Namespace option — internally it does `netns.Set`? Let me check: vishvananda/netlink's subscribe with Namespace: it uses `EnterNetNS`? Actually `LinkSubscribeWithOptions` with `opts.Namespace` calls `ns.Open()`... I recall it does `netns.Set(ns)` on a locked OS thread within the internal socket goroutine, not the caller. Hmm, actually in netlink lib, `LinkSubscribeWithOptions` → `LinkSubscribeAt` with `EnterNetNS`? There's a `socketInNetns` helper: if Namespace is set, it locks the OS thread and sets the netns to create the socket, then restores. The socket goroutine is internal. The caller's thread netns unchanged.

So `netlink.LinkByName` (root ns) in reportStitchMarks and interfaceAttributes runs against the root namespace — that's intended (the stitch interface lives in root ns). Pre-existing behavior for overlayToolsInterface. OK.

But wait — a pre-existing subtlety: base's emitInterfaceEvent also called interfaceAttributes (with overlayToolsInterface) from the watcher goroutine. Same. OK.

Issue candidate 29: In `reportStitchMarks`, `snapshot.Name` — states entries may have stale names? states updated on events. Fine.

Now let me double-check the diff hunk in `watch`: `case <-netemTicker.C: w.pollNetemChanges(...); w.reportStitchMarks(states, registry)`. Fine.

Let me also check the release notes — is there a release-note requirement? There's a `.cursor/rules/release-note-review.mdc` file. Let me read it; it may require adding release notes for user-visible changes. The PR adds user-visible behavior (events stream changes). Let me check docs/rn — is there an "unreleased" or current-version rn file that should mention this? docs/rn/0.83.md exists. Let me check release-note-review.mdc and whether docs/rn has a dev/unreleased section.
read · completed

Input

{
  "filePath": "/source/head/.cursor/rules/release-note-review.mdc"
}

Output

<path>/source/head/.cursor/rules/release-note-review.mdc</path>
<type>file</type>
<content>
1: ---
2: description: Verify release-note mutability when reviewing PR documentation
3: alwaysApply: true
4: ---
5: 
6: # Release-note review
7: 
8: When reviewing a PR, inspect any changes under `docs/rn/`:
9: 
10: - Verify the target release is still unreleased before treating the change as valid.
11: - Treat release notes for published releases as immutable; flag edits or additions there.
12: - Recommend moving new content to the next unreleased release note or the appropriate evergreen documentation.

(End of file - total 12 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f09fc001xz3ON4QjpiT0vl",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dd0850019pu9eWPwYXBzD3",
  "callID": "call_ba561656a480471eb71440da",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/.cursor/rules/release-note-review.mdc"
    },
    "output": "<path>/source/head/.cursor/rules/release-note-review.mdc</path>\n<type>file</type>\n<content>\n1: ---\n2: description: Verify release-note mutability when reviewing PR documentation\n3: alwaysApply: true\n4: ---\n5: \n6: # Release-note review\n7: \n8: When reviewing a PR, inspect any changes under `docs/rn/`:\n9: \n10: - Verify the target release is still unreleased before treating the change as valid.\n11: - Treat release notes for published releases as immutable; flag edits or additions there.\n12: - Recommend moving new content to the next unreleased release note or the appropriate evergreen documentation.\n\n(End of file - total 12 lines)\n</content>",
    "title": "source/head/.cursor/rules/release-note-review.mdc",
    "metadata": {
      "preview": "---\ndescription: Verify release-note mutability when reviewing PR documentation\nalwaysApply: true\n---\n\n# Release-note review\n\nWhen reviewing a PR, inspect any changes under `docs/rn/`:\n\n- Verify the target release is still unreleased before treating the change as valid.\n- Treat release notes for published releases as immutable; flag edits or additions there.\n- Recommend moving new content to the next unreleased release note or the appropriate evergreen documentation.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/.cursor/rules/release-note-review.mdc",
        "text": "---\ndescription: Verify release-note mutability when reviewing PR documentation\nalwaysApply: true\n---\n\n# Release-note review\n\nWhen reviewing a PR, inspect any changes under `docs/rn/`:\n\n- Verify the target release is still unreleased before treating the change as valid.\n- Treat release notes for published releases as immutable; flag edits or additions there.\n- Recommend moving new content to the next unreleased release note or the appropriate evergreen documentation.",
        "lineStart": 1,
        "lineEnd": 12,
        "totalLines": 12,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565409282,
      "end": 1794565409291
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/docs/rn",
  "pattern": "unreleased|dev|next"
}

Output

Found 52 matches
/source/head/docs/rn/0.68.md:
  Line 13: The docs are available in the github repo and later on we will merge them in to the Containerlab.dev website as well. For now, we wanted to make sure you give it a go if you have a use case for it and provide your feedback with us. There is a [postman-like collection](https://github.com/srl-labs/clab-api-server?tab=readme-ov-file#-flashpost-collection) for you to have a quick look whats possible and how to use the API.

  Line 39: * container health will be shown in the inspect output next to the state #2539


/source/head/docs/rn/0.67.md:
  Line 15: Thanks to @danlindow, Containerlab will now [generate Nornir' Simple Inventory](../manual/inventory.md#nornir) right next to the Ansible inventory. This opens up a door to your reusing your existing automation stacks built with Nornir.


/source/head/docs/rn/0.46.md:
  Line 79: curl -sL srlinux.dev/clab-srl | clab dep -c -t -

  Line 85: curl -sL srlinux.dev/clab-srl | \


/source/head/docs/rn/0.74.md:
  Line 64: - Disabled TX offload on IOL node management interface, fixing SSH connectivity from other devices on the bridge. Thanks @bendergm #3077


/source/head/docs/rn/0.11.0.md:
  Line 26: The versatility of containerlab is in its ability to run anywhere where linux runs and wire up anything that can be packaged in a docker container. But it is quite hard to package in a container a piece of a real hardware. Still, we need it more often than not to connect devices like traffic generators or physical chassis to containerlab labs.


/source/head/docs/rn/0.13.0.md:
  Line 13: 1. Arista Ma0 MAC address is now having Arista OUI, instead of docker generated local MAC. Additionally, [System MAC address is now generated](https://github.com/srl-labs/containerlab/pull/362) as the next MAC address from Ma0 interface.


/source/head/docs/rn/0.77.md:
  Line 64: The documentation toolchain moved to Zensical while keeping the existing `mkdocs.yml` configuration. Local docs development still starts with `make serve-docs`, and the home page, tags, navigation, and several example pages were refreshed to match the new engine.


/source/head/docs/rn/0.64.md:
  Line 24: │                │ lo        │ N/A     │                   │     1 │ 65536 │ device │ unknown │

  Line 39: The devcontainer has been massaged to allow for [sudo-less](../install.md#sudo-less-operation) lab deployment introduced in 0.63.3.

  Line 41: We have also added the [vscode-containerlab](https://github.com/srl-labs/vscode-containerlab) extension to it, so that you get the most out of your vscode experience when using the devcontainer.


/source/head/docs/rn/0.71.md:
  Line 19: Or `CLAB_TOPO=srlinux.dev/clab-srl clab dep -c` to deploy a lab with the topology passed via environment variable.


/source/head/docs/rn/0.57.md:
  Line 18:     curl -sL https://containerlab.dev/setup | sudo -E bash -s "setup-bash-prompt"

  Line 51: - set docker version to 26.1.4 in the devcontainer and quick setup scripts. This removes the drift when new docker version introduce breaking changes #2207


/source/head/docs/rn/0.82.md:
  Line 7: Containerlab can now run MikroTik RouterOS CHR from the [official `mikrotik/chr` image](https://hub.docker.com/r/mikrotik/chr) with the [new `mikrotik_chr` kind](../manual/kinds/mikrotik_chr.md). The image is used as is - no [vrnetlab](../manual/vrnetlab.md) build - and is published for `amd64` and `arm64`, booting with KVM when `/dev/kvm` is available and falling back to QEMU's TCG emulation otherwise:

  Line 38: The model-driven startup template is split by SR OS release. Releases up to 26.3 keep the CCM8 TLS cipher their TLS bootstrap relies on, while SR OS 26.7, later releases and development images - which report version `0.0.0` - use a template without it. The obsolete `system grpc md-cli` and `md-cli-session` lines are emitted only for releases up to 25.10. The classic SR, IXR and SAR templates follow the same CCM8 cutoff.


/source/head/docs/rn/0.79.md:
  Line 79: The new [`flake.nix`](https://github.com/srl-labs/containerlab/blob/main/flake.nix) provides reproducible containerlab packages for `x86_64-linux` and `aarch64-linux`, a NixOS module, and a development shell with Go, `gopls`, and `golangci-lint`.


/source/head/docs/rn/0.76.md:
  Line 9: > While NVIDIA does not distribute the Cumulus VX image anymore through their developer's portal, the sneaky petes always find a way to get their hands on a qcow2.


/source/head/docs/rn/0.70.md:
  Line 7: A big shout-out to @carlmontanari for picking up the fallen flag and working on the Containerlab Go API by decoupling the core logic from the CLI implementation. There is still some work to be done, but already now if you want to leverage Containerlab programmatically as a Go package, you should be able to do so. Check the https://pkg.go.dev/github.com/srl-labs/containerlab for the documentation and see how our CLI uses the options and passes them to the core functions to parametrize and run labs.


/source/head/docs/rn/0.48.md:
  Line 42: * Improvements to the devcontainer documentation #1689


/source/head/docs/rn/0.39.md:
  Line 26:                     next-hop "192.168.0.1" {


/source/head/docs/rn/0.83.md:
  Line 59: Persistent node volumes now survive a plain `destroy`, just as a local lab directory does. A subsequent deploy adopts the retained PersistentVolumeClaims and boots from the saved device state. `destroy --cleanup` removes the claims and managed namespace, while `deploy --reconfigure` and `redeploy --cleanup` also start from clean storage.

  Line 75: The new [`logs`](../cmd/logs.md) command displays or follows a node's log with Docker, Podman and c9s. With c9s it reads the log of the node's primary device container:


/source/head/docs/rn/0.26.md:
  Line 23: : Get started: https://learn.srlinux.dev                       :

  Line 24: : Container:   https://go.srlinux.dev/container-image          :

  Line 25: : Docs:        https://doc.srlinux.dev/21-11                   :

  Line 26: : Rel. notes:  https://doc.srlinux.dev/rn21-11-2               :

  Line 27: : YANG:        https://yang.srlinux.dev/v21.11.2               :

  Line 28: : Discord:     https://go.srlinux.dev/discord                  :

  Line 29: : Contact:     https://go.srlinux.dev/contact-sales            :

  Line 69: * next-ui-based graph works better with long image names in tooltips #834


/source/head/docs/rn/0.60.md:
  Line 87: The devcontainer integration is a way to start a lab on a laptop, desktop, server or VM without installing anything on the host besides Docker. If you rememeber how easy it was to start a lab in Codespaces, you will be happy to get the same UX now with your local compute.

  Line 91: * [for macOS](../macos.md#devcontainer)

  Line 92: * [and Windows](../windows.md#devcontainer)

  Line 100: DevPod takes the devcontainer experience and adds better UX on top of it :wink:

  Line 102: An open-source project by Loft Labs, DevPod makes it possible to use the same devcontainer specification and create a "workspace" that uses almost any IDE known to men and deploys it on a wide range of providers.


/source/head/docs/rn/0.49.md:
  Line 30: * ixia-c example lab has been updated by @bortok to feature latest developments done for the ixia-c kind #1795


/source/head/docs/rn/0.12.0.md:
  Line 38: We also [added a lab](https://clabs.netdevops.me/security/gnmitls/) that pictures the net positive effect of having those commands when creating TLS certificates for secured gNMI connectivity.

  Line 56: When a new release comes out we let you know next time you deploy a lab, a tiny message will pop up in the log saying that a new one is ready to make your labs even more efficient and easy.

  Line 59: INFO[0001] 🎉 New containerlab version 0.12.0 is available! Release notes: https://containerlab.dev/rn/0.12.0

  Line 60: Run 'containerlab version upgrade' to upgrade or go check other installation options at https://containerlab.dev/install/ 


/source/head/docs/rn/0.55.md:
  Line 12: curl -L http://containerlab.dev/setup \

  Line 29: curl -L http://containerlab.dev/setup \

  Line 37: curl -L http://containerlab.dev/setup \


/source/head/docs/rn/0.80.md:
  Line 78: The management (again!) network can join a Tailscale tailnet. In sidecar mode every node gets a tailscale sidecar container and appears as a device in your tailnet, authenticated with a reusable auth-key:

  Line 87: In proxy mode the whole lab appears as a single device in the tailnet, authenticated via SSO. Individual nodes are exposed by forwarding ports with the `/ts` port suffix, e.g. `8022:22/ts` maps port 8022 of the lab device to SSH of that node.


/source/head/docs/rn/0.25.md:
  Line 31: * containerlab site moved to containerlab.dev domain


/source/head/docs/rn/0.69.md:
  Line 117: * fix devcontainer build #2746


/source/head/docs/rn/0.53.md:
  Line 20: This feature is in the "preview" status, we will likely change the command structure in the next release.


/source/head/docs/rn/0.75.md:
  Line 20: - Place additional `*.gotmpl` files in a `clab_templates` directory next to the main template; they are loaded and invokable with Go's `{{ template "name.gotmpl" . }}` from the top-level file.

  Line 65: Thanks @Rucdev #3167
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f0ac10018ScBN00l1itaOQ",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dd0850019pu9eWPwYXBzD3",
  "callID": "call_0900ba29df7241978bc1b04a",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/docs/rn",
      "pattern": "unreleased|dev|next"
    },
    "output": "Found 52 matches\n/source/head/docs/rn/0.68.md:\n  Line 13: The docs are available in the github repo and later on we will merge them in to the Containerlab.dev website as well. For now, we wanted to make sure you give it a go if you have a use case for it and provide your feedback with us. There is a [postman-like collection](https://github.com/srl-labs/clab-api-server?tab=readme-ov-file#-flashpost-collection) for you to have a quick look whats possible and how to use the API.\n\n  Line 39: * container health will be shown in the inspect output next to the state #2539\n\n\n/source/head/docs/rn/0.67.md:\n  Line 15: Thanks to @danlindow, Containerlab will now [generate Nornir' Simple Inventory](../manual/inventory.md#nornir) right next to the Ansible inventory. This opens up a door to your reusing your existing automation stacks built with Nornir.\n\n\n/source/head/docs/rn/0.46.md:\n  Line 79: curl -sL srlinux.dev/clab-srl | clab dep -c -t -\n\n  Line 85: curl -sL srlinux.dev/clab-srl | \\\n\n\n/source/head/docs/rn/0.74.md:\n  Line 64: - Disabled TX offload on IOL node management interface, fixing SSH connectivity from other devices on the bridge. Thanks @bendergm #3077\n\n\n/source/head/docs/rn/0.11.0.md:\n  Line 26: The versatility of containerlab is in its ability to run anywhere where linux runs and wire up anything that can be packaged in a docker container. But it is quite hard to package in a container a piece of a real hardware. Still, we need it more often than not to connect devices like traffic generators or physical chassis to containerlab labs.\n\n\n/source/head/docs/rn/0.13.0.md:\n  Line 13: 1. Arista Ma0 MAC address is now having Arista OUI, instead of docker generated local MAC. Additionally, [System MAC address is now generated](https://github.com/srl-labs/containerlab/pull/362) as the next MAC address from Ma0 interface.\n\n\n/source/head/docs/rn/0.77.md:\n  Line 64: The documentation toolchain moved to Zensical while keeping the existing `mkdocs.yml` configuration. Local docs development still starts with `make serve-docs`, and the home page, tags, navigation, and several example pages were refreshed to match the new engine.\n\n\n/source/head/docs/rn/0.64.md:\n  Line 24: │                │ lo        │ N/A     │                   │     1 │ 65536 │ device │ unknown │\n\n  Line 39: The devcontainer has been massaged to allow for [sudo-less](../install.md#sudo-less-operation) lab deployment introduced in 0.63.3.\n\n  Line 41: We have also added the [vscode-containerlab](https://github.com/srl-labs/vscode-containerlab) extension to it, so that you get the most out of your vscode experience when using the devcontainer.\n\n\n/source/head/docs/rn/0.71.md:\n  Line 19: Or `CLAB_TOPO=srlinux.dev/clab-srl clab dep -c` to deploy a lab with the topology passed via environment variable.\n\n\n/source/head/docs/rn/0.57.md:\n  Line 18:     curl -sL https://containerlab.dev/setup | sudo -E bash -s \"setup-bash-prompt\"\n\n  Line 51: - set docker version to 26.1.4 in the devcontainer and quick setup scripts. This removes the drift when new docker version introduce breaking changes #2207\n\n\n/source/head/docs/rn/0.82.md:\n  Line 7: Containerlab can now run MikroTik RouterOS CHR from the [official `mikrotik/chr` image](https://hub.docker.com/r/mikrotik/chr) with the [new `mikrotik_chr` kind](../manual/kinds/mikrotik_chr.md). The image is used as is - no [vrnetlab](../manual/vrnetlab.md) build - and is published for `amd64` and `arm64`, booting with KVM when `/dev/kvm` is available and falling back to QEMU's TCG emulation otherwise:\n\n  Line 38: The model-driven startup template is split by SR OS release. Releases up to 26.3 keep the CCM8 TLS cipher their TLS bootstrap relies on, while SR OS 26.7, later releases and development images - which report version `0.0.0` - use a template without it. The obsolete `system grpc md-cli` and `md-cli-session` lines are emitted only for releases up to 25.10. The classic SR, IXR and SAR templates follow the same CCM8 cutoff.\n\n\n/source/head/docs/rn/0.79.md:\n  Line 79: The new [`flake.nix`](https://github.com/srl-labs/containerlab/blob/main/flake.nix) provides reproducible containerlab packages for `x86_64-linux` and `aarch64-linux`, a NixOS module, and a development shell with Go, `gopls`, and `golangci-lint`.\n\n\n/source/head/docs/rn/0.76.md:\n  Line 9: > While NVIDIA does not distribute the Cumulus VX image anymore through their developer's portal, the sneaky petes always find a way to get their hands on a qcow2.\n\n\n/source/head/docs/rn/0.70.md:\n  Line 7: A big shout-out to @carlmontanari for picking up the fallen flag and working on the Containerlab Go API by decoupling the core logic from the CLI implementation. There is still some work to be done, but already now if you want to leverage Containerlab programmatically as a Go package, you should be able to do so. Check the https://pkg.go.dev/github.com/srl-labs/containerlab for the documentation and see how our CLI uses the options and passes them to the core functions to parametrize and run labs.\n\n\n/source/head/docs/rn/0.48.md:\n  Line 42: * Improvements to the devcontainer documentation #1689\n\n\n/source/head/docs/rn/0.39.md:\n  Line 26:                     next-hop \"192.168.0.1\" {\n\n\n/source/head/docs/rn/0.83.md:\n  Line 59: Persistent node volumes now survive a plain `destroy`, just as a local lab directory does. A subsequent deploy adopts the retained PersistentVolumeClaims and boots from the saved device state. `destroy --cleanup` removes the claims and managed namespace, while `deploy --reconfigure` and `redeploy --cleanup` also start from clean storage.\n\n  Line 75: The new [`logs`](../cmd/logs.md) command displays or follows a node's log with Docker, Podman and c9s. With c9s it reads the log of the node's primary device container:\n\n\n/source/head/docs/rn/0.26.md:\n  Line 23: : Get started: https://learn.srlinux.dev                       :\n\n  Line 24: : Container:   https://go.srlinux.dev/container-image          :\n\n  Line 25: : Docs:        https://doc.srlinux.dev/21-11                   :\n\n  Line 26: : Rel. notes:  https://doc.srlinux.dev/rn21-11-2               :\n\n  Line 27: : YANG:        https://yang.srlinux.dev/v21.11.2               :\n\n  Line 28: : Discord:     https://go.srlinux.dev/discord                  :\n\n  Line 29: : Contact:     https://go.srlinux.dev/contact-sales            :\n\n  Line 69: * next-ui-based graph works better with long image names in tooltips #834\n\n\n/source/head/docs/rn/0.60.md:\n  Line 87: The devcontainer integration is a way to start a lab on a laptop, desktop, server or VM without installing anything on the host besides Docker. If you rememeber how easy it was to start a lab in Codespaces, you will be happy to get the same UX now with your local compute.\n\n  Line 91: * [for macOS](../macos.md#devcontainer)\n\n  Line 92: * [and Windows](../windows.md#devcontainer)\n\n  Line 100: DevPod takes the devcontainer experience and adds better UX on top of it :wink:\n\n  Line 102: An open-source project by Loft Labs, DevPod makes it possible to use the same devcontainer specification and create a \"workspace\" that uses almost any IDE known to men and deploys it on a wide range of providers.\n\n\n/source/head/docs/rn/0.49.md:\n  Line 30: * ixia-c example lab has been updated by @bortok to feature latest developments done for the ixia-c kind #1795\n\n\n/source/head/docs/rn/0.12.0.md:\n  Line 38: We also [added a lab](https://clabs.netdevops.me/security/gnmitls/) that pictures the net positive effect of having those commands when creating TLS certificates for secured gNMI connectivity.\n\n  Line 56: When a new release comes out we let you know next time you deploy a lab, a tiny message will pop up in the log saying that a new one is ready to make your labs even more efficient and easy.\n\n  Line 59: INFO[0001] 🎉 New containerlab version 0.12.0 is available! Release notes: https://containerlab.dev/rn/0.12.0\n\n  Line 60: Run 'containerlab version upgrade' to upgrade or go check other installation options at https://containerlab.dev/install/ \n\n\n/source/head/docs/rn/0.55.md:\n  Line 12: curl -L http://containerlab.dev/setup \\\n\n  Line 29: curl -L http://containerlab.dev/setup \\\n\n  Line 37: curl -L http://containerlab.dev/setup \\\n\n\n/source/head/docs/rn/0.80.md:\n  Line 78: The management (again!) network can join a Tailscale tailnet. In sidecar mode every node gets a tailscale sidecar container and appears as a device in your tailnet, authenticated with a reusable auth-key:\n\n  Line 87: In proxy mode the whole lab appears as a single device in the tailnet, authenticated via SSO. Individual nodes are exposed by forwarding ports with the `/ts` port suffix, e.g. `8022:22/ts` maps port 8022 of the lab device to SSH of that node.\n\n\n/source/head/docs/rn/0.25.md:\n  Line 31: * containerlab site moved to containerlab.dev domain\n\n\n/source/head/docs/rn/0.69.md:\n  Line 117: * fix devcontainer build #2746\n\n\n/source/head/docs/rn/0.53.md:\n  Line 20: This feature is in the \"preview\" status, we will likely change the command structure in the next release.\n\n\n/source/head/docs/rn/0.75.md:\n  Line 20: - Place additional `*.gotmpl` files in a `clab_templates` directory next to the main template; they are loaded and invokable with Go's `{{ template \"name.gotmpl\" . }}` from the top-level file.\n\n  Line 65: Thanks @Rucdev #3167\n",
    "title": "unreleased|dev|next",
    "metadata": {
      "matches": 52,
      "truncated": false
    },
    "time": {
      "start": 1794565409479,
      "end": 1794565409499
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/docs/rn/0.83.md",
  "limit": 60,
  "offset": 140
}

Output

<path>/source/head/docs/rn/0.83.md</path>
<type>file</type>
<content>
140: A reboot issued from within an [SR Linux](../manual/kinds/srl.md#reboot) node, such as `tools platform chassis reboot`, now brings the node back with its links, saved configuration and management address intact.
141: 
142: Each `nokia_srlinux` node uses an internal `<node-name>-netns` holder container for its network namespace. The holder is hidden from `inspect` unless `--all` is set and is removed with the node. SR Linux nodes now default to the `unless-stopped` restart policy, while an explicitly configured policy is preserved. Nodes with a user-defined `network-mode` keep the previous behavior.
143: 
144: Done in #3567 thanks to @sacckth and @kaelemc
145: 
146: ## Per-node runtime deprecated
147: 
148: The node-level `runtime` parameter is deprecated and will be removed in a future release. Mixing runtimes within a lab is not supported because management networking and lab-wide operations use the lab-wide runtime. Setting `runtime` on a node, group, kind or defaults block still works but emits a deprecation notice.
149: 
150: Use the global `--runtime` flag or `CLAB_RUNTIME` environment variable instead:
151: 
152: ```bash
153: containerlab deploy -t mylab.clab.yml --runtime podman
154: ```
155: 
156: Done in #3527 thanks to @FloSch62
157: 
158: ## Miscellaneous
159: 
160: - `tools snapshot save` now snapshots the deployed nodes of a partially built lab instead of failing on nodes whose containers were not created. [#3537](https://github.com/srl-labs/containerlab/pull/3537)
161: - Ciena SAOS nodes now stage a topology-supplied license file—provided as a path, URL or embedded blob—into `/config/license` and expose it to the vrnetlab launcher through `SAOS_LICENSE_PATH`. [#3535](https://github.com/srl-labs/containerlab/pull/3535)
162: - SR-SIM finds its running instance using the full process command line, fixing discovery when FEX emulates SR OS on ARM hosts. [#3538](https://github.com/srl-labs/containerlab/pull/3538)
163: - `containerlab events` no longer misses interfaces created while a watcher starts. Failed netlink subscriptions are retried and re-established, with changes during the outage reconciled instead of silently ending interface reporting. [#3532](https://github.com/srl-labs/containerlab/pull/3532)
164: - FRR keeps `vtysh` available throughout installation of the configuration-save wrapper, closing a startup race that could prevent the initial configuration from loading. [#3555](https://github.com/srl-labs/containerlab/pull/3555)
165: - Cisco IOL now propagates a `mgmt-intf` override to the VM launcher when a non-default management interface is selected. [#3557](https://github.com/srl-labs/containerlab/pull/3557)
166: - Destroy and reconfigure operations reliably remove `vxlan-stitch` host interfaces by waiting for node deletion before host-link cleanup, including partial labs with no remaining containers. [#3571](https://github.com/srl-labs/containerlab/pull/3571)
167: - Open vSwitch bridges no longer accumulate stale auto-generated `clab-*` ports across deploy and redeploy operations when endpoint names require sanitized Linux interface names. Destroy also cleans up orphaned generated ports, and `ovs-vsctl` cleanup calls time out instead of hanging when `ovs-vswitchd` is unavailable. [#3573](https://github.com/srl-labs/containerlab/pull/3573)
168: - Empty node, kind and defaults definitions are handled correctly: nodes without a body inherit kind, group and configuration values, while empty kind or defaults blocks no longer cause panics. [#3518](https://github.com/srl-labs/containerlab/pull/3518)
169: - Docker and Podman resolve `network-mode: container:` targets correctly when a lab name contains the node name, fixing deployments of SR Linux nodes with their new network-namespace holders. [#3577](https://github.com/srl-labs/containerlab/pull/3577)
170: - The go-jose dependency was updated to 4.1.8. [#3569](https://github.com/srl-labs/containerlab/pull/3569)
171: - Documentation was clarified for [OcNOS image requirements](../manual/kinds/ipinfusion-ocnos.md), HwSKU-dependent [Dell SONiC interface names](../manual/kinds/dell_sonic.md), and [SR Linux platform licensing](../manual/kinds/srl.md#license). [#3552](https://github.com/srl-labs/containerlab/pull/3552) [#3553](https://github.com/srl-labs/containerlab/pull/3553) [#3575](https://github.com/srl-labs/containerlab/pull/3575)

(End of file - total 171 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f0b91001S69bBszjJSfX9H",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dd0850019pu9eWPwYXBzD3",
  "callID": "call_84e29c16cb0d4d59b93ce7a6",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/docs/rn/0.83.md",
      "limit": 60,
      "offset": 140
    },
    "output": "<path>/source/head/docs/rn/0.83.md</path>\n<type>file</type>\n<content>\n140: A reboot issued from within an [SR Linux](../manual/kinds/srl.md#reboot) node, such as `tools platform chassis reboot`, now brings the node back with its links, saved configuration and management address intact.\n141: \n142: Each `nokia_srlinux` node uses an internal `<node-name>-netns` holder container for its network namespace. The holder is hidden from `inspect` unless `--all` is set and is removed with the node. SR Linux nodes now default to the `unless-stopped` restart policy, while an explicitly configured policy is preserved. Nodes with a user-defined `network-mode` keep the previous behavior.\n143: \n144: Done in #3567 thanks to @sacckth and @kaelemc\n145: \n146: ## Per-node runtime deprecated\n147: \n148: The node-level `runtime` parameter is deprecated and will be removed in a future release. Mixing runtimes within a lab is not supported because management networking and lab-wide operations use the lab-wide runtime. Setting `runtime` on a node, group, kind or defaults block still works but emits a deprecation notice.\n149: \n150: Use the global `--runtime` flag or `CLAB_RUNTIME` environment variable instead:\n151: \n152: ```bash\n153: containerlab deploy -t mylab.clab.yml --runtime podman\n154: ```\n155: \n156: Done in #3527 thanks to @FloSch62\n157: \n158: ## Miscellaneous\n159: \n160: - `tools snapshot save` now snapshots the deployed nodes of a partially built lab instead of failing on nodes whose containers were not created. [#3537](https://github.com/srl-labs/containerlab/pull/3537)\n161: - Ciena SAOS nodes now stage a topology-supplied license file—provided as a path, URL or embedded blob—into `/config/license` and expose it to the vrnetlab launcher through `SAOS_LICENSE_PATH`. [#3535](https://github.com/srl-labs/containerlab/pull/3535)\n162: - SR-SIM finds its running instance using the full process command line, fixing discovery when FEX emulates SR OS on ARM hosts. [#3538](https://github.com/srl-labs/containerlab/pull/3538)\n163: - `containerlab events` no longer misses interfaces created while a watcher starts. Failed netlink subscriptions are retried and re-established, with changes during the outage reconciled instead of silently ending interface reporting. [#3532](https://github.com/srl-labs/containerlab/pull/3532)\n164: - FRR keeps `vtysh` available throughout installation of the configuration-save wrapper, closing a startup race that could prevent the initial configuration from loading. [#3555](https://github.com/srl-labs/containerlab/pull/3555)\n165: - Cisco IOL now propagates a `mgmt-intf` override to the VM launcher when a non-default management interface is selected. [#3557](https://github.com/srl-labs/containerlab/pull/3557)\n166: - Destroy and reconfigure operations reliably remove `vxlan-stitch` host interfaces by waiting for node deletion before host-link cleanup, including partial labs with no remaining containers. [#3571](https://github.com/srl-labs/containerlab/pull/3571)\n167: - Open vSwitch bridges no longer accumulate stale auto-generated `clab-*` ports across deploy and redeploy operations when endpoint names require sanitized Linux interface names. Destroy also cleans up orphaned generated ports, and `ovs-vsctl` cleanup calls time out instead of hanging when `ovs-vswitchd` is unavailable. [#3573](https://github.com/srl-labs/containerlab/pull/3573)\n168: - Empty node, kind and defaults definitions are handled correctly: nodes without a body inherit kind, group and configuration values, while empty kind or defaults blocks no longer cause panics. [#3518](https://github.com/srl-labs/containerlab/pull/3518)\n169: - Docker and Podman resolve `network-mode: container:` targets correctly when a lab name contains the node name, fixing deployments of SR Linux nodes with their new network-namespace holders. [#3577](https://github.com/srl-labs/containerlab/pull/3577)\n170: - The go-jose dependency was updated to 4.1.8. [#3569](https://github.com/srl-labs/containerlab/pull/3569)\n171: - Documentation was clarified for [OcNOS image requirements](../manual/kinds/ipinfusion-ocnos.md), HwSKU-dependent [Dell SONiC interface names](../manual/kinds/dell_sonic.md), and [SR Linux platform licensing](../manual/kinds/srl.md#license). [#3552](https://github.com/srl-labs/containerlab/pull/3552) [#3553](https://github.com/srl-labs/containerlab/pull/3553) [#3575](https://github.com/srl-labs/containerlab/pull/3575)\n\n(End of file - total 171 lines)\n</content>",
    "title": "source/head/docs/rn/0.83.md",
    "metadata": {
      "preview": "A reboot issued from within an [SR Linux](../manual/kinds/srl.md#reboot) node, such as `tools platform chassis reboot`, now brings the node back with its links, saved configuration and management address intact.\n\nEach `nokia_srlinux` node uses an internal `<node-name>-netns` holder container for its network namespace. The holder is hidden from `inspect` unless `--all` is set and is removed with the node. SR Linux nodes now default to the `unless-stopped` restart policy, while an explicitly configured policy is preserved. Nodes with a user-defined `network-mode` keep the previous behavior.\n\nDone in #3567 thanks to @sacckth and @kaelemc\n\n## Per-node runtime deprecated\n\nThe node-level `runtime` parameter is deprecated and will be removed in a future release. Mixing runtimes within a lab is not supported because management networking and lab-wide operations use the lab-wide runtime. Setting `runtime` on a node, group, kind or defaults block still works but emits a deprecation notice.\n\nUse the global `--runtime` flag or `CLAB_RUNTIME` environment variable instead:\n\n```bash\ncontainerlab deploy -t mylab.clab.yml --runtime podman\n```\n\nDone in #3527 thanks to @FloSch62\n\n## Miscellaneous\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/docs/rn/0.83.md",
        "text": "A reboot issued from within an [SR Linux](../manual/kinds/srl.md#reboot) node, such as `tools platform chassis reboot`, now brings the node back with its links, saved configuration and management address intact.\n\nEach `nokia_srlinux` node uses an internal `<node-name>-netns` holder container for its network namespace. The holder is hidden from `inspect` unless `--all` is set and is removed with the node. SR Linux nodes now default to the `unless-stopped` restart policy, while an explicitly configured policy is preserved. Nodes with a user-defined `network-mode` keep the previous behavior.\n\nDone in #3567 thanks to @sacckth and @kaelemc\n\n## Per-node runtime deprecated\n\nThe node-level `runtime` parameter is deprecated and will be removed in a future release. Mixing runtimes within a lab is not supported because management networking and lab-wide operations use the lab-wide runtime. Setting `runtime` on a node, group, kind or defaults block still works but emits a deprecation notice.\n\nUse the global `--runtime` flag or `CLAB_RUNTIME` environment variable instead:\n\n```bash\ncontainerlab deploy -t mylab.clab.yml --runtime podman\n```\n\nDone in #3527 thanks to @FloSch62\n\n## Miscellaneous\n\n- `tools snapshot save` now snapshots the deployed nodes of a partially built lab instead of failing on nodes whose containers were not created. [#3537](https://github.com/srl-labs/containerlab/pull/3537)\n- Ciena SAOS nodes now stage a topology-supplied license file—provided as a path, URL or embedded blob—into `/config/license` and expose it to the vrnetlab launcher through `SAOS_LICENSE_PATH`. [#3535](https://github.com/srl-labs/containerlab/pull/3535)\n- SR-SIM finds its running instance using the full process command line, fixing discovery when FEX emulates SR OS on ARM hosts. [#3538](https://github.com/srl-labs/containerlab/pull/3538)\n- `containerlab events` no longer misses interfaces created while a watcher starts. Failed netlink subscriptions are retried and re-established, with changes during the outage reconciled instead of silently ending interface reporting. [#3532](https://github.com/srl-labs/containerlab/pull/3532)\n- FRR keeps `vtysh` available throughout installation of the configuration-save wrapper, closing a startup race that could prevent the initial configuration from loading. [#3555](https://github.com/srl-labs/containerlab/pull/3555)\n- Cisco IOL now propagates a `mgmt-intf` override to the VM launcher when a non-default management interface is selected. [#3557](https://github.com/srl-labs/containerlab/pull/3557)\n- Destroy and reconfigure operations reliably remove `vxlan-stitch` host interfaces by waiting for node deletion before host-link cleanup, including partial labs with no remaining containers. [#3571](https://github.com/srl-labs/containerlab/pull/3571)\n- Open vSwitch bridges no longer accumulate stale auto-generated `clab-*` ports across deploy and redeploy operations when endpoint names require sanitized Linux interface names. Destroy also cleans up orphaned generated ports, and `ovs-vsctl` cleanup calls time out instead of hanging when `ovs-vswitchd` is unavailable. [#3573](https://github.com/srl-labs/containerlab/pull/3573)\n- Empty node, kind and defaults definitions are handled correctly: nodes without a body inherit kind, group and configuration values, while empty kind or defaults blocks no longer cause panics. [#3518](https://github.com/srl-labs/containerlab/pull/3518)\n- Docker and Podman resolve `network-mode: container:` targets correctly when a lab name contains the node name, fixing deployments of SR Linux nodes with their new network-namespace holders. [#3577](https://github.com/srl-labs/containerlab/pull/3577)\n- The go-jose dependency was updated to 4.1.8. [#3569](https://github.com/srl-labs/containerlab/pull/3569)\n- Documentation was clarified for [OcNOS image requirements](../manual/kinds/ipinfusion-ocnos.md), HwSKU-dependent [Dell SONiC interface names](../manual/kinds/dell_sonic.md), and [SR Linux platform licensing](../manual/kinds/srl.md#license). [#3552](https://github.com/srl-labs/containerlab/pull/3552) [#3553](https://github.com/srl-labs/containerlab/pull/3553) [#3575](https://github.com/srl-labs/containerlab/pull/3575)",
        "lineStart": 140,
        "lineEnd": 171,
        "totalLines": 171,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565409687,
      "end": 1794565409694
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46f0ba100180W55Pnlp08gok",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46dd0850019pu9eWPwYXBzD3",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 79543,
    "input": 3797,
    "output": 73,
    "reasoning": 5529,
    "cache": {
      "read": 70144,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46dd0850019pu9eWPwYXBzD3",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565329029,
    "completed": 1794565409701
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 79543,
    "input": 3797,
    "output": 73,
    "reasoning": 5529,
    "cache": {
      "read": 70144,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 11
step-start
{
  "type": "step-start",
  "id": "prt_1d46f14f7001ze9tfkOyrY2zFn",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f0bab001aLmUyzWYdKl1KK"
}
Reasoning
The release notes 0.83 is the current release under development. This PR's diff doesn't add a release note entry. The rule says: "When reviewing a PR, inspect any changes under `docs/rn/`" — the PR doesn't change docs/rn. The rule doesn't strictly require adding one; it governs how to handle existing changes under docs/rn. The user-visible behavior change (events stream re-reports stitched interfaces as delete+create) could warrant a release-note/evergreen-doc note. But I should be careful not to over-require. The `events` docs describe when notifications are emitted; the new delete+create rename behavior is a notable consumer-visible change. I'll flag a P4 doc gap anchored to `emit`/`track` change, pointing to `docs/cmd/events.md`.

Now let me check whether there's anything else referencing `emitInterfaceStatsEvent` in tests or elsewhere (removed function). Grep showed only sendInterfaceEvent now. Good.

Check `netlink_test.go` for overlayToolsInterface test — exists.

Also check `git-mutations.mdc` — not relevant to review content.

Let me double check the events streaming command code that consumes aggregatedEvent, e.g. `cmd/events.go` or wherever `aggregatedEvent` is consumed, to see if the delete+create sequences could break something (e.g., graph). Let me grep aggregatedEvent.
grep · completed

Input

{
  "path": "/source/head",
  "pattern": "aggregatedEvent",
  "include": "*.go"
}

Output

Found 46 matches
/source/head/core/events/types.go:
  Line 5: type aggregatedEvent struct {


/source/head/core/events/formatter.go:
  Line 12: type formatter func(aggregatedEvent) error

  Line 31: 	return func(ev aggregatedEvent) error {

  Line 81: 	return func(ev aggregatedEvent) error {

  Line 89: func mergedEventAttributes(ev aggregatedEvent) map[string]string {


/source/head/core/events/netlink.go:
  Line 32: 	events                 chan<- aggregatedEvent

  Line 40: 	events chan<- aggregatedEvent,

  Line 940: 	event := aggregatedEvent{


/source/head/core/events/stream.go:
  Line 45: 	eventCh := make(chan aggregatedEvent, 128)

  Line 133: 			if err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {

  Line 173: // aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the

  Line 180: func aggregatedEventFromLabRuntimeEvent(

  Line 183: ) aggregatedEvent {

  Line 195: 			attributes = aggregatedEventFromContainerSnapshot(&container).Attributes

  Line 214: 	return aggregatedEvent{

  Line 259: 	eventSink chan<- aggregatedEvent,

  Line 292: 			aggregated := aggregatedEventFromContainerEvent(ctx, runtime, ev)

  Line 302: func aggregatedEventFromContainerEvent(

  Line 306: ) aggregatedEvent {

  Line 341: 	return aggregatedEvent{

  Line 470: 	sink chan<- aggregatedEvent,

  Line 478: 		event := aggregatedEventFromContainerSnapshot(&container)

  Line 491: func aggregatedEventFromContainerSnapshot(

  Line 493: ) aggregatedEvent {

  Line 495: 		return aggregatedEvent{}

  Line 534: 	return aggregatedEvent{


/source/head/core/events/parity_test.go:
  Line 118: ) aggregatedEvent {

  Line 135: 	return aggregatedEventFromContainerEvent(context.Background(),

  Line 181: ) aggregatedEvent {

  Line 191: 	return aggregatedEventFromLabRuntimeEvent(clab, clablabruntime.Event{

  Line 210: func assertAttributeParity(t *testing.T, docker, c9s aggregatedEvent, dockerOnly map[string]bool) {

  Line 340: 		docker := aggregatedEventFromContainerSnapshot(&container)

  Line 404: ) aggregatedEvent {

  Line 410: 	return aggregatedEvent{

  Line 421: ) aggregatedEvent {

  Line 424: 	return aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{

  Line 546: 	ev := aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{


/source/head/core/events/netlink_watch_test.go:
  Line 28: func collectEvents(ctx context.Context, events <-chan aggregatedEvent) *eventLog {

  Line 162: 	events := make(chan aggregatedEvent, 1024)

  Line 314: 			events := make(chan aggregatedEvent, 8)

  Line 366: 	events := make(chan aggregatedEvent, 8)

  Line 399: func drainEvents(events chan aggregatedEvent) []reportedEvent {

  Line 428: 	events := make(chan aggregatedEvent, 8)

  Line 449: 	events := make(chan aggregatedEvent, 8)

  Line 470: 	events := make(chan aggregatedEvent, 8)

  Line 512: 	events := make(chan aggregatedEvent, 8)
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f245c001jjqK75HxGtfJte",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f0bab001aLmUyzWYdKl1KK",
  "callID": "call_83884b5e32894214ab2f129c",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head",
      "pattern": "aggregatedEvent",
      "include": "*.go"
    },
    "output": "Found 46 matches\n/source/head/core/events/types.go:\n  Line 5: type aggregatedEvent struct {\n\n\n/source/head/core/events/formatter.go:\n  Line 12: type formatter func(aggregatedEvent) error\n\n  Line 31: \treturn func(ev aggregatedEvent) error {\n\n  Line 81: \treturn func(ev aggregatedEvent) error {\n\n  Line 89: func mergedEventAttributes(ev aggregatedEvent) map[string]string {\n\n\n/source/head/core/events/netlink.go:\n  Line 32: \tevents                 chan<- aggregatedEvent\n\n  Line 40: \tevents chan<- aggregatedEvent,\n\n  Line 940: \tevent := aggregatedEvent{\n\n\n/source/head/core/events/stream.go:\n  Line 45: \teventCh := make(chan aggregatedEvent, 128)\n\n  Line 133: \t\t\tif err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {\n\n  Line 173: // aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the\n\n  Line 180: func aggregatedEventFromLabRuntimeEvent(\n\n  Line 183: ) aggregatedEvent {\n\n  Line 195: \t\t\tattributes = aggregatedEventFromContainerSnapshot(&container).Attributes\n\n  Line 214: \treturn aggregatedEvent{\n\n  Line 259: \teventSink chan<- aggregatedEvent,\n\n  Line 292: \t\t\taggregated := aggregatedEventFromContainerEvent(ctx, runtime, ev)\n\n  Line 302: func aggregatedEventFromContainerEvent(\n\n  Line 306: ) aggregatedEvent {\n\n  Line 341: \treturn aggregatedEvent{\n\n  Line 470: \tsink chan<- aggregatedEvent,\n\n  Line 478: \t\tevent := aggregatedEventFromContainerSnapshot(&container)\n\n  Line 491: func aggregatedEventFromContainerSnapshot(\n\n  Line 493: ) aggregatedEvent {\n\n  Line 495: \t\treturn aggregatedEvent{}\n\n  Line 534: \treturn aggregatedEvent{\n\n\n/source/head/core/events/parity_test.go:\n  Line 118: ) aggregatedEvent {\n\n  Line 135: \treturn aggregatedEventFromContainerEvent(context.Background(),\n\n  Line 181: ) aggregatedEvent {\n\n  Line 191: \treturn aggregatedEventFromLabRuntimeEvent(clab, clablabruntime.Event{\n\n  Line 210: func assertAttributeParity(t *testing.T, docker, c9s aggregatedEvent, dockerOnly map[string]bool) {\n\n  Line 340: \t\tdocker := aggregatedEventFromContainerSnapshot(&container)\n\n  Line 404: ) aggregatedEvent {\n\n  Line 410: \treturn aggregatedEvent{\n\n  Line 421: ) aggregatedEvent {\n\n  Line 424: \treturn aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{\n\n  Line 546: \tev := aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{\n\n\n/source/head/core/events/netlink_watch_test.go:\n  Line 28: func collectEvents(ctx context.Context, events <-chan aggregatedEvent) *eventLog {\n\n  Line 162: \tevents := make(chan aggregatedEvent, 1024)\n\n  Line 314: \t\t\tevents := make(chan aggregatedEvent, 8)\n\n  Line 366: \tevents := make(chan aggregatedEvent, 8)\n\n  Line 399: func drainEvents(events chan aggregatedEvent) []reportedEvent {\n\n  Line 428: \tevents := make(chan aggregatedEvent, 8)\n\n  Line 449: \tevents := make(chan aggregatedEvent, 8)\n\n  Line 470: \tevents := make(chan aggregatedEvent, 8)\n\n  Line 512: \tevents := make(chan aggregatedEvent, 8)\n",
    "title": "aggregatedEvent",
    "metadata": {
      "matches": 46,
      "truncated": false
    },
    "time": {
      "start": 1794565416034,
      "end": 1794565416071
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/events/netlink_test.go"
}

Output

<path>/source/head/core/events/netlink_test.go</path>
<type>file</type>
<content>
1: package events
2: 
3: import (
4: 	"maps"
5: 	"testing"
6: 
7: 	clabconstants "github.com/srl-labs/containerlab/constants"
8: 	clabruntime "github.com/srl-labs/containerlab/runtime"
9: )
10: 
11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {
12: 	base := map[string]string{
13: 		"ifname": "eth1",
14: 		"alias":  "e1-1",
15: 		"type":   "veth",
16: 	}
17: 
18: 	tests := map[string]*clabruntime.GenericContainer{
19: 		"no labels": {},
20: 		"lab only":  {Labels: map[string]string{clabconstants.Containerlab: "lab"}},
21: 		"node only": {Labels: map[string]string{clabconstants.NodeName: "n1"}},
22: 		// lab+node set, but no stitch interface exists, so attributes stay put.
23: 		"no stitch iface": {Labels: map[string]string{
24: 			clabconstants.Containerlab: "no-such-lab",
25: 			clabconstants.NodeName:     "no-such-node",
26: 		}},
27: 	}
28: 
29: 	for name, container := range tests {
30: 		t.Run(name, func(t *testing.T) {
31: 			attrs := maps.Clone(base)
32: 			overlayToolsInterface(container, attrs)
33: 
34: 			if !maps.Equal(attrs, base) {
35: 				t.Fatalf("attributes changed unexpectedly: got %v want %v", attrs, base)
36: 			}
37: 		})
38: 	}
39: }

(End of file - total 39 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f24bd00168oen7FbmTYtzA",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f0bab001aLmUyzWYdKl1KK",
  "callID": "call_a4b75952136b47488e416bc7",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/netlink_test.go"
    },
    "output": "<path>/source/head/core/events/netlink_test.go</path>\n<type>file</type>\n<content>\n1: package events\n2: \n3: import (\n4: \t\"maps\"\n5: \t\"testing\"\n6: \n7: \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n8: \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n9: )\n10: \n11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {\n12: \tbase := map[string]string{\n13: \t\t\"ifname\": \"eth1\",\n14: \t\t\"alias\":  \"e1-1\",\n15: \t\t\"type\":   \"veth\",\n16: \t}\n17: \n18: \ttests := map[string]*clabruntime.GenericContainer{\n19: \t\t\"no labels\": {},\n20: \t\t\"lab only\":  {Labels: map[string]string{clabconstants.Containerlab: \"lab\"}},\n21: \t\t\"node only\": {Labels: map[string]string{clabconstants.NodeName: \"n1\"}},\n22: \t\t// lab+node set, but no stitch interface exists, so attributes stay put.\n23: \t\t\"no stitch iface\": {Labels: map[string]string{\n24: \t\t\tclabconstants.Containerlab: \"no-such-lab\",\n25: \t\t\tclabconstants.NodeName:     \"no-such-node\",\n26: \t\t}},\n27: \t}\n28: \n29: \tfor name, container := range tests {\n30: \t\tt.Run(name, func(t *testing.T) {\n31: \t\t\tattrs := maps.Clone(base)\n32: \t\t\toverlayToolsInterface(container, attrs)\n33: \n34: \t\t\tif !maps.Equal(attrs, base) {\n35: \t\t\t\tt.Fatalf(\"attributes changed unexpectedly: got %v want %v\", attrs, base)\n36: \t\t\t}\n37: \t\t})\n38: \t}\n39: }\n\n(End of file - total 39 lines)\n</content>",
    "title": "source/head/core/events/netlink_test.go",
    "metadata": {
      "preview": "package events\n\nimport (\n\t\"maps\"\n\t\"testing\"\n\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n)\n\nfunc TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {\n\tbase := map[string]string{\n\t\t\"ifname\": \"eth1\",\n\t\t\"alias\":  \"e1-1\",\n\t\t\"type\":   \"veth\",\n\t}\n\n\ttests := map[string]*clabruntime.GenericContainer{\n\t\t\"no labels\": {},\n\t\t\"lab only\":  {Labels: map[string]string{clabconstants.Containerlab: \"lab\"}},",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/netlink_test.go",
        "text": "package events\n\nimport (\n\t\"maps\"\n\t\"testing\"\n\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n)\n\nfunc TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {\n\tbase := map[string]string{\n\t\t\"ifname\": \"eth1\",\n\t\t\"alias\":  \"e1-1\",\n\t\t\"type\":   \"veth\",\n\t}\n\n\ttests := map[string]*clabruntime.GenericContainer{\n\t\t\"no labels\": {},\n\t\t\"lab only\":  {Labels: map[string]string{clabconstants.Containerlab: \"lab\"}},\n\t\t\"node only\": {Labels: map[string]string{clabconstants.NodeName: \"n1\"}},\n\t\t// lab+node set, but no stitch interface exists, so attributes stay put.\n\t\t\"no stitch iface\": {Labels: map[string]string{\n\t\t\tclabconstants.Containerlab: \"no-such-lab\",\n\t\t\tclabconstants.NodeName:     \"no-such-node\",\n\t\t}},\n\t}\n\n\tfor name, container := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tattrs := maps.Clone(base)\n\t\t\toverlayToolsInterface(container, attrs)\n\n\t\t\tif !maps.Equal(attrs, base) {\n\t\t\t\tt.Fatalf(\"attributes changed unexpectedly: got %v want %v\", attrs, base)\n\t\t\t}\n\t\t})\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 39,
        "totalLines": 39,
        "truncated": false
      }
    },
    "time": {
      "start": 1794565416129,
      "end": 1794565416134
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46f24e4001Dq8DFqeSyHN0Mr",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f0bab001aLmUyzWYdKl1KK",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 83670,
    "input": 3975,
    "output": 42,
    "reasoning": 293,
    "cache": {
      "read": 79360,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46f0bab001aLmUyzWYdKl1KK",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565409707,
    "completed": 1794565416168
  },
  "parentID": "msg_1d46a1f70001REibDVUjhvUdJT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 83670,
    "input": 3975,
    "output": 42,
    "reasoning": 293,
    "cache": {
      "read": 79360,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 12
compaction
{
  "type": "compaction",
  "id": "prt_1d46f24ea001WVc05ut17j6ufZ",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f24e90018l7Tw4fHeU6LjX",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_1d46dd0850019pu9eWPwYXBzD3"
}
Message metadata
{
  "role": "user",
  "id": "msg_1d46f24e90018l7Tw4fHeU6LjX",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565416169
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 13
step-start
{
  "type": "step-start",
  "id": "prt_1d46f2db5001rGZ33pjFFy700U",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f24fd0016TiilkMxPchYE2"
}
Reasoning
Summarize the review task state.
## Objective
- Review a read-only PR snapshot at `/source` (repo: srl-labs/containerlab, head `1c9b3577d08f7524fd228e5ab4df3dd3fc107f53`, base `f57133d88d7f26767e78a9f4c0f81a9ed070fe8b`) against standards.json rules (karpathy-guidelines.mdc, ponytail.mdc), tracking both changed paths and relevant callers/tests/docs/schema, then return a trusted result schema with findings.

## Important Details
- Changed paths (manifest.json): `core/events/netlink.go` (M) and `core/events/netlink_watch_test.go` (M). Both are modified.
- Snapshot layout: `/source/head/`, `/source/base/`, `/source/diff.txt`, `/source/manifest.json`, `/source/standards.json`, `/source/standards/*.mdc`.
- Note: direct `read` on `/source` (directory) is denied by permission rules; must read concrete file paths.
- PR summary (from diff analysis):
  - `netlinkWatcher` gains a `reported map[int]reportedInterface` (per-interface last-reported attributes + `since` time).
  - New `reportedInterface{attributes map[string]string; since time.Time}` type.
  - New package-level `var stitchMarkWindow = time.Minute` — window during which host-side stitch interfaces are polled for after a link is first reported.
  - New watcher methods: `emit` (tracks reported state; converts `update`→`create` after emitting a `delete` under the old ifname when rename detected), `emitStats` (emits create-without-counters on rename before stats event), `track` (delete old name + store `maps.Clone(attributes)`), `reportStitchMarks` (called on netem ticker tick; for veth links reported under their own name within `stitchMarkWindow`, resolves host-side stitch via `interfaceAttributes` → `overlayToolsInterface` → `clablinks.ToolsInterface` → `netlink.LinkByName` in root netns; emits update when stitch altname exists).
  - `sendInterfaceEvent` (registry method) replaced base `emitInterfaceEvent` and lost the base's `container == nil` guard — callers verified as guarded (`emit`/`emitStats` check `w.container == nil`; `track` only reached via those).
  - `w.reported` is only touched from the watch-loop goroutine (no race); persists across resubscribes.
- Analysis findings so far (candidate findings, not yet finalized):
  - P4 candidate: wasted `interfaceAttributes` call (root-netns `LinkByName` syscall) in `emit`'s delete path when `previous` exists — result discarded.
  - P4 candidate: `since` never refreshes (window measured from FIRST report); slow lab deploys (>1 min between node link creation and stitch mark) miss the rename, though it self-corrects on any later link update or resubscribe. No `ponytail:` comment marking the deliberate ceiling (ponytail rule requires naming ceiling/upgrade path).
  - Pre-existing (not worsened): with `includeSnapshot=false`, links present at first subscription are in `states` but not `w.reported`; later update/delete events reference never-reported interfaces. Same in base.
  - Test coverage gap: `reportStitchMarks` rename path (positive case) is untested; only negative case tested (`TestReportStitchMarksLeavesUnmarkedLinks`).
- Constraints: source-only review, no test execution; must disclose that limitation. Use read offsets for truncated output, group independent tool calls, glob/grep for surrounding code. Must return the trusted result schema at the end.

## Work State
### Completed
- Read `standards.json`, both referenced rule files (`standards/karpathy-guidelines.mdc`, `standards/ponytail.mdc`), `diff.txt`, `manifest.json`.
- Read full head `core/events/netlink.go` (1390 lines) and head `core/events/netlink_watch_test.go` (534 lines).
- Read base `core/events/netlink.go` (offsets 230–630, 630–1310) to compare behavior.
- Grepped head for `sendInterfaceEvent|emitInterfaceStatsEvent|emitInterfaceEvent` (all call sites in netlink.go lines 688–934) and for `ToolsInterface|reportStitchMarks|stitchMarkWindow` (callers: `core/netem.go:97`, `core/list.go:176`, `links/link_veth_stitched.go:302`, tests).
- Read `links/link_veth_stitched.go` (stitch mechanism) and head `docs/cmd/events.md`.
- Grepped docs for interface event docs (`docs/manual/clabernetes/runtime.md` documents ifname/state/stats events, lines 800–979+).
- Verified `w.reported` single-goroutine access; verified `track` stores `maps.Clone(attributes)` so post-`track` mutation in `emitStats` is safe; verified test expectations in `TestEmitStatsReportsRenamedLinkFirst` and `TestReportStitchMarksLeavesUnmarkedLinks` are consistent.

### Active
- Finalizing the review: remaining checks before producing findings and the trusted result schema — re-verify head `netlink.go` `emit`/`track`/`reportStitchMarks` code sections in full detail (base read used offsets; head emit logic seen via grep only at lines ~650–760, 896–934), confirm no `sendInterfaceEvent` callers outside netlink.go, and confirm whether any docs/schema updates are needed for the new delete+create-on-rename event sequence.

### Blocked
- None. Source-only review limitation (no test execution) must be disclosed in final output rather than being treated as a blocker.

## Next Move
1. Re-read head `core/events/netlink.go` around the new/changed functions (emit ~lines 650–760, interfaceAttributes/overlayToolsInterface ~860–934) to confirm exact behavior of the delete path and rename conversion before recording findings.
2. Confirm remaining checks: grep for other `sendInterfaceEvent`/`emit` callers repo-wide, skim `docs/manual/clabernetes/runtime.md` events section for docs impact of rename (delete+create) behavior, then compose findings (wasted interfaceAttributes call P4; stale `since` window / missing `ponytail:` comment P4; untested positive reportStitchMarks path as coverage note; pre-existing unreported-link deletes) and return the trusted result schema with the source-only limitation disclosed.

## Relevant Files
- `/source/standards.json` — lists the two governing rule files.
- `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (simplicity first, surgical changes, ponytail ceiling-comment rule).
- `/source/diff.txt`, `/source/manifest.json` — the two changed paths and snapshot inventory.
- `/source/head/core/events/netlink.go` — main change: `reported` map, `reportedInterface`, `stitchMarkWindow`, `emit`/`emitStats`/`track`/`reportStitchMarks`, `sendInterfaceEvent`.
- `/source/base/core/events/netlink.go` — pre-change version for diff comparison (emitInterfaceEvent/emitInterfaceStatsEvent with nil-container guard).
- `/source/head/core/events/netlink_watch_test.go` — updated tests (`TestReportStitchMarksLeavesUnmarkedLinks`, `TestEmitReportsRenamedLinkDeleted`, `TestEmitStatsReportsRenamedLinkFirst`).
- `/source/head/core/events/netlink_test.go` — `TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched`.
- `/source/head/links/link_veth_stitched.go` — `ToolsInterface` (lines ~299–302) used by `overlayToolsInterface`.
- `/source/head/core/netem.go` (line 97), `/source/head/core/list.go` (line 176) — other `ToolsInterface` callers.
- `/source/head/docs/cmd/events.md`, `/source/head/docs/manual/clabernetes/runtime.md` — docs describing interface events; check for needed updates on rename behavior.
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46f6ac6001kVtSwkVNSlEnO0",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f24fd0016TiilkMxPchYE2",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 16376,
    "input": 14592,
    "output": 1775,
    "reasoning": 9,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46f24fd0016TiilkMxPchYE2",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565416189,
    "completed": 1794565434059
  },
  "parentID": "msg_1d46f24e90018l7Tw4fHeU6LjX",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 16376,
    "input": 14592,
    "output": 1775,
    "reasoning": 9,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 14
Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.
Message metadata
{
  "role": "user",
  "id": "msg_1d46f6ace001VpF1gWj071crQT",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565434062
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 15
step-start
{
  "type": "step-start",
  "id": "prt_1d46f72dc001UNH26L21SwUnXS",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f6ad5001AQ0jOgyR8B4o8C"
}
Reasoning
I have completed the investigation. Let me verify a couple of remaining details before finalizing:

1. Re-read the head netlink.go emit/track/reportStitchMarks sections in full to confirm exact behavior (I've seen most of it via grep, but let me do one final read of the key sections to cite exact line numbers).
2. Then compose the review.

Let me read head netlink.go around lines 600-780 (emit/track) and 860-1000 (interfaceAttributes/overlayToolsInterface/sendInterfaceEvent), plus the diff to get exact line ranges.

Actually I've done most of this per the summary. Let me do a final confirmation read of the changed regions so line anchors are exact.
Let me do the final confirmation reads of the changed regions to anchor findings precisely.
read · completed

Input

{
  "filePath": "/source/head/core/events/netlink.go",
  "limit": 175,
  "offset": 640
}

Output

<path>/source/head/core/events/netlink.go</path>
<type>file</type>
<content>
640: 			snapshot.Corruption = 0
641: 		}
642: 
643: 		if !snapshot.equal(previous) {
644: 			states[idx] = snapshot
645: 			w.emit(registry, "update", snapshot)
646: 		}
647: 	}
648: }
649: 
650: // reportStitchMarks reports the links whose host-side stitch interface got
651: // marked after their last event. Only veths reported under their own name
652: // shortly before are looked at: the node's end of a veth-stitch link is a veth
653: // and is marked while its lab deploys.
654: func (w *netlinkWatcher) reportStitchMarks(
655: 	states map[int]ifaceSnapshot,
656: 	registry *netlinkRegistry,
657: ) {
658: 	for idx, snapshot := range states {
659: 		reported, ok := w.reported[idx]
660: 		if !ok || snapshot.Type != "veth" ||
661: 			reported.attributes["ifname"] != snapshot.Name ||
662: 			time.Since(reported.since) > stitchMarkWindow {
663: 			continue
664: 		}
665: 
666: 		if interfaceAttributes(w.container, snapshot)["ifname"] != snapshot.Name {
667: 			w.emit(registry, "update", snapshot)
668: 		}
669: 	}
670: }
671: 
672: // emit reports an event of a link. A deletion names the link as it was last
673: // reported. A link reported under another name before, such as the node's own
674: // interface until its stitch interface got marked, is first reported deleted
675: // under that name, so that clients do not keep both; it is then new to them.
676: func (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {
677: 	if w.container == nil {
678: 		return
679: 	}
680: 
681: 	if action == "delete" {
682: 		attributes := interfaceAttributes(w.container, snapshot)
683: 		if previous, ok := w.reported[snapshot.Index]; ok {
684: 			attributes = previous.attributes
685: 		}
686: 
687: 		delete(w.reported, snapshot.Index)
688: 		registry.sendInterfaceEvent(w.container, action, attributes, time.Now())
689: 
690: 		return
691: 	}
692: 
693: 	attributes := interfaceAttributes(w.container, snapshot)
694: 	if w.track(registry, snapshot.Index, attributes) && action == "update" {
695: 		action = "create"
696: 	}
697: 
698: 	registry.sendInterfaceEvent(w.container, action, attributes, time.Now())
699: }
700: 
701: // emitStats reports the counters of a link, under the name emit reports it.
702: func (w *netlinkWatcher) emitStats(
703: 	registry *netlinkRegistry,
704: 	snapshot ifaceSnapshot,
705: 	metrics ifaceStatsMetrics,
706: ) {
707: 	if !registry.includeStats || w.container == nil || !snapshot.HasStats {
708: 		return
709: 	}
710: 
711: 	attributes := interfaceAttributes(w.container, snapshot)
712: 	if w.track(registry, snapshot.Index, attributes) {
713: 		registry.sendInterfaceEvent(
714: 			w.container,
715: 			"create",
716: 			maps.Clone(attributes),
717: 			metrics.Timestamp,
718: 		)
719: 	}
720: 
721: 	interfaceStatsAttributes(attributes, metrics)
722: 	registry.sendInterfaceEvent(w.container, "stats", attributes, metrics.Timestamp)
723: }
724: 
725: // track records what the link at index is reported as. When it was reported
726: // under another name before, it reports that name deleted and returns true.
727: func (w *netlinkWatcher) track(
728: 	registry *netlinkRegistry,
729: 	index int,
730: 	attributes map[string]string,
731: ) bool {
732: 	if w.reported == nil {
733: 		w.reported = make(map[int]reportedInterface)
734: 	}
735: 
736: 	previous, known := w.reported[index]
737: 
738: 	since := time.Now()
739: 	if known {
740: 		since = previous.since
741: 	}
742: 
743: 	w.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}
744: 
745: 	if !known || previous.attributes["ifname"] == attributes["ifname"] {
746: 		return false
747: 	}
748: 
749: 	registry.sendInterfaceEvent(w.container, "delete", previous.attributes, time.Now())
750: 
751: 	return true
752: }
753: 
754: func firstContainerName(container *clabruntime.GenericContainer) string {
755: 	if container == nil || len(container.Names) == 0 {
756: 		return ""
757: 	}
758: 
759: 	return container.Names[0]
760: }
761: 
762: func containerLabel(container *clabruntime.GenericContainer) string {
763: 	if container == nil || container.Labels == nil {
764: 		return ""
765: 	}
766: 
767: 	return container.Labels[clabconstants.Containerlab]
768: }
769: 
770: // interfaceSnapshotAttributes are the attributes every interface event reports for the
771: // interface itself.
772: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {
773: 	attributes := map[string]string{
774: 		"ifname": snapshot.Name,
775: 		"index":  strconv.Itoa(snapshot.Index),
776: 		"mtu":    strconv.Itoa(snapshot.MTU),
777: 		"state":  snapshot.OperState,
778: 		"type":   snapshot.Type,
779: 	}
780: 
781: 	if snapshot.Alias != "" {
782: 		attributes["alias"] = snapshot.Alias
783: 	}
784: 
785: 	if snapshot.MAC != "" {
786: 		attributes["mac"] = snapshot.MAC
787: 	}
788: 
789: 	return attributes
790: }
791: 
792: // interfaceStatsAttributes adds the counters and rates of a stats event.
793: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {
794: 	attributes["rx_bytes"] = strconv.FormatUint(metrics.RxBytes, 10)
795: 	attributes["tx_bytes"] = strconv.FormatUint(metrics.TxBytes, 10)
796: 	attributes["rx_packets"] = strconv.FormatUint(metrics.RxPackets, 10)
797: 	attributes["tx_packets"] = strconv.FormatUint(metrics.TxPackets, 10)
798: 	attributes["rx_bps"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)
799: 	attributes["tx_bps"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)
800: 	attributes["rx_pps"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)
801: 	attributes["tx_pps"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)
802: 	attributes["interval_seconds"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)
803: }
804: 
805: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those
806: // of the netlink interface events, for the node the runtime runs. Values the runtime could not
807: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.
808: func labRuntimeInterfaceAttributes(
809: 	lab, name string,
810: 	iface *clablabruntime.InterfaceEventData,
811: ) map[string]string {
812: 	attributes := interfaceSnapshotAttributes(ifaceSnapshot{
813: 		Index:     iface.Index,
814: 		Name:      iface.Name,

(Showing lines 640-814 of 1390. Use offset=815 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f7a550014oaAonkMyOmL9q",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f6ad5001AQ0jOgyR8B4o8C",
  "callID": "call_2c5c932d0c414f7895bff946",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/netlink.go",
      "limit": 175,
      "offset": 640
    },
    "output": "<path>/source/head/core/events/netlink.go</path>\n<type>file</type>\n<content>\n640: \t\t\tsnapshot.Corruption = 0\n641: \t\t}\n642: \n643: \t\tif !snapshot.equal(previous) {\n644: \t\t\tstates[idx] = snapshot\n645: \t\t\tw.emit(registry, \"update\", snapshot)\n646: \t\t}\n647: \t}\n648: }\n649: \n650: // reportStitchMarks reports the links whose host-side stitch interface got\n651: // marked after their last event. Only veths reported under their own name\n652: // shortly before are looked at: the node's end of a veth-stitch link is a veth\n653: // and is marked while its lab deploys.\n654: func (w *netlinkWatcher) reportStitchMarks(\n655: \tstates map[int]ifaceSnapshot,\n656: \tregistry *netlinkRegistry,\n657: ) {\n658: \tfor idx, snapshot := range states {\n659: \t\treported, ok := w.reported[idx]\n660: \t\tif !ok || snapshot.Type != \"veth\" ||\n661: \t\t\treported.attributes[\"ifname\"] != snapshot.Name ||\n662: \t\t\ttime.Since(reported.since) > stitchMarkWindow {\n663: \t\t\tcontinue\n664: \t\t}\n665: \n666: \t\tif interfaceAttributes(w.container, snapshot)[\"ifname\"] != snapshot.Name {\n667: \t\t\tw.emit(registry, \"update\", snapshot)\n668: \t\t}\n669: \t}\n670: }\n671: \n672: // emit reports an event of a link. A deletion names the link as it was last\n673: // reported. A link reported under another name before, such as the node's own\n674: // interface until its stitch interface got marked, is first reported deleted\n675: // under that name, so that clients do not keep both; it is then new to them.\n676: func (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {\n677: \tif w.container == nil {\n678: \t\treturn\n679: \t}\n680: \n681: \tif action == \"delete\" {\n682: \t\tattributes := interfaceAttributes(w.container, snapshot)\n683: \t\tif previous, ok := w.reported[snapshot.Index]; ok {\n684: \t\t\tattributes = previous.attributes\n685: \t\t}\n686: \n687: \t\tdelete(w.reported, snapshot.Index)\n688: \t\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n689: \n690: \t\treturn\n691: \t}\n692: \n693: \tattributes := interfaceAttributes(w.container, snapshot)\n694: \tif w.track(registry, snapshot.Index, attributes) && action == \"update\" {\n695: \t\taction = \"create\"\n696: \t}\n697: \n698: \tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n699: }\n700: \n701: // emitStats reports the counters of a link, under the name emit reports it.\n702: func (w *netlinkWatcher) emitStats(\n703: \tregistry *netlinkRegistry,\n704: \tsnapshot ifaceSnapshot,\n705: \tmetrics ifaceStatsMetrics,\n706: ) {\n707: \tif !registry.includeStats || w.container == nil || !snapshot.HasStats {\n708: \t\treturn\n709: \t}\n710: \n711: \tattributes := interfaceAttributes(w.container, snapshot)\n712: \tif w.track(registry, snapshot.Index, attributes) {\n713: \t\tregistry.sendInterfaceEvent(\n714: \t\t\tw.container,\n715: \t\t\t\"create\",\n716: \t\t\tmaps.Clone(attributes),\n717: \t\t\tmetrics.Timestamp,\n718: \t\t)\n719: \t}\n720: \n721: \tinterfaceStatsAttributes(attributes, metrics)\n722: \tregistry.sendInterfaceEvent(w.container, \"stats\", attributes, metrics.Timestamp)\n723: }\n724: \n725: // track records what the link at index is reported as. When it was reported\n726: // under another name before, it reports that name deleted and returns true.\n727: func (w *netlinkWatcher) track(\n728: \tregistry *netlinkRegistry,\n729: \tindex int,\n730: \tattributes map[string]string,\n731: ) bool {\n732: \tif w.reported == nil {\n733: \t\tw.reported = make(map[int]reportedInterface)\n734: \t}\n735: \n736: \tprevious, known := w.reported[index]\n737: \n738: \tsince := time.Now()\n739: \tif known {\n740: \t\tsince = previous.since\n741: \t}\n742: \n743: \tw.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}\n744: \n745: \tif !known || previous.attributes[\"ifname\"] == attributes[\"ifname\"] {\n746: \t\treturn false\n747: \t}\n748: \n749: \tregistry.sendInterfaceEvent(w.container, \"delete\", previous.attributes, time.Now())\n750: \n751: \treturn true\n752: }\n753: \n754: func firstContainerName(container *clabruntime.GenericContainer) string {\n755: \tif container == nil || len(container.Names) == 0 {\n756: \t\treturn \"\"\n757: \t}\n758: \n759: \treturn container.Names[0]\n760: }\n761: \n762: func containerLabel(container *clabruntime.GenericContainer) string {\n763: \tif container == nil || container.Labels == nil {\n764: \t\treturn \"\"\n765: \t}\n766: \n767: \treturn container.Labels[clabconstants.Containerlab]\n768: }\n769: \n770: // interfaceSnapshotAttributes are the attributes every interface event reports for the\n771: // interface itself.\n772: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n773: \tattributes := map[string]string{\n774: \t\t\"ifname\": snapshot.Name,\n775: \t\t\"index\":  strconv.Itoa(snapshot.Index),\n776: \t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n777: \t\t\"state\":  snapshot.OperState,\n778: \t\t\"type\":   snapshot.Type,\n779: \t}\n780: \n781: \tif snapshot.Alias != \"\" {\n782: \t\tattributes[\"alias\"] = snapshot.Alias\n783: \t}\n784: \n785: \tif snapshot.MAC != \"\" {\n786: \t\tattributes[\"mac\"] = snapshot.MAC\n787: \t}\n788: \n789: \treturn attributes\n790: }\n791: \n792: // interfaceStatsAttributes adds the counters and rates of a stats event.\n793: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n794: \tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n795: \tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n796: \tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n797: \tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n798: \tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n799: \tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n800: \tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n801: \tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n802: \tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n803: }\n804: \n805: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n806: // of the netlink interface events, for the node the runtime runs. Values the runtime could not\n807: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.\n808: func labRuntimeInterfaceAttributes(\n809: \tlab, name string,\n810: \tiface *clablabruntime.InterfaceEventData,\n811: ) map[string]string {\n812: \tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n813: \t\tIndex:     iface.Index,\n814: \t\tName:      iface.Name,\n\n(Showing lines 640-814 of 1390. Use offset=815 to continue.)\n</content>",
    "title": "source/head/core/events/netlink.go",
    "metadata": {
      "preview": "\t\t\tsnapshot.Corruption = 0\n\t\t}\n\n\t\tif !snapshot.equal(previous) {\n\t\t\tstates[idx] = snapshot\n\t\t\tw.emit(registry, \"update\", snapshot)\n\t\t}\n\t}\n}\n\n// reportStitchMarks reports the links whose host-side stitch interface got\n// marked after their last event. Only veths reported under their own name\n// shortly before are looked at: the node's end of a veth-stitch link is a veth\n// and is marked while its lab deploys.\nfunc (w *netlinkWatcher) reportStitchMarks(\n\tstates map[int]ifaceSnapshot,\n\tregistry *netlinkRegistry,\n) {\n\tfor idx, snapshot := range states {\n\t\treported, ok := w.reported[idx]",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/netlink.go",
        "text": "\t\t\tsnapshot.Corruption = 0\n\t\t}\n\n\t\tif !snapshot.equal(previous) {\n\t\t\tstates[idx] = snapshot\n\t\t\tw.emit(registry, \"update\", snapshot)\n\t\t}\n\t}\n}\n\n// reportStitchMarks reports the links whose host-side stitch interface got\n// marked after their last event. Only veths reported under their own name\n// shortly before are looked at: the node's end of a veth-stitch link is a veth\n// and is marked while its lab deploys.\nfunc (w *netlinkWatcher) reportStitchMarks(\n\tstates map[int]ifaceSnapshot,\n\tregistry *netlinkRegistry,\n) {\n\tfor idx, snapshot := range states {\n\t\treported, ok := w.reported[idx]\n\t\tif !ok || snapshot.Type != \"veth\" ||\n\t\t\treported.attributes[\"ifname\"] != snapshot.Name ||\n\t\t\ttime.Since(reported.since) > stitchMarkWindow {\n\t\t\tcontinue\n\t\t}\n\n\t\tif interfaceAttributes(w.container, snapshot)[\"ifname\"] != snapshot.Name {\n\t\t\tw.emit(registry, \"update\", snapshot)\n\t\t}\n\t}\n}\n\n// emit reports an event of a link. A deletion names the link as it was last\n// reported. A link reported under another name before, such as the node's own\n// interface until its stitch interface got marked, is first reported deleted\n// under that name, so that clients do not keep both; it is then new to them.\nfunc (w *netlinkWatcher) emit(registry *netlinkRegistry, action string, snapshot ifaceSnapshot) {\n\tif w.container == nil {\n\t\treturn\n\t}\n\n\tif action == \"delete\" {\n\t\tattributes := interfaceAttributes(w.container, snapshot)\n\t\tif previous, ok := w.reported[snapshot.Index]; ok {\n\t\t\tattributes = previous.attributes\n\t\t}\n\n\t\tdelete(w.reported, snapshot.Index)\n\t\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n\n\t\treturn\n\t}\n\n\tattributes := interfaceAttributes(w.container, snapshot)\n\tif w.track(registry, snapshot.Index, attributes) && action == \"update\" {\n\t\taction = \"create\"\n\t}\n\n\tregistry.sendInterfaceEvent(w.container, action, attributes, time.Now())\n}\n\n// emitStats reports the counters of a link, under the name emit reports it.\nfunc (w *netlinkWatcher) emitStats(\n\tregistry *netlinkRegistry,\n\tsnapshot ifaceSnapshot,\n\tmetrics ifaceStatsMetrics,\n) {\n\tif !registry.includeStats || w.container == nil || !snapshot.HasStats {\n\t\treturn\n\t}\n\n\tattributes := interfaceAttributes(w.container, snapshot)\n\tif w.track(registry, snapshot.Index, attributes) {\n\t\tregistry.sendInterfaceEvent(\n\t\t\tw.container,\n\t\t\t\"create\",\n\t\t\tmaps.Clone(attributes),\n\t\t\tmetrics.Timestamp,\n\t\t)\n\t}\n\n\tinterfaceStatsAttributes(attributes, metrics)\n\tregistry.sendInterfaceEvent(w.container, \"stats\", attributes, metrics.Timestamp)\n}\n\n// track records what the link at index is reported as. When it was reported\n// under another name before, it reports that name deleted and returns true.\nfunc (w *netlinkWatcher) track(\n\tregistry *netlinkRegistry,\n\tindex int,\n\tattributes map[string]string,\n) bool {\n\tif w.reported == nil {\n\t\tw.reported = make(map[int]reportedInterface)\n\t}\n\n\tprevious, known := w.reported[index]\n\n\tsince := time.Now()\n\tif known {\n\t\tsince = previous.since\n\t}\n\n\tw.reported[index] = reportedInterface{attributes: maps.Clone(attributes), since: since}\n\n\tif !known || previous.attributes[\"ifname\"] == attributes[\"ifname\"] {\n\t\treturn false\n\t}\n\n\tregistry.sendInterfaceEvent(w.container, \"delete\", previous.attributes, time.Now())\n\n\treturn true\n}\n\nfunc firstContainerName(container *clabruntime.GenericContainer) string {\n\tif container == nil || len(container.Names) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn container.Names[0]\n}\n\nfunc containerLabel(container *clabruntime.GenericContainer) string {\n\tif container == nil || container.Labels == nil {\n\t\treturn \"\"\n\t}\n\n\treturn container.Labels[clabconstants.Containerlab]\n}\n\n// interfaceSnapshotAttributes are the attributes every interface event reports for the\n// interface itself.\nfunc interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n\tattributes := map[string]string{\n\t\t\"ifname\": snapshot.Name,\n\t\t\"index\":  strconv.Itoa(snapshot.Index),\n\t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n\t\t\"state\":  snapshot.OperState,\n\t\t\"type\":   snapshot.Type,\n\t}\n\n\tif snapshot.Alias != \"\" {\n\t\tattributes[\"alias\"] = snapshot.Alias\n\t}\n\n\tif snapshot.MAC != \"\" {\n\t\tattributes[\"mac\"] = snapshot.MAC\n\t}\n\n\treturn attributes\n}\n\n// interfaceStatsAttributes adds the counters and rates of a stats event.\nfunc interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n}\n\n// labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n// of the netlink interface events, for the node the runtime runs. Values the runtime could not\n// read (no index or MTU without a shell in the node) are left out rather than reported as 0.\nfunc labRuntimeInterfaceAttributes(\n\tlab, name string,\n\tiface *clablabruntime.InterfaceEventData,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n\t\tIndex:     iface.Index,\n\t\tName:      iface.Name,",
        "lineStart": 640,
        "lineEnd": 814,
        "totalLines": 1390,
        "truncated": true
      }
    },
    "time": {
      "start": 1794565438043,
      "end": 1794565438059
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/events/netlink.go",
  "limit": 130,
  "offset": 880
}

Output

<path>/source/head/core/events/netlink.go</path>
<type>file</type>
<content>
880: 		if snapshot.Rate != 0 {
881: 			attributes["netem_rate"] = strconv.Itoa(snapshot.Rate) + "kbit"
882: 		}
883: 		if snapshot.Corruption != 0 {
884: 			attributes["netem_corruption"] = strconv.FormatFloat(
885: 				snapshot.Corruption,
886: 				'f',
887: 				2,
888: 				64,
889: 			) + "%"
890: 		}
891: 	}
892: 
893: 	return attributes
894: }
895: 
896: // overlayToolsInterface rewrites attributes to the host-side stitch interface
897: // when one exists, matching `inspect interfaces`.
898: func overlayToolsInterface(
899: 	container *clabruntime.GenericContainer,
900: 	attributes map[string]string,
901: ) {
902: 	if container == nil {
903: 		return
904: 	}
905: 
906: 	lab, node := clabcore.TopoIdentity(container.Labels)
907: 	if lab == "" || node == "" {
908: 		return
909: 	}
910: 
911: 	topoName := attributes["alias"]
912: 	if topoName == "" {
913: 		topoName = attributes["ifname"]
914: 	}
915: 
916: 	tools, ok := clablinks.ToolsInterface(lab, node, topoName)
917: 	if !ok {
918: 		return
919: 	}
920: 
921: 	snapshot := snapshotFromLink(tools)
922: 	attributes["ifname"] = snapshot.Name
923: 	attributes["alias"] = topoName
924: 	attributes["index"] = strconv.Itoa(snapshot.Index)
925: 	attributes["mtu"] = strconv.Itoa(snapshot.MTU)
926: 	attributes["state"] = snapshot.OperState
927: 	attributes["type"] = snapshot.Type
928: 
929: 	if snapshot.MAC != "" {
930: 		attributes["mac"] = snapshot.MAC
931: 	}
932: }
933: 
934: func (r *netlinkRegistry) sendInterfaceEvent(
935: 	container *clabruntime.GenericContainer,
936: 	action string,
937: 	attributes map[string]string,
938: 	timestamp time.Time,
939: ) {
940: 	event := aggregatedEvent{
941: 		Timestamp:   timestamp,
942: 		Type:        "interface",
943: 		Action:      action,
944: 		ActorID:     container.ShortID,
945: 		ActorName:   firstContainerName(container),
946: 		ActorFullID: container.ID,
947: 		Attributes:  attributes,
948: 	}
949: 
950: 	select {
951: 	case r.events <- event:
952: 	case <-r.ctx.Done():
953: 	}
954: }
955: 
956: func waitForNamespacePath(
957: 	ctx context.Context,
958: 	runtime clabruntime.ContainerRuntime,
959: 	containerID string,
960: ) (string, error) {
961: 	const (
962: 		attempts   = 5
963: 		retryDelay = 200 * time.Millisecond
964: 	)
965: 
966: 	var lastErr error
967: 
968: 	for i := 0; i < attempts; i++ {
969: 		nsPath, err := runtime.GetNSPath(ctx, containerID)
970: 		if err == nil && nsPath != "" {
971: 			return nsPath, nil
972: 		}
973: 
974: 		if err != nil {
975: 			lastErr = err
976: 		}
977: 
978: 		select {
979: 		case <-time.After(retryDelay):
980: 		case <-ctx.Done():
981: 			return "", ctx.Err()
982: 		}
983: 	}
984: 
985: 	if lastErr != nil {
986: 		return "", lastErr
987: 	}
988: 
989: 	return "", fmt.Errorf("namespace path not ready for container %s", containerID)
990: }
991: 
992: func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {
993: 	if netHandle == nil {
994: 		return nil, fmt.Errorf("netlink handle is nil")
995: 	}
996: 
997: 	links, err := netHandle.LinkList()
998: 	if err != nil {
999: 		return nil, fmt.Errorf("unable to list links: %w", err)
1000: 	}
1001: 
1002: 	states := make(map[int]ifaceSnapshot, len(links))
1003: 	for _, link := range links {
1004: 		snapshot := snapshotFromLink(link)
1005: 		states[snapshot.Index] = snapshot
1006: 	}
1007: 
1008: 	return states, nil
1009: }

(Showing lines 880-1009 of 1390. Use offset=1010 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f7ad1001IPLZBsTSjhMGt8",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f6ad5001AQ0jOgyR8B4o8C",
  "callID": "call_de709ce3a1ec482283d5c49f",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/netlink.go",
      "limit": 130,
      "offset": 880
    },
    "output": "<path>/source/head/core/events/netlink.go</path>\n<type>file</type>\n<content>\n880: \t\tif snapshot.Rate != 0 {\n881: \t\t\tattributes[\"netem_rate\"] = strconv.Itoa(snapshot.Rate) + \"kbit\"\n882: \t\t}\n883: \t\tif snapshot.Corruption != 0 {\n884: \t\t\tattributes[\"netem_corruption\"] = strconv.FormatFloat(\n885: \t\t\t\tsnapshot.Corruption,\n886: \t\t\t\t'f',\n887: \t\t\t\t2,\n888: \t\t\t\t64,\n889: \t\t\t) + \"%\"\n890: \t\t}\n891: \t}\n892: \n893: \treturn attributes\n894: }\n895: \n896: // overlayToolsInterface rewrites attributes to the host-side stitch interface\n897: // when one exists, matching `inspect interfaces`.\n898: func overlayToolsInterface(\n899: \tcontainer *clabruntime.GenericContainer,\n900: \tattributes map[string]string,\n901: ) {\n902: \tif container == nil {\n903: \t\treturn\n904: \t}\n905: \n906: \tlab, node := clabcore.TopoIdentity(container.Labels)\n907: \tif lab == \"\" || node == \"\" {\n908: \t\treturn\n909: \t}\n910: \n911: \ttopoName := attributes[\"alias\"]\n912: \tif topoName == \"\" {\n913: \t\ttopoName = attributes[\"ifname\"]\n914: \t}\n915: \n916: \ttools, ok := clablinks.ToolsInterface(lab, node, topoName)\n917: \tif !ok {\n918: \t\treturn\n919: \t}\n920: \n921: \tsnapshot := snapshotFromLink(tools)\n922: \tattributes[\"ifname\"] = snapshot.Name\n923: \tattributes[\"alias\"] = topoName\n924: \tattributes[\"index\"] = strconv.Itoa(snapshot.Index)\n925: \tattributes[\"mtu\"] = strconv.Itoa(snapshot.MTU)\n926: \tattributes[\"state\"] = snapshot.OperState\n927: \tattributes[\"type\"] = snapshot.Type\n928: \n929: \tif snapshot.MAC != \"\" {\n930: \t\tattributes[\"mac\"] = snapshot.MAC\n931: \t}\n932: }\n933: \n934: func (r *netlinkRegistry) sendInterfaceEvent(\n935: \tcontainer *clabruntime.GenericContainer,\n936: \taction string,\n937: \tattributes map[string]string,\n938: \ttimestamp time.Time,\n939: ) {\n940: \tevent := aggregatedEvent{\n941: \t\tTimestamp:   timestamp,\n942: \t\tType:        \"interface\",\n943: \t\tAction:      action,\n944: \t\tActorID:     container.ShortID,\n945: \t\tActorName:   firstContainerName(container),\n946: \t\tActorFullID: container.ID,\n947: \t\tAttributes:  attributes,\n948: \t}\n949: \n950: \tselect {\n951: \tcase r.events <- event:\n952: \tcase <-r.ctx.Done():\n953: \t}\n954: }\n955: \n956: func waitForNamespacePath(\n957: \tctx context.Context,\n958: \truntime clabruntime.ContainerRuntime,\n959: \tcontainerID string,\n960: ) (string, error) {\n961: \tconst (\n962: \t\tattempts   = 5\n963: \t\tretryDelay = 200 * time.Millisecond\n964: \t)\n965: \n966: \tvar lastErr error\n967: \n968: \tfor i := 0; i < attempts; i++ {\n969: \t\tnsPath, err := runtime.GetNSPath(ctx, containerID)\n970: \t\tif err == nil && nsPath != \"\" {\n971: \t\t\treturn nsPath, nil\n972: \t\t}\n973: \n974: \t\tif err != nil {\n975: \t\t\tlastErr = err\n976: \t\t}\n977: \n978: \t\tselect {\n979: \t\tcase <-time.After(retryDelay):\n980: \t\tcase <-ctx.Done():\n981: \t\t\treturn \"\", ctx.Err()\n982: \t\t}\n983: \t}\n984: \n985: \tif lastErr != nil {\n986: \t\treturn \"\", lastErr\n987: \t}\n988: \n989: \treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n990: }\n991: \n992: func snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n993: \tif netHandle == nil {\n994: \t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n995: \t}\n996: \n997: \tlinks, err := netHandle.LinkList()\n998: \tif err != nil {\n999: \t\treturn nil, fmt.Errorf(\"unable to list links: %w\", err)\n1000: \t}\n1001: \n1002: \tstates := make(map[int]ifaceSnapshot, len(links))\n1003: \tfor _, link := range links {\n1004: \t\tsnapshot := snapshotFromLink(link)\n1005: \t\tstates[snapshot.Index] = snapshot\n1006: \t}\n1007: \n1008: \treturn states, nil\n1009: }\n\n(Showing lines 880-1009 of 1390. Use offset=1010 to continue.)\n</content>",
    "title": "source/head/core/events/netlink.go",
    "metadata": {
      "preview": "\t\tif snapshot.Rate != 0 {\n\t\t\tattributes[\"netem_rate\"] = strconv.Itoa(snapshot.Rate) + \"kbit\"\n\t\t}\n\t\tif snapshot.Corruption != 0 {\n\t\t\tattributes[\"netem_corruption\"] = strconv.FormatFloat(\n\t\t\t\tsnapshot.Corruption,\n\t\t\t\t'f',\n\t\t\t\t2,\n\t\t\t\t64,\n\t\t\t) + \"%\"\n\t\t}\n\t}\n\n\treturn attributes\n}\n\n// overlayToolsInterface rewrites attributes to the host-side stitch interface\n// when one exists, matching `inspect interfaces`.\nfunc overlayToolsInterface(\n\tcontainer *clabruntime.GenericContainer,",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/netlink.go",
        "text": "\t\tif snapshot.Rate != 0 {\n\t\t\tattributes[\"netem_rate\"] = strconv.Itoa(snapshot.Rate) + \"kbit\"\n\t\t}\n\t\tif snapshot.Corruption != 0 {\n\t\t\tattributes[\"netem_corruption\"] = strconv.FormatFloat(\n\t\t\t\tsnapshot.Corruption,\n\t\t\t\t'f',\n\t\t\t\t2,\n\t\t\t\t64,\n\t\t\t) + \"%\"\n\t\t}\n\t}\n\n\treturn attributes\n}\n\n// overlayToolsInterface rewrites attributes to the host-side stitch interface\n// when one exists, matching `inspect interfaces`.\nfunc overlayToolsInterface(\n\tcontainer *clabruntime.GenericContainer,\n\tattributes map[string]string,\n) {\n\tif container == nil {\n\t\treturn\n\t}\n\n\tlab, node := clabcore.TopoIdentity(container.Labels)\n\tif lab == \"\" || node == \"\" {\n\t\treturn\n\t}\n\n\ttopoName := attributes[\"alias\"]\n\tif topoName == \"\" {\n\t\ttopoName = attributes[\"ifname\"]\n\t}\n\n\ttools, ok := clablinks.ToolsInterface(lab, node, topoName)\n\tif !ok {\n\t\treturn\n\t}\n\n\tsnapshot := snapshotFromLink(tools)\n\tattributes[\"ifname\"] = snapshot.Name\n\tattributes[\"alias\"] = topoName\n\tattributes[\"index\"] = strconv.Itoa(snapshot.Index)\n\tattributes[\"mtu\"] = strconv.Itoa(snapshot.MTU)\n\tattributes[\"state\"] = snapshot.OperState\n\tattributes[\"type\"] = snapshot.Type\n\n\tif snapshot.MAC != \"\" {\n\t\tattributes[\"mac\"] = snapshot.MAC\n\t}\n}\n\nfunc (r *netlinkRegistry) sendInterfaceEvent(\n\tcontainer *clabruntime.GenericContainer,\n\taction string,\n\tattributes map[string]string,\n\ttimestamp time.Time,\n) {\n\tevent := aggregatedEvent{\n\t\tTimestamp:   timestamp,\n\t\tType:        \"interface\",\n\t\tAction:      action,\n\t\tActorID:     container.ShortID,\n\t\tActorName:   firstContainerName(container),\n\t\tActorFullID: container.ID,\n\t\tAttributes:  attributes,\n\t}\n\n\tselect {\n\tcase r.events <- event:\n\tcase <-r.ctx.Done():\n\t}\n}\n\nfunc waitForNamespacePath(\n\tctx context.Context,\n\truntime clabruntime.ContainerRuntime,\n\tcontainerID string,\n) (string, error) {\n\tconst (\n\t\tattempts   = 5\n\t\tretryDelay = 200 * time.Millisecond\n\t)\n\n\tvar lastErr error\n\n\tfor i := 0; i < attempts; i++ {\n\t\tnsPath, err := runtime.GetNSPath(ctx, containerID)\n\t\tif err == nil && nsPath != \"\" {\n\t\t\treturn nsPath, nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlastErr = err\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(retryDelay):\n\t\tcase <-ctx.Done():\n\t\t\treturn \"\", ctx.Err()\n\t\t}\n\t}\n\n\tif lastErr != nil {\n\t\treturn \"\", lastErr\n\t}\n\n\treturn \"\", fmt.Errorf(\"namespace path not ready for container %s\", containerID)\n}\n\nfunc snapshotInterfaces(netHandle *netlink.Handle) (map[int]ifaceSnapshot, error) {\n\tif netHandle == nil {\n\t\treturn nil, fmt.Errorf(\"netlink handle is nil\")\n\t}\n\n\tlinks, err := netHandle.LinkList()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to list links: %w\", err)\n\t}\n\n\tstates := make(map[int]ifaceSnapshot, len(links))\n\tfor _, link := range links {\n\t\tsnapshot := snapshotFromLink(link)\n\t\tstates[snapshot.Index] = snapshot\n\t}\n\n\treturn states, nil\n}",
        "lineStart": 880,
        "lineEnd": 1009,
        "totalLines": 1390,
        "truncated": true
      }
    },
    "time": {
      "start": 1794565438167,
      "end": 1794565438177
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46f7ae3001kfUqw9BZTgh0xs",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f6ad5001AQ0jOgyR8B4o8C",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 15928,
    "input": 15705,
    "output": 73,
    "reasoning": 150,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46f6ad5001AQ0jOgyR8B4o8C",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565434069,
    "completed": 1794565438183
  },
  "parentID": "msg_1d46f6ace001VpF1gWj071crQT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 15928,
    "input": 15705,
    "output": 73,
    "reasoning": 150,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 16
step-start
{
  "type": "step-start",
  "id": "prt_1d46f82640017j2ZXpg07T2pkm",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f7aec001SI9ScXtnFhM8mW"
}
Reasoning
One more check: the `interfaceAttributes` function definition (where it calls snapshotAttributes + overlayToolsInterface) to confirm the wasted call in emit's delete path and double-call in reportStitchMarks. Let me read lines ~815-880.
read · completed

Input

{
  "filePath": "/source/head/core/events/netlink.go",
  "limit": 45,
  "offset": 830
}

Output

<path>/source/head/core/events/netlink.go</path>
<type>file</type>
<content>
830: 	}
831: 	if name != "" {
832: 		attributes["name"] = name
833: 	}
834: 
835: 	if stats := iface.Stats; stats != nil {
836: 		interfaceStatsAttributes(attributes, ifaceStatsMetrics{
837: 			RxBytes:   stats.RxBytes,
838: 			TxBytes:   stats.TxBytes,
839: 			RxPackets: stats.RxPackets,
840: 			TxPackets: stats.TxPackets,
841: 			RxBps:     stats.RxBps,
842: 			TxBps:     stats.TxBps,
843: 			RxPps:     stats.RxPps,
844: 			TxPps:     stats.TxPps,
845: 			Interval:  stats.Interval,
846: 		})
847: 	}
848: 
849: 	return attributes
850: }
851: 
852: func interfaceAttributes(
853: 	container *clabruntime.GenericContainer,
854: 	snapshot ifaceSnapshot,
855: ) map[string]string {
856: 	attributes := interfaceSnapshotAttributes(snapshot)
857: 	attributes["origin"] = "netlink"
858: 
859: 	if lab := containerLabel(container); lab != "" {
860: 		attributes["lab"] = lab
861: 	}
862: 
863: 	if name := firstContainerName(container); name != "" {
864: 		attributes["name"] = name
865: 	}
866: 
867: 	overlayToolsInterface(container, attributes)
868: 
869: 	// Add netem attributes if present
870: 	if snapshot.HasNetem {
871: 		if snapshot.Delay != "" {
872: 			attributes["netem_delay"] = snapshot.Delay
873: 		}
874: 		if snapshot.Jitter != "" {

(Showing lines 830-874 of 1390. Use offset=875 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46f84e0001NZxqGXVsf1bn6l",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f7aec001SI9ScXtnFhM8mW",
  "callID": "call_32716fd9386244f7a8112585",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/netlink.go",
      "limit": 45,
      "offset": 830
    },
    "output": "<path>/source/head/core/events/netlink.go</path>\n<type>file</type>\n<content>\n830: \t}\n831: \tif name != \"\" {\n832: \t\tattributes[\"name\"] = name\n833: \t}\n834: \n835: \tif stats := iface.Stats; stats != nil {\n836: \t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n837: \t\t\tRxBytes:   stats.RxBytes,\n838: \t\t\tTxBytes:   stats.TxBytes,\n839: \t\t\tRxPackets: stats.RxPackets,\n840: \t\t\tTxPackets: stats.TxPackets,\n841: \t\t\tRxBps:     stats.RxBps,\n842: \t\t\tTxBps:     stats.TxBps,\n843: \t\t\tRxPps:     stats.RxPps,\n844: \t\t\tTxPps:     stats.TxPps,\n845: \t\t\tInterval:  stats.Interval,\n846: \t\t})\n847: \t}\n848: \n849: \treturn attributes\n850: }\n851: \n852: func interfaceAttributes(\n853: \tcontainer *clabruntime.GenericContainer,\n854: \tsnapshot ifaceSnapshot,\n855: ) map[string]string {\n856: \tattributes := interfaceSnapshotAttributes(snapshot)\n857: \tattributes[\"origin\"] = \"netlink\"\n858: \n859: \tif lab := containerLabel(container); lab != \"\" {\n860: \t\tattributes[\"lab\"] = lab\n861: \t}\n862: \n863: \tif name := firstContainerName(container); name != \"\" {\n864: \t\tattributes[\"name\"] = name\n865: \t}\n866: \n867: \toverlayToolsInterface(container, attributes)\n868: \n869: \t// Add netem attributes if present\n870: \tif snapshot.HasNetem {\n871: \t\tif snapshot.Delay != \"\" {\n872: \t\t\tattributes[\"netem_delay\"] = snapshot.Delay\n873: \t\t}\n874: \t\tif snapshot.Jitter != \"\" {\n\n(Showing lines 830-874 of 1390. Use offset=875 to continue.)\n</content>",
    "title": "source/head/core/events/netlink.go",
    "metadata": {
      "preview": "\t}\n\tif name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\tif stats := iface.Stats; stats != nil {\n\t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n\t\t\tRxBytes:   stats.RxBytes,\n\t\t\tTxBytes:   stats.TxBytes,\n\t\t\tRxPackets: stats.RxPackets,\n\t\t\tTxPackets: stats.TxPackets,\n\t\t\tRxBps:     stats.RxBps,\n\t\t\tTxBps:     stats.TxBps,\n\t\t\tRxPps:     stats.RxPps,\n\t\t\tTxPps:     stats.TxPps,\n\t\t\tInterval:  stats.Interval,\n\t\t})\n\t}\n\n\treturn attributes",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/netlink.go",
        "text": "\t}\n\tif name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\tif stats := iface.Stats; stats != nil {\n\t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n\t\t\tRxBytes:   stats.RxBytes,\n\t\t\tTxBytes:   stats.TxBytes,\n\t\t\tRxPackets: stats.RxPackets,\n\t\t\tTxPackets: stats.TxPackets,\n\t\t\tRxBps:     stats.RxBps,\n\t\t\tTxBps:     stats.TxBps,\n\t\t\tRxPps:     stats.RxPps,\n\t\t\tTxPps:     stats.TxPps,\n\t\t\tInterval:  stats.Interval,\n\t\t})\n\t}\n\n\treturn attributes\n}\n\nfunc interfaceAttributes(\n\tcontainer *clabruntime.GenericContainer,\n\tsnapshot ifaceSnapshot,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(snapshot)\n\tattributes[\"origin\"] = \"netlink\"\n\n\tif lab := containerLabel(container); lab != \"\" {\n\t\tattributes[\"lab\"] = lab\n\t}\n\n\tif name := firstContainerName(container); name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\toverlayToolsInterface(container, attributes)\n\n\t// Add netem attributes if present\n\tif snapshot.HasNetem {\n\t\tif snapshot.Delay != \"\" {\n\t\t\tattributes[\"netem_delay\"] = snapshot.Delay\n\t\t}\n\t\tif snapshot.Jitter != \"\" {",
        "lineStart": 830,
        "lineEnd": 874,
        "totalLines": 1390,
        "truncated": true
      }
    },
    "time": {
      "start": 1794565440742,
      "end": 1794565440763
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46f84ff001SaOih0KBIS6psN",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f7aec001SI9ScXtnFhM8mW",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 19266,
    "input": 3312,
    "output": 29,
    "reasoning": 53,
    "cache": {
      "read": 15872,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46f7aec001SI9ScXtnFhM8mW",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565438188,
    "completed": 1794565440772
  },
  "parentID": "msg_1d46f6ace001VpF1gWj071crQT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 19266,
    "input": 3312,
    "output": 29,
    "reasoning": 53,
    "cache": {
      "read": 15872,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 17
step-start
{
  "type": "step-start",
  "id": "prt_1d46f8c6e001jDRUMUSdvNzKom",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f850c0010YqzrLDvEm4ked"
}
Reasoning
All confirmed. Now let me also quickly check the `diff.txt` line ranges to anchor findings to head lines — I have the head file lines directly, which is what I'll anchor to.

Findings finalized:

1. **P4** — `emit` delete path computes `interfaceAttributes` before checking `w.reported`, discarding the result when a previous report exists (`netlink.go:682-685`). `interfaceAttributes` runs `overlayToolsInterface` → `clablinks.ToolsInterface` → `netlink.LinkByName` in the root netns. Every delete event of a tracked interface performs a wasted netlink lookup. Reorder to check `w.reported` first and only compute attributes when unknown.

2. **P3/P4** — `track` preserves the original `since` forever, and `reportStitchMarks` measures the stitch-mark window from the FIRST report of the link. Trigger: a veth-stitch link whose far-end altname is applied more than `stitchMarkWindow` (1 minute) after the node end was first reported — realistic when the opposite endpoint's container is slow to start (image pull) so stitching happens in `PostDeploy` long after the first node's interface was reported; also after a subscription outage longer than the window. Impact: the interface stays reported under the node-side name (`eth1`) instead of the stitch name; self-corrects only on a later node-side change or resubscribe. Also per ponytail rule, deliberate ceilings should carry a `ponytail:` comment naming the ceiling/upgrade path — the comment explains the mechanism but not the tradeoff. Suggest: either refresh `since` on each `track` call, document the ceiling with a `ponytail:` comment, or note the tradeoff. Actually, would refreshing `since` help the slow-deploy scenario? No — no events fire on the node side between deploy and mark. So the only correction is a wider window or documenting. I'll frame it as: window is measured from the first report; slow stitching (opposite endpoint deployed minutes later) is missed and never retried; recommend documenting the ceiling with a `ponytail:` comment and/or refreshing the window when the interface is polled (reportStitchMarks could bump since for links whose stitch doesn't exist yet... that changes semantics though — actually bumping `since` while polling would keep the window "hot" until the mark appears or a minute after the last poll; but the ticker polls every second so since would always be fresh → window becomes meaningless/infinite scanning. Hmm. Actually since is only bumped for links that pass the candidate filter — reported under own name. If we refresh on poll, all veth links stay candidates forever → every tick calls interfaceAttributes for every veth → expensive. So the one-minute window is a deliberate cost bound. So the honest suggestion is: keep the window but mark the ceiling with a `ponytail:` comment (per ponytail rule), and optionally note the residual gap. Severity: P4 (optional improvement; the PR strictly improves on base behavior).

Hmm wait — actually, is it P3? The prior behavior was: stitched links were reported under the stitch name only if the link changed after marking. The PR improves this. The residual miss in slow deploys means some stitched links still report under node names — same as base behavior, not a regression. So P4 is right.

3. **P4** — Docs: `docs/cmd/events.md` states interface notifications are emitted when a link "appears, disappears, or when its relevant properties change." The PR introduces re-reporting: a stitched link is now also re-reported (delete under the old name + create under the stitch name) without any property of the node-side link changing, when its host-side stitch interface gets marked. Consumers keyed on `ifname` will see delete+create pairs for the same logical interface. A short note in `docs/cmd/events.md` (and a `docs/rn/0.83.md` Miscellaneous bullet, since 0.83 is the unreleased release) would document it.

4. Coverage note: `reportStitchMarks`'s positive path (a link whose stitch got marked is re-reported) has no direct test; only the negative path is tested (`TestReportStitchMarksLeavesUnmarkedLinks`). The rename mechanism itself is covered indirectly through `emit`/`track` tests. Smallest check: a unit test with a fake stitch mark (as the other tests do) asserting delete+create is emitted for a within-window link.

Also verify: are there any other callers of removed `sendInterfaceEvent` (base) — I grepped earlier, all call sites are within netlink.go and guarded. Fine.

Severity table: two P4s and one P3? Let me reconsider finding 1 — wasted syscall per delete event. Every interface delete triggers one extra LinkByName (root ns) even when the link was previously reported. Cost: single netlink RTM_GETLINK roundtrip per delete event; trivial in absolute terms but avoidable and trivially fixable. P4.

Finding 2: P4 as reasoned.

Finding 3: P4 doc.

No P0-P3 findings. Coverage: complete = true? I've reviewed all changed paths, base comparison, callers, tests, docs. Source-only (no test execution) — disclose. I'd say coverage.complete = true with notes disclosing the source-only limitation and the untested positive reportStitchMarks path (that's a finding-adjacent coverage note — actually the test gap: should it be a finding? Review guidance item 6 says recommend smallest useful check for a concrete gap. The positive reportStitchMarks path is the core new logic and it's untested. I'd make it a P4 finding? Or coverage note. The instruction: "Verification: inspect whether relevant tests or runnable checks cover changed behavior... Recommend the smallest useful check for a concrete gap." The gap is concrete: the new `reportStitchMarks` positive path (emitting delete+create for a marked stitch) is not covered by any test; the mechanism is only tested through `emit`/`track` and the negative reportStitchMarks case. Since `reportStitchMarks` has nontrivial filtering logic (window, ifname comparison), an untested positive path is a real gap. I'll make it a P4 finding rather than just a coverage note, since it's actionable.

Also the harness in netlink_watch_test.go seems to support faked stitches (TestReportStitchMarksLeavesUnmarkedLinks exists), so adding a positive case is cheap.

Let me now check: does `TestReportStitchMarksLeavesUnmarkedLinks` use a fake stitch? Earlier summary says yes ("reported too long ago, are not reported again"). Fine.

One more consideration — the events doc line: let me confirm the exact wording in docs/cmd/events.md around line 32. From earlier read: "Interface notifications are emitted when a link appears, disappears, or when its relevant properties (such as its state or netem parameters) change." I'll anchor to docs/cmd/events.md L32.

Also should I check `docs/rn/0.83.md` Miscellaneous — the PR doesn't add an entry. The release-note-review rule only applies to changes under docs/rn/ (none). But recommending an rn entry for user-visible behavior is reasonable as part of the docs finding. I'll mention it briefly within the docs finding's suggestion, not as a separate finding.

Now write the final review. Locations (head):
- netlink.go L682-687 (wasted interfaceAttributes in delete path).
- netlink.go L650-670 + L736-743 (stitch window from first report).
- docs/cmd/events.md L32 (doc gap).
- netlink_watch_test.go L449-486 area (TestReportStitchMarksLeavesUnmarkedLinks — positive path missing). Actually the test starts at line ~449? From grep: line 449 `events := make(chan aggregatedEvent, 8)` within tests; TestReportStitchMarksLeavesUnmarkedLinks — I don't know its exact start line. Let me grep for it to get the line number.
grep · completed

Input

{
  "path": "/source/head/core/events/netlink_watch_test.go",
  "pattern": "^func Test"
}

Output

Found 18 matches
/source/head/core/events/labruntime_test.go:
  Line 10: func TestLabRuntimeEventStreamRequestScope(t *testing.T) {


/source/head/core/events/netlink_test.go:
  Line 11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {


/source/head/core/events/parity_test.go:
  Line 231: func TestContainerEventParity(t *testing.T) {

  Line 334: func TestContainerSnapshotParity(t *testing.T) {

  Line 359: func TestContainerStateUsesDockerVocabulary(t *testing.T) {

  Line 437: func TestInterfaceEventParity(t *testing.T) {

  Line 523: func TestInterfaceEventOmitsUnknownValues(t *testing.T) {

  Line 543: func TestLabRuntimeTopologyEventsKeepTheirAttributes(t *testing.T) {


/source/head/core/events/netlink_watch_test.go:
  Line 177: func TestNetlinkWatcherReportsExistingAndNewLinks(t *testing.T) {

  Line 208: func TestNetlinkWatcherReportsLinksAddedWhileStarting(t *testing.T) {

  Line 236: func TestNetlinkWatcherRetriesNamespaceLookup(t *testing.T) {

  Line 267: func TestNetlinkWatcherStopsAfterRetries(t *testing.T) {

  Line 288: func TestProcessExistingAfterResubscribe(t *testing.T) {

  Line 361: func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {

  Line 427: func TestEmitReportsRenamedLinkDeleted(t *testing.T) {

  Line 448: func TestEmitDeletesLinkAsLastReported(t *testing.T) {

  Line 469: func TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {

  Line 511: func TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46fd8cc001egUmFklUgCkf3P",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f850c0010YqzrLDvEm4ked",
  "callID": "call_fe4e50bf26cc4c73a232df19",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/core/events/netlink_watch_test.go",
      "pattern": "^func Test"
    },
    "output": "Found 18 matches\n/source/head/core/events/labruntime_test.go:\n  Line 10: func TestLabRuntimeEventStreamRequestScope(t *testing.T) {\n\n\n/source/head/core/events/netlink_test.go:\n  Line 11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {\n\n\n/source/head/core/events/parity_test.go:\n  Line 231: func TestContainerEventParity(t *testing.T) {\n\n  Line 334: func TestContainerSnapshotParity(t *testing.T) {\n\n  Line 359: func TestContainerStateUsesDockerVocabulary(t *testing.T) {\n\n  Line 437: func TestInterfaceEventParity(t *testing.T) {\n\n  Line 523: func TestInterfaceEventOmitsUnknownValues(t *testing.T) {\n\n  Line 543: func TestLabRuntimeTopologyEventsKeepTheirAttributes(t *testing.T) {\n\n\n/source/head/core/events/netlink_watch_test.go:\n  Line 177: func TestNetlinkWatcherReportsExistingAndNewLinks(t *testing.T) {\n\n  Line 208: func TestNetlinkWatcherReportsLinksAddedWhileStarting(t *testing.T) {\n\n  Line 236: func TestNetlinkWatcherRetriesNamespaceLookup(t *testing.T) {\n\n  Line 267: func TestNetlinkWatcherStopsAfterRetries(t *testing.T) {\n\n  Line 288: func TestProcessExistingAfterResubscribe(t *testing.T) {\n\n  Line 361: func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {\n\n  Line 427: func TestEmitReportsRenamedLinkDeleted(t *testing.T) {\n\n  Line 448: func TestEmitDeletesLinkAsLastReported(t *testing.T) {\n\n  Line 469: func TestEmitStatsReportsRenamedLinkFirst(t *testing.T) {\n\n  Line 511: func TestReportStitchMarksLeavesUnmarkedLinks(t *testing.T) {\n",
    "title": "^func Test",
    "metadata": {
      "matches": 18,
      "truncated": false
    },
    "time": {
      "start": 1794565462226,
      "end": 1794565462248
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/docs/cmd/events.md",
  "pattern": "Interface notifications"
}

Output

Found 1 matches
/source/head/docs/cmd/events.md:
  Line 32: - Interface notifications are emitted when a link appears, disappears, or when its relevant properties (operational state, MTU, alias, MAC address, type) change. Initial snapshots use the `snapshot` action when `--initial-state` is requested. When interface statistics are enabled the stream also includes `interface stats` updates with byte/packet counters and rate estimates.
Tool metadata
{
  "type": "tool",
  "id": "prt_1d46fd92f0012NgxlJLjb2TtSL",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f850c0010YqzrLDvEm4ked",
  "callID": "call_7a007c8b41c2448f97d2a3fe",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/docs/cmd/events.md",
      "pattern": "Interface notifications"
    },
    "output": "Found 1 matches\n/source/head/docs/cmd/events.md:\n  Line 32: - Interface notifications are emitted when a link appears, disappears, or when its relevant properties (operational state, MTU, alias, MAC address, type) change. Initial snapshots use the `snapshot` action when `--initial-state` is requested. When interface statistics are enabled the stream also includes `interface stats` updates with byte/packet counters and rate estimates.\n",
    "title": "Interface notifications",
    "metadata": {
      "matches": 1,
      "truncated": false
    },
    "time": {
      "start": 1794565462324,
      "end": 1794565462337
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1d46fd945001dALD5zZ3xoEwMv",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46f850c0010YqzrLDvEm4ked",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 21527,
    "input": 561,
    "output": 47,
    "reasoning": 1719,
    "cache": {
      "read": 19200,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46f850c0010YqzrLDvEm4ked",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565440780,
    "completed": 1794565462346
  },
  "parentID": "msg_1d46f6ace001VpF1gWj071crQT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 21527,
    "input": 561,
    "output": 47,
    "reasoning": 1719,
    "cache": {
      "read": 19200,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 18
step-start
{
  "type": "step-start",
  "id": "prt_1d46fe0c6001C9HNRzmX6tfQZj",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46fd9510016WBZEih108ioOd"
}
Reasoning
I have everything. Write the final review.

Findings:
1. P4 — Wasted `interfaceAttributes` call in `emit` delete path (netlink.go:682-687).
2. P4 — Stitch-mark window measured from first report; slow stitching missed and unmarked by a ponytail ceiling comment (netlink.go:650-670, 736-743).
3. P4 — Docs don't mention the new delete+create re-report on stitch marking (docs/cmd/events.md:32; netlink.go:672-699).
4. P4 — `reportStitchMarks` positive path untested (netlink_watch_test.go:511).

Coverage: complete, source-only review, no test execution.
All checks are complete. Here is the full review.

# Review: stitched-interface rename reporting in the netlink watcher

## Summary

This PR improves how `clab events` reports veth-stitch links: a per-interface record of the last-reported attributes (`w.reported`) lets the watcher detect that a link is now known under its host-side stitch interface name, emit a `delete` under the old name, and re-`create` it under the stitch name — both on live link updates and proactively, via a one-second netem-ticker poll (`reportStitchMarks`) within a one-minute window after the link was first reported. The overall design is lean, the rename handling is consistent across `emit`, `emitStats`, and `track`, and the tests cover the rename mechanics well. I found no correctness defects; the findings below are minor efficiency, documentation, and test-coverage improvements.

| Priority | Count | Summary |
|---|---|---|
| P0 | 0 | — |
| P1 | 0 | — |
| P2 | 0 | — |
| P3 | 0 | — |
| P4 | 4 | Wasted root-netns lookup on delete; undocumented event-stream behavior change; stitch-window ceiling unmarked/untested positive path |

## Findings

### 1. `emit` computes attributes before consulting `w.reported`, wasting a root-netns lookup on every delete (P4)

**Location:** [core/events/netlink.go:681-687](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/core/events/netlink.go#L681-L687) (head)

**Problem:** In the `delete` branch, `attributes := interfaceAttributes(w.container, snapshot)` is computed first, and only then overwritten with `previous.attributes` when the index is known. `interfaceAttributes` ends in `overlayToolsInterface` → `clablinks.ToolsInterface` → `netlink.LinkByName`, a root-netns `RTM_GETLINK` round trip ([core/events/netlink.go:852-867](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/core/events/netlink.go#L852-L867), [core/events/netlink.go:898-919](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/core/events/netlink.go#L898-L919)).

**Trigger:** Every interface `delete` event for a previously reported interface — i.e., the common case for link teardown during `destroy` or `redeploy`.

**Impact:** One wasted netlink lookup per delete event. Small in absolute terms, but free to avoid.

**Correction:** Check `w.reported[snapshot.Index]` first and only call `interfaceAttributes` when no previous report exists:

```go
if action == "delete" {
    previous, ok := w.reported[snapshot.Index]
    attributes := previous.attributes
    if !ok {
        attributes = interfaceAttributes(w.container, snapshot)
    }
    delete(w.reported, snapshot.Index)
    ...
}
```

### 2. The stitch-mark window is measured from the first report, so slow stitching is silently missed; the ceiling is not marked per the ponytail rule (P4)

**Location:** [core/events/netlink.go:650-670](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/core/events/netlink.go#L650-L670) and [core/events/netlink.go:736-743](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/core/events/netlink.go#L736-L743) (head)

**Problem:** `track` preserves the original `since` timestamp (`since = previous.since`) forever, and `reportStitchMarks` skips any link where `time.Since(reported.since) > stitchMarkWindow` (one minute). The window therefore measures from the *first* time the watcher reported the link, not from the most recent poll. In a veth-stitch deploy where the opposite endpoint's container starts slowly (image pull, slow node startup), stitching happens in `PostDeploy` after the first node's interface was already reported — potentially more than a minute later. The rename is then never reported: the interface stays under the node-side name (`eth1`) until the node-side link itself changes or the watcher resubscribes. Note that refreshing `since` on every poll is not the right fix either — it would keep every veth a polling candidate forever and turn the window into an unbounded scan; the one-minute bound is a deliberate cost ceiling.

**Trigger:** Slow deploys where the gap between a node-end veth being created and its host-side altname being applied exceeds one minute; also subscription outages longer than the window.

**Impact:** For those links, events report `ifname: eth1` instead of the stitch name — the same limitation the base code had, so this is a residual gap in an improvement, not a regression. But the repository's ponytail rule asks that deliberate ceilings carry a `ponytail:` comment naming the ceiling and the upgrade path; the comment on `reportStitchMarks` explains the mechanism but not this tradeoff.

**Correction:** Add a `ponytail:` comment at `stitchMarkWindow` stating the ceiling (e.g., "links stitched more than one minute after first report are not renamed in the stream until the link changes or the watcher resubscribes; a root-namespace monitor for altname additions would close this"). Optionally extend the window if deploy observations show it is tight.

### 3. The new delete+create re-report of stitched links is undocumented (P4)

**Location:** [docs/cmd/events.md:32](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/docs/cmd/events.md#L32) (head), introduced by [core/events/netlink.go:672-699](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/core/events/netlink.go#L672-L699)

**Problem:** The events documentation states that interface notifications are emitted "when a link appears, disappears, or when its relevant properties … change." This PR adds a new class of emission: a link whose properties did not change can be re-reported as a `delete` under its node-side name followed by a `create` under the host-side stitch interface name, both live (via `track`) and proactively (via `reportStitchMarks`). Consumers that key records on `ifname` — the documented contract — will see teardown+creation pairs for the same logical interface whenever a stitch is marked.

**Trigger:** Any consumer of `clab events` watching a lab with veth-stitch links, during deploy or link reconfiguration.

**Impact:** The documented event model does not match the observable stream, which can surprise integrators (e.g., the VS Code extension) into treating the rename as a link removal and re-add.

**Correction:** Add one or two sentences to `docs/cmd/events.md` explaining that a stitched interface may be reported as `delete` under its node-side name and `create` under the stitch interface name when the host-side stitch is marked, and that `alias` carries the topology name throughout. Since release 0.83 is the current unreleased release, a short Miscellaneous bullet in `docs/rn/0.83.md` would also fit; the `release-note-review` rule itself is not violated because this PR touches no files under `docs/rn/`.

### 4. The positive path of `reportStitchMarks` is untested (P4)

**Location:** [core/events/netlink_watch_test.go:511](https://github.com/srl-labs/containerlab/blob/<HEAD_SHA>/core/events/netlink_watch_test.go#L511) (head)

**Problem:** `TestReportStitchMarksLeavesUnmarkedLinks` covers only the negative filtering cases (stitch already reflected, expired window, never reported). The core new behavior — a within-window link reported under its own name whose host-side stitch gets marked, producing a `delete` of the old name and a `create` under the stitch name — has no direct test. The rename mechanics are covered indirectly through `TestEmitReportsRenamedLinkDeleted` and `TestEmitStatsReportsRenamedLinkFirst`, but the polling function's candidate filter (`snapshot.Type == "veth"`, name comparison, window check) and its interaction with `emit` are not exercised end to end.

**Trigger:** A future refactor of `reportStitchMarks` (e.g., reordering the window check or the type check) would not be caught by the suite.

**Impact:** Low, but this is the headline behavior of the PR, and the existing test harness already fakes stitch marks, so the missing case is cheap to add.

**Correction:** Add one test in `netlink_watch_test.go` modeled on `TestReportStitchMarksLeavesUnmarkedLinks`: pre-seed `watcher.reported` with a veth reported under its own name with a fresh `since`, fake a stitch mark in the harness, call `reportStitchMarks`, and assert the expected `delete` + `create` sequence in the collected events.

## Coverage notes

- This was a source-only review: I inspected the head and base snapshots, the full diff, both changed files, callers of the changed functions, the events documentation, release notes, and the repository's review rules. I did not execute the test suite, run `make format`, or exercise the code; statements about tests reflect source inspection only.
- All changed paths (`core/events/netlink.go`, `core/events/netlink_watch_test.go`) and their relevant surrounding code were reviewed. The base-vs-head comparison confirmed the old `container == nil` guard on interface events is preserved by the guards inside `emit` and `emitStats`; all call sites of the new `sendInterfaceEvent` are within these guarded paths.
- The pre-existing behavior that links present at the first subscription are recorded in `states` but not in `w.reported` (with `includeSnapshot=false`) was checked and is not worsened by this PR; it only matters for later `delete`/`update` events, which already fall back to freshly computed attributes.
- `w.reported` is accessed only from the watcher goroutine (`emit`, `emitStats`, `track`, `reportStitchMarks` are all invoked from `watch`/`collectAndEmitStats`), and `track` stores `maps.Clone(attributes)`, so the later mutation of the freshly built attributes map in `emitStats` cannot corrupt stored state. I found no race or aliasing issue.
- The ponytail ceiling-comment rule was applied to the `stitchMarkWindow` heuristic (finding 2); no other deliberate simplification in this PR appeared to warrant a ceiling marker.

```json
{
  "version": 1,
  "findings": [
    {
      "priority": "P4",
      "title": "`emit` computes `interfaceAttributes` before checking `w.reported`, wasting a root-netns lookup on every delete",
      "location": {
        "revision": "head",
        "path": "core/events/netlink.go",
        "start": 681,
        "end": 687
      },
      "problem": "In the `delete` branch of `emit`, `attributes := interfaceAttributes(w.container, snapshot)` is computed before the code checks `w.reported`, and the freshly computed attributes are then discarded whenever a previous report exists. `interfaceAttributes` ends in `overlayToolsInterface` -> `clablinks.ToolsInterface` -> `netlink.LinkByName`, a root-netns `RTM_GETLINK` round trip.",
      "trigger": "Every interface `delete` event for a previously reported interface, which is the common case for link teardown during `destroy` or `redeploy`.",
      "impact": "One wasted netlink lookup per delete event. Small in absolute terms, but free to avoid.",
      "suggestion": "Look up `w.reported[snapshot.Index]` first and only call `interfaceAttributes` when no previous report exists, for example: `previous, ok := w.reported[snapshot.Index]; attributes := previous.attributes; if !ok { attributes = interfaceAttributes(w.container, snapshot) }`."
    },
    {
      "priority": "P4",
      "title": "Stitch-mark window is measured from the first report and the ceiling is not marked per the ponytail rule",
      "location": {
        "revision": "head",
        "path": "core/events/netlink.go",
        "start": 650,
        "end": 670
      },
      "problem": "`track` preserves the original `since` timestamp forever (`since = previous.since`), and `reportStitchMarks` skips any link where `time.Since(reported.since) > stitchMarkWindow`. The window therefore measures from the first time the watcher reported the link, not from the most recent poll. Refreshing `since` on every poll would instead keep every veth a polling candidate forever, so the one-minute bound is a deliberate cost ceiling.",
      "trigger": "A veth-stitch link whose host-side altname is applied more than one minute after the node end was first reported, which happens when the opposite endpoint's container starts slowly (image pull) so stitching occurs in `PostDeploy` long after the first node's interface was reported, or after a subscription outage longer than the window.",
      "impact": "Those interfaces remain reported under the node-side name (`eth1`) instead of the stitch name until the node-side link changes or the watcher resubscribes. This matches the base behavior, so it is a residual gap in an improvement rather than a regression, but the repository's ponytail rule asks that deliberate ceilings carry a `ponytail:` comment naming the ceiling and upgrade path, and the comment on `reportStitchMarks` explains only the mechanism.",
      "suggestion": "Add a `ponytail:` comment at `stitchMarkWindow` stating the ceiling, for example that links stitched more than one minute after first report are not renamed in the stream until the link changes or the watcher resubscribes, with a root-namespace altname monitor as the upgrade path. Optionally widen the window if deploy observations show it is tight."
    },
    {
      "priority": "P4",
      "title": "New delete+create re-report of stitched interfaces is undocumented in `docs/cmd/events.md`",
      "location": {
        "revision": "head",
        "path": "docs/cmd/events.md",
        "start": 32,
        "end": 32
      },
      "problem": "The events documentation states that interface notifications are emitted when a link appears, disappears, or when its relevant properties change. This PR adds a new class of emission: a link whose node-side properties did not change can be re-reported as a `delete` under its node-side name followed by a `create` under the host-side stitch interface name, both live via `track` and proactively via `reportStitchMarks` (introduced in `core/events/netlink.go` lines 672-699).",
      "trigger": "Any consumer of `clab events` watching a lab with veth-stitch links, during deploy or link reconfiguration.",
      "impact": "Consumers that key records on `ifname`, the documented contract, will observe teardown-plus-creation pairs for the same logical interface whenever a stitch is marked, which can surprise integrators into treating the rename as a link removal and re-add.",
      "suggestion": "Add one or two sentences to `docs/cmd/events.md` explaining that a stitched interface may be reported as `delete` under its node-side name and `create` under the stitch interface name when the host-side stitch is marked, and that `alias` carries the topology name throughout. Since release 0.83 is the current unreleased release, a short Miscellaneous bullet in `docs/rn/0.83.md` would also fit."
    },
    {
      "priority": "P4",
      "title": "Positive path of `reportStitchMarks` is untested",
      "location": {
        "revision": "head",
        "path": "core/events/netlink_watch_test.go",
        "start": 511,
        "end": 511
      },
      "problem": "`TestReportStitchMarksLeavesUnmarkedLinks` covers only the negative filtering cases (stitch already reflected, expired window, never reported). The core new behavior, a within-window link reported under its own name whose host-side stitch gets marked and which produces a `delete` of the old name and a `create` under the stitch name, has no direct test. The rename mechanics are covered indirectly by `TestEmitReportsRenamedLinkDeleted` and `TestEmitStatsReportsRenamedLinkFirst`, but the polling function's candidate filter and its interaction with `emit` are not exercised end to end.",
      "trigger": "A future refactor of `reportStitchMarks`, such as reordering the window or type check, would not be caught by the test suite.",
      "impact": "Low, but this polling logic is the headline behavior of the PR and the existing test harness already fakes stitch marks, so the missing case is cheap to add.",
      "suggestion": "Add one test in `core/events/netlink_watch_test.go` modeled on `TestReportStitchMarksLeavesUnmarkedLinks`: pre-seed `watcher.reported` with a veth reported under its own name with a fresh `since`, fake a stitch mark in the harness, call `reportStitchMarks`, and assert the expected `delete` plus `create` sequence in the collected events."
    }
  ],
  "coverage": {
    "complete": true,
    "notes": [
      "Source-only review: head and base snapshots, the full diff, both changed files, callers of the changed functions, the events documentation, release notes, and the repository review rules were inspected. Tests and formatters were not executed.",
      "All changed paths (`core/events/netlink.go`, `core/events/netlink_watch_test.go`) and their surrounding code were reviewed; the base comparison confirmed the removed `container == nil` guard is preserved by guards inside `emit` and `emitStats`, and all `sendInterfaceEvent` call sites are within guarded paths.",
      "`w.reported` is accessed only from the watcher goroutine, and `track` stores `maps.Clone(attributes)`, so no race or aliasing issue was found in the new state tracking.",
      "Pre-existing behavior where links present at the first subscription are recorded in `states` but not `w.reported` with `includeSnapshot=false` was checked and is not worsened by this PR; it is noted as pre-existing rather than a finding.",
      "The ponytail ceiling-comment rule was applied to the `stitchMarkWindow` heuristic in finding 2; no other deliberate simplification in this PR appeared to warrant a ceiling marker."
    ]
  }
}
```
step-finish
{
  "type": "step-finish",
  "id": "prt_1d470676000181CnY4jBpPMXBg",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "messageID": "msg_1d46fd9510016WBZEih108ioOd",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 26223,
    "input": 534,
    "output": 4027,
    "reasoning": 158,
    "cache": {
      "read": 21504,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1d46fd9510016WBZEih108ioOd",
  "sessionID": "ses_e2b95e719ffeoD7jkbBhYGJfgm",
  "time": {
    "created": 1794565462353,
    "completed": 1794565498726
  },
  "parentID": "msg_1d46f6ace001VpF1gWj071crQT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-Gbrdqe",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 26223,
    "input": 534,
    "output": 4027,
    "reasoning": 158,
    "cache": {
      "read": 21504,
      "write": 0
    }
  },
  "finish": "stop"
}